ngram
listlengths
0
67.8k
[ "GenotypesRefAlt from .phenotypes import Phenotypes from .covariates import Covariates from .haplotypes import Extra,", ".phenotypes import Phenotypes from .covariates import Covariates from .haplotypes import Extra, Variant, Haplotype,", "Genotypes, GenotypesRefAlt from .phenotypes import Phenotypes from .covariates import Covariates from .haplotypes import", ".data import Data from .genotypes import Genotypes, GenotypesRefAlt from .phenotypes import Phenotypes from", "from .genotypes import Genotypes, GenotypesRefAlt from .phenotypes import Phenotypes from .covariates import Covariates", "import Phenotypes from .covariates import Covariates from .haplotypes import Extra, Variant, Haplotype, Haplotypes", "from .data import Data from .genotypes import Genotypes, GenotypesRefAlt from .phenotypes import Phenotypes", "from .phenotypes import Phenotypes from .covariates import Covariates from .haplotypes import Extra, Variant,", "import Genotypes, GenotypesRefAlt from .phenotypes import Phenotypes from .covariates import Covariates from .haplotypes", "<gh_stars>0 from .data import Data from .genotypes import Genotypes, GenotypesRefAlt from .phenotypes import", "Data from .genotypes import Genotypes, GenotypesRefAlt from .phenotypes import Phenotypes from .covariates import", ".genotypes import Genotypes, GenotypesRefAlt from .phenotypes import Phenotypes from .covariates import Covariates from", "import Data from .genotypes import Genotypes, GenotypesRefAlt from .phenotypes import Phenotypes from .covariates" ]
[ "video label') parser.add_argument('--mask', type=str, help='image file suffix') args = parser.parse_args() #fdict = sort_unity_files(args.filepath,", "label=\"green (mean = \" + Gmean + \")\") Bmean = \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b,", "------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask) for key", "'.json' # build file path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx = fpath.rindex('\\\\') + 1 fname", "hist_r[1] fig = plt.figure() # figure() #plt.yscale('log') Rmean = \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r, color='r',", "numpy as np im = Image.fromarray(np.uint8(img)) # Split into 3 channels r, g,", "------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask) model =", "count_b = hist_b[0] # Plot manual bins = hist_r[1] fig = plt.figure() #", "In[52]: def make_video(fdict, model, preproc=False): \"\"\" Make video from image dictionary. video.avi is", "*= conf.norm_const simst = \"Frame: {}, Actual steering angle: {:.2f}\".format(str(fno), pst) cv2.putText(image, simst,", "g.point(lambda i: i + gv) # Blue b = b.point(lambda i: i +", "json file. The argument passed in the path for a file, that was", "gv) # Blue b = b.point(lambda i: i + bv) # Recombine back", "from image dictionary. video.avi is written to disk Parameters ------- fdict: collections.OrderedDict, ordered", "as mpimg img = mpimg.imread('steph.jpeg') myimg = changeRGB(img, 60, 0, 0) plt.imshow(myimg) \"\"\"", "bv) # Recombine back to RGB image result = Image.merge('RGB', (r, g, b))", "f.read() # load json fjson = json.loads(file) # get and return steering angle", "type \"heavy\" or \"torrential\" st: range to draw a random slant from Returns", "dictionary Sorted dictionary containing key and file path Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\'", "not in sys.path: sys.path.append(module_path) import argparse import fnmatch import json import os from", "scale logarithmic # plt.yscale('log', nonposy='clip') # set y limit, may need to change", "= 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask = '*.jpg' #fdict = sort_unity_files(path, mask) #model = 'nvidia2' #make_video(fdict,", "e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the key in example above is 0 (first characters before", "get name e.g. 12893_cam-image_array_.jpg fname = fsplit[-1] # get number e.g. 12893 fnumber", "#fdict = sort_unity_files(args.filepath, args.mask) #make_video(fdict, model, True) # saved as nvidia2.avi #make_video(args.filepath, args.model,", "to small overlaid image y_offset: top padding from large to small overlaid image", "to blue channel Output ------- myimg: uint8 numpy image array Example ------- import", "as np im = Image.fromarray(np.uint8(img)) # Split into 3 channels r, g, b", "same path, will be named record_12893.json We open that file and return the", "image image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) # add Info to frame cv2.putText(image,", "i: i + rv) # Green g = g.point(lambda i: i + gv)", "a random number for slant st = np.random.randint(-1 * st, st) if(rt!='light'): #", "to image Parameters ---------- image_arr: numpy array containing image rt: string, rain type", "order files in the right order. \"\"\" import fnmatch import os from collections", "plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return fig # change rgb values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img, rv=0,", "plt.rcParams[\"figure.figsize\"] = (6,4) myfig = plot_img_hist(img) \"\"\" # from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from", "image2), axis=1) image = cimgs # write to video video.write(image); # increment frame", "l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[42]: def plot_img_hist(img, scheme='rgb'): \"\"\" Plot", "to sort the output of this sort_unity_files().\") return fdict # In[41]: def overlay_imgs(s_img,", "as nvidia2.avi if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description='Make Video script')", "(50, 115), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # create a preprocessed", "resize so we can write some info onto image image = cv2.resize(image, (IMAGE_WIDTH,", "PIL import Image import numpy as np im = Image.fromarray(np.uint8(img)) # Split into", "#model = 'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi def plot_img_hist(img, scheme='rgb'):", "# saved as nvidia2.avi def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an rgb", "Rmean + \")\") Gmean = \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g, color='g', alpha=0.45, label=\"green (mean =", "------- image_arr: numpy array containing image with rain Example -------- \"\"\" import Automold", "fsplit[-1] # get number e.g. 12893 fnumber = fsplit[-1].split('_') fnumber = fnumber[0] #", "parser.parse_args() #fdict = sort_unity_files(args.filepath, args.mask) #make_video(fdict, model, True) # saved as nvidia2.avi #make_video(args.filepath,", "cv2.LINE_AA) # overlay histogram image = overlay_imgs(image2, image) pst = get_sdsandbox_json_steer_angle(fdict[key]) pst *=", "= 256 count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) #img =", "rain Example -------- \"\"\" import Automold as am # print(\"Adding rain...\") if(st !=", "\"\"\" Make video from image dictionary. video.avi is written to disk Parameters -------", "the output of this sort_unity_files().\") return fdict # In[41]: def overlay_imgs(s_img, l_img, x_offset=50,", "we can make use # of locally defined modules module_path = os.path.abspath(os.path.join('..')) if", "# change rgb values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img, rv=0, gv=0, bv=0): \"\"\" Change", "uint8 numpy array myimg = np.asarray(result) return myimg # subset 100 images -", "key in sorted(fdict): image = cv2.imread(fdict[key]) # 120x160x3 # get histogram myfig =", "\" + Rmean + \")\") Gmean = \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g, color='g', alpha=0.45, label=\"green", "passed in the path for a file, that was stored with a corresponding", "we can write some info onto image image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA)", "hist_b[0] # Plot manual bins = hist_r[1] fig = plt.figure() plt.bar(bins[:-1], count_r, color='r',", "fjson['user/angle'] return st_angle # In[ ]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay", "image l_img: numpy array, large image x_offset: left padding from large to small", "image2 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) image_copy = image # resize so we", "write to video video.write(image); # increment frame counter fno = fno + 1", "plt.grid() # make y scale logarithmic # plt.yscale('log', nonposy='clip') # set y limit,", "filepath Returns ------- st_angle: steering angle Example ------- fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa =", "image_arr: numpy array containing image rt: string, rain type \"heavy\" or \"torrential\" st:", "info onto image image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) # add Info to", "uint8 numpy image array rv: integer, value to be added to red channel", "(255, 255, 255), 2, cv2.LINE_AA) # create a preprocessed copy to compare what", "Bmean = \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b, color='b', alpha=0.4, label=\"blue (mean = \" + Bmean", "can write some info onto image image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) #", "scheme: string, 'rgb' (default) or , 'yuv-rgb' If scheme is rgb, maximum number", "image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) # add Info to frame cv2.putText(image, model,", "steering angle Example ------- fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa = get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\" import", "Image import numpy as np im = Image.fromarray(np.uint8(img)) # Split into 3 channels", "# overlay image2 = overlay_imgs(image4, image2) # concatenate if (preproc == True): #", "255), 2, cv2.LINE_AA) # overlay histogram image = overlay_imgs(image2, image) pst = get_sdsandbox_json_steer_angle(fdict[key])", "if(rt!='light'): # heavy or torrential image_arr = am.add_rain_single(image_arr, rain_type=rt, slant=st) else: # no", "hist_b[0] # Plot manual bins = hist_r[1] fig = plt.figure() # figure() #plt.yscale('log')", "def sort_unity_files(path, mask): \"\"\" Create a sorted dictionary from unity (SDSandbox) files e.g.", "padding from large to small overlaid image Returns ------- image_arr: numpy array containing", "path, will be named record_12893.json We open that file and return the steering", "* st, st) if(rt!='light'): # heavy or torrential image_arr = am.add_rain_single(image_arr, rain_type=rt, slant=st)", "padding from large to small overlaid image y_offset: top padding from large to", "= hist_r[1] fig = plt.figure() plt.bar(bins[:-1], count_r, color='r', alpha=0.5) plt.bar(bins[:-1], count_g, color='g', alpha=0.5)", "containing image rt: string, rain type \"heavy\" or \"torrential\" st: range to draw", "https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img, rv=0, gv=0, bv=0): \"\"\" Change RGB values using PIL Parameters", "mpimg.imread('steph.jpeg') myimg = changeRGB(img, 60, 0, 0) plt.imshow(myimg) \"\"\" from PIL import Image", "plt.close(fig) #return fig # change rgb values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img, rv=0, gv=0,", "bins = hist_r[1] fig = plt.figure() # figure() #plt.yscale('log') Rmean = \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1],", "concatenate if (preproc == True): # wide angle cimgs = np.concatenate((image, image2), axis=1)", "fig = plt.figure() plt.bar(bins[:-1], count_r, color='r', alpha=0.5) plt.bar(bins[:-1], count_g, color='g', alpha=0.5) plt.bar(bins[:-1], count_b,", "= image # resize so we can write some info onto image image", "#path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask = '*.jpg' filemask = os.path.expanduser(path + mask) path, mask", "to bring this from existing module def add_rain(image_arr, rt=None, st=0): \"\"\" Add rain", "= changeRGB(img, 60, 0, 0) plt.imshow(myimg) \"\"\" from PIL import Image import numpy", "as plt ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 = cv2.imread(ipath) # 120x160x3 plt.rcParams[\"figure.figsize\"] = (6,4)", "Parameters ------- fpath: string, filepath Returns ------- st_angle: steering angle Example ------- fpath", "-------- \"\"\" import Automold as am # print(\"Adding rain...\") if(st != 0): #", "fdict = OrderedDict() matches = [] for root, dirnames, filenames in os.walk(path): for", "angle. Parameters ------- fpath: string, filepath Returns ------- st_angle: steering angle Example -------", "json import os from io import BytesIO from PIL import Image import base64", "RGBmean + \")\") # add a grid plt.grid() # make y scale logarithmic", "np.zeros(nb_bins) count_b = np.zeros(nb_bins) # Calculate manual hist x = np.array(img) x =", "json file with with steering angle, in the same path, will be named", "split string fsplit = fpath.split('\\\\') # get name e.g. 12893_cam-image_array_.jpg fname = fsplit[-1]", "slant st = np.random.randint(-1 * st, st) if(rt!='light'): # heavy or torrential image_arr", "image result = Image.merge('RGB', (r, g, b)) # Convert to uint8 numpy array", "file f = open(fname, \"r\") file = f.read() # load json fjson =", "import BytesIO from PIL import Image import base64 import numpy as np import", "#import cv2 #s_img = cv2.imread(\"smaller_image.png\") #l_img = cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] =", "Exception as e: print(\"Exception raise: \" + str(e)) cv2.destroyAllWindows() video.release() # subset 100", "100 images - should be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask = '*.jpg' #fdict", "type=str, help='image file suffix') args = parser.parse_args() #fdict = sort_unity_files(args.filepath, args.mask) #make_video(fdict, model,", "'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 = cv2.imread(ipath) # 120x160x3 plt.rcParams[\"figure.figsize\"] = (6,4) myfig = plot_img_hist(img) \"\"\"", "image2 = overlay_imgs(image4, image2) # concatenate if (preproc == True): # wide angle", "'rgb' (default) or , 'yuv-rgb' If scheme is rgb, maximum number of values", "Video script') parser.add_argument('--filepath', type=str, help='tcpflow log') parser.add_argument('--model', type=str, help='model name for video label')", "should be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask = '*.jpg' #fdict = sort_unity_files(path, mask)", "the steering angle. Parameters ------- fpath: string, filepath Returns ------- st_angle: steering angle", "\"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b, color='b', alpha=0.4, label=\"blue (mean = \" + Bmean + \")\")", "# draw a random number for slant st = np.random.randint(-1 * st, st)", "import json import os from io import BytesIO from PIL import Image import", "np import matplotlib.pyplot as plt nb_bins = 256 count_r = np.zeros(nb_bins) count_g =", "image) pst = get_sdsandbox_json_steer_angle(fdict[key]) pst *= conf.norm_const simst = \"Frame: {}, Actual steering", "sort_unity_files(path, mask) #model = 'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi if", "bins = hist_r[1] fig = plt.figure() plt.bar(bins[:-1], count_r, color='r', alpha=0.5) plt.bar(bins[:-1], count_g, color='g',", "a preprocessed copy to compare what simulator generates to what network \"sees\" if", "gv: integer, value to be added to green channel bv, integer, value to", "number of values in a bins is expected to 3 digit, otherwise 6", "nonposy='clip') # set y limit, may need to change # No plotting max", "name preproc: boolean, show preprocessed image next to original Returns none Example -------", "small image l_img: numpy array, large image x_offset: left padding from large to", "image4 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) # overlay image2 = overlay_imgs(image4, image2) #", "json fjson = json.loads(file) # get and return steering angle attribute st_angle =", "= json.loads(file) # get and return steering angle attribute st_angle = fjson['user/angle'] return", "slant image_arr = am.add_rain_single(image_arr) return image_arr # In[52]: def make_video(fdict, model, preproc=False): \"\"\"", "st=0): \"\"\" Add rain to image Parameters ---------- image_arr: numpy array containing image", "io import BytesIO from PIL import Image import base64 import numpy as np", "key in sorted(fdict): print(\"key: {}, value:{}\".format(key,fdict[key])) Note ------- File path format is OS", "histogram image = overlay_imgs(image2, image) pst = get_sdsandbox_json_steer_angle(fdict[key]) pst *= conf.norm_const simst =", "= ag.preprocess(image_copy) image2 = cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2, 'Network Image', (50, 50),", "bins=nb_bins, range=[0, 255]) count_r = hist_r[0] count_g = hist_g[0] count_b = hist_b[0] #", "help='tcpflow log') parser.add_argument('--model', type=str, help='model name for video label') parser.add_argument('--mask', type=str, help='image file", "r.point(lambda i: i + rv) # Green g = g.point(lambda i: i +", "with with steering angle, in the same path, will be named record_12893.json We", "# Convert to uint8 numpy array myimg = np.asarray(result) return myimg # subset", "x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[ ]: # TODO, need to bring", "image2 = cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2, 'Network Image', (50, 50), font, 1,", "to red channel gv: integer, value to be added to green channel bv,", "import argparse import fnmatch import json import os from io import BytesIO from", "'Network Image', (50, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # histogram", "#!/usr/bin/env python # coding: utf-8 # In[40]: def sort_unity_files(path, mask): \"\"\" Create a", "= np.concatenate((image, image2), axis=1) image = cimgs # write to video video.write(image); #", "left padding from large to small overlaid image y_offset: top padding from large", "containing image with rain Example -------- \"\"\" import Automold as am # print(\"Adding", "mask) model = 'nvidia2' make_video(fdict, model, True) # saved as nvidia2.avi \"\"\" import", "fnmatch import json import os from io import BytesIO from PIL import Image", "os.path.split(filemask) fdict = OrderedDict() matches = [] for root, dirnames, filenames in os.walk(path):", "= get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\" import json # split string fsplit = fpath.split('\\\\') #", "import argparse parser = argparse.ArgumentParser(description='Make Video script') parser.add_argument('--filepath', type=str, help='tcpflow log') parser.add_argument('--model', type=str,", "{:.2f}\".format(str(fno), pst) cv2.putText(image, simst, (50, 115), font, 1, (255, 255, 255), 2, cv2.LINE_AA)", "of values in a bins is expected to 3 digit, otherwise 6 digits", "in example above is 0 (first characters before underscore in 0_cam-image_array_.jpg) Parameters ----------", "IMAGE_WIDTH, IMAGE_HEIGHT = 800, 600 if(preproc == True): # wide angle VIDEO_WIDTH =", "\"\"\" Add rain to image Parameters ---------- image_arr: numpy array containing image rt:", "insert of small image inlaid Example -------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return", "= 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask = '*.jpg' filemask = os.path.expanduser(path + mask) path, mask =", "video_name = model + '.avi' VIDEO_WIDTH, VIDEO_HEIGHT = 800, 600 IMAGE_WIDTH, IMAGE_HEIGHT =", "Returns ------- image_arr: numpy array containing image with rain Example -------- \"\"\" import", "cv2 import numpy as np import matplotlib.pyplot as plt ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1", "path to files mask : string file type Returns ------- fdict: dictionary Sorted", "= fpath[0:idx] + fname # open and read file f = open(fname, \"r\")", "__name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description='Make Video script') parser.add_argument('--filepath', type=str, help='tcpflow", "color='r', alpha=0.5, label=\"red (mean = \" + Rmean + \")\") Gmean = \"{:.2f}\".format(np.mean(x[1]))", "array, small image l_img: numpy array, large image x_offset: left padding from large", "video from image dictionary. video.avi is written to disk Parameters ------- fdict: collections.OrderedDict,", "'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa = get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\" import json # split string fsplit =", "# subset 100 images - should be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask =", "attribute st_angle = fjson['user/angle'] return st_angle # In[ ]: def overlay_imgs(s_img, l_img, x_offset=50,", "to be added to red channel gv: integer, value to be added to", "return the steering angle. Parameters ------- fpath: string, filepath Returns ------- st_angle: steering", "= fpath.rindex('\\\\') + 1 fname = fpath[0:idx] + fname # open and read", "= np.zeros(nb_bins) # Calculate manual hist x = np.array(img) x = x.transpose(2, 0,", "# font font = cv2.FONT_HERSHEY_SIMPLEX # frame count fno = 1 try: for", "# In[40]: def sort_unity_files(path, mask): \"\"\" Create a sorted dictionary from unity (SDSandbox)", "fdict[int(filename.split('_')[0])] = os.path.join(root, filename) print(\"Use sorted() function in your for loop to sort", "\"sees\" if (preproc == True): # wide angle image2 = ag.preprocess(image_copy) image2 =", "for an rgb array Parameters ------- img: numpy array scheme: string, 'rgb' (default)", "120x160x3 plt.rcParams[\"figure.figsize\"] = (6,4) myfig = plot_img_hist(img) \"\"\" # from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/", "= sort_unity_files(path, mask) for key in sorted(fdict): print(\"key: {}, value:{}\".format(key,fdict[key])) Note ------- File", "= 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask) model = 'nvidia2' make_video(fdict,", "path, mask = os.path.split(filemask) fdict = OrderedDict() matches = [] for root, dirnames,", "import Image import numpy as np import matplotlib.pyplot as plt nb_bins = 256", "\"\"\" Overlay two numpy array images Parameters ---------- s_img: numpy array, small image", "plt nb_bins = 256 count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins)", "os from io import BytesIO from PIL import Image import base64 import numpy", "angle, looks something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg The json file with with steering", "ordered dictionary of file names model: string, model name preproc: boolean, show preprocessed", "\"\"\" Get steering angle stored in json file. The argument passed in the", "fnumber = fnumber[0] # build json file name e.g. record_12893.json fname = 'record_'", "intensity value distributions (mean = \" + RGBmean + \")\") # add a", "numpy as np import matplotlib.pyplot as plt import Augment_cls as Augmentation import cv2", "array containing large image with insert of small image inlaid Example -------- \"\"\"", "import base64 import numpy as np import matplotlib.pyplot as plt import Augment_cls as", "1) hist_r = np.histogram(x[0], bins=nb_bins, range=[0, 255]) hist_g = np.histogram(x[1], bins=nb_bins, range=[0, 255])", "numpy image array rv: integer, value to be added to red channel gv:", "values using PIL Parameters ------- img: uint8 numpy image array rv: integer, value", "l_img # In[42]: def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an rgb array", "overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy array images Parameters ---------- s_img:", "import matplotlib.image as mpimg img = mpimg.imread('steph.jpeg') myimg = changeRGB(img, 60, 0, 0)", "# save plt.close(myfig) # overlay image2 = overlay_imgs(image4, image2) # concatenate if (preproc", "model, True) # saved as nvidia2.avi def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for", "in the same path, will be named record_12893.json We open that file and", "Parameters ---------- image_arr: numpy array containing image rt: string, rain type \"heavy\" or", "for key in sorted(fdict): image = cv2.imread(fdict[key]) # 120x160x3 # get histogram myfig", "= am.add_rain_single(image_arr) return image_arr # In[52]: def make_video(fdict, model, preproc=False): \"\"\" Make video", "collections.OrderedDict, ordered dictionary of file names model: string, model name preproc: boolean, show", "font font = cv2.FONT_HERSHEY_SIMPLEX # frame count fno = 1 try: for key", "+ '.json' # build file path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx = fpath.rindex('\\\\') + 1", "looks something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg The json file with with steering angle,", "\")\") # show labels plt.legend(loc='upper right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255, step=25)) plt.ylabel(\"Pixels\") RGBmean =", "# write to video video.write(image); # increment frame counter fno = fno +", "will be named record_12893.json We open that file and return the steering angle.", "simulator generates to what network \"sees\" if (preproc == True): # wide angle", "count_b = np.zeros(nb_bins) # Calculate manual hist x = np.array(img) x = x.transpose(2,", "import numpy as np im = Image.fromarray(np.uint8(img)) # Split into 3 channels r,", "== True): # wide angle cimgs = np.concatenate((image, image2), axis=1) image = cimgs", "files mask : string file type Returns ------- fdict: dictionary Sorted dictionary containing", "Example ------- import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('steph.jpeg')", "make y scale logarithmic # plt.yscale('log', nonposy='clip') # set y limit, may need", "insert of small image inlaid Example -------- \"\"\" #import cv2 #s_img = cv2.imread(\"smaller_image.png\")", "= fno + 1 except Exception as e: print(\"Exception raise: \" + str(e))", "video name video_name = model + '.avi' VIDEO_WIDTH, VIDEO_HEIGHT = 800, 600 IMAGE_WIDTH,", "sorted() function in your for loop to sort the output of this sort_unity_files().\")", "if (preproc == True): # wide angle image2 = ag.preprocess(image_copy) image2 = cv2.resize(image2,", "rv: integer, value to be added to red channel gv: integer, value to", "green channel bv, integer, value to be added to blue channel Output -------", "containing large image with insert of small image inlaid Example -------- \"\"\" #import", "[] for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])]", "for one off images #ymax = 10000 #plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return fig", "a sorted dictionary from unity (SDSandbox) files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the key in", "------- fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa = get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\" import json # split", "as plt nb_bins = 256 count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b =", "image with insert of small image inlaid Example -------- \"\"\" #import cv2 #s_img", "Plot manual bins = hist_r[1] fig = plt.figure() plt.bar(bins[:-1], count_r, color='r', alpha=0.5) plt.bar(bins[:-1],", "counter fno = fno + 1 except Exception as e: print(\"Exception raise: \"", "the key in example above is 0 (first characters before underscore in 0_cam-image_array_.jpg)", "(50, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # overlay histogram image", "cv2 import conf # instantiate augmentation class ag = Augmentation.Augment_cls(model) # video name", "manual bins = hist_r[1] fig = plt.figure() plt.bar(bins[:-1], count_r, color='r', alpha=0.5) plt.bar(bins[:-1], count_g,", ": string path to files mask : string file type Returns ------- fdict:", "preproc: boolean, show preprocessed image next to original Returns none Example ------- path", "saved as nvidia2.avi #make_video(args.filepath, args.model, True) # example # python utils.py --filepath=C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\ \\", "Image.fromarray(np.uint8(img)) # Split into 3 channels r, g, b = im.split() # Red", "#model = 'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi if __name__ ==", "= \" + Rmean + \")\") Gmean = \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g, color='g', alpha=0.45,", "fnumber[0] # build json file name e.g. record_12893.json fname = 'record_' + fnumber", "# concatenate if (preproc == True): # wide angle cimgs = np.concatenate((image, image2),", "channel gv: integer, value to be added to green channel bv, integer, value", "make_video(fdict, model, True) # saved as nvidia2.avi \"\"\" import os import sys #", "https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL import Image import numpy as np import matplotlib.pyplot", "= hist_b[0] # Plot manual bins = hist_r[1] fig = plt.figure() plt.bar(bins[:-1], count_r,", "Create a sorted dictionary from unity (SDSandbox) files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the key", "Image import numpy as np import matplotlib.pyplot as plt nb_bins = 256 count_r", "that was stored with a corresponding json file containing a steering angle, looks", "small image inlaid Example -------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img #", "# heavy or torrential image_arr = am.add_rain_single(image_arr, rain_type=rt, slant=st) else: # no slant", "value to be added to green channel bv, integer, value to be added", "channel bv, integer, value to be added to blue channel Output ------- myimg:", "that file and return the steering angle. Parameters ------- fpath: string, filepath Returns", "s_img return l_img # In[ ]: # TODO, need to bring this from", "# saved as nvidia2.avi #make_video(args.filepath, args.model, True) # example # python utils.py --filepath=C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\", "= np.histogram(x[2], bins=nb_bins, range=[0, 255]) count_r = hist_r[0] count_g = hist_g[0] count_b =", "# 120x160x3 # get histogram myfig = plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\") image2 = cv2.imread(\"temp_plot.png\")", "back to RGB image result = Image.merge('RGB', (r, g, b)) # Convert to", "Red r = r.point(lambda i: i + rv) # Green g = g.point(lambda", "count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) # Calculate manual hist x = np.array(img)", "= 'nvidia2' make_video(fdict, model, True) # saved as nvidia2.avi \"\"\" import os import", "be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask = '*.jpg' #fdict = sort_unity_files(path, mask) #model", "red channel gv: integer, value to be added to green channel bv, integer,", "In[41]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy array images Parameters", "fdict: dictionary Sorted dictionary containing key and file path Example ------- path =", "or torrential image_arr = am.add_rain_single(image_arr, rain_type=rt, slant=st) else: # no slant image_arr =", "loop to sort the output of this sort_unity_files().\") return fdict # In[41]: def", "containing key and file path Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg'", "count_r, color='r', alpha=0.5, label=\"red (mean = \" + Rmean + \")\") Gmean =", "argparse import fnmatch import json import os from io import BytesIO from PIL", "fno = 1 try: for key in sorted(fdict): image = cv2.imread(fdict[key]) # 120x160x3", "files in the right order. \"\"\" import fnmatch import os from collections import", "= cv2.imread(\"temp_plot.png\") # save plt.close(myfig) # overlay image2 = overlay_imgs(image4, image2) # concatenate", "off images #ymax = 10000 #plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return fig # change", "= plot_img_hist(img) \"\"\" # from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL import Image import", "= cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[ ]:", "1 fname = fpath[0:idx] + fname # open and read file f =", "mask = '*.jpg' fdict = sort_unity_files(path, mask) model = 'nvidia2' make_video(fdict, model, True)", "l_img: numpy array, large image x_offset: left padding from large to small overlaid", "axis=1) image = cimgs # write to video video.write(image); # increment frame counter", "RGBmean = \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity value distributions (mean = \" + RGBmean +", "count_b, color='b', alpha=0.4, label=\"blue (mean = \" + Bmean + \")\") # show", "return l_img # In[ ]: # TODO, need to bring this from existing", "in sorted(fdict): image = cv2.imread(fdict[key]) # 120x160x3 # get histogram myfig = plot_img_hist(image,", "Augmentation import cv2 import conf # instantiate augmentation class ag = Augmentation.Augment_cls(model) #", "File path format is OS dependant. OrderedDict must by sorted to order files", "= mpimg.imread('steph.jpeg') myimg = changeRGB(img, 60, 0, 0) plt.imshow(myimg) \"\"\" from PIL import", "(mean = \" + Bmean + \")\") # show labels plt.legend(loc='upper right') plt.xlabel(\"Bins\")", "from Returns ------- image_arr: numpy array containing image with rain Example -------- \"\"\"", "= 'record_' + fnumber + '.json' # build file path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx", "is written to disk Parameters ------- fdict: collections.OrderedDict, ordered dictionary of file names", "255), 2, cv2.LINE_AA) # create a preprocessed copy to compare what simulator generates", "rt=None, st=0): \"\"\" Add rain to image Parameters ---------- image_arr: numpy array containing", "Example ------- fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa = get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\" import json #", "255, 255), 2, cv2.LINE_AA) # overlay histogram image = overlay_imgs(image2, image) pst =", "image array rv: integer, value to be added to red channel gv: integer,", "def make_video(fdict, model, preproc=False): \"\"\" Make video from image dictionary. video.avi is written", "example above is 0 (first characters before underscore in 0_cam-image_array_.jpg) Parameters ---------- path", "show labels plt.legend(loc='upper right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255, step=25)) plt.ylabel(\"Pixels\") RGBmean = \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB", "cv2.putText(image2, 'Network Image', (50, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA) #", "# add Info to frame cv2.putText(image, model, (50, 50), font, 1, (255, 255,", "add a grid plt.grid() # make y scale logarithmic # plt.yscale('log', nonposy='clip') #", "np im = Image.fromarray(np.uint8(img)) # Split into 3 channels r, g, b =", "plt.bar(bins[:-1], count_g, color='g', alpha=0.5) plt.bar(bins[:-1], count_b, color='b', alpha=0.5) return fig # In[43]: #", "saved as nvidia2.avi if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description='Make Video", "image2 = ag.preprocess(image_copy) image2 = cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2, 'Network Image', (50,", "plt.bar(bins[:-1], count_b, color='b', alpha=0.4, label=\"blue (mean = \" + Bmean + \")\") #", "next to original Returns none Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg'", "large image with insert of small image inlaid Example -------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]]", "write some info onto image image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) # add", "of small image inlaid Example -------- \"\"\" #import cv2 #s_img = cv2.imread(\"smaller_image.png\") #l_img", "2, cv2.LINE_AA) # overlay histogram image = overlay_imgs(image2, image) pst = get_sdsandbox_json_steer_angle(fdict[key]) pst", "i: i + bv) # Recombine back to RGB image result = Image.merge('RGB',", "saved as nvidia2.avi def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an rgb array", "model, preproc=False): \"\"\" Make video from image dictionary. video.avi is written to disk", "= 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa = get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\" import json # split string fsplit", "array Parameters ------- img: numpy array scheme: string, 'rgb' (default) or , 'yuv-rgb'", "\"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g, color='g', alpha=0.45, label=\"green (mean = \" + Gmean + \")\")", "need to change # No plotting max for one off images #ymax =", "model + '.avi' VIDEO_WIDTH, VIDEO_HEIGHT = 800, 600 IMAGE_WIDTH, IMAGE_HEIGHT = 800, 600", "image myfig = plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) #", "fno = fno + 1 except Exception as e: print(\"Exception raise: \" +", "fig # In[43]: # fpath = fdict[key] def get_sdsandbox_json_steer_angle(fpath): \"\"\" Get steering angle", "os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import argparse import fnmatch import json", "True) # saved as nvidia2.avi \"\"\" import os import sys # append local", "image_copy = image # resize so we can write some info onto image", "suffix') args = parser.parse_args() #fdict = sort_unity_files(args.filepath, args.mask) #make_video(fdict, model, True) # saved", "alpha=0.4, label=\"blue (mean = \" + Bmean + \")\") # show labels plt.legend(loc='upper", "g = g.point(lambda i: i + gv) # Blue b = b.point(lambda i:", "VIDEO_WIDTH, VIDEO_HEIGHT = 800, 600 IMAGE_WIDTH, IMAGE_HEIGHT = 800, 600 if(preproc == True):", "In[ ]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy array images", "array images Parameters ---------- s_img: numpy array, small image l_img: numpy array, large", "import matplotlib.pyplot as plt import Augment_cls as Augmentation import cv2 import conf #", "OS dependant. OrderedDict must by sorted to order files in the right order.", "use # of locally defined modules module_path = os.path.abspath(os.path.join('..')) if module_path not in", "------- fig: matplotlib.pyplot figure Example ------- import cv2 import numpy as np import", "import cv2 import numpy as np import matplotlib.pyplot as plt ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg'", "np import matplotlib.pyplot as plt import Augment_cls as Augmentation import cv2 import conf", "from large to small overlaid image y_offset: top padding from large to small", "# assumed 11fps # font font = cv2.FONT_HERSHEY_SIMPLEX # frame count fno =", "= overlay_imgs(image2, image) pst = get_sdsandbox_json_steer_angle(fdict[key]) pst *= conf.norm_const simst = \"Frame: {},", "small overlaid image Returns ------- image_arr: numpy array containing large image with insert", "stored with a corresponding json file containing a steering angle, looks something like:", "from existing module def add_rain(image_arr, rt=None, st=0): \"\"\" Add rain to image Parameters", "image dictionary. video.avi is written to disk Parameters ------- fdict: collections.OrderedDict, ordered dictionary", "# load json fjson = json.loads(file) # get and return steering angle attribute", "# set y limit, may need to change # No plotting max for", "# get number e.g. 12893 fnumber = fsplit[-1].split('_') fnumber = fnumber[0] # build", "# x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[ ]: # TODO,", "raise: \" + str(e)) cv2.destroyAllWindows() video.release() # subset 100 images - should be", "count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) # Calculate manual hist", "= sort_unity_files(path, mask) model = 'nvidia2' make_video(fdict, model, True) # saved as nvidia2.avi", "hist_b = np.histogram(x[2], bins=nb_bins, range=[0, 255]) count_r = hist_r[0] count_g = hist_g[0] count_b", "np.histogram(x[0], bins=nb_bins, range=[0, 255]) hist_g = np.histogram(x[1], bins=nb_bins, range=[0, 255]) hist_b = np.histogram(x[2],", "a corresponding json file containing a steering angle, looks something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\", "model name preproc: boolean, show preprocessed image next to original Returns none Example", "= Augmentation.Augment_cls(model) # video name video_name = model + '.avi' VIDEO_WIDTH, VIDEO_HEIGHT =", "to green channel bv, integer, value to be added to blue channel Output", "read file f = open(fname, \"r\") file = f.read() # load json fjson", "plotting max for one off images #ymax = 10000 #plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig)", "value:{}\".format(key,fdict[key])) Note ------- File path format is OS dependant. OrderedDict must by sorted", "------- img: uint8 numpy image array rv: integer, value to be added to", "Info to frame cv2.putText(image, model, (50, 50), font, 1, (255, 255, 255), 2,", "(255, 255, 255), 2, cv2.LINE_AA) # overlay histogram image = overlay_imgs(image2, image) pst", "nvidia2.avi #make_video(args.filepath, args.model, True) # example # python utils.py --filepath=C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\ \\ # --model=nvidia2", "fname = 'record_' + fnumber + '.json' # build file path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json'", "---------- s_img: numpy array, small image l_img: numpy array, large image x_offset: left", "Where the key in example above is 0 (first characters before underscore in", "def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an rgb array Parameters ------- img:", "dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])] = os.path.join(root, filename)", "array Example ------- import matplotlib.pyplot as plt import matplotlib.image as mpimg img =", "font, 1, (255, 255, 255), 2, cv2.LINE_AA) # histogram on network image myfig", "so we can make use # of locally defined modules module_path = os.path.abspath(os.path.join('..'))", "st = np.random.randint(-1 * st, st) if(rt!='light'): # heavy or torrential image_arr =", "file. The argument passed in the path for a file, that was stored", "plt.xticks(np.arange(0, 255, step=25)) plt.ylabel(\"Pixels\") RGBmean = \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity value distributions (mean =", "draw a random slant from Returns ------- image_arr: numpy array containing image with", "st) if(rt!='light'): # heavy or torrential image_arr = am.add_rain_single(image_arr, rain_type=rt, slant=st) else: #", "path for a file, that was stored with a corresponding json file containing", "fig # change rgb values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img, rv=0, gv=0, bv=0): \"\"\"", "try: for key in sorted(fdict): image = cv2.imread(fdict[key]) # 120x160x3 # get histogram", "count_g, color='g', alpha=0.5) plt.bar(bins[:-1], count_b, color='b', alpha=0.5) return fig # In[43]: # fpath", "the path for a file, that was stored with a corresponding json file", "is expected to 3 digit, otherwise 6 digits and y-axys is plotted on", "Automold as am # print(\"Adding rain...\") if(st != 0): # draw a random", "\")\") Gmean = \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g, color='g', alpha=0.45, label=\"green (mean = \" +", "(preproc == True): # wide angle cimgs = np.concatenate((image, image2), axis=1) image =", "# show labels plt.legend(loc='upper right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255, step=25)) plt.ylabel(\"Pixels\") RGBmean = \"{:.2f}\".format(np.mean(x))", "120x160x3 # get histogram myfig = plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\") image2 = cv2.imread(\"temp_plot.png\") #", "= \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g, color='g', alpha=0.45, label=\"green (mean = \" + Gmean +", "np.zeros(nb_bins) # Calculate manual hist x = np.array(img) x = x.transpose(2, 0, 1)", "\"\"\" Create a sorted dictionary from unity (SDSandbox) files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the", "b)) # Convert to uint8 numpy array myimg = np.asarray(result) return myimg #", "# example # python utils.py --filepath=C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\ \\ # --model=nvidia2 --mask=*.jpg # In[ ]:", "alpha=0.5) return fig # In[43]: # fpath = fdict[key] def get_sdsandbox_json_steer_angle(fpath): \"\"\" Get", "nb_bins = 256 count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) #img", "plt import matplotlib.image as mpimg img = mpimg.imread('steph.jpeg') myimg = changeRGB(img, 60, 0,", "value to be added to red channel gv: integer, value to be added", "image_arr # In[52]: def make_video(fdict, model, preproc=False): \"\"\" Make video from image dictionary.", "np.histogram(x[2], bins=nb_bins, range=[0, 255]) count_r = hist_r[0] count_g = hist_g[0] count_b = hist_b[0]", "= 1 try: for key in sorted(fdict): image = cv2.imread(fdict[key]) # 120x160x3 #", "logarithmic # plt.yscale('log', nonposy='clip') # set y limit, may need to change #", "small overlaid image y_offset: top padding from large to small overlaid image Returns", "numpy array containing image rt: string, rain type \"heavy\" or \"torrential\" st: range", "argparse parser = argparse.ArgumentParser(description='Make Video script') parser.add_argument('--filepath', type=str, help='tcpflow log') parser.add_argument('--model', type=str, help='model", "2, cv2.LINE_AA) # histogram on network image myfig = plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4", "like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg The json file with with steering angle, in the", "print(jsa) \"\"\" import json # split string fsplit = fpath.split('\\\\') # get name", "type Returns ------- fdict: dictionary Sorted dictionary containing key and file path Example", "change rgb values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img, rv=0, gv=0, bv=0): \"\"\" Change RGB", "return fdict # In[41]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy", "i + gv) # Blue b = b.point(lambda i: i + bv) #", "Change RGB values using PIL Parameters ------- img: uint8 numpy image array rv:", "sorted(fdict): print(\"key: {}, value:{}\".format(key,fdict[key])) Note ------- File path format is OS dependant. OrderedDict", "distributions (mean = \" + RGBmean + \")\") # add a grid plt.grid()", "Image import base64 import numpy as np import matplotlib.pyplot as plt import Augment_cls", "on log scale. Returns ------- fig: matplotlib.pyplot figure Example ------- import cv2 import", "ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return fig # change rgb values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img,", "# overlay histogram image = overlay_imgs(image2, image) pst = get_sdsandbox_json_steer_angle(fdict[key]) pst *= conf.norm_const", "= argparse.ArgumentParser(description='Make Video script') parser.add_argument('--filepath', type=str, help='tcpflow log') parser.add_argument('--model', type=str, help='model name for", "make_video(fdict, model, preproc=False): \"\"\" Make video from image dictionary. video.avi is written to", "small image inlaid Example -------- \"\"\" #import cv2 #s_img = cv2.imread(\"smaller_image.png\") #l_img =", "(mean = \" + Rmean + \")\") Gmean = \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g, color='g',", "s_img return l_img # In[42]: def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an", "as np import matplotlib.pyplot as plt import Augment_cls as Augmentation import cv2 import", "open that file and return the steering angle. Parameters ------- fpath: string, filepath", "os from collections import OrderedDict #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask = '*.jpg' filemask =", "np.zeros(nb_bins) #img = Image.open('16_left-2.jpeg') # Calculate manual hist x = np.array(img) x =", "# get and return steering angle attribute st_angle = fjson['user/angle'] return st_angle #", "cv2.imread(\"temp_plot.png\") # save plt.close(myfig) # overlay image2 = overlay_imgs(image4, image2) # concatenate if", "#path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask = '*.jpg' #fdict = sort_unity_files(path, mask) #model = 'nvidia2'", "= np.zeros(nb_bins) count_b = np.zeros(nb_bins) # Calculate manual hist x = np.array(img) x", "for slant st = np.random.randint(-1 * st, st) if(rt!='light'): # heavy or torrential", "plot_img_hist(img) \"\"\" # from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL import Image import numpy", "rv=0, gv=0, bv=0): \"\"\" Change RGB values using PIL Parameters ------- img: uint8", "build file path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx = fpath.rindex('\\\\') + 1 fname = fpath[0:idx]", "# https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img, rv=0, gv=0, bv=0): \"\"\" Change RGB values using PIL", "import Augment_cls as Augmentation import cv2 import conf # instantiate augmentation class ag", "# Blue b = b.point(lambda i: i + bv) # Recombine back to", "and return steering angle attribute st_angle = fjson['user/angle'] return st_angle # In[ ]:", "import conf # instantiate augmentation class ag = Augmentation.Augment_cls(model) # video name video_name", "= f.read() # load json fjson = json.loads(file) # get and return steering", "Image.open('16_left-2.jpeg') # Calculate manual hist x = np.array(img) x = x.transpose(2, 0, 1)", "+ \")\") # show labels plt.legend(loc='upper right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255, step=25)) plt.ylabel(\"Pixels\") RGBmean", "'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi def plot_img_hist(img, scheme='rgb'): \"\"\" Plot", "https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL import Image import numpy as np import matplotlib.pyplot as plt", "json file containing a steering angle, looks something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg The", "count_b = np.zeros(nb_bins) #img = Image.open('16_left-2.jpeg') # Calculate manual hist x = np.array(img)", "disk Parameters ------- fdict: collections.OrderedDict, ordered dictionary of file names model: string, model", "img1 = cv2.imread(ipath) # 120x160x3 plt.rcParams[\"figure.figsize\"] = (6,4) myfig = plot_img_hist(img) \"\"\" #", "manual bins = hist_r[1] fig = plt.figure() # figure() #plt.yscale('log') Rmean = \"{:.2f}\".format(np.mean(x[0]))", "print(\"key: {}, value:{}\".format(key,fdict[key])) Note ------- File path format is OS dependant. OrderedDict must", "from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL import Image import numpy as np import", "os.path.join(root, filename) print(\"Use sorted() function in your for loop to sort the output", "= os.path.split(filemask) fdict = OrderedDict() matches = [] for root, dirnames, filenames in", "Example ------- import cv2 import numpy as np import matplotlib.pyplot as plt ipath", "== \"__main__\": import argparse parser = argparse.ArgumentParser(description='Make Video script') parser.add_argument('--filepath', type=str, help='tcpflow log')", "\" + RGBmean + \")\") # add a grid plt.grid() # make y", "cv2.putText(image, model, (50, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # overlay", "mask) #model = 'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi def plot_img_hist(img,", "12893_cam-image_array_.jpg The json file with with steering angle, in the same path, will", "r = r.point(lambda i: i + rv) # Green g = g.point(lambda i:", "bins=nb_bins, range=[0, 255]) hist_g = np.histogram(x[1], bins=nb_bins, range=[0, 255]) hist_b = np.histogram(x[2], bins=nb_bins,", "= Image.merge('RGB', (r, g, b)) # Convert to uint8 numpy array myimg =", "parser = argparse.ArgumentParser(description='Make Video script') parser.add_argument('--filepath', type=str, help='tcpflow log') parser.add_argument('--model', type=str, help='model name", "color='g', alpha=0.5) plt.bar(bins[:-1], count_b, color='b', alpha=0.5) return fig # In[43]: # fpath =", "# build file path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx = fpath.rindex('\\\\') + 1 fname =", "+ bv) # Recombine back to RGB image result = Image.merge('RGB', (r, g,", "filemask = os.path.expanduser(path + mask) path, mask = os.path.split(filemask) fdict = OrderedDict() matches", "\"\"\" import os import sys # append local path so we can make", "import json # split string fsplit = fpath.split('\\\\') # get name e.g. 12893_cam-image_array_.jpg", "angle image2 = ag.preprocess(image_copy) image2 = cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2, 'Network Image',", "# Plot manual bins = hist_r[1] fig = plt.figure() plt.bar(bins[:-1], count_r, color='r', alpha=0.5)", "# Green g = g.point(lambda i: i + gv) # Blue b =", "right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255, step=25)) plt.ylabel(\"Pixels\") RGBmean = \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity value distributions", "to be added to blue channel Output ------- myimg: uint8 numpy image array", "255, 255), 2, cv2.LINE_AA) # create a preprocessed copy to compare what simulator", "The json file with with steering angle, in the same path, will be", "one off images #ymax = 10000 #plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return fig #", "= b.point(lambda i: i + bv) # Recombine back to RGB image result", "\"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity value distributions (mean = \" + RGBmean + \")\") #", "image_arr = am.add_rain_single(image_arr, rain_type=rt, slant=st) else: # no slant image_arr = am.add_rain_single(image_arr) return", "Plot manual bins = hist_r[1] fig = plt.figure() # figure() #plt.yscale('log') Rmean =", "= 256 count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) # Calculate", "to draw a random slant from Returns ------- image_arr: numpy array containing image", "string, rain type \"heavy\" or \"torrential\" st: range to draw a random slant", "Rmean = \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r, color='r', alpha=0.5, label=\"red (mean = \" + Rmean", "range to draw a random slant from Returns ------- image_arr: numpy array containing", "b = im.split() # Red r = r.point(lambda i: i + rv) #", "VIDEO_HEIGHT)) # assumed 11fps # font font = cv2.FONT_HERSHEY_SIMPLEX # frame count fno", "load json fjson = json.loads(file) # get and return steering angle attribute st_angle", "if(st != 0): # draw a random number for slant st = np.random.randint(-1", "make use # of locally defined modules module_path = os.path.abspath(os.path.join('..')) if module_path not", "corresponding json file containing a steering angle, looks something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg", "Returns ------- st_angle: steering angle Example ------- fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa = get_sdsandbox_json_steer_angle(fpath)", "{}, Actual steering angle: {:.2f}\".format(str(fno), pst) cv2.putText(image, simst, (50, 115), font, 1, (255,", "= \"Frame: {}, Actual steering angle: {:.2f}\".format(str(fno), pst) cv2.putText(image, simst, (50, 115), font,", "!= 0): # draw a random number for slant st = np.random.randint(-1 *", "array, large image x_offset: left padding from large to small overlaid image y_offset:", "255, step=25)) plt.ylabel(\"Pixels\") RGBmean = \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity value distributions (mean = \"", "1, (255, 255, 255), 2, cv2.LINE_AA) # create a preprocessed copy to compare", "import os from collections import OrderedDict #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask = '*.jpg' filemask", "plt.bar(bins[:-1], count_r, color='r', alpha=0.5, label=\"red (mean = \" + Rmean + \")\") Gmean", "np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) # Calculate manual hist x =", "e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx = fpath.rindex('\\\\') + 1 fname = fpath[0:idx] + fname #", "count_g, color='g', alpha=0.45, label=\"green (mean = \" + Gmean + \")\") Bmean =", "matches = [] for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames,", "onto image image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) # add Info to frame", "from PIL import Image import numpy as np im = Image.fromarray(np.uint8(img)) # Split", "#make_video(fdict, model, True) # saved as nvidia2.avi #make_video(args.filepath, args.model, True) # example #", "overlaid image Returns ------- image_arr: numpy array containing large image with insert of", "(preproc == True): # wide angle image2 = ag.preprocess(image_copy) image2 = cv2.resize(image2, (IMAGE_WIDTH,", "large to small overlaid image y_offset: top padding from large to small overlaid", "rain_type=rt, slant=st) else: # no slant image_arr = am.add_rain_single(image_arr) return image_arr # In[52]:", "top padding from large to small overlaid image Returns ------- image_arr: numpy array", "fdict: collections.OrderedDict, ordered dictionary of file names model: string, model name preproc: boolean,", "nvidia2.avi def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an rgb array Parameters -------", "integer, value to be added to red channel gv: integer, value to be", "(mean = \" + RGBmean + \")\") # add a grid plt.grid() #", "+ 1 fname = fpath[0:idx] + fname # open and read file f", "is OS dependant. OrderedDict must by sorted to order files in the right", "preproc=False): \"\"\" Make video from image dictionary. video.avi is written to disk Parameters", "existing module def add_rain(image_arr, rt=None, st=0): \"\"\" Add rain to image Parameters ----------", "3 digit, otherwise 6 digits and y-axys is plotted on log scale. Returns", "True) # saved as nvidia2.avi if __name__ == \"__main__\": import argparse parser =", "= 'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi def plot_img_hist(img, scheme='rgb'): \"\"\"", "args.mask) #make_video(fdict, model, True) # saved as nvidia2.avi #make_video(args.filepath, args.model, True) # example", "cv2.putText(image, simst, (50, 115), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # create", "fpath.split('\\\\') # get name e.g. 12893_cam-image_array_.jpg fname = fsplit[-1] # get number e.g.", "256 count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) #img = Image.open('16_left-2.jpeg')", "right order. \"\"\" import fnmatch import os from collections import OrderedDict #path =", "600 if(preproc == True): # wide angle VIDEO_WIDTH = IMAGE_WIDTH*2 video = cv2.VideoWriter(video_name,", "Returns ------- image_arr: numpy array containing large image with insert of small image", "{}, value:{}\".format(key,fdict[key])) Note ------- File path format is OS dependant. OrderedDict must by", "mask) path, mask = os.path.split(filemask) fdict = OrderedDict() matches = [] for root,", "simst, (50, 115), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # create a", "sort the output of this sort_unity_files().\") return fdict # In[41]: def overlay_imgs(s_img, l_img,", "file type Returns ------- fdict: dictionary Sorted dictionary containing key and file path", "above is 0 (first characters before underscore in 0_cam-image_array_.jpg) Parameters ---------- path :", "+ RGBmean + \")\") # add a grid plt.grid() # make y scale", "plt.figure() plt.bar(bins[:-1], count_r, color='r', alpha=0.5) plt.bar(bins[:-1], count_g, color='g', alpha=0.5) plt.bar(bins[:-1], count_b, color='b', alpha=0.5)", "Bmean + \")\") # show labels plt.legend(loc='upper right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255, step=25)) plt.ylabel(\"Pixels\")", "IMAGE_HEIGHT), cv2.INTER_AREA) # add Info to frame cv2.putText(image, model, (50, 50), font, 1,", "blue channel Output ------- myimg: uint8 numpy image array Example ------- import matplotlib.pyplot", "local path so we can make use # of locally defined modules module_path", "\"torrential\" st: range to draw a random slant from Returns ------- image_arr: numpy", "rgb values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img, rv=0, gv=0, bv=0): \"\"\" Change RGB values", "values in a bins is expected to 3 digit, otherwise 6 digits and", "hist_r = np.histogram(x[0], bins=nb_bins, range=[0, 255]) hist_g = np.histogram(x[1], bins=nb_bins, range=[0, 255]) hist_b", "# In[52]: def make_video(fdict, model, preproc=False): \"\"\" Make video from image dictionary. video.avi", "numpy array myimg = np.asarray(result) return myimg # subset 100 images - should", "True): # wide angle VIDEO_WIDTH = IMAGE_WIDTH*2 video = cv2.VideoWriter(video_name, 0, 11, (VIDEO_WIDTH,", "numpy as np import matplotlib.pyplot as plt ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 = cv2.imread(ipath)", "cimgs = np.concatenate((image, image2), axis=1) image = cimgs # write to video video.write(image);", "using PIL Parameters ------- img: uint8 numpy image array rv: integer, value to", "Returns ------- fig: matplotlib.pyplot figure Example ------- import cv2 import numpy as np", "path format is OS dependant. OrderedDict must by sorted to order files in", "or , 'yuv-rgb' If scheme is rgb, maximum number of values in a", "a file, that was stored with a corresponding json file containing a steering", "copy to compare what simulator generates to what network \"sees\" if (preproc ==", "dictionary. video.avi is written to disk Parameters ------- fdict: collections.OrderedDict, ordered dictionary of", "cv2 #s_img = cv2.imread(\"smaller_image.png\") #l_img = cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img", "from unity (SDSandbox) files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the key in example above is", "sort_unity_files(path, mask) model = 'nvidia2' make_video(fdict, model, True) # saved as nvidia2.avi \"\"\"", "np.array(img) x = x.transpose(2, 0, 1) hist_r = np.histogram(x[0], bins=nb_bins, range=[0, 255]) hist_g", "large to small overlaid image Returns ------- image_arr: numpy array containing large image", "\"__main__\": import argparse parser = argparse.ArgumentParser(description='Make Video script') parser.add_argument('--filepath', type=str, help='tcpflow log') parser.add_argument('--model',", "import matplotlib.pyplot as plt ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 = cv2.imread(ipath) # 120x160x3 plt.rcParams[\"figure.figsize\"]", "plt.bar(bins[:-1], count_g, color='g', alpha=0.45, label=\"green (mean = \" + Gmean + \")\") Bmean", "y_offset=50): \"\"\" Overlay two numpy array images Parameters ---------- s_img: numpy array, small", "------- fdict: dictionary Sorted dictionary containing key and file path Example ------- path", "your for loop to sort the output of this sort_unity_files().\") return fdict #", "angle VIDEO_WIDTH = IMAGE_WIDTH*2 video = cv2.VideoWriter(video_name, 0, 11, (VIDEO_WIDTH, VIDEO_HEIGHT)) # assumed", "Plot histogram for an rgb array Parameters ------- img: numpy array scheme: string,", "color='r', alpha=0.5) plt.bar(bins[:-1], count_g, color='g', alpha=0.5) plt.bar(bins[:-1], count_b, color='b', alpha=0.5) return fig #", "get and return steering angle attribute st_angle = fjson['user/angle'] return st_angle # In[", "#return fig # change rgb values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img, rv=0, gv=0, bv=0):", "os.walk(path): for filename in fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])] = os.path.join(root, filename) print(\"Use sorted() function", "= np.zeros(nb_bins) count_b = np.zeros(nb_bins) #img = Image.open('16_left-2.jpeg') # Calculate manual hist x", "added to red channel gv: integer, value to be added to green channel", "'.avi' VIDEO_WIDTH, VIDEO_HEIGHT = 800, 600 IMAGE_WIDTH, IMAGE_HEIGHT = 800, 600 if(preproc ==", "sort_unity_files(args.filepath, args.mask) #make_video(fdict, model, True) # saved as nvidia2.avi #make_video(args.filepath, args.model, True) #", "is plotted on log scale. Returns ------- fig: matplotlib.pyplot figure Example ------- import", "= am.add_rain_single(image_arr, rain_type=rt, slant=st) else: # no slant image_arr = am.add_rain_single(image_arr) return image_arr", "plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) # overlay image2 =", "mask = os.path.split(filemask) fdict = OrderedDict() matches = [] for root, dirnames, filenames", "matplotlib.pyplot as plt import Augment_cls as Augmentation import cv2 import conf # instantiate", "1 except Exception as e: print(\"Exception raise: \" + str(e)) cv2.destroyAllWindows() video.release() #", "800, 600 IMAGE_WIDTH, IMAGE_HEIGHT = 800, 600 if(preproc == True): # wide angle", "= plt.figure() # figure() #plt.yscale('log') Rmean = \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r, color='r', alpha=0.5, label=\"red", "= overlay_imgs(image4, image2) # concatenate if (preproc == True): # wide angle cimgs", "bins is expected to 3 digit, otherwise 6 digits and y-axys is plotted", "Example -------- \"\"\" #import cv2 #s_img = cv2.imread(\"smaller_image.png\") #l_img = cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50", "image2) # concatenate if (preproc == True): # wide angle cimgs = np.concatenate((image,", "'yuv-rgb' If scheme is rgb, maximum number of values in a bins is", "hist_r[0] count_g = hist_g[0] count_b = hist_b[0] # Plot manual bins = hist_r[1]", "changeRGB(img, 60, 0, 0) plt.imshow(myimg) \"\"\" from PIL import Image import numpy as", "video.avi is written to disk Parameters ------- fdict: collections.OrderedDict, ordered dictionary of file", "image_arr: numpy array containing large image with insert of small image inlaid Example", "np.zeros(nb_bins) count_b = np.zeros(nb_bins) #img = Image.open('16_left-2.jpeg') # Calculate manual hist x =", "frame count fno = 1 try: for key in sorted(fdict): image = cv2.imread(fdict[key])", "#fdict = sort_unity_files(path, mask) #model = 'nvidia2' #make_video(fdict, model, True) # saved as", "mask) for key in sorted(fdict): print(\"key: {}, value:{}\".format(key,fdict[key])) Note ------- File path format", "matplotlib.pyplot as plt nb_bins = 256 count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b", "y limit, may need to change # No plotting max for one off", "alpha=0.45, label=\"green (mean = \" + Gmean + \")\") Bmean = \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1],", "image y_offset: top padding from large to small overlaid image Returns ------- image_arr:", "as e: print(\"Exception raise: \" + str(e)) cv2.destroyAllWindows() video.release() # subset 100 images", "e.g. 12893_cam-image_array_.jpg fname = fsplit[-1] # get number e.g. 12893 fnumber = fsplit[-1].split('_')", "Split into 3 channels r, g, b = im.split() # Red r =", "= np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) #img = Image.open('16_left-2.jpeg') # Calculate", "angle Example ------- fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa = get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\" import json", "in os.walk(path): for filename in fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])] = os.path.join(root, filename) print(\"Use sorted()", "return fig # In[43]: # fpath = fdict[key] def get_sdsandbox_json_steer_angle(fpath): \"\"\" Get steering", "integer, value to be added to blue channel Output ------- myimg: uint8 numpy", "6 digits and y-axys is plotted on log scale. Returns ------- fig: matplotlib.pyplot", "= \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity value distributions (mean = \" + RGBmean + \")\")", "fdict = sort_unity_files(path, mask) model = 'nvidia2' make_video(fdict, model, True) # saved as", "= np.histogram(x[0], bins=nb_bins, range=[0, 255]) hist_g = np.histogram(x[1], bins=nb_bins, range=[0, 255]) hist_b =", "cv2.INTER_AREA) # add Info to frame cv2.putText(image, model, (50, 50), font, 1, (255,", "= cv2.imread(\"smaller_image.png\") #l_img = cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img", "= fnumber[0] # build json file name e.g. record_12893.json fname = 'record_' +", "font, 1, (255, 255, 255), 2, cv2.LINE_AA) # overlay histogram image = overlay_imgs(image2,", "unity (SDSandbox) files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the key in example above is 0", "def add_rain(image_arr, rt=None, st=0): \"\"\" Add rain to image Parameters ---------- image_arr: numpy", "log scale. Returns ------- fig: matplotlib.pyplot figure Example ------- import cv2 import numpy", "idx = fpath.rindex('\\\\') + 1 fname = fpath[0:idx] + fname # open and", "# Recombine back to RGB image result = Image.merge('RGB', (r, g, b)) #", "= fsplit[-1].split('_') fnumber = fnumber[0] # build json file name e.g. record_12893.json fname", "what simulator generates to what network \"sees\" if (preproc == True): # wide", "overlay_imgs(image2, image) pst = get_sdsandbox_json_steer_angle(fdict[key]) pst *= conf.norm_const simst = \"Frame: {}, Actual", "images - should be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask = '*.jpg' #fdict =", "import matplotlib.pyplot as plt nb_bins = 256 count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins)", "-------- \"\"\" #import cv2 #s_img = cv2.imread(\"smaller_image.png\") #l_img = cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0],", "angle stored in json file. The argument passed in the path for a", "ag = Augmentation.Augment_cls(model) # video name video_name = model + '.avi' VIDEO_WIDTH, VIDEO_HEIGHT", "was stored with a corresponding json file containing a steering angle, looks something", "ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 = cv2.imread(ipath) # 120x160x3 plt.rcParams[\"figure.figsize\"] = (6,4) myfig =", "Example -------- \"\"\" import Automold as am # print(\"Adding rain...\") if(st != 0):", "inlaid Example -------- \"\"\" #import cv2 #s_img = cv2.imread(\"smaller_image.png\") #l_img = cv2.imread(\"larger_image.jpg\") #", "cimgs # write to video video.write(image); # increment frame counter fno = fno", "image Returns ------- image_arr: numpy array containing large image with insert of small", "add Info to frame cv2.putText(image, model, (50, 50), font, 1, (255, 255, 255),", "------- myimg: uint8 numpy image array Example ------- import matplotlib.pyplot as plt import", "No plotting max for one off images #ymax = 10000 #plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\")", "be added to green channel bv, integer, value to be added to blue", "= cv2.FONT_HERSHEY_SIMPLEX # frame count fno = 1 try: for key in sorted(fdict):", "l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[ ]: # TODO, need to", "image inlaid Example -------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[42]:", "11fps # font font = cv2.FONT_HERSHEY_SIMPLEX # frame count fno = 1 try:", "fjson = json.loads(file) # get and return steering angle attribute st_angle = fjson['user/angle']", "bv=0): \"\"\" Change RGB values using PIL Parameters ------- img: uint8 numpy image", "written to disk Parameters ------- fdict: collections.OrderedDict, ordered dictionary of file names model:", "count_b, color='b', alpha=0.5) return fig # In[43]: # fpath = fdict[key] def get_sdsandbox_json_steer_angle(fpath):", "array myimg = np.asarray(result) return myimg # subset 100 images - should be", "fpath[0:idx] + fname # open and read file f = open(fname, \"r\") file", "large image x_offset: left padding from large to small overlaid image y_offset: top", "overlay histogram image = overlay_imgs(image2, image) pst = get_sdsandbox_json_steer_angle(fdict[key]) pst *= conf.norm_const simst", "BytesIO from PIL import Image import base64 import numpy as np import matplotlib.pyplot", "steering angle, in the same path, will be named record_12893.json We open that", "= cv2.imread(ipath) # 120x160x3 plt.rcParams[\"figure.figsize\"] = (6,4) myfig = plot_img_hist(img) \"\"\" # from", "RGB values using PIL Parameters ------- img: uint8 numpy image array rv: integer,", "in sys.path: sys.path.append(module_path) import argparse import fnmatch import json import os from io", "IMAGE_HEIGHT = 800, 600 if(preproc == True): # wide angle VIDEO_WIDTH = IMAGE_WIDTH*2", "st_angle = fjson['user/angle'] return st_angle # In[ ]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50):", "0 (first characters before underscore in 0_cam-image_array_.jpg) Parameters ---------- path : string path", "count_b = hist_b[0] # Plot manual bins = hist_r[1] fig = plt.figure() plt.bar(bins[:-1],", "st: range to draw a random slant from Returns ------- image_arr: numpy array", "to video video.write(image); # increment frame counter fno = fno + 1 except", "# In[ ]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy array", "steering angle, looks something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg The json file with with", "characters before underscore in 0_cam-image_array_.jpg) Parameters ---------- path : string path to files", "s_img: numpy array, small image l_img: numpy array, large image x_offset: left padding", "(50, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # histogram on network", "dictionary from unity (SDSandbox) files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the key in example above", "image inlaid Example -------- \"\"\" #import cv2 #s_img = cv2.imread(\"smaller_image.png\") #l_img = cv2.imread(\"larger_image.jpg\")", "0): # draw a random number for slant st = np.random.randint(-1 * st,", "plt.ylabel(\"Pixels\") RGBmean = \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity value distributions (mean = \" + RGBmean", "font = cv2.FONT_HERSHEY_SIMPLEX # frame count fno = 1 try: for key in", "conf.norm_const simst = \"Frame: {}, Actual steering angle: {:.2f}\".format(str(fno), pst) cv2.putText(image, simst, (50,", "plt.yscale('log', nonposy='clip') # set y limit, may need to change # No plotting", "grid plt.grid() # make y scale logarithmic # plt.yscale('log', nonposy='clip') # set y", "for a file, that was stored with a corresponding json file containing a", "b.point(lambda i: i + bv) # Recombine back to RGB image result =", "'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) # overlay image2 = overlay_imgs(image4,", "on network image myfig = plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4 = cv2.imread(\"temp_plot.png\") # save", "Get steering angle stored in json file. The argument passed in the path", "locally defined modules module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import", "string, filepath Returns ------- st_angle: steering angle Example ------- fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa", "mpimg img = mpimg.imread('steph.jpeg') myimg = changeRGB(img, 60, 0, 0) plt.imshow(myimg) \"\"\" from", "= np.zeros(nb_bins) #img = Image.open('16_left-2.jpeg') # Calculate manual hist x = np.array(img) x", "If scheme is rgb, maximum number of values in a bins is expected", "fname # open and read file f = open(fname, \"r\") file = f.read()", "of file names model: string, model name preproc: boolean, show preprocessed image next", "Parameters ---------- path : string path to files mask : string file type", "\")\") # add a grid plt.grid() # make y scale logarithmic # plt.yscale('log',", "= np.random.randint(-1 * st, st) if(rt!='light'): # heavy or torrential image_arr = am.add_rain_single(image_arr,", "range=[0, 255]) count_r = hist_r[0] count_g = hist_g[0] count_b = hist_b[0] # Plot", "115), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # create a preprocessed copy", "string, 'rgb' (default) or , 'yuv-rgb' If scheme is rgb, maximum number of", "count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) #img = Image.open('16_left-2.jpeg') #", "rt: string, rain type \"heavy\" or \"torrential\" st: range to draw a random", "= 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 = cv2.imread(ipath) # 120x160x3 plt.rcParams[\"figure.figsize\"] = (6,4) myfig = plot_img_hist(img)", "# build json file name e.g. record_12893.json fname = 'record_' + fnumber +", "+ gv) # Blue b = b.point(lambda i: i + bv) # Recombine", "(r, g, b)) # Convert to uint8 numpy array myimg = np.asarray(result) return", "Augmentation.Augment_cls(model) # video name video_name = model + '.avi' VIDEO_WIDTH, VIDEO_HEIGHT = 800,", "numpy image array Example ------- import matplotlib.pyplot as plt import matplotlib.image as mpimg", "rgb, maximum number of values in a bins is expected to 3 digit,", "Recombine back to RGB image result = Image.merge('RGB', (r, g, b)) # Convert", "\" + str(e)) cv2.destroyAllWindows() video.release() # subset 100 images - should be quicker", "img: uint8 numpy image array rv: integer, value to be added to red", "label=\"blue (mean = \" + Bmean + \")\") # show labels plt.legend(loc='upper right')", "torrential image_arr = am.add_rain_single(image_arr, rain_type=rt, slant=st) else: # no slant image_arr = am.add_rain_single(image_arr)", "x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[42]: def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram", "what network \"sees\" if (preproc == True): # wide angle image2 = ag.preprocess(image_copy)", "#mask = '*.jpg' filemask = os.path.expanduser(path + mask) path, mask = os.path.split(filemask) fdict", "= parser.parse_args() #fdict = sort_unity_files(args.filepath, args.mask) #make_video(fdict, model, True) # saved as nvidia2.avi", "to uint8 numpy array myimg = np.asarray(result) return myimg # subset 100 images", "in a bins is expected to 3 digit, otherwise 6 digits and y-axys", "open(fname, \"r\") file = f.read() # load json fjson = json.loads(file) # get", "integer, value to be added to green channel bv, integer, value to be", "= \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r, color='r', alpha=0.5, label=\"red (mean = \" + Rmean +", "= fsplit[-1] # get number e.g. 12893 fnumber = fsplit[-1].split('_') fnumber = fnumber[0]", "import numpy as np import matplotlib.pyplot as plt import Augment_cls as Augmentation import", "string fsplit = fpath.split('\\\\') # get name e.g. 12893_cam-image_array_.jpg fname = fsplit[-1] #", "to small overlaid image Returns ------- image_arr: numpy array containing large image with", "file containing a steering angle, looks something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg The json", "with insert of small image inlaid Example -------- \"\"\" #import cv2 #s_img =", "0) plt.imshow(myimg) \"\"\" from PIL import Image import numpy as np im =", "= 10000 #plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return fig # change rgb values #", "import Automold as am # print(\"Adding rain...\") if(st != 0): # draw a", "sort_unity_files(path, mask) for key in sorted(fdict): print(\"key: {}, value:{}\".format(key,fdict[key])) Note ------- File path", "= cv2.VideoWriter(video_name, 0, 11, (VIDEO_WIDTH, VIDEO_HEIGHT)) # assumed 11fps # font font =", "this from existing module def add_rain(image_arr, rt=None, st=0): \"\"\" Add rain to image", "\"r\") file = f.read() # load json fjson = json.loads(file) # get and", "PIL import Image import numpy as np import matplotlib.pyplot as plt nb_bins =", "two numpy array images Parameters ---------- s_img: numpy array, small image l_img: numpy", "network \"sees\" if (preproc == True): # wide angle image2 = ag.preprocess(image_copy) image2", "+ \")\") Gmean = \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g, color='g', alpha=0.45, label=\"green (mean = \"", "record_12893.json fname = 'record_' + fnumber + '.json' # build file path e.g.", "plt import Augment_cls as Augmentation import cv2 import conf # instantiate augmentation class", "l_img # In[ ]: # TODO, need to bring this from existing module", "------- image_arr: numpy array containing large image with insert of small image inlaid", "fname = fpath[0:idx] + fname # open and read file f = open(fname,", "some info onto image image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) # add Info", "= hist_b[0] # Plot manual bins = hist_r[1] fig = plt.figure() # figure()", "fpath = fdict[key] def get_sdsandbox_json_steer_angle(fpath): \"\"\" Get steering angle stored in json file.", "1, (255, 255, 255), 2, cv2.LINE_AA) # histogram on network image myfig =", "= \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b, color='b', alpha=0.4, label=\"blue (mean = \" + Bmean +", "rv) # Green g = g.point(lambda i: i + gv) # Blue b", "mask): \"\"\" Create a sorted dictionary from unity (SDSandbox) files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where", "numpy as np import matplotlib.pyplot as plt nb_bins = 256 count_r = np.zeros(nb_bins)", "12893 fnumber = fsplit[-1].split('_') fnumber = fnumber[0] # build json file name e.g.", "if (preproc == True): # wide angle cimgs = np.concatenate((image, image2), axis=1) image", "import numpy as np import matplotlib.pyplot as plt ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 =", "e: print(\"Exception raise: \" + str(e)) cv2.destroyAllWindows() video.release() # subset 100 images -", "= 'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi if __name__ == \"__main__\":", "am # print(\"Adding rain...\") if(st != 0): # draw a random number for", "= '*.jpg' #fdict = sort_unity_files(path, mask) #model = 'nvidia2' #make_video(fdict, model, True) #", "True) # saved as nvidia2.avi #make_video(args.filepath, args.model, True) # example # python utils.py", "bv, integer, value to be added to blue channel Output ------- myimg: uint8", "img: numpy array scheme: string, 'rgb' (default) or , 'yuv-rgb' If scheme is", "wide angle cimgs = np.concatenate((image, image2), axis=1) image = cimgs # write to", "in your for loop to sort the output of this sort_unity_files().\") return fdict", "+ Rmean + \")\") Gmean = \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g, color='g', alpha=0.45, label=\"green (mean", "boolean, show preprocessed image next to original Returns none Example ------- path =", "from PIL import Image import numpy as np import matplotlib.pyplot as plt nb_bins", "this sort_unity_files().\") return fdict # In[41]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay", "image_arr: numpy array containing image with rain Example -------- \"\"\" import Automold as", "path : string path to files mask : string file type Returns -------", "hist_g = np.histogram(x[1], bins=nb_bins, range=[0, 255]) hist_b = np.histogram(x[2], bins=nb_bins, range=[0, 255]) count_r", "save plt.close(myfig) image_copy = image # resize so we can write some info", "print(\"Use sorted() function in your for loop to sort the output of this", "---------- path : string path to files mask : string file type Returns", "= np.histogram(x[1], bins=nb_bins, range=[0, 255]) hist_b = np.histogram(x[2], bins=nb_bins, range=[0, 255]) count_r =", "np.concatenate((image, image2), axis=1) image = cimgs # write to video video.write(image); # increment", "'nvidia2' make_video(fdict, model, True) # saved as nvidia2.avi \"\"\" import os import sys", "= get_sdsandbox_json_steer_angle(fdict[key]) pst *= conf.norm_const simst = \"Frame: {}, Actual steering angle: {:.2f}\".format(str(fno),", "digits and y-axys is plotted on log scale. Returns ------- fig: matplotlib.pyplot figure", "if(preproc == True): # wide angle VIDEO_WIDTH = IMAGE_WIDTH*2 video = cv2.VideoWriter(video_name, 0,", "add_rain(image_arr, rt=None, st=0): \"\"\" Add rain to image Parameters ---------- image_arr: numpy array", "(IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) # add Info to frame cv2.putText(image, model, (50, 50), font,", "for loop to sort the output of this sort_unity_files().\") return fdict # In[41]:", "------- img: numpy array scheme: string, 'rgb' (default) or , 'yuv-rgb' If scheme", "\")\") Bmean = \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b, color='b', alpha=0.4, label=\"blue (mean = \" +", "name e.g. 12893_cam-image_array_.jpg fname = fsplit[-1] # get number e.g. 12893 fnumber =", "model, True) # saved as nvidia2.avi if __name__ == \"__main__\": import argparse parser", "fdict = sort_unity_files(path, mask) for key in sorted(fdict): print(\"key: {}, value:{}\".format(key,fdict[key])) Note -------", "\"heavy\" or \"torrential\" st: range to draw a random slant from Returns -------", "append local path so we can make use # of locally defined modules", "= fdict[key] def get_sdsandbox_json_steer_angle(fpath): \"\"\" Get steering angle stored in json file. The", "\"\"\" Change RGB values using PIL Parameters ------- img: uint8 numpy image array", "Returns ------- fdict: dictionary Sorted dictionary containing key and file path Example -------", "# Split into 3 channels r, g, b = im.split() # Red r", "path Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask)", "plt.imshow(myimg) \"\"\" from PIL import Image import numpy as np im = Image.fromarray(np.uint8(img))", "script') parser.add_argument('--filepath', type=str, help='tcpflow log') parser.add_argument('--model', type=str, help='model name for video label') parser.add_argument('--mask',", "= open(fname, \"r\") file = f.read() # load json fjson = json.loads(file) #", "# video name video_name = model + '.avi' VIDEO_WIDTH, VIDEO_HEIGHT = 800, 600", "containing large image with insert of small image inlaid Example -------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0],", "# increment frame counter fno = fno + 1 except Exception as e:", "0, 11, (VIDEO_WIDTH, VIDEO_HEIGHT)) # assumed 11fps # font font = cv2.FONT_HERSHEY_SIMPLEX #", "= \" + RGBmean + \")\") # add a grid plt.grid() # make", "# saved as nvidia2.avi if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description='Make", "nvidia2.avi if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description='Make Video script') parser.add_argument('--filepath',", "image rt: string, rain type \"heavy\" or \"torrential\" st: range to draw a", "x_offset: left padding from large to small overlaid image y_offset: top padding from", "sorted(fdict): image = cv2.imread(fdict[key]) # 120x160x3 # get histogram myfig = plot_img_hist(image, 'rgb')", "------- fpath: string, filepath Returns ------- st_angle: steering angle Example ------- fpath =", "'*.jpg' #fdict = sort_unity_files(path, mask) #model = 'nvidia2' #make_video(fdict, model, True) # saved", "# https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL import Image import numpy as np import matplotlib.pyplot as", "number e.g. 12893 fnumber = fsplit[-1].split('_') fnumber = fnumber[0] # build json file", "fpath: string, filepath Returns ------- st_angle: steering angle Example ------- fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg'", "fig = plt.figure() # figure() #plt.yscale('log') Rmean = \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r, color='r', alpha=0.5,", "10000 #plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return fig # change rgb values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil", "fpath.rindex('\\\\') + 1 fname = fpath[0:idx] + fname # open and read file", "help='model name for video label') parser.add_argument('--mask', type=str, help='image file suffix') args = parser.parse_args()", "frame counter fno = fno + 1 except Exception as e: print(\"Exception raise:", "module_path not in sys.path: sys.path.append(module_path) import argparse import fnmatch import json import os", "from PIL import Image import base64 import numpy as np import matplotlib.pyplot as", "# coding: utf-8 # In[40]: def sort_unity_files(path, mask): \"\"\" Create a sorted dictionary", "Blue b = b.point(lambda i: i + bv) # Recombine back to RGB", "OrderedDict #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask = '*.jpg' filemask = os.path.expanduser(path + mask) path,", "= fpath.split('\\\\') # get name e.g. 12893_cam-image_array_.jpg fname = fsplit[-1] # get number", "= '*.jpg' filemask = os.path.expanduser(path + mask) path, mask = os.path.split(filemask) fdict =", "image_arr = am.add_rain_single(image_arr) return image_arr # In[52]: def make_video(fdict, model, preproc=False): \"\"\" Make", "= os.path.expanduser(path + mask) path, mask = os.path.split(filemask) fdict = OrderedDict() matches =", "otherwise 6 digits and y-axys is plotted on log scale. Returns ------- fig:", "0_cam-image_array_.jpg) Parameters ---------- path : string path to files mask : string file", "bring this from existing module def add_rain(image_arr, rt=None, st=0): \"\"\" Add rain to", "Calculate manual hist x = np.array(img) x = x.transpose(2, 0, 1) hist_r =", "cv2.VideoWriter(video_name, 0, 11, (VIDEO_WIDTH, VIDEO_HEIGHT)) # assumed 11fps # font font = cv2.FONT_HERSHEY_SIMPLEX", "added to green channel bv, integer, value to be added to blue channel", "# wide angle cimgs = np.concatenate((image, image2), axis=1) image = cimgs # write", "cv2.LINE_AA) # create a preprocessed copy to compare what simulator generates to what", "pst *= conf.norm_const simst = \"Frame: {}, Actual steering angle: {:.2f}\".format(str(fno), pst) cv2.putText(image,", "cv2.imread(fdict[key]) # 120x160x3 # get histogram myfig = plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\") image2 =", "(SDSandbox) files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the key in example above is 0 (first", "need to bring this from existing module def add_rain(image_arr, rt=None, st=0): \"\"\" Add", "------- import cv2 import numpy as np import matplotlib.pyplot as plt ipath =", "fname = fsplit[-1] # get number e.g. 12893 fnumber = fsplit[-1].split('_') fnumber =", "---------- image_arr: numpy array containing image rt: string, rain type \"heavy\" or \"torrential\"", "alpha=0.5, label=\"red (mean = \" + Rmean + \")\") Gmean = \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1],", "with steering angle, in the same path, will be named record_12893.json We open", "# instantiate augmentation class ag = Augmentation.Augment_cls(model) # video name video_name = model", "0, 1) hist_r = np.histogram(x[0], bins=nb_bins, range=[0, 255]) hist_g = np.histogram(x[1], bins=nb_bins, range=[0,", "#plt.yscale('log') Rmean = \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r, color='r', alpha=0.5, label=\"red (mean = \" +", "get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\" import json # split string fsplit = fpath.split('\\\\') # get", "overlaid image y_offset: top padding from large to small overlaid image Returns -------", "for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])] =", "= (6,4) myfig = plot_img_hist(img) \"\"\" # from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL", "\"Frame: {}, Actual steering angle: {:.2f}\".format(str(fno), pst) cv2.putText(image, simst, (50, 115), font, 1,", "# append local path so we can make use # of locally defined", "path so we can make use # of locally defined modules module_path =", "plotted on log scale. Returns ------- fig: matplotlib.pyplot figure Example ------- import cv2", "video.release() # subset 100 images - should be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask", "+ fname # open and read file f = open(fname, \"r\") file =", "video = cv2.VideoWriter(video_name, 0, 11, (VIDEO_WIDTH, VIDEO_HEIGHT)) # assumed 11fps # font font", "image = cimgs # write to video video.write(image); # increment frame counter fno", "In[40]: def sort_unity_files(path, mask): \"\"\" Create a sorted dictionary from unity (SDSandbox) files", "to disk Parameters ------- fdict: collections.OrderedDict, ordered dictionary of file names model: string,", "limit, may need to change # No plotting max for one off images", "record_12893.json We open that file and return the steering angle. Parameters ------- fpath:", "return l_img # In[42]: def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an rgb", "rgb array Parameters ------- img: numpy array scheme: string, 'rgb' (default) or ,", "= cv2.imread(fdict[key]) # 120x160x3 # get histogram myfig = plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\") image2", "import fnmatch import json import os from io import BytesIO from PIL import", "fdict # In[41]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy array", "# save plt.close(myfig) image_copy = image # resize so we can write some", "= plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\") image2 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) image_copy = image", "\"\"\" # from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL import Image import numpy as", "model = 'nvidia2' make_video(fdict, model, True) # saved as nvidia2.avi \"\"\" import os", "fnumber + '.json' # build file path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx = fpath.rindex('\\\\') +", "sys.path.append(module_path) import argparse import fnmatch import json import os from io import BytesIO", "= hist_r[1] fig = plt.figure() # figure() #plt.yscale('log') Rmean = \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r,", "myimg = changeRGB(img, 60, 0, 0) plt.imshow(myimg) \"\"\" from PIL import Image import", "argument passed in the path for a file, that was stored with a", "by sorted to order files in the right order. \"\"\" import fnmatch import", "string, model name preproc: boolean, show preprocessed image next to original Returns none", "'*.jpg' fdict = sort_unity_files(path, mask) for key in sorted(fdict): print(\"key: {}, value:{}\".format(key,fdict[key])) Note", "cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) # add Info to frame cv2.putText(image, model, (50, 50),", "file name e.g. record_12893.json fname = 'record_' + fnumber + '.json' # build", "must by sorted to order files in the right order. \"\"\" import fnmatch", "as nvidia2.avi def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an rgb array Parameters", "function in your for loop to sort the output of this sort_unity_files().\") return", "import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('steph.jpeg') myimg =", "preprocessed copy to compare what simulator generates to what network \"sees\" if (preproc", "histogram on network image myfig = plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4 = cv2.imread(\"temp_plot.png\") #", "am.add_rain_single(image_arr, rain_type=rt, slant=st) else: # no slant image_arr = am.add_rain_single(image_arr) return image_arr #", "changeRGB(img, rv=0, gv=0, bv=0): \"\"\" Change RGB values using PIL Parameters ------- img:", "to order files in the right order. \"\"\" import fnmatch import os from", "Augment_cls as Augmentation import cv2 import conf # instantiate augmentation class ag =", "- should be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask = '*.jpg' #fdict = sort_unity_files(path,", "matplotlib.pyplot as plt ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 = cv2.imread(ipath) # 120x160x3 plt.rcParams[\"figure.figsize\"] =", "x.transpose(2, 0, 1) hist_r = np.histogram(x[0], bins=nb_bins, range=[0, 255]) hist_g = np.histogram(x[1], bins=nb_bins,", "wide angle image2 = ag.preprocess(image_copy) image2 = cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2, 'Network", "image Parameters ---------- image_arr: numpy array containing image rt: string, rain type \"heavy\"", "rain...\") if(st != 0): # draw a random number for slant st =", "name for video label') parser.add_argument('--mask', type=str, help='image file suffix') args = parser.parse_args() #fdict", "plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\") image2 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) image_copy = image #", "(255, 255, 255), 2, cv2.LINE_AA) # histogram on network image myfig = plot_img_hist(image,", "image array Example ------- import matplotlib.pyplot as plt import matplotlib.image as mpimg img", "be named record_12893.json We open that file and return the steering angle. Parameters", "mask : string file type Returns ------- fdict: dictionary Sorted dictionary containing key", "nvidia2.avi \"\"\" import os import sys # append local path so we can", "model, (50, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # overlay histogram", "args = parser.parse_args() #fdict = sort_unity_files(args.filepath, args.mask) #make_video(fdict, model, True) # saved as", "Green g = g.point(lambda i: i + gv) # Blue b = b.point(lambda", "args.model, True) # example # python utils.py --filepath=C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\ \\ # --model=nvidia2 --mask=*.jpg #", "We open that file and return the steering angle. Parameters ------- fpath: string,", "array containing image rt: string, rain type \"heavy\" or \"torrential\" st: range to", "maximum number of values in a bins is expected to 3 digit, otherwise", "'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx = fpath.rindex('\\\\') + 1 fname = fpath[0:idx] + fname # open", "= '*.jpg' fdict = sort_unity_files(path, mask) for key in sorted(fdict): print(\"key: {}, value:{}\".format(key,fdict[key]))", "json.loads(file) # get and return steering angle attribute st_angle = fjson['user/angle'] return st_angle", "to 3 digit, otherwise 6 digits and y-axys is plotted on log scale.", "array containing image with rain Example -------- \"\"\" import Automold as am #", "count fno = 1 try: for key in sorted(fdict): image = cv2.imread(fdict[key]) #", "values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def changeRGB(img, rv=0, gv=0, bv=0): \"\"\" Change RGB values using", "angle: {:.2f}\".format(str(fno), pst) cv2.putText(image, simst, (50, 115), font, 1, (255, 255, 255), 2,", "ag.preprocess(image_copy) image2 = cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2, 'Network Image', (50, 50), font,", "random number for slant st = np.random.randint(-1 * st, st) if(rt!='light'): # heavy", "named record_12893.json We open that file and return the steering angle. Parameters -------", "255, 255), 2, cv2.LINE_AA) # histogram on network image myfig = plot_img_hist(image, 'yuv-rgb')", "a grid plt.grid() # make y scale logarithmic # plt.yscale('log', nonposy='clip') # set", "for video label') parser.add_argument('--mask', type=str, help='image file suffix') args = parser.parse_args() #fdict =", "# In[41]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy array images", "= [] for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, mask):", "color='b', alpha=0.4, label=\"blue (mean = \" + Bmean + \")\") # show labels", "steering angle stored in json file. The argument passed in the path for", "as plt import matplotlib.image as mpimg img = mpimg.imread('steph.jpeg') myimg = changeRGB(img, 60,", "in 0_cam-image_array_.jpg) Parameters ---------- path : string path to files mask : string", "scheme is rgb, maximum number of values in a bins is expected to", "------- st_angle: steering angle Example ------- fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa = get_sdsandbox_json_steer_angle(fpath) print(jsa)", "plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255, step=25)) plt.ylabel(\"Pixels\") RGBmean = \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity value distributions (mean", "#make_video(fdict, model, True) # saved as nvidia2.avi def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram", "into 3 channels r, g, b = im.split() # Red r = r.point(lambda", "fno + 1 except Exception as e: print(\"Exception raise: \" + str(e)) cv2.destroyAllWindows()", "-------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[42]: def plot_img_hist(img, scheme='rgb'):", "overlay image2 = overlay_imgs(image4, image2) # concatenate if (preproc == True): # wide", "(mean = \" + Gmean + \")\") Bmean = \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b, color='b',", "filename) print(\"Use sorted() function in your for loop to sort the output of", "figure Example ------- import cv2 import numpy as np import matplotlib.pyplot as plt", "= np.asarray(result) return myimg # subset 100 images - should be quicker #path", "name video_name = model + '.avi' VIDEO_WIDTH, VIDEO_HEIGHT = 800, 600 IMAGE_WIDTH, IMAGE_HEIGHT", "# wide angle image2 = ag.preprocess(image_copy) image2 = cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2,", "sort_unity_files(path, mask) #model = 'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi def", "sys # append local path so we can make use # of locally", "------- File path format is OS dependant. OrderedDict must by sorted to order", "\"\"\" import json # split string fsplit = fpath.split('\\\\') # get name e.g.", "large image with insert of small image inlaid Example -------- \"\"\" #import cv2", "parser.add_argument('--filepath', type=str, help='tcpflow log') parser.add_argument('--model', type=str, help='model name for video label') parser.add_argument('--mask', type=str,", "b = b.point(lambda i: i + bv) # Recombine back to RGB image", "True) # saved as nvidia2.avi def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an", "get histogram myfig = plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\") image2 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig)", "# open and read file f = open(fname, \"r\") file = f.read() #", "numpy array images Parameters ---------- s_img: numpy array, small image l_img: numpy array,", "cv2.imread(\"temp_plot.png\") # save plt.close(myfig) image_copy = image # resize so we can write", "for key in sorted(fdict): print(\"key: {}, value:{}\".format(key,fdict[key])) Note ------- File path format is", "(6,4) myfig = plot_img_hist(img) \"\"\" # from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL import", "parser.add_argument('--mask', type=str, help='image file suffix') args = parser.parse_args() #fdict = sort_unity_files(args.filepath, args.mask) #make_video(fdict,", "from collections import OrderedDict #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask = '*.jpg' filemask = os.path.expanduser(path", "The argument passed in the path for a file, that was stored with", "increment frame counter fno = fno + 1 except Exception as e: print(\"Exception", "the same path, will be named record_12893.json We open that file and return", "cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[ ]: #", "expected to 3 digit, otherwise 6 digits and y-axys is plotted on log", "step=25)) plt.ylabel(\"Pixels\") RGBmean = \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity value distributions (mean = \" +", "'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask) for key in sorted(fdict): print(\"key:", "sorted to order files in the right order. \"\"\" import fnmatch import os", "myimg # subset 100 images - should be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask", "y-axys is plotted on log scale. Returns ------- fig: matplotlib.pyplot figure Example -------", "return image_arr # In[52]: def make_video(fdict, model, preproc=False): \"\"\" Make video from image", "'*.jpg' filemask = os.path.expanduser(path + mask) path, mask = os.path.split(filemask) fdict = OrderedDict()", "range=[0, 255]) hist_b = np.histogram(x[2], bins=nb_bins, range=[0, 255]) count_r = hist_r[0] count_g =", "dictionary of file names model: string, model name preproc: boolean, show preprocessed image", "import sys # append local path so we can make use # of", "Image', (50, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # histogram on", "file path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx = fpath.rindex('\\\\') + 1 fname = fpath[0:idx] +", "image next to original Returns none Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask =", "]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy array images Parameters", "fdict[key] def get_sdsandbox_json_steer_angle(fpath): \"\"\" Get steering angle stored in json file. The argument", "------- fdict: collections.OrderedDict, ordered dictionary of file names model: string, model name preproc:", "cv2.imread(\"smaller_image.png\") #l_img = cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img #", "preprocessed image next to original Returns none Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask", "be added to red channel gv: integer, value to be added to green", "underscore in 0_cam-image_array_.jpg) Parameters ---------- path : string path to files mask :", "matplotlib.image as mpimg img = mpimg.imread('steph.jpeg') myimg = changeRGB(img, 60, 0, 0) plt.imshow(myimg)", "generates to what network \"sees\" if (preproc == True): # wide angle image2", "return steering angle attribute st_angle = fjson['user/angle'] return st_angle # In[ ]: def", "numpy array, small image l_img: numpy array, large image x_offset: left padding from", "fsplit = fpath.split('\\\\') # get name e.g. 12893_cam-image_array_.jpg fname = fsplit[-1] # get", "output of this sort_unity_files().\") return fdict # In[41]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50):", "as am # print(\"Adding rain...\") if(st != 0): # draw a random number", "random slant from Returns ------- image_arr: numpy array containing image with rain Example", "# TODO, need to bring this from existing module def add_rain(image_arr, rt=None, st=0):", "plt ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 = cv2.imread(ipath) # 120x160x3 plt.rcParams[\"figure.figsize\"] = (6,4) myfig", "or \"torrential\" st: range to draw a random slant from Returns ------- image_arr:", "str(e)) cv2.destroyAllWindows() video.release() # subset 100 images - should be quicker #path =", "type=str, help='tcpflow log') parser.add_argument('--model', type=str, help='model name for video label') parser.add_argument('--mask', type=str, help='image", "print(\"Adding rain...\") if(st != 0): # draw a random number for slant st", "and file path Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict =", "os.path.expanduser(path + mask) path, mask = os.path.split(filemask) fdict = OrderedDict() matches = []", "slant from Returns ------- image_arr: numpy array containing image with rain Example --------", "am.add_rain_single(image_arr) return image_arr # In[52]: def make_video(fdict, model, preproc=False): \"\"\" Make video from", "path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask) model = 'nvidia2'", "50), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # histogram on network image", "Image.merge('RGB', (r, g, b)) # Convert to uint8 numpy array myimg = np.asarray(result)", "from large to small overlaid image Returns ------- image_arr: numpy array containing large", "base64 import numpy as np import matplotlib.pyplot as plt import Augment_cls as Augmentation", "path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx = fpath.rindex('\\\\') + 1 fname = fpath[0:idx] + fname", "count_r, color='r', alpha=0.5) plt.bar(bins[:-1], count_g, color='g', alpha=0.5) plt.bar(bins[:-1], count_b, color='b', alpha=0.5) return fig", "= os.path.join(root, filename) print(\"Use sorted() function in your for loop to sort the", "hist_r[1] fig = plt.figure() plt.bar(bins[:-1], count_r, color='r', alpha=0.5) plt.bar(bins[:-1], count_g, color='g', alpha=0.5) plt.bar(bins[:-1],", "channel Output ------- myimg: uint8 numpy image array Example ------- import matplotlib.pyplot as", "image with rain Example -------- \"\"\" import Automold as am # print(\"Adding rain...\")", "figure() #plt.yscale('log') Rmean = \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r, color='r', alpha=0.5, label=\"red (mean = \"", "= np.array(img) x = x.transpose(2, 0, 1) hist_r = np.histogram(x[0], bins=nb_bins, range=[0, 255])", "# figure() #plt.yscale('log') Rmean = \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r, color='r', alpha=0.5, label=\"red (mean =", "a bins is expected to 3 digit, otherwise 6 digits and y-axys is", "import os import sys # append local path so we can make use", "e.g. record_12893.json fname = 'record_' + fnumber + '.json' # build file path", "of locally defined modules module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path)", "600 IMAGE_WIDTH, IMAGE_HEIGHT = 800, 600 if(preproc == True): # wide angle VIDEO_WIDTH", "dependant. OrderedDict must by sorted to order files in the right order. \"\"\"", "hist x = np.array(img) x = x.transpose(2, 0, 1) hist_r = np.histogram(x[0], bins=nb_bins,", "------- import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('steph.jpeg') myimg", "g, b)) # Convert to uint8 numpy array myimg = np.asarray(result) return myimg", "jsa = get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\" import json # split string fsplit = fpath.split('\\\\')", "inlaid Example -------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[42]: def", "count_g = hist_g[0] count_b = hist_b[0] # Plot manual bins = hist_r[1] fig", "# from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL import Image import numpy as np", "myfig = plot_img_hist(img) \"\"\" # from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 # https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ from PIL import Image", "plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an rgb array Parameters ------- img: numpy", "file with with steering angle, in the same path, will be named record_12893.json", "histogram myfig = plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\") image2 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) image_copy", "except Exception as e: print(\"Exception raise: \" + str(e)) cv2.destroyAllWindows() video.release() # subset", "cv2.imread(ipath) # 120x160x3 plt.rcParams[\"figure.figsize\"] = (6,4) myfig = plot_img_hist(img) \"\"\" # from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600", "steering angle attribute st_angle = fjson['user/angle'] return st_angle # In[ ]: def overlay_imgs(s_img,", "# make y scale logarithmic # plt.yscale('log', nonposy='clip') # set y limit, may", "key in example above is 0 (first characters before underscore in 0_cam-image_array_.jpg) Parameters", "# of locally defined modules module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path:", "= \" + Bmean + \")\") # show labels plt.legend(loc='upper right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0,", "Output ------- myimg: uint8 numpy image array Example ------- import matplotlib.pyplot as plt", "True): # wide angle cimgs = np.concatenate((image, image2), axis=1) image = cimgs #", "50), font, 1, (255, 255, 255), 2, cv2.LINE_AA) # overlay histogram image =", "of this sort_unity_files().\") return fdict # In[41]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\"", "np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) #img = Image.open('16_left-2.jpeg') # Calculate manual", "# no slant image_arr = am.add_rain_single(image_arr) return image_arr # In[52]: def make_video(fdict, model,", "IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2, 'Network Image', (50, 50), font, 1, (255, 255, 255), 2,", "a random slant from Returns ------- image_arr: numpy array containing image with rain", "\"\"\" Plot histogram for an rgb array Parameters ------- img: numpy array scheme:", "# print(\"Adding rain...\") if(st != 0): # draw a random number for slant", "sys.path: sys.path.append(module_path) import argparse import fnmatch import json import os from io import", "# In[ ]: # TODO, need to bring this from existing module def", "a steering angle, looks something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg The json file with", "import OrderedDict #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask = '*.jpg' filemask = os.path.expanduser(path + mask)", "1, (255, 255, 255), 2, cv2.LINE_AA) # overlay histogram image = overlay_imgs(image2, image)", "subset 100 images - should be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask = '*.jpg'", "file, that was stored with a corresponding json file containing a steering angle,", "Parameters ------- img: numpy array scheme: string, 'rgb' (default) or , 'yuv-rgb' If", "image = overlay_imgs(image2, image) pst = get_sdsandbox_json_steer_angle(fdict[key]) pst *= conf.norm_const simst = \"Frame:", "\"\"\" import Automold as am # print(\"Adding rain...\") if(st != 0): # draw", "angle, in the same path, will be named record_12893.json We open that file", "#make_video(args.filepath, args.model, True) # example # python utils.py --filepath=C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\ \\ # --model=nvidia2 --mask=*.jpg", "file = f.read() # load json fjson = json.loads(file) # get and return", "array scheme: string, 'rgb' (default) or , 'yuv-rgb' If scheme is rgb, maximum", "image = cv2.imread(fdict[key]) # 120x160x3 # get histogram myfig = plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\")", "mask = '*.jpg' fdict = sort_unity_files(path, mask) for key in sorted(fdict): print(\"key: {},", "and y-axys is plotted on log scale. Returns ------- fig: matplotlib.pyplot figure Example", "\"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r, color='r', alpha=0.5, label=\"red (mean = \" + Rmean + \")\")", "stored in json file. The argument passed in the path for a file,", "python # coding: utf-8 # In[40]: def sort_unity_files(path, mask): \"\"\" Create a sorted", "as np import matplotlib.pyplot as plt ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 = cv2.imread(ipath) #", "type=str, help='model name for video label') parser.add_argument('--mask', type=str, help='image file suffix') args =", "of small image inlaid Example -------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img", "json file name e.g. record_12893.json fname = 'record_' + fnumber + '.json' #", "no slant image_arr = am.add_rain_single(image_arr) return image_arr # In[52]: def make_video(fdict, model, preproc=False):", "'rgb') myfig.savefig(\"temp_plot.png\") image2 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) image_copy = image # resize", "before underscore in 0_cam-image_array_.jpg) Parameters ---------- path : string path to files mask", "(IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2, 'Network Image', (50, 50), font, 1, (255, 255, 255),", "Parameters ------- img: uint8 numpy image array rv: integer, value to be added", "st, st) if(rt!='light'): # heavy or torrential image_arr = am.add_rain_single(image_arr, rain_type=rt, slant=st) else:", "return myimg # subset 100 images - should be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\'", "uint8 numpy image array Example ------- import matplotlib.pyplot as plt import matplotlib.image as", "is rgb, maximum number of values in a bins is expected to 3", "+ rv) # Green g = g.point(lambda i: i + gv) # Blue", "import numpy as np import matplotlib.pyplot as plt nb_bins = 256 count_r =", "f = open(fname, \"r\") file = f.read() # load json fjson = json.loads(file)", "= 800, 600 IMAGE_WIDTH, IMAGE_HEIGHT = 800, 600 if(preproc == True): # wide", "255), 2, cv2.LINE_AA) # histogram on network image myfig = plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\")", "build json file name e.g. record_12893.json fname = 'record_' + fnumber + '.json'", "quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask = '*.jpg' #fdict = sort_unity_files(path, mask) #model =", "with insert of small image inlaid Example -------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img", "'*.jpg' fdict = sort_unity_files(path, mask) model = 'nvidia2' make_video(fdict, model, True) # saved", "array rv: integer, value to be added to red channel gv: integer, value", "to be added to green channel bv, integer, value to be added to", "collections import OrderedDict #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask = '*.jpg' filemask = os.path.expanduser(path +", "plt.figure() # figure() #plt.yscale('log') Rmean = \"{:.2f}\".format(np.mean(x[0])) plt.bar(bins[:-1], count_r, color='r', alpha=0.5, label=\"red (mean", "Gmean = \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g, color='g', alpha=0.45, label=\"green (mean = \" + Gmean", "if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description='Make Video script') parser.add_argument('--filepath', type=str,", "path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask) for key in", "0, 0) plt.imshow(myimg) \"\"\" from PIL import Image import numpy as np im", "value distributions (mean = \" + RGBmean + \")\") # add a grid", "import os from io import BytesIO from PIL import Image import base64 import", "rain to image Parameters ---------- image_arr: numpy array containing image rt: string, rain", "model, True) # saved as nvidia2.avi #make_video(args.filepath, args.model, True) # example # python", "myfig = plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) # overlay", "+ \")\") Bmean = \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b, color='b', alpha=0.4, label=\"blue (mean = \"", "sort_unity_files().\") return fdict # In[41]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two", "coding: utf-8 # In[40]: def sort_unity_files(path, mask): \"\"\" Create a sorted dictionary from", "get number e.g. 12893 fnumber = fsplit[-1].split('_') fnumber = fnumber[0] # build json", "and read file f = open(fname, \"r\") file = f.read() # load json", "root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])] = os.path.join(root,", "as Augmentation import cv2 import conf # instantiate augmentation class ag = Augmentation.Augment_cls(model)", "# histogram on network image myfig = plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4 = cv2.imread(\"temp_plot.png\")", "+ Bmean + \")\") # show labels plt.legend(loc='upper right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255, step=25))", "Parameters ---------- s_img: numpy array, small image l_img: numpy array, large image x_offset:", "= 800, 600 if(preproc == True): # wide angle VIDEO_WIDTH = IMAGE_WIDTH*2 video", "images Parameters ---------- s_img: numpy array, small image l_img: numpy array, large image", "60, 0, 0) plt.imshow(myimg) \"\"\" from PIL import Image import numpy as np", "file path Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path,", "# resize so we can write some info onto image image = cv2.resize(image,", "# create a preprocessed copy to compare what simulator generates to what network", "image # resize so we can write some info onto image image =", "containing a steering angle, looks something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg The json file", "frame cv2.putText(image, model, (50, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA) #", "#img = Image.open('16_left-2.jpeg') # Calculate manual hist x = np.array(img) x = x.transpose(2,", "channels r, g, b = im.split() # Red r = r.point(lambda i: i", "labels plt.legend(loc='upper right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255, step=25)) plt.ylabel(\"Pixels\") RGBmean = \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity", "+ fnumber + '.json' # build file path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx = fpath.rindex('\\\\')", "key and file path Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict", "+ \")\") # add a grid plt.grid() # make y scale logarithmic #", "may need to change # No plotting max for one off images #ymax", "get_sdsandbox_json_steer_angle(fdict[key]) pst *= conf.norm_const simst = \"Frame: {}, Actual steering angle: {:.2f}\".format(str(fno), pst)", "argparse.ArgumentParser(description='Make Video script') parser.add_argument('--filepath', type=str, help='tcpflow log') parser.add_argument('--model', type=str, help='model name for video", "e.g. 12893 fnumber = fsplit[-1].split('_') fnumber = fnumber[0] # build json file name", "= cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2, 'Network Image', (50, 50), font, 1, (255,", "Convert to uint8 numpy array myimg = np.asarray(result) return myimg # subset 100", "as plt import Augment_cls as Augmentation import cv2 import conf # instantiate augmentation", "]: # TODO, need to bring this from existing module def add_rain(image_arr, rt=None,", "import Image import numpy as np im = Image.fromarray(np.uint8(img)) # Split into 3", "string file type Returns ------- fdict: dictionary Sorted dictionary containing key and file", "np.random.randint(-1 * st, st) if(rt!='light'): # heavy or torrential image_arr = am.add_rain_single(image_arr, rain_type=rt,", "C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the key in example above is 0 (first characters before underscore", "model, True) # saved as nvidia2.avi \"\"\" import os import sys # append", "model: string, model name preproc: boolean, show preprocessed image next to original Returns", "label=\"red (mean = \" + Rmean + \")\") Gmean = \"{:.2f}\".format(np.mean(x[1])) plt.bar(bins[:-1], count_g,", "+ str(e)) cv2.destroyAllWindows() video.release() # subset 100 images - should be quicker #path", "# add a grid plt.grid() # make y scale logarithmic # plt.yscale('log', nonposy='clip')", "fnumber = fsplit[-1].split('_') fnumber = fnumber[0] # build json file name e.g. record_12893.json", "to change # No plotting max for one off images #ymax = 10000", "i: i + gv) # Blue b = b.point(lambda i: i + bv)", "myfig.savefig(\"temp_plot.png\") image4 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) # overlay image2 = overlay_imgs(image4, image2)", "VIDEO_WIDTH = IMAGE_WIDTH*2 video = cv2.VideoWriter(video_name, 0, 11, (VIDEO_WIDTH, VIDEO_HEIGHT)) # assumed 11fps", "plt.legend(loc='upper right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255, step=25)) plt.ylabel(\"Pixels\") RGBmean = \"{:.2f}\".format(np.mean(x)) plt.title(\"RGB intensity value", "rain type \"heavy\" or \"torrential\" st: range to draw a random slant from", "== True): # wide angle VIDEO_WIDTH = IMAGE_WIDTH*2 video = cv2.VideoWriter(video_name, 0, 11,", "# fpath = fdict[key] def get_sdsandbox_json_steer_angle(fpath): \"\"\" Get steering angle stored in json", "== True): # wide angle image2 = ag.preprocess(image_copy) image2 = cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT),", "name e.g. record_12893.json fname = 'record_' + fnumber + '.json' # build file", "pst = get_sdsandbox_json_steer_angle(fdict[key]) pst *= conf.norm_const simst = \"Frame: {}, Actual steering angle:", "as np import matplotlib.pyplot as plt nb_bins = 256 count_r = np.zeros(nb_bins) count_g", "log') parser.add_argument('--model', type=str, help='model name for video label') parser.add_argument('--mask', type=str, help='image file suffix')", "def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy array images Parameters ----------", "np import matplotlib.pyplot as plt ipath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' img1 = cv2.imread(ipath) # 120x160x3", "\" + Gmean + \")\") Bmean = \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b, color='b', alpha=0.4, label=\"blue", "filename in fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])] = os.path.join(root, filename) print(\"Use sorted() function in your", "wide angle VIDEO_WIDTH = IMAGE_WIDTH*2 video = cv2.VideoWriter(video_name, 0, 11, (VIDEO_WIDTH, VIDEO_HEIGHT)) #", "#make_video(fdict, model, True) # saved as nvidia2.avi if __name__ == \"__main__\": import argparse", "module def add_rain(image_arr, rt=None, st=0): \"\"\" Add rain to image Parameters ---------- image_arr:", "sorted dictionary from unity (SDSandbox) files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the key in example", "else: # no slant image_arr = am.add_rain_single(image_arr) return image_arr # In[52]: def make_video(fdict,", "RGB image result = Image.merge('RGB', (r, g, b)) # Convert to uint8 numpy", "numpy array scheme: string, 'rgb' (default) or , 'yuv-rgb' If scheme is rgb,", "255]) count_r = hist_r[0] count_g = hist_g[0] count_b = hist_b[0] # Plot manual", "x_offset=50, y_offset=50): \"\"\" Overlay two numpy array images Parameters ---------- s_img: numpy array,", "from io import BytesIO from PIL import Image import base64 import numpy as", "simst = \"Frame: {}, Actual steering angle: {:.2f}\".format(str(fno), pst) cv2.putText(image, simst, (50, 115),", "np.histogram(x[1], bins=nb_bins, range=[0, 255]) hist_b = np.histogram(x[2], bins=nb_bins, range=[0, 255]) count_r = hist_r[0]", "# frame count fno = 1 try: for key in sorted(fdict): image =", "= 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask) for key in sorted(fdict):", "'record_' + fnumber + '.json' # build file path e.g. 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\record_12893.json' idx =", "PIL Parameters ------- img: uint8 numpy image array rv: integer, value to be", "(VIDEO_WIDTH, VIDEO_HEIGHT)) # assumed 11fps # font font = cv2.FONT_HERSHEY_SIMPLEX # frame count", "json # split string fsplit = fpath.split('\\\\') # get name e.g. 12893_cam-image_array_.jpg fname", "instantiate augmentation class ag = Augmentation.Augment_cls(model) # video name video_name = model +", "fnmatch import os from collections import OrderedDict #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask = '*.jpg'", "# 120x160x3 plt.rcParams[\"figure.figsize\"] = (6,4) myfig = plot_img_hist(img) \"\"\" # from https://discuss.pytorch.org/t/plot-a-histogram-for-multiple-images-full-dataset/67600 #", "video.write(image); # increment frame counter fno = fno + 1 except Exception as", "alpha=0.5) plt.bar(bins[:-1], count_b, color='b', alpha=0.5) return fig # In[43]: # fpath = fdict[key]", "set y limit, may need to change # No plotting max for one", "in sorted(fdict): print(\"key: {}, value:{}\".format(key,fdict[key])) Note ------- File path format is OS dependant.", "can make use # of locally defined modules module_path = os.path.abspath(os.path.join('..')) if module_path", "file and return the steering angle. Parameters ------- fpath: string, filepath Returns -------", "plt.title(\"RGB intensity value distributions (mean = \" + RGBmean + \")\") # add", "= g.point(lambda i: i + gv) # Blue b = b.point(lambda i: i", "import fnmatch import os from collections import OrderedDict #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask =", "800, 600 if(preproc == True): # wide angle VIDEO_WIDTH = IMAGE_WIDTH*2 video =", "max for one off images #ymax = 10000 #plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return", "g, b = im.split() # Red r = r.point(lambda i: i + rv)", "number for slant st = np.random.randint(-1 * st, st) if(rt!='light'): # heavy or", "myimg: uint8 numpy image array Example ------- import matplotlib.pyplot as plt import matplotlib.image", "= plt.figure() plt.bar(bins[:-1], count_r, color='r', alpha=0.5) plt.bar(bins[:-1], count_g, color='g', alpha=0.5) plt.bar(bins[:-1], count_b, color='b',", "filenames in os.walk(path): for filename in fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])] = os.path.join(root, filename) print(\"Use", "IMAGE_WIDTH*2 video = cv2.VideoWriter(video_name, 0, 11, (VIDEO_WIDTH, VIDEO_HEIGHT)) # assumed 11fps # font", "bins=nb_bins, range=[0, 255]) hist_b = np.histogram(x[2], bins=nb_bins, range=[0, 255]) count_r = hist_r[0] count_g", "as nvidia2.avi #make_video(args.filepath, args.model, True) # example # python utils.py --filepath=C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\ \\ #", "defined modules module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import argparse", "if module_path not in sys.path: sys.path.append(module_path) import argparse import fnmatch import json import", "create a preprocessed copy to compare what simulator generates to what network \"sees\"", "alpha=0.5) plt.bar(bins[:-1], count_g, color='g', alpha=0.5) plt.bar(bins[:-1], count_b, color='b', alpha=0.5) return fig # In[43]:", "#ymax = 10000 #plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return fig # change rgb values", "+ '.avi' VIDEO_WIDTH, VIDEO_HEIGHT = 800, 600 IMAGE_WIDTH, IMAGE_HEIGHT = 800, 600 if(preproc", "cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) cv2.putText(image2, 'Network Image', (50, 50), font, 1, (255, 255,", "= hist_g[0] count_b = hist_b[0] # Plot manual bins = hist_r[1] fig =", "steering angle. Parameters ------- fpath: string, filepath Returns ------- st_angle: steering angle Example", "matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('steph.jpeg') myimg = changeRGB(img,", "open and read file f = open(fname, \"r\") file = f.read() # load", "cv2.destroyAllWindows() video.release() # subset 100 images - should be quicker #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\'", "for filename in fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])] = os.path.join(root, filename) print(\"Use sorted() function in", "np.asarray(result) return myimg # subset 100 images - should be quicker #path =", "# get histogram myfig = plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\") image2 = cv2.imread(\"temp_plot.png\") # save", "added to blue channel Output ------- myimg: uint8 numpy image array Example -------", "OrderedDict() matches = [] for root, dirnames, filenames in os.walk(path): for filename in", "assumed 11fps # font font = cv2.FONT_HERSHEY_SIMPLEX # frame count fno = 1", "plt.close(myfig) # overlay image2 = overlay_imgs(image4, image2) # concatenate if (preproc == True):", "draw a random number for slant st = np.random.randint(-1 * st, st) if(rt!='light'):", "in the right order. \"\"\" import fnmatch import os from collections import OrderedDict", "11, (VIDEO_WIDTH, VIDEO_HEIGHT)) # assumed 11fps # font font = cv2.FONT_HERSHEY_SIMPLEX # frame", "True): # wide angle image2 = ag.preprocess(image_copy) image2 = cv2.resize(image2, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA)", "'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask = '*.jpg' filemask = os.path.expanduser(path + mask) path, mask = os.path.split(filemask)", ": string file type Returns ------- fdict: dictionary Sorted dictionary containing key and", "= plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) # overlay image2", "y_offset: top padding from large to small overlaid image Returns ------- image_arr: numpy", "\" + Bmean + \")\") # show labels plt.legend(loc='upper right') plt.xlabel(\"Bins\") plt.xticks(np.arange(0, 255,", "string path to files mask : string file type Returns ------- fdict: dictionary", "# saved as nvidia2.avi \"\"\" import os import sys # append local path", "= fjson['user/angle'] return st_angle # In[ ]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\"", "= s_img return l_img # In[ ]: # TODO, need to bring this", "file suffix') args = parser.parse_args() #fdict = sort_unity_files(args.filepath, args.mask) #make_video(fdict, model, True) #", "= Image.open('16_left-2.jpeg') # Calculate manual hist x = np.array(img) x = x.transpose(2, 0,", "# wide angle VIDEO_WIDTH = IMAGE_WIDTH*2 video = cv2.VideoWriter(video_name, 0, 11, (VIDEO_WIDTH, VIDEO_HEIGHT))", "r, g, b = im.split() # Red r = r.point(lambda i: i +", "slant=st) else: # no slant image_arr = am.add_rain_single(image_arr) return image_arr # In[52]: def", "overlay_imgs(image4, image2) # concatenate if (preproc == True): # wide angle cimgs =", "image with insert of small image inlaid Example -------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] =", "show preprocessed image next to original Returns none Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\'", "i + rv) # Green g = g.point(lambda i: i + gv) #", "fig: matplotlib.pyplot figure Example ------- import cv2 import numpy as np import matplotlib.pyplot", "help='image file suffix') args = parser.parse_args() #fdict = sort_unity_files(args.filepath, args.mask) #make_video(fdict, model, True)", "with a corresponding json file containing a steering angle, looks something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\", "= im.split() # Red r = r.point(lambda i: i + rv) # Green", "True) # example # python utils.py --filepath=C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\ \\ # --model=nvidia2 --mask=*.jpg # In[", "Parameters ------- fdict: collections.OrderedDict, ordered dictionary of file names model: string, model name", "to original Returns none Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict", "numpy array, large image x_offset: left padding from large to small overlaid image", "is 0 (first characters before underscore in 0_cam-image_array_.jpg) Parameters ---------- path : string", "# plt.yscale('log', nonposy='clip') # set y limit, may need to change # No", "print(\"Exception raise: \" + str(e)) cv2.destroyAllWindows() video.release() # subset 100 images - should", "OrderedDict must by sorted to order files in the right order. \"\"\" import", "so we can write some info onto image image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT),", "Example -------- \"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[42]: def plot_img_hist(img,", "\"\"\" l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[42]: def plot_img_hist(img, scheme='rgb'): \"\"\"", "image x_offset: left padding from large to small overlaid image y_offset: top padding", "format is OS dependant. OrderedDict must by sorted to order files in the", "= cimgs # write to video video.write(image); # increment frame counter fno =", "= np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) # Calculate manual hist x", "with rain Example -------- \"\"\" import Automold as am # print(\"Adding rain...\") if(st", "heavy or torrential image_arr = am.add_rain_single(image_arr, rain_type=rt, slant=st) else: # no slant image_arr", "cv2.INTER_AREA) cv2.putText(image2, 'Network Image', (50, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA)", "x = x.transpose(2, 0, 1) hist_r = np.histogram(x[0], bins=nb_bins, range=[0, 255]) hist_g =", "(first characters before underscore in 0_cam-image_array_.jpg) Parameters ---------- path : string path to", "\"\"\" import fnmatch import os from collections import OrderedDict #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' #mask", "and return the steering angle. Parameters ------- fpath: string, filepath Returns ------- st_angle:", "C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg The json file with with steering angle, in the same", "names model: string, model name preproc: boolean, show preprocessed image next to original", "= IMAGE_WIDTH*2 video = cv2.VideoWriter(video_name, 0, 11, (VIDEO_WIDTH, VIDEO_HEIGHT)) # assumed 11fps #", "plt.close(myfig) image_copy = image # resize so we can write some info onto", "= '*.jpg' fdict = sort_unity_files(path, mask) model = 'nvidia2' make_video(fdict, model, True) #", "PIL import Image import base64 import numpy as np import matplotlib.pyplot as plt", "y scale logarithmic # plt.yscale('log', nonposy='clip') # set y limit, may need to", "'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi if __name__ == \"__main__\": import", "= r.point(lambda i: i + rv) # Green g = g.point(lambda i: i", "1 try: for key in sorted(fdict): image = cv2.imread(fdict[key]) # 120x160x3 # get", "get_sdsandbox_json_steer_angle(fpath): \"\"\" Get steering angle stored in json file. The argument passed in", "= os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import argparse import fnmatch import", "Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask) for", "'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask) model = 'nvidia2' make_video(fdict, model,", "to frame cv2.putText(image, model, (50, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA)", "change # No plotting max for one off images #ymax = 10000 #plt.ylim(0,", "in json file. The argument passed in the path for a file, that", "compare what simulator generates to what network \"sees\" if (preproc == True): #", "\\ 12893_cam-image_array_.jpg The json file with with steering angle, in the same path,", "cv2.LINE_AA) # histogram on network image myfig = plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4 =", "sort_unity_files(path, mask): \"\"\" Create a sorted dictionary from unity (SDSandbox) files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg", "os import sys # append local path so we can make use #", "import Image import base64 import numpy as np import matplotlib.pyplot as plt import", "x = np.array(img) x = x.transpose(2, 0, 1) hist_r = np.histogram(x[0], bins=nb_bins, range=[0,", "Make video from image dictionary. video.avi is written to disk Parameters ------- fdict:", "import cv2 import conf # instantiate augmentation class ag = Augmentation.Augment_cls(model) # video", "Sorted dictionary containing key and file path Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask", "return st_angle # In[ ]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two", "cv2.FONT_HERSHEY_SIMPLEX # frame count fno = 1 try: for key in sorted(fdict): image", "manual hist x = np.array(img) x = x.transpose(2, 0, 1) hist_r = np.histogram(x[0],", "in fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])] = os.path.join(root, filename) print(\"Use sorted() function in your for", "= cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) # add Info to frame cv2.putText(image, model, (50,", "= sort_unity_files(args.filepath, args.mask) #make_video(fdict, model, True) # saved as nvidia2.avi #make_video(args.filepath, args.model, True)", "= \" + Gmean + \")\") Bmean = \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b, color='b', alpha=0.4,", "In[ ]: # TODO, need to bring this from existing module def add_rain(image_arr,", "saved as nvidia2.avi \"\"\" import os import sys # append local path so", "mask) #model = 'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi if __name__", "Overlay two numpy array images Parameters ---------- s_img: numpy array, small image l_img:", "none Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask)", "Note ------- File path format is OS dependant. OrderedDict must by sorted to", "im = Image.fromarray(np.uint8(img)) # Split into 3 channels r, g, b = im.split()", "gv=0, bv=0): \"\"\" Change RGB values using PIL Parameters ------- img: uint8 numpy", "myfig = plot_img_hist(image, 'rgb') myfig.savefig(\"temp_plot.png\") image2 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) image_copy =", "Returns none Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path,", "color='g', alpha=0.45, label=\"green (mean = \" + Gmean + \")\") Bmean = \"{:.2f}\".format(np.mean(x[2]))", "nb_bins = 256 count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) #", "= cv2.imread(\"temp_plot.png\") # save plt.close(myfig) image_copy = image # resize so we can", "dictionary containing key and file path Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask =", "video video.write(image); # increment frame counter fno = fno + 1 except Exception", "255]) hist_g = np.histogram(x[1], bins=nb_bins, range=[0, 255]) hist_b = np.histogram(x[2], bins=nb_bins, range=[0, 255])", "count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) #img = Image.open('16_left-2.jpeg') # Calculate manual hist", "# In[43]: # fpath = fdict[key] def get_sdsandbox_json_steer_angle(fpath): \"\"\" Get steering angle stored", "= x.transpose(2, 0, 1) hist_r = np.histogram(x[0], bins=nb_bins, range=[0, 255]) hist_g = np.histogram(x[1],", "# get name e.g. 12893_cam-image_array_.jpg fname = fsplit[-1] # get number e.g. 12893", "+ mask) path, mask = os.path.split(filemask) fdict = OrderedDict() matches = [] for", "= Image.fromarray(np.uint8(img)) # Split into 3 channels r, g, b = im.split() #", "Add rain to image Parameters ---------- image_arr: numpy array containing image rt: string,", "# No plotting max for one off images #ymax = 10000 #plt.ylim(0, ymax)", "3 channels r, g, b = im.split() # Red r = r.point(lambda i:", "result = Image.merge('RGB', (r, g, b)) # Convert to uint8 numpy array myimg", "Gmean + \")\") Bmean = \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b, color='b', alpha=0.4, label=\"blue (mean =", "save plt.close(myfig) # overlay image2 = overlay_imgs(image4, image2) # concatenate if (preproc ==", "= sort_unity_files(path, mask) #model = 'nvidia2' #make_video(fdict, model, True) # saved as nvidia2.avi", "in the path for a file, that was stored with a corresponding json", "pst) cv2.putText(image, simst, (50, 115), font, 1, (255, 255, 255), 2, cv2.LINE_AA) #", "to compare what simulator generates to what network \"sees\" if (preproc == True):", ", 'yuv-rgb' If scheme is rgb, maximum number of values in a bins", "count_r = hist_r[0] count_g = hist_g[0] count_b = hist_b[0] # Plot manual bins", "\"\"\" #import cv2 #s_img = cv2.imread(\"smaller_image.png\") #l_img = cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]]", "+ 1 except Exception as e: print(\"Exception raise: \" + str(e)) cv2.destroyAllWindows() video.release()", "# Plot manual bins = hist_r[1] fig = plt.figure() # figure() #plt.yscale('log') Rmean", "myfig.savefig(\"temp_plot.png\") image2 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig) image_copy = image # resize so", "as nvidia2.avi \"\"\" import os import sys # append local path so we", "+ Gmean + \")\") Bmean = \"{:.2f}\".format(np.mean(x[2])) plt.bar(bins[:-1], count_b, color='b', alpha=0.4, label=\"blue (mean", "mask): fdict[int(filename.split('_')[0])] = os.path.join(root, filename) print(\"Use sorted() function in your for loop to", "the right order. \"\"\" import fnmatch import os from collections import OrderedDict #path", "fnmatch.filter(filenames, mask): fdict[int(filename.split('_')[0])] = os.path.join(root, filename) print(\"Use sorted() function in your for loop", "file names model: string, model name preproc: boolean, show preprocessed image next to", "x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[ ]: # TODO, need", "'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\subset_100\\\\' #mask = '*.jpg' #fdict = sort_unity_files(path, mask) #model = 'nvidia2' #make_video(fdict, model,", "digit, otherwise 6 digits and y-axys is plotted on log scale. Returns -------", "steering angle: {:.2f}\".format(str(fno), pst) cv2.putText(image, simst, (50, 115), font, 1, (255, 255, 255),", "In[42]: def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an rgb array Parameters -------", "to files mask : string file type Returns ------- fdict: dictionary Sorted dictionary", "something like: C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\ \\ 12893_cam-image_array_.jpg The json file with with steering angle, in", "i + bv) # Recombine back to RGB image result = Image.merge('RGB', (r,", "order. \"\"\" import fnmatch import os from collections import OrderedDict #path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\'", "def get_sdsandbox_json_steer_angle(fpath): \"\"\" Get steering angle stored in json file. The argument passed", "angle cimgs = np.concatenate((image, image2), axis=1) image = cimgs # write to video", "range=[0, 255]) hist_g = np.histogram(x[1], bins=nb_bins, range=[0, 255]) hist_b = np.histogram(x[2], bins=nb_bins, range=[0,", "= s_img return l_img # In[42]: def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for", "augmentation class ag = Augmentation.Augment_cls(model) # video name video_name = model + '.avi'", "fsplit[-1].split('_') fnumber = fnumber[0] # build json file name e.g. record_12893.json fname =", "numpy array containing large image with insert of small image inlaid Example --------", "numpy array containing image with rain Example -------- \"\"\" import Automold as am", "img = mpimg.imread('steph.jpeg') myimg = changeRGB(img, 60, 0, 0) plt.imshow(myimg) \"\"\" from PIL", "def changeRGB(img, rv=0, gv=0, bv=0): \"\"\" Change RGB values using PIL Parameters -------", "#plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return fig # change rgb values # https://stackoverflow.com/questions/59320564/how-to-access-and-change-color-channels-using-pil def", "matplotlib.pyplot figure Example ------- import cv2 import numpy as np import matplotlib.pyplot as", "im.split() # Red r = r.point(lambda i: i + rv) # Green g", "#l_img = cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return l_img # In[", "# Calculate manual hist x = np.array(img) x = x.transpose(2, 0, 1) hist_r", "In[43]: # fpath = fdict[key] def get_sdsandbox_json_steer_angle(fpath): \"\"\" Get steering angle stored in", "= model + '.avi' VIDEO_WIDTH, VIDEO_HEIGHT = 800, 600 IMAGE_WIDTH, IMAGE_HEIGHT = 800,", "l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy array images Parameters ---------- s_img: numpy", "= hist_r[0] count_g = hist_g[0] count_b = hist_b[0] # Plot manual bins =", "fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa = get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\" import json # split string", "to what network \"sees\" if (preproc == True): # wide angle image2 =", "scale. Returns ------- fig: matplotlib.pyplot figure Example ------- import cv2 import numpy as", "module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import argparse import fnmatch", "2, cv2.LINE_AA) # create a preprocessed copy to compare what simulator generates to", "#mask = '*.jpg' #fdict = sort_unity_files(path, mask) #model = 'nvidia2' #make_video(fdict, model, True)", "files e.g. C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\0_cam-image_array_.jpg Where the key in example above is 0 (first characters", "st_angle: steering angle Example ------- fpath = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\12893_cam-image_array_.jpg' jsa = get_sdsandbox_json_steer_angle(fpath) print(jsa) \"\"\"", "color='b', alpha=0.5) return fig # In[43]: # fpath = fdict[key] def get_sdsandbox_json_steer_angle(fpath): \"\"\"", "class ag = Augmentation.Augment_cls(model) # video name video_name = model + '.avi' VIDEO_WIDTH,", "= OrderedDict() matches = [] for root, dirnames, filenames in os.walk(path): for filename", "histogram for an rgb array Parameters ------- img: numpy array scheme: string, 'rgb'", "font, 1, (255, 255, 255), 2, cv2.LINE_AA) # create a preprocessed copy to", "myimg = np.asarray(result) return myimg # subset 100 images - should be quicker", "to RGB image result = Image.merge('RGB', (r, g, b)) # Convert to uint8", "\"\"\" from PIL import Image import numpy as np im = Image.fromarray(np.uint8(img)) #", "# In[42]: def plot_img_hist(img, scheme='rgb'): \"\"\" Plot histogram for an rgb array Parameters", "hist_g[0] count_b = hist_b[0] # Plot manual bins = hist_r[1] fig = plt.figure()", "parser.add_argument('--model', type=str, help='model name for video label') parser.add_argument('--mask', type=str, help='image file suffix') args", "VIDEO_HEIGHT = 800, 600 IMAGE_WIDTH, IMAGE_HEIGHT = 800, 600 if(preproc == True): #", "12893_cam-image_array_.jpg fname = fsplit[-1] # get number e.g. 12893 fnumber = fsplit[-1].split('_') fnumber", "be added to blue channel Output ------- myimg: uint8 numpy image array Example", "# split string fsplit = fpath.split('\\\\') # get name e.g. 12893_cam-image_array_.jpg fname =", "# Red r = r.point(lambda i: i + rv) # Green g =", "256 count_r = np.zeros(nb_bins) count_g = np.zeros(nb_bins) count_b = np.zeros(nb_bins) # Calculate manual", "scheme='rgb'): \"\"\" Plot histogram for an rgb array Parameters ------- img: numpy array", "label') parser.add_argument('--mask', type=str, help='image file suffix') args = parser.parse_args() #fdict = sort_unity_files(args.filepath, args.mask)", "original Returns none Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict =", "Example ------- path = 'C:\\\\Users\\\\aczd097\\\\Downloads\\\\dataset\\\\unity\\\\log_sample\\\\logs_Mon_Jul_13_08_29_01_2020\\\\' mask = '*.jpg' fdict = sort_unity_files(path, mask) model", "images #ymax = 10000 #plt.ylim(0, ymax) plt.savefig(\"temp_plot.jpg\") plt.close(fig) #return fig # change rgb", "plt.bar(bins[:-1], count_b, color='b', alpha=0.5) return fig # In[43]: # fpath = fdict[key] def", "angle attribute st_angle = fjson['user/angle'] return st_angle # In[ ]: def overlay_imgs(s_img, l_img,", "an rgb array Parameters ------- img: numpy array scheme: string, 'rgb' (default) or", "(default) or , 'yuv-rgb' If scheme is rgb, maximum number of values in", "utf-8 # In[40]: def sort_unity_files(path, mask): \"\"\" Create a sorted dictionary from unity", "plt.bar(bins[:-1], count_r, color='r', alpha=0.5) plt.bar(bins[:-1], count_g, color='g', alpha=0.5) plt.bar(bins[:-1], count_b, color='b', alpha=0.5) return", "TODO, need to bring this from existing module def add_rain(image_arr, rt=None, st=0): \"\"\"", "network image myfig = plot_img_hist(image, 'yuv-rgb') myfig.savefig(\"temp_plot.png\") image4 = cv2.imread(\"temp_plot.png\") # save plt.close(myfig)", "modules module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import argparse import", "conf # instantiate augmentation class ag = Augmentation.Augment_cls(model) # video name video_name =", "#s_img = cv2.imread(\"smaller_image.png\") #l_img = cv2.imread(\"larger_image.jpg\") # x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img return", "255]) hist_b = np.histogram(x[2], bins=nb_bins, range=[0, 255]) count_r = hist_r[0] count_g = hist_g[0]", "<filename>src/utils/utils.py<gh_stars>1-10 #!/usr/bin/env python # coding: utf-8 # In[40]: def sort_unity_files(path, mask): \"\"\" Create", "value to be added to blue channel Output ------- myimg: uint8 numpy image", "Actual steering angle: {:.2f}\".format(str(fno), pst) cv2.putText(image, simst, (50, 115), font, 1, (255, 255,", "st_angle # In[ ]: def overlay_imgs(s_img, l_img, x_offset=50, y_offset=50): \"\"\" Overlay two numpy" ]
[ "License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "writing, software # distributed under the License is distributed on an \"AS IS\"", "the specific language governing permissions and limitations # under the License. from a10_neutron_lbaas.tests.unit", "# def test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'),", "self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self): super(TestA10ConfigProvider, self).setUp({'provider':", "Unless required by applicable law or agreed to in writing, software # distributed", "get in devices. # This actually tests the number of devices with status", "See the # License for the specific language governing permissions and limitations #", "def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances)", "self.assertEqual('LSI', v['v_method'].upper()) def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self): expected = True actual = False", "sorted(actual)) # def test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get(", "\"License\"); you may # not use this file except in compliance with the", "test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults) # def test_image_defaults_members(self): # image_defaults = self.a.config.image_defaults # actual =", "the License. from a10_neutron_lbaas.tests.unit import test_base class TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self):", "Apache License, Version 2.0 (the \"License\"); you may # not use this file", "def test_ip_in_ip(self): expected = True actual = False for k, v in self.a.config.get_devices().items():", "actual = v['ip_in_ip'] self.assertEqual(expected, actual) # TODO(dougwig) -- test new a10_config members #", "the License. You may obtain # a copy of the License at #", "members # def test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults) # def test_image_defaults_members(self): # image_defaults = self.a.config.image_defaults", "self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'),", "self).setUp({'provider': 'prov1'}) def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'), 'tardis') def test_vthunder_api_version(self): v = self.a.config.get_vthunder_config()", "parsnig the JSON structure found in the file # and comparing that against", "law or agreed to in writing, software # distributed under the License is", "new a10_config members # def test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults) # def test_image_defaults_members(self): # image_defaults", "may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "the Apache License, Version 2.0 (the \"License\"); you may # not use this", "This actually tests the number of devices with status == True self.assertEqual(10, len(self.a.config.get_devices()))", "tests the number of devices with status == True self.assertEqual(10, len(self.a.config.get_devices())) def test_expected_ports(self):", "setUp(self): super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'}) def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'), 'tardis') def test_vthunder_api_version(self): v", "for k, v in self.a.config.get_devices().items(): if \"ip_in_ip\" in v: actual = v['ip_in_ip'] self.assertEqual(expected,", "express or implied. See the # License for the specific language governing permissions", "structure found in the file # and comparing that against what we get", "in self.a.config.get_devices().items(): if \"ip_in_ip\" in v: actual = v['ip_in_ip'] self.assertEqual(expected, actual) # TODO(dougwig)", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "CONDITIONS OF ANY KIND, either express or implied. See the # License for", "not use this file except in compliance with the License. You may obtain", "def setUp(self): super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'}) def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'), 'tardis') def test_vthunder_api_version(self):", "updated # A better test would seem to be be parsnig the JSON", "\"properties\", \"disk_format\"] # self.assertListEqual(sorted(expected), sorted(actual)) # def test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(),", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "with the License. You may obtain # a copy of the License at", "= [\"name\", \"id\", \"visibility\", \"tags\", \"min_disk\", # \"min_ram\", \"container_format\", \"protected\", # \"properties\", \"disk_format\"]", "devices. # This actually tests the number of devices with status == True", "be updated # A better test would seem to be be parsnig the", "status == True self.assertEqual(10, len(self.a.config.get_devices())) def test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port'])", "Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not", "for k, v in self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper()) def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self): expected", "[\"name\", \"id\", \"visibility\", \"tags\", \"min_disk\", # \"min_ram\", \"container_format\", \"protected\", # \"properties\", \"disk_format\"] #", "License for the specific language governing permissions and limitations # under the License.", "= v['ip_in_ip'] self.assertEqual(expected, actual) # TODO(dougwig) -- test new a10_config members # def", "self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get(", "# def test_image_defaults_members(self): # image_defaults = self.a.config.image_defaults # actual = image_defaults.keys() # expected", "True self.assertEqual(10, len(self.a.config.get_devices())) def test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port']) def test_expected_protocols(self):", "\"min_ram\", \"container_format\", \"protected\", # \"properties\", \"disk_format\"] # self.assertListEqual(sorted(expected), sorted(actual)) # def test_instance_defaults(self): #", "def test_v_method(self): for k, v in self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper()) def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def", "2.0 (the \"License\"); you may # not use this file except in compliance", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self): super(TestA10ConfigProvider,", "self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port']) def test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def", "test_v_method(self): for k, v in self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper()) def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self):", "self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def test_v_method(self): for k, v in self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper()) def", "expected = True actual = False for k, v in self.a.config.get_devices().items(): if \"ip_in_ip\"", "governing permissions and limitations # under the License. from a10_neutron_lbaas.tests.unit import test_base class", "True actual = False for k, v in self.a.config.get_devices().items(): if \"ip_in_ip\" in v:", "False for k, v in self.a.config.get_devices().items(): if \"ip_in_ip\" in v: actual = v['ip_in_ip']", "and comparing that against what we get in devices. # This actually tests", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "devices with status == True self.assertEqual(10, len(self.a.config.get_devices())) def test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port'])", "actual = False for k, v in self.a.config.get_devices().items(): if \"ip_in_ip\" in v: actual", "a10_config members # def test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults) # def test_image_defaults_members(self): # image_defaults =", "self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self):", "use this file except in compliance with the License. You may obtain #", "# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT", "k, v in self.a.config.get_devices().items(): if \"ip_in_ip\" in v: actual = v['ip_in_ip'] self.assertEqual(expected, actual)", "has to be updated # A better test would seem to be be", "self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def test_v_method(self): for k, v in self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper()) def test_alternate_shared_partition(self):", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #", "compliance with the License. You may obtain # a copy of the License", "v['v_method'].upper()) def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self): expected = True actual = False for", "# def test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults) # def test_image_defaults_members(self): # image_defaults = self.a.config.image_defaults #", "and limitations # under the License. from a10_neutron_lbaas.tests.unit import test_base class TestA10Config(test_base.UnitTestBase): def", "License, Version 2.0 (the \"License\"); you may # not use this file except", "= True actual = False for k, v in self.a.config.get_devices().items(): if \"ip_in_ip\" in", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'),", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "-- test new a10_config members # def test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults) # def test_image_defaults_members(self):", "'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase): def", "test config, this test has to be updated # A better test would", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "implied. See the # License for the specific language governing permissions and limitations", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "OF ANY KIND, either express or implied. See the # License for the", "len(self.a.config.get_devices())) def test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port']) def test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol'])", "test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'), 'tardis') def test_vthunder_api_version(self): v = self.a.config.get_vthunder_config() self.assertEqual(v['api_version'], '9.9') self.assertEqual(v['nova_flavor'],", "image_defaults.keys() # expected = [\"name\", \"id\", \"visibility\", \"tags\", \"min_disk\", # \"min_ram\", \"container_format\", \"protected\",", "def test_image_defaults_members(self): # image_defaults = self.a.config.image_defaults # actual = image_defaults.keys() # expected =", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "\"tags\", \"min_disk\", # \"min_ram\", \"container_format\", \"protected\", # \"properties\", \"disk_format\"] # self.assertListEqual(sorted(expected), sorted(actual)) #", "self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def test_v_method(self): for k, v in self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper())", "# This actually tests the number of devices with status == True self.assertEqual(10,", "the number of devices with status == True self.assertEqual(10, len(self.a.config.get_devices())) def test_expected_ports(self): self.assertEqual(8443,", "we update the test config, this test has to be updated # A", "2014, <NAME> (dougwig), A10 Networks # # Licensed under the Apache License, Version", "actual = image_defaults.keys() # expected = [\"name\", \"id\", \"visibility\", \"tags\", \"min_disk\", # \"min_ram\",", "\"disk_format\"] # self.assertListEqual(sorted(expected), sorted(actual)) # def test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices)", "self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection)", "be parsnig the JSON structure found in the file # and comparing that", "class TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self): super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'}) def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'), 'tardis')", "= image_defaults.keys() # expected = [\"name\", \"id\", \"visibility\", \"tags\", \"min_disk\", # \"min_ram\", \"container_format\",", "self.a.config.image_defaults # actual = image_defaults.keys() # expected = [\"name\", \"id\", \"visibility\", \"tags\", \"min_disk\",", "# self.assertIsNotNone(self.a.config.image_defaults) # def test_image_defaults_members(self): # image_defaults = self.a.config.image_defaults # actual = image_defaults.keys()", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the", "what we get in devices. # This actually tests the number of devices", "if \"ip_in_ip\" in v: actual = v['ip_in_ip'] self.assertEqual(expected, actual) # TODO(dougwig) -- test", "def test_num_appliances(self): # Everytime we update the test config, this test has to", "TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self): # Everytime we update the test config,", "you may # not use this file except in compliance with the License.", "a10_neutron_lbaas.tests.unit import test_base class TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self): # Everytime we", "agreed to in writing, software # distributed under the License is distributed on", "found in the file # and comparing that against what we get in", "self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'),", "self.assertListEqual(sorted(expected), sorted(actual)) # def test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices)", "self.a.config.get_device('ax4')['port']) def test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def test_v_method(self): for k,", "self.a.config.get_device('ax4')['protocol']) def test_v_method(self): for k, v in self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper()) def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition'])", "# Everytime we update the test config, this test has to be updated", "test has to be updated # A better test would seem to be", "in self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper()) def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self): expected = True actual", "self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults())", "(the \"License\"); you may # not use this file except in compliance with", "\"protected\", # \"properties\", \"disk_format\"] # self.assertListEqual(sorted(expected), sorted(actual)) # def test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults) def", "self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get(", "super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'}) def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'), 'tardis') def test_vthunder_api_version(self): v =", "'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'),", "KIND, either express or implied. See the # License for the specific language", "may # not use this file except in compliance with the License. You", "\"visibility\", \"tags\", \"min_disk\", # \"min_ram\", \"container_format\", \"protected\", # \"properties\", \"disk_format\"] # self.assertListEqual(sorted(expected), sorted(actual))", "seem to be be parsnig the JSON structure found in the file #", "file # and comparing that against what we get in devices. # This", "under the License. from a10_neutron_lbaas.tests.unit import test_base class TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def", "expected = [\"name\", \"id\", \"visibility\", \"tags\", \"min_disk\", # \"min_ram\", \"container_format\", \"protected\", # \"properties\",", "(dougwig), A10 Networks # # Licensed under the Apache License, Version 2.0 (the", "either express or implied. See the # License for the specific language governing", "'prov1'}) def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'), 'tardis') def test_vthunder_api_version(self): v = self.a.config.get_vthunder_config() self.assertEqual(v['api_version'],", "# # Unless required by applicable law or agreed to in writing, software", "# actual = image_defaults.keys() # expected = [\"name\", \"id\", \"visibility\", \"tags\", \"min_disk\", #", "file except in compliance with the License. You may obtain # a copy", "this file except in compliance with the License. You may obtain # a", "Copyright 2014, <NAME> (dougwig), A10 Networks # # Licensed under the Apache License,", "this test has to be updated # A better test would seem to", "self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'),", "# Unless required by applicable law or agreed to in writing, software #", "def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'), 'tardis') def test_vthunder_api_version(self): v = self.a.config.get_vthunder_config() self.assertEqual(v['api_version'], '9.9')", "self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port']) def test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def test_v_method(self):", "\"ip_in_ip\" in v: actual = v['ip_in_ip'] self.assertEqual(expected, actual) # TODO(dougwig) -- test new", "by applicable law or agreed to in writing, software # distributed under the", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "the file # and comparing that against what we get in devices. #", "self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self): super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'}) def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'),", "== True self.assertEqual(10, len(self.a.config.get_devices())) def test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port']) def", "under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "or implied. See the # License for the specific language governing permissions and", "# TODO(dougwig) -- test new a10_config members # def test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults) #", "test new a10_config members # def test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults) # def test_image_defaults_members(self): #", "# Copyright 2014, <NAME> (dougwig), A10 Networks # # Licensed under the Apache", "permissions and limitations # under the License. from a10_neutron_lbaas.tests.unit import test_base class TestA10Config(test_base.UnitTestBase):", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults()) class", "def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self): # Everytime we update the test config, this", "TODO(dougwig) -- test new a10_config members # def test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults) # def", "better test would seem to be be parsnig the JSON structure found in", "with status == True self.assertEqual(10, len(self.a.config.get_devices())) def test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443,", "# expected = [\"name\", \"id\", \"visibility\", \"tags\", \"min_disk\", # \"min_ram\", \"container_format\", \"protected\", #", "# and comparing that against what we get in devices. # This actually", "self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'), 'tardis') def test_vthunder_api_version(self): v = self.a.config.get_vthunder_config() self.assertEqual(v['api_version'], '9.9') self.assertEqual(v['nova_flavor'], 'acos.min')", "\"container_format\", \"protected\", # \"properties\", \"disk_format\"] # self.assertListEqual(sorted(expected), sorted(actual)) # def test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults)", "v in self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper()) def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self): expected = True", "License. You may obtain # a copy of the License at # #", "test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get(", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "= False for k, v in self.a.config.get_devices().items(): if \"ip_in_ip\" in v: actual =", "the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "from a10_neutron_lbaas.tests.unit import test_base class TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self): # Everytime", "License. from a10_neutron_lbaas.tests.unit import test_base class TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self): #", "# A better test would seem to be be parsnig the JSON structure", "against what we get in devices. # This actually tests the number of", "for the specific language governing permissions and limitations # under the License. from", "self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port']) def test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https',", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "specific language governing permissions and limitations # under the License. from a10_neutron_lbaas.tests.unit import", "class TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self): # Everytime we update the test", "A10 Networks # # Licensed under the Apache License, Version 2.0 (the \"License\");", "config, this test has to be updated # A better test would seem", "actually tests the number of devices with status == True self.assertEqual(10, len(self.a.config.get_devices())) def", "self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port']) def test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol'])", "self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper()) def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self): expected = True actual =", "v: actual = v['ip_in_ip'] self.assertEqual(expected, actual) # TODO(dougwig) -- test new a10_config members", "# image_defaults = self.a.config.image_defaults # actual = image_defaults.keys() # expected = [\"name\", \"id\",", "self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances)", "'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self): super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'}) def", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may", "TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self): super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'}) def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'), 'tardis') def", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "test would seem to be be parsnig the JSON structure found in the", "comparing that against what we get in devices. # This actually tests the", "image_defaults = self.a.config.image_defaults # actual = image_defaults.keys() # expected = [\"name\", \"id\", \"visibility\",", "def test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults) # def test_image_defaults_members(self): # image_defaults = self.a.config.image_defaults # actual", "ANY KIND, either express or implied. See the # License for the specific", "the # License for the specific language governing permissions and limitations # under", "except in compliance with the License. You may obtain # a copy of", "v['ip_in_ip'] self.assertEqual(expected, actual) # TODO(dougwig) -- test new a10_config members # def test_image_defaults(self):", "self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'),", "update the test config, this test has to be updated # A better", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "\"min_disk\", # \"min_ram\", \"container_format\", \"protected\", # \"properties\", \"disk_format\"] # self.assertListEqual(sorted(expected), sorted(actual)) # def", "self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self): super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'}) def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor') self.assertEqual(self.a.config.get('best_spaceship'),", "actual) # TODO(dougwig) -- test new a10_config members # def test_image_defaults(self): # self.assertIsNotNone(self.a.config.image_defaults)", "self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self): super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'}) def test_top_level(self):", "self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self): expected = True actual = False for k, v in", "to in writing, software # distributed under the License is distributed on an", "You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "JSON structure found in the file # and comparing that against what we", "Everytime we update the test config, this test has to be updated #", "we get in devices. # This actually tests the number of devices with", "k, v in self.a.config.get_devices().items(): self.assertEqual('LSI', v['v_method'].upper()) def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self): expected =", "test_ip_in_ip(self): expected = True actual = False for k, v in self.a.config.get_devices().items(): if", "self.assertIsNotNone(self.a.config.image_defaults) # def test_image_defaults_members(self): # image_defaults = self.a.config.image_defaults # actual = image_defaults.keys() #", "that against what we get in devices. # This actually tests the number", "import test_base class TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self): # Everytime we update", "self.assertEqual(expected, actual) # TODO(dougwig) -- test new a10_config members # def test_image_defaults(self): #", "self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def test_v_method(self): for k, v in self.a.config.get_devices().items(): self.assertEqual('LSI',", "test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self): expected = True actual = False for k, v", "# self.assertListEqual(sorted(expected), sorted(actual)) # def test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(),", "'vport_defaults'), self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self): super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'}) def test_top_level(self): self.assertEqual(self.a.config.get('who_should_win'), 'the-doctor')", "required by applicable law or agreed to in writing, software # distributed under", "# under the License. from a10_neutron_lbaas.tests.unit import test_base class TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances'))", "def test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port']) def test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http',", "v in self.a.config.get_devices().items(): if \"ip_in_ip\" in v: actual = v['ip_in_ip'] self.assertEqual(expected, actual) #", "Networks # # Licensed under the Apache License, Version 2.0 (the \"License\"); you", "# self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database)", "def test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def test_v_method(self): for k, v", "applicable law or agreed to in writing, software # distributed under the License", "test_base class TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self): # Everytime we update the", "to be updated # A better test would seem to be be parsnig", "in devices. # This actually tests the number of devices with status ==", "distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #", "number of devices with status == True self.assertEqual(10, len(self.a.config.get_devices())) def test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port'])", "OR CONDITIONS OF ANY KIND, either express or implied. See the # License", "test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def test_v_method(self): for k, v in", "obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "language governing permissions and limitations # under the License. from a10_neutron_lbaas.tests.unit import test_base", "the test config, this test has to be updated # A better test", "A better test would seem to be be parsnig the JSON structure found", "<NAME> (dougwig), A10 Networks # # Licensed under the Apache License, Version 2.0", "of devices with status == True self.assertEqual(10, len(self.a.config.get_devices())) def test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80,", "self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase): def setUp(self): super(TestA10ConfigProvider, self).setUp({'provider': 'prov1'})", "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #", "in compliance with the License. You may obtain # a copy of the", "the JSON structure found in the file # and comparing that against what", "# not use this file except in compliance with the License. You may", "test_num_appliances(self): # Everytime we update the test config, this test has to be", "or agreed to in writing, software # distributed under the License is distributed", "in v: actual = v['ip_in_ip'] self.assertEqual(expected, actual) # TODO(dougwig) -- test new a10_config", "# \"min_ram\", \"container_format\", \"protected\", # \"properties\", \"disk_format\"] # self.assertListEqual(sorted(expected), sorted(actual)) # def test_instance_defaults(self):", "# License for the specific language governing permissions and limitations # under the", "self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def test_v_method(self): for k, v in self.a.config.get_devices().items():", "in the file # and comparing that against what we get in devices.", "test_verify_appliances(self): self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self): # Everytime we update the test config, this test", "test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port']) def test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol'])", "self.a.config.get_devices().items(): if \"ip_in_ip\" in v: actual = v['ip_in_ip'] self.assertEqual(expected, actual) # TODO(dougwig) --", "= self.a.config.image_defaults # actual = image_defaults.keys() # expected = [\"name\", \"id\", \"visibility\", \"tags\",", "# \"properties\", \"disk_format\"] # self.assertListEqual(sorted(expected), sorted(actual)) # def test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self):", "def test_alternate_shared_partition(self): self.assertTrue(self.a.config.get_device('axadp-alt')['shared_partition']) def test_ip_in_ip(self): expected = True actual = False for k,", "limitations # under the License. from a10_neutron_lbaas.tests.unit import test_base class TestA10Config(test_base.UnitTestBase): def test_verify_appliances(self):", "test_image_defaults_members(self): # image_defaults = self.a.config.image_defaults # actual = image_defaults.keys() # expected = [\"name\",", "self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.use_database) self.assertEqual(self.a.config.get('verify_appliances'), self.a.config.verify_appliances) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database)", "self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.config.database_connection) self.assertEqual(self.a.config.get('use_database'), self.a.config.config.use_database) self.assertEqual(self.a.config.get( 'verify_appliances'), self.a.config.config.verify_appliances) self.assertEqual(self.a.config.get( 'vport_defaults'), self.a.config.get_vport_defaults()) class TestA10ConfigProvider(test_base.UnitTestBase):", "to be be parsnig the JSON structure found in the file # and", "self.assertTrue(self.a.config.get('verify_appliances')) def test_num_appliances(self): # Everytime we update the test config, this test has", "under the Apache License, Version 2.0 (the \"License\"); you may # not use", "self.assertEqual(10, len(self.a.config.get_devices())) def test_expected_ports(self): self.assertEqual(8443, self.a.config.get_device('ax1')['port']) self.assertEqual(80, self.a.config.get_device('ax3')['port']) self.assertEqual(443, self.a.config.get_device('ax4')['port']) def test_expected_protocols(self): self.assertEqual('https',", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See", "def test_instance_defaults(self): # self.assertIsNotNone(self.a.config.instance_defaults) def test_backwards_compat(self): self.assertEqual(self.a.config.get_devices(), self.a.config.devices) self.assertEqual(self.a.config.get_devices(), self.a.config.config.devices) self.assertEqual(self.a.config.get( 'database_connection'), self.a.config.database_connection)", "self.assertEqual(443, self.a.config.get_device('ax4')['port']) def test_expected_protocols(self): self.assertEqual('https', self.a.config.get_device('ax1')['protocol']) self.assertEqual('http', self.a.config.get_device('ax3')['protocol']) self.assertEqual('https', self.a.config.get_device('ax4')['protocol']) def test_v_method(self): for", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "\"id\", \"visibility\", \"tags\", \"min_disk\", # \"min_ram\", \"container_format\", \"protected\", # \"properties\", \"disk_format\"] # self.assertListEqual(sorted(expected),", "in writing, software # distributed under the License is distributed on an \"AS", "would seem to be be parsnig the JSON structure found in the file", "Version 2.0 (the \"License\"); you may # not use this file except in", "be be parsnig the JSON structure found in the file # and comparing" ]
[ "= config.attributes[\"engine\"] for table in meta.tables: engine.execute(f'DROP TABLE IF EXISTS \"{table}\" CASCADE') engine.execute(\"DROP", "engine = config.attributes[\"engine\"] for table in meta.tables: engine.execute(f'DROP TABLE IF EXISTS \"{table}\" CASCADE')", "engine.execute(f'DROP TABLE IF EXISTS \"{table}\" CASCADE') engine.execute(\"DROP TABLE IF EXISTS alembic_version\") engine.execute(\"DROP SCHEMA", "click.echo(\"Catched error when trying to check database existence!\") def set_config_to_context(context: click.Context, settings: DataBaseSettings)", "def create_all(config: Config) -> None: \"\"\" Create all metadata tables. \"\"\" _create_all(config) def", "engine.execute(\"DROP TABLE IF EXISTS alembic_version\") engine.execute(\"DROP SCHEMA IF EXISTS huey\") meta.drop_all() click.secho(\"Completed.\", fg=\"green\")", "settings: DataBaseSettings) -> None: \"\"\" Set Alembic config to Click context for easy", "<reponame>TinkoffCreditSystems/overhave import click import sqlalchemy_utils as sau from alembic.config import Config from sqlalchemy.engine.url", "metadata tables. \"\"\" _create_all(config) def _drop_all(config: Config) -> None: click.echo(\"Dropping...\") meta = config.attributes[\"metadata\"]", "meta.drop_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop all metadata tables, attributes, schema\") @click.pass_obj def drop_all(config: Config)", "settings.setup_db() config = Config() config.attributes[\"engine\"] = settings.create_engine() config.attributes[\"metadata\"] = database.metadata context.obj = config", "metadata tables, attributes, schema. \"\"\" click.confirm(\"Does it really need?\", abort=True) _drop_all(config) def _ensure_database_exists(db_url:", "existence!\") def set_config_to_context(context: click.Context, settings: DataBaseSettings) -> None: \"\"\" Set Alembic config to", "def set_config_to_context(context: click.Context, settings: DataBaseSettings) -> None: \"\"\" Set Alembic config to Click", "_drop_all(config: Config) -> None: click.echo(\"Dropping...\") meta = config.attributes[\"metadata\"] engine = config.attributes[\"engine\"] for table", "_create_all(config: Config) -> None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create all metadata tables\") @click.pass_obj", "None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create all metadata tables\") @click.pass_obj def create_all(config: Config)", "None: \"\"\" Set Alembic config to Click context for easy operations and migrations", "Alembic config to Click context for easy operations and migrations ability. \"\"\" _ensure_database_exists(settings.db_url)", "click.confirm(\"Does it really need?\", abort=True) _drop_all(config) def _ensure_database_exists(db_url: URL) -> None: try: if", "attributes, schema. \"\"\" click.confirm(\"Does it really need?\", abort=True) _drop_all(config) def _ensure_database_exists(db_url: URL) ->", "@click.command(short_help=\"Drop all metadata tables, attributes, schema\") @click.pass_obj def drop_all(config: Config) -> None: \"\"\"", "sqlalchemy.engine.url import URL from sqlalchemy.exc import OperationalError from overhave import db as database", "need?\", abort=True) _drop_all(config) def _ensure_database_exists(db_url: URL) -> None: try: if not sau.database_exists(db_url): sau.create_database(db_url)", "database from overhave.base_settings import DataBaseSettings def _create_all(config: Config) -> None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\",", "Config) -> None: click.echo(\"Dropping...\") meta = config.attributes[\"metadata\"] engine = config.attributes[\"engine\"] for table in", "-> None: \"\"\" Set Alembic config to Click context for easy operations and", "create_all(config: Config) -> None: \"\"\" Create all metadata tables. \"\"\" _create_all(config) def _drop_all(config:", "DataBaseSettings) -> None: \"\"\" Set Alembic config to Click context for easy operations", "tables. \"\"\" _create_all(config) def _drop_all(config: Config) -> None: click.echo(\"Dropping...\") meta = config.attributes[\"metadata\"] engine", "import OperationalError from overhave import db as database from overhave.base_settings import DataBaseSettings def", "attributes, schema\") @click.pass_obj def drop_all(config: Config) -> None: \"\"\" Drop all metadata tables,", "sau.database_exists(db_url): sau.create_database(db_url) except OperationalError as e: click.echo(e) click.echo(\"Catched error when trying to check", "except OperationalError as e: click.echo(e) click.echo(\"Catched error when trying to check database existence!\")", "\"\"\" _create_all(config) def _drop_all(config: Config) -> None: click.echo(\"Dropping...\") meta = config.attributes[\"metadata\"] engine =", "schema\") @click.pass_obj def drop_all(config: Config) -> None: \"\"\" Drop all metadata tables, attributes,", "meta.tables: engine.execute(f'DROP TABLE IF EXISTS \"{table}\" CASCADE') engine.execute(\"DROP TABLE IF EXISTS alembic_version\") engine.execute(\"DROP", "context for easy operations and migrations ability. \"\"\" _ensure_database_exists(settings.db_url) settings.setup_db() config = Config()", "\"\"\" Create all metadata tables. \"\"\" _create_all(config) def _drop_all(config: Config) -> None: click.echo(\"Dropping...\")", "for easy operations and migrations ability. \"\"\" _ensure_database_exists(settings.db_url) settings.setup_db() config = Config() config.attributes[\"engine\"]", "config.attributes[\"engine\"] for table in meta.tables: engine.execute(f'DROP TABLE IF EXISTS \"{table}\" CASCADE') engine.execute(\"DROP TABLE", "tables\") @click.pass_obj def create_all(config: Config) -> None: \"\"\" Create all metadata tables. \"\"\"", "sau from alembic.config import Config from sqlalchemy.engine.url import URL from sqlalchemy.exc import OperationalError", "Click context for easy operations and migrations ability. \"\"\" _ensure_database_exists(settings.db_url) settings.setup_db() config =", "click import sqlalchemy_utils as sau from alembic.config import Config from sqlalchemy.engine.url import URL", "from sqlalchemy.engine.url import URL from sqlalchemy.exc import OperationalError from overhave import db as", "engine.execute(\"DROP SCHEMA IF EXISTS huey\") meta.drop_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop all metadata tables, attributes,", "click.Context, settings: DataBaseSettings) -> None: \"\"\" Set Alembic config to Click context for", "\"\"\" _ensure_database_exists(settings.db_url) settings.setup_db() config = Config() config.attributes[\"engine\"] = settings.create_engine() config.attributes[\"metadata\"] = database.metadata context.obj", "EXISTS alembic_version\") engine.execute(\"DROP SCHEMA IF EXISTS huey\") meta.drop_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop all metadata", "drop_all(config: Config) -> None: \"\"\" Drop all metadata tables, attributes, schema. \"\"\" click.confirm(\"Does", "import db as database from overhave.base_settings import DataBaseSettings def _create_all(config: Config) -> None:", "from overhave.base_settings import DataBaseSettings def _create_all(config: Config) -> None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\")", "and migrations ability. \"\"\" _ensure_database_exists(settings.db_url) settings.setup_db() config = Config() config.attributes[\"engine\"] = settings.create_engine() config.attributes[\"metadata\"]", "\"\"\" click.confirm(\"Does it really need?\", abort=True) _drop_all(config) def _ensure_database_exists(db_url: URL) -> None: try:", "Config from sqlalchemy.engine.url import URL from sqlalchemy.exc import OperationalError from overhave import db", "it really need?\", abort=True) _drop_all(config) def _ensure_database_exists(db_url: URL) -> None: try: if not", "click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop all metadata tables, attributes, schema\") @click.pass_obj def drop_all(config: Config) ->", "None: \"\"\" Create all metadata tables. \"\"\" _create_all(config) def _drop_all(config: Config) -> None:", "click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create all metadata tables\") @click.pass_obj def create_all(config: Config) -> None: \"\"\"", "click.echo(e) click.echo(\"Catched error when trying to check database existence!\") def set_config_to_context(context: click.Context, settings:", "-> None: try: if not sau.database_exists(db_url): sau.create_database(db_url) except OperationalError as e: click.echo(e) click.echo(\"Catched", "to check database existence!\") def set_config_to_context(context: click.Context, settings: DataBaseSettings) -> None: \"\"\" Set", "in meta.tables: engine.execute(f'DROP TABLE IF EXISTS \"{table}\" CASCADE') engine.execute(\"DROP TABLE IF EXISTS alembic_version\")", "operations and migrations ability. \"\"\" _ensure_database_exists(settings.db_url) settings.setup_db() config = Config() config.attributes[\"engine\"] = settings.create_engine()", "from overhave import db as database from overhave.base_settings import DataBaseSettings def _create_all(config: Config)", "if not sau.database_exists(db_url): sau.create_database(db_url) except OperationalError as e: click.echo(e) click.echo(\"Catched error when trying", "def _drop_all(config: Config) -> None: click.echo(\"Dropping...\") meta = config.attributes[\"metadata\"] engine = config.attributes[\"engine\"] for", "\"{table}\" CASCADE') engine.execute(\"DROP TABLE IF EXISTS alembic_version\") engine.execute(\"DROP SCHEMA IF EXISTS huey\") meta.drop_all()", "import click import sqlalchemy_utils as sau from alembic.config import Config from sqlalchemy.engine.url import", "= config.attributes[\"metadata\"] engine = config.attributes[\"engine\"] for table in meta.tables: engine.execute(f'DROP TABLE IF EXISTS", "\"\"\" Drop all metadata tables, attributes, schema. \"\"\" click.confirm(\"Does it really need?\", abort=True)", "IF EXISTS \"{table}\" CASCADE') engine.execute(\"DROP TABLE IF EXISTS alembic_version\") engine.execute(\"DROP SCHEMA IF EXISTS", "fg=\"green\") @click.command(short_help=\"Create all metadata tables\") @click.pass_obj def create_all(config: Config) -> None: \"\"\" Create", "check database existence!\") def set_config_to_context(context: click.Context, settings: DataBaseSettings) -> None: \"\"\" Set Alembic", "Config) -> None: \"\"\" Create all metadata tables. \"\"\" _create_all(config) def _drop_all(config: Config)", "error when trying to check database existence!\") def set_config_to_context(context: click.Context, settings: DataBaseSettings) ->", "Create all metadata tables. \"\"\" _create_all(config) def _drop_all(config: Config) -> None: click.echo(\"Dropping...\") meta", "huey\") meta.drop_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop all metadata tables, attributes, schema\") @click.pass_obj def drop_all(config:", "set_config_to_context(context: click.Context, settings: DataBaseSettings) -> None: \"\"\" Set Alembic config to Click context", "overhave.base_settings import DataBaseSettings def _create_all(config: Config) -> None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create", "abort=True) _drop_all(config) def _ensure_database_exists(db_url: URL) -> None: try: if not sau.database_exists(db_url): sau.create_database(db_url) except", "from sqlalchemy.exc import OperationalError from overhave import db as database from overhave.base_settings import", "SCHEMA IF EXISTS huey\") meta.drop_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop all metadata tables, attributes, schema\")", "-> None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create all metadata tables\") @click.pass_obj def create_all(config:", "@click.pass_obj def create_all(config: Config) -> None: \"\"\" Create all metadata tables. \"\"\" _create_all(config)", "@click.command(short_help=\"Create all metadata tables\") @click.pass_obj def create_all(config: Config) -> None: \"\"\" Create all", "_create_all(config) def _drop_all(config: Config) -> None: click.echo(\"Dropping...\") meta = config.attributes[\"metadata\"] engine = config.attributes[\"engine\"]", "table in meta.tables: engine.execute(f'DROP TABLE IF EXISTS \"{table}\" CASCADE') engine.execute(\"DROP TABLE IF EXISTS", "CASCADE') engine.execute(\"DROP TABLE IF EXISTS alembic_version\") engine.execute(\"DROP SCHEMA IF EXISTS huey\") meta.drop_all() click.secho(\"Completed.\",", "@click.pass_obj def drop_all(config: Config) -> None: \"\"\" Drop all metadata tables, attributes, schema.", "def _ensure_database_exists(db_url: URL) -> None: try: if not sau.database_exists(db_url): sau.create_database(db_url) except OperationalError as", "when trying to check database existence!\") def set_config_to_context(context: click.Context, settings: DataBaseSettings) -> None:", "database existence!\") def set_config_to_context(context: click.Context, settings: DataBaseSettings) -> None: \"\"\" Set Alembic config", "_drop_all(config) def _ensure_database_exists(db_url: URL) -> None: try: if not sau.database_exists(db_url): sau.create_database(db_url) except OperationalError", "to Click context for easy operations and migrations ability. \"\"\" _ensure_database_exists(settings.db_url) settings.setup_db() config", "Set Alembic config to Click context for easy operations and migrations ability. \"\"\"", "EXISTS huey\") meta.drop_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop all metadata tables, attributes, schema\") @click.pass_obj def", "migrations ability. \"\"\" _ensure_database_exists(settings.db_url) settings.setup_db() config = Config() config.attributes[\"engine\"] = settings.create_engine() config.attributes[\"metadata\"] =", "None: \"\"\" Drop all metadata tables, attributes, schema. \"\"\" click.confirm(\"Does it really need?\",", "ability. \"\"\" _ensure_database_exists(settings.db_url) settings.setup_db() config = Config() config.attributes[\"engine\"] = settings.create_engine() config.attributes[\"metadata\"] = database.metadata", "import DataBaseSettings def _create_all(config: Config) -> None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create all", "meta = config.attributes[\"metadata\"] engine = config.attributes[\"engine\"] for table in meta.tables: engine.execute(f'DROP TABLE IF", "-> None: click.echo(\"Dropping...\") meta = config.attributes[\"metadata\"] engine = config.attributes[\"engine\"] for table in meta.tables:", "overhave import db as database from overhave.base_settings import DataBaseSettings def _create_all(config: Config) ->", "None: click.echo(\"Dropping...\") meta = config.attributes[\"metadata\"] engine = config.attributes[\"engine\"] for table in meta.tables: engine.execute(f'DROP", "Config) -> None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create all metadata tables\") @click.pass_obj def", "sqlalchemy_utils as sau from alembic.config import Config from sqlalchemy.engine.url import URL from sqlalchemy.exc", "click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create all metadata tables\") @click.pass_obj def create_all(config: Config) ->", "TABLE IF EXISTS alembic_version\") engine.execute(\"DROP SCHEMA IF EXISTS huey\") meta.drop_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop", "metadata tables, attributes, schema\") @click.pass_obj def drop_all(config: Config) -> None: \"\"\" Drop all", "db as database from overhave.base_settings import DataBaseSettings def _create_all(config: Config) -> None: click.echo(\"Creating...\")", "-> None: \"\"\" Drop all metadata tables, attributes, schema. \"\"\" click.confirm(\"Does it really", "Drop all metadata tables, attributes, schema. \"\"\" click.confirm(\"Does it really need?\", abort=True) _drop_all(config)", "all metadata tables, attributes, schema. \"\"\" click.confirm(\"Does it really need?\", abort=True) _drop_all(config) def", "really need?\", abort=True) _drop_all(config) def _ensure_database_exists(db_url: URL) -> None: try: if not sau.database_exists(db_url):", "as sau from alembic.config import Config from sqlalchemy.engine.url import URL from sqlalchemy.exc import", "config.attributes[\"metadata\"] engine = config.attributes[\"engine\"] for table in meta.tables: engine.execute(f'DROP TABLE IF EXISTS \"{table}\"", "URL) -> None: try: if not sau.database_exists(db_url): sau.create_database(db_url) except OperationalError as e: click.echo(e)", "trying to check database existence!\") def set_config_to_context(context: click.Context, settings: DataBaseSettings) -> None: \"\"\"", "sqlalchemy.exc import OperationalError from overhave import db as database from overhave.base_settings import DataBaseSettings", "None: try: if not sau.database_exists(db_url): sau.create_database(db_url) except OperationalError as e: click.echo(e) click.echo(\"Catched error", "OperationalError as e: click.echo(e) click.echo(\"Catched error when trying to check database existence!\") def", "config to Click context for easy operations and migrations ability. \"\"\" _ensure_database_exists(settings.db_url) settings.setup_db()", "URL from sqlalchemy.exc import OperationalError from overhave import db as database from overhave.base_settings", "def drop_all(config: Config) -> None: \"\"\" Drop all metadata tables, attributes, schema. \"\"\"", "tables, attributes, schema. \"\"\" click.confirm(\"Does it really need?\", abort=True) _drop_all(config) def _ensure_database_exists(db_url: URL)", "schema. \"\"\" click.confirm(\"Does it really need?\", abort=True) _drop_all(config) def _ensure_database_exists(db_url: URL) -> None:", "try: if not sau.database_exists(db_url): sau.create_database(db_url) except OperationalError as e: click.echo(e) click.echo(\"Catched error when", "import Config from sqlalchemy.engine.url import URL from sqlalchemy.exc import OperationalError from overhave import", "fg=\"green\") @click.command(short_help=\"Drop all metadata tables, attributes, schema\") @click.pass_obj def drop_all(config: Config) -> None:", "OperationalError from overhave import db as database from overhave.base_settings import DataBaseSettings def _create_all(config:", "TABLE IF EXISTS \"{table}\" CASCADE') engine.execute(\"DROP TABLE IF EXISTS alembic_version\") engine.execute(\"DROP SCHEMA IF", "alembic_version\") engine.execute(\"DROP SCHEMA IF EXISTS huey\") meta.drop_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop all metadata tables,", "IF EXISTS huey\") meta.drop_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop all metadata tables, attributes, schema\") @click.pass_obj", "alembic.config import Config from sqlalchemy.engine.url import URL from sqlalchemy.exc import OperationalError from overhave", "import sqlalchemy_utils as sau from alembic.config import Config from sqlalchemy.engine.url import URL from", "not sau.database_exists(db_url): sau.create_database(db_url) except OperationalError as e: click.echo(e) click.echo(\"Catched error when trying to", "tables, attributes, schema\") @click.pass_obj def drop_all(config: Config) -> None: \"\"\" Drop all metadata", "all metadata tables\") @click.pass_obj def create_all(config: Config) -> None: \"\"\" Create all metadata", "_ensure_database_exists(db_url: URL) -> None: try: if not sau.database_exists(db_url): sau.create_database(db_url) except OperationalError as e:", "for table in meta.tables: engine.execute(f'DROP TABLE IF EXISTS \"{table}\" CASCADE') engine.execute(\"DROP TABLE IF", "all metadata tables. \"\"\" _create_all(config) def _drop_all(config: Config) -> None: click.echo(\"Dropping...\") meta =", "import URL from sqlalchemy.exc import OperationalError from overhave import db as database from", "metadata tables\") @click.pass_obj def create_all(config: Config) -> None: \"\"\" Create all metadata tables.", "IF EXISTS alembic_version\") engine.execute(\"DROP SCHEMA IF EXISTS huey\") meta.drop_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Drop all", "all metadata tables, attributes, schema\") @click.pass_obj def drop_all(config: Config) -> None: \"\"\" Drop", "Config) -> None: \"\"\" Drop all metadata tables, attributes, schema. \"\"\" click.confirm(\"Does it", "def _create_all(config: Config) -> None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create all metadata tables\")", "DataBaseSettings def _create_all(config: Config) -> None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create all metadata", "e: click.echo(e) click.echo(\"Catched error when trying to check database existence!\") def set_config_to_context(context: click.Context,", "click.echo(\"Dropping...\") meta = config.attributes[\"metadata\"] engine = config.attributes[\"engine\"] for table in meta.tables: engine.execute(f'DROP TABLE", "-> None: \"\"\" Create all metadata tables. \"\"\" _create_all(config) def _drop_all(config: Config) ->", "EXISTS \"{table}\" CASCADE') engine.execute(\"DROP TABLE IF EXISTS alembic_version\") engine.execute(\"DROP SCHEMA IF EXISTS huey\")", "from alembic.config import Config from sqlalchemy.engine.url import URL from sqlalchemy.exc import OperationalError from", "as e: click.echo(e) click.echo(\"Catched error when trying to check database existence!\") def set_config_to_context(context:", "config.attributes[\"metadata\"].create_all() click.secho(\"Completed.\", fg=\"green\") @click.command(short_help=\"Create all metadata tables\") @click.pass_obj def create_all(config: Config) -> None:", "sau.create_database(db_url) except OperationalError as e: click.echo(e) click.echo(\"Catched error when trying to check database", "as database from overhave.base_settings import DataBaseSettings def _create_all(config: Config) -> None: click.echo(\"Creating...\") config.attributes[\"metadata\"].create_all()", "_ensure_database_exists(settings.db_url) settings.setup_db() config = Config() config.attributes[\"engine\"] = settings.create_engine() config.attributes[\"metadata\"] = database.metadata context.obj =", "easy operations and migrations ability. \"\"\" _ensure_database_exists(settings.db_url) settings.setup_db() config = Config() config.attributes[\"engine\"] =", "\"\"\" Set Alembic config to Click context for easy operations and migrations ability." ]
[ "('furniture', _('Furniture')), ('disease', _('Disease / Illness')), ('genres', _('Musical genre')), ('villains', _('Villain')), ('excuses', _('Excuses", "migrations, transaction, IntegrityError from django.utils.translation import gettext_lazy as _ CATEGORIES = ( ('elements',", "apps.get_model('basta', 'Category') for category in CATEGORIES: try: with transaction.atomic(): Category.objects.get( name = category[0],", "to quit your job')), ('doatdate', _('Things to do on a date')), ('hobbies', _('Hobby", "def uninitialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category in CATEGORIES: try: with", ").delete() except IntegrityError: pass class Migration(migrations.Migration): dependencies = [ ('basta', '0017_auto_20200503_2155') ] operations", "'name', 'surname','plant', 'animal', 'location', 'film', 'object', 'brand' ] def initialize_categories(apps, schema_editor): Category =", "('doatdate', _('Things to do on a date')), ('hobbies', _('Hobby / Activity')), ('uniforms', _('People", "do on a date')), ('hobbies', _('Hobby / Activity')), ('uniforms', _('People in uniform')), ('literary',", "transaction.atomic(): Category.objects.get( name = category[0], ).delete() except IntegrityError: pass class Migration(migrations.Migration): dependencies =", "'Category') for category in CATEGORIES: try: with transaction.atomic(): Category.objects.create( name = category[0], default", "for category in CATEGORIES: try: with transaction.atomic(): Category.objects.create( name = category[0], default =", "= [ ('basta', '0017_auto_20200503_2155') ] operations = [ migrations.RunPython( initialize_categories, uninitialize_categories ), ]", "DEFAULTS ) except IntegrityError: pass def uninitialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for", "_('Excuses not to go to a party')), ('reasonsquitjob',_('Reasons to quit your job')), ('doatdate',", "go to a party')), ('reasonsquitjob',_('Reasons to quit your job')), ('doatdate', _('Things to do", "import gettext_lazy as _ CATEGORIES = ( ('elements', _('Chemical element')), ('petnames', _('Pet name')),", "try: with transaction.atomic(): Category.objects.create( name = category[0], default = category[0] in DEFAULTS )", "class Migration(migrations.Migration): dependencies = [ ('basta', '0017_auto_20200503_2155') ] operations = [ migrations.RunPython( initialize_categories,", "dependencies = [ ('basta', '0017_auto_20200503_2155') ] operations = [ migrations.RunPython( initialize_categories, uninitialize_categories ),", "'location', 'film', 'object', 'brand' ] def initialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for", "= category[0] in DEFAULTS ) except IntegrityError: pass def uninitialize_categories(apps, schema_editor): Category =", "= category[0], ).delete() except IntegrityError: pass class Migration(migrations.Migration): dependencies = [ ('basta', '0017_auto_20200503_2155')", "literature')) ) DEFAULTS = [ 'name', 'surname','plant', 'animal', 'location', 'film', 'object', 'brand' ]", "from django.utils.translation import gettext_lazy as _ CATEGORIES = ( ('elements', _('Chemical element')), ('petnames',", "your job')), ('doatdate', _('Things to do on a date')), ('hobbies', _('Hobby / Activity')),", "import migrations, transaction, IntegrityError from django.utils.translation import gettext_lazy as _ CATEGORIES = (", "('excuses', _('Excuses not to go to a party')), ('reasonsquitjob',_('Reasons to quit your job')),", "django.utils.translation import gettext_lazy as _ CATEGORIES = ( ('elements', _('Chemical element')), ('petnames', _('Pet", "_('Pet name')), ('transportation', _('Means of transportation')), ('furniture', _('Furniture')), ('disease', _('Disease / Illness')), ('genres',", "category[0], default = category[0] in DEFAULTS ) except IntegrityError: pass def uninitialize_categories(apps, schema_editor):", "_('Villain')), ('excuses', _('Excuses not to go to a party')), ('reasonsquitjob',_('Reasons to quit your", "Migration(migrations.Migration): dependencies = [ ('basta', '0017_auto_20200503_2155') ] operations = [ migrations.RunPython( initialize_categories, uninitialize_categories", "Category.objects.get( name = category[0], ).delete() except IntegrityError: pass class Migration(migrations.Migration): dependencies = [", "a date')), ('hobbies', _('Hobby / Activity')), ('uniforms', _('People in uniform')), ('literary', _('Work of", "for category in CATEGORIES: try: with transaction.atomic(): Category.objects.get( name = category[0], ).delete() except", "('petnames', _('Pet name')), ('transportation', _('Means of transportation')), ('furniture', _('Furniture')), ('disease', _('Disease / Illness')),", "in uniform')), ('literary', _('Work of literature')) ) DEFAULTS = [ 'name', 'surname','plant', 'animal',", "_('People in uniform')), ('literary', _('Work of literature')) ) DEFAULTS = [ 'name', 'surname','plant',", "party')), ('reasonsquitjob',_('Reasons to quit your job')), ('doatdate', _('Things to do on a date')),", "pass class Migration(migrations.Migration): dependencies = [ ('basta', '0017_auto_20200503_2155') ] operations = [ migrations.RunPython(", "default = category[0] in DEFAULTS ) except IntegrityError: pass def uninitialize_categories(apps, schema_editor): Category", "IntegrityError: pass class Migration(migrations.Migration): dependencies = [ ('basta', '0017_auto_20200503_2155') ] operations = [", "= apps.get_model('basta', 'Category') for category in CATEGORIES: try: with transaction.atomic(): Category.objects.create( name =", "transaction, IntegrityError from django.utils.translation import gettext_lazy as _ CATEGORIES = ( ('elements', _('Chemical", "uninitialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category in CATEGORIES: try: with transaction.atomic():", "job')), ('doatdate', _('Things to do on a date')), ('hobbies', _('Hobby / Activity')), ('uniforms',", "date')), ('hobbies', _('Hobby / Activity')), ('uniforms', _('People in uniform')), ('literary', _('Work of literature'))", "Category = apps.get_model('basta', 'Category') for category in CATEGORIES: try: with transaction.atomic(): Category.objects.create( name", "of transportation')), ('furniture', _('Furniture')), ('disease', _('Disease / Illness')), ('genres', _('Musical genre')), ('villains', _('Villain')),", "('genres', _('Musical genre')), ('villains', _('Villain')), ('excuses', _('Excuses not to go to a party')),", "_('Furniture')), ('disease', _('Disease / Illness')), ('genres', _('Musical genre')), ('villains', _('Villain')), ('excuses', _('Excuses not", "('disease', _('Disease / Illness')), ('genres', _('Musical genre')), ('villains', _('Villain')), ('excuses', _('Excuses not to", "('transportation', _('Means of transportation')), ('furniture', _('Furniture')), ('disease', _('Disease / Illness')), ('genres', _('Musical genre')),", "gettext_lazy as _ CATEGORIES = ( ('elements', _('Chemical element')), ('petnames', _('Pet name')), ('transportation',", "to do on a date')), ('hobbies', _('Hobby / Activity')), ('uniforms', _('People in uniform')),", "in CATEGORIES: try: with transaction.atomic(): Category.objects.get( name = category[0], ).delete() except IntegrityError: pass", "Illness')), ('genres', _('Musical genre')), ('villains', _('Villain')), ('excuses', _('Excuses not to go to a", "/ Activity')), ('uniforms', _('People in uniform')), ('literary', _('Work of literature')) ) DEFAULTS =", "to go to a party')), ('reasonsquitjob',_('Reasons to quit your job')), ('doatdate', _('Things to", "from django.db import migrations, transaction, IntegrityError from django.utils.translation import gettext_lazy as _ CATEGORIES", "= [ 'name', 'surname','plant', 'animal', 'location', 'film', 'object', 'brand' ] def initialize_categories(apps, schema_editor):", "in CATEGORIES: try: with transaction.atomic(): Category.objects.create( name = category[0], default = category[0] in", "/ Illness')), ('genres', _('Musical genre')), ('villains', _('Villain')), ('excuses', _('Excuses not to go to", "a party')), ('reasonsquitjob',_('Reasons to quit your job')), ('doatdate', _('Things to do on a", "_('Disease / Illness')), ('genres', _('Musical genre')), ('villains', _('Villain')), ('excuses', _('Excuses not to go", "= category[0], default = category[0] in DEFAULTS ) except IntegrityError: pass def uninitialize_categories(apps,", "def initialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category in CATEGORIES: try: with", "('uniforms', _('People in uniform')), ('literary', _('Work of literature')) ) DEFAULTS = [ 'name',", "'brand' ] def initialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category in CATEGORIES:", "of literature')) ) DEFAULTS = [ 'name', 'surname','plant', 'animal', 'location', 'film', 'object', 'brand'", "schema_editor): Category = apps.get_model('basta', 'Category') for category in CATEGORIES: try: with transaction.atomic(): Category.objects.create(", "as _ CATEGORIES = ( ('elements', _('Chemical element')), ('petnames', _('Pet name')), ('transportation', _('Means", "'Category') for category in CATEGORIES: try: with transaction.atomic(): Category.objects.get( name = category[0], ).delete()", "_('Work of literature')) ) DEFAULTS = [ 'name', 'surname','plant', 'animal', 'location', 'film', 'object',", "( ('elements', _('Chemical element')), ('petnames', _('Pet name')), ('transportation', _('Means of transportation')), ('furniture', _('Furniture')),", "category in CATEGORIES: try: with transaction.atomic(): Category.objects.create( name = category[0], default = category[0]", "category[0] in DEFAULTS ) except IntegrityError: pass def uninitialize_categories(apps, schema_editor): Category = apps.get_model('basta',", "IntegrityError: pass def uninitialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category in CATEGORIES:", "pass def uninitialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category in CATEGORIES: try:", "_('Means of transportation')), ('furniture', _('Furniture')), ('disease', _('Disease / Illness')), ('genres', _('Musical genre')), ('villains',", "('reasonsquitjob',_('Reasons to quit your job')), ('doatdate', _('Things to do on a date')), ('hobbies',", "django.db import migrations, transaction, IntegrityError from django.utils.translation import gettext_lazy as _ CATEGORIES =", "except IntegrityError: pass def uninitialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category in", "_('Musical genre')), ('villains', _('Villain')), ('excuses', _('Excuses not to go to a party')), ('reasonsquitjob',_('Reasons", "initialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category in CATEGORIES: try: with transaction.atomic():", "to a party')), ('reasonsquitjob',_('Reasons to quit your job')), ('doatdate', _('Things to do on", ") except IntegrityError: pass def uninitialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category", ") DEFAULTS = [ 'name', 'surname','plant', 'animal', 'location', 'film', 'object', 'brand' ] def", "schema_editor): Category = apps.get_model('basta', 'Category') for category in CATEGORIES: try: with transaction.atomic(): Category.objects.get(", "IntegrityError from django.utils.translation import gettext_lazy as _ CATEGORIES = ( ('elements', _('Chemical element')),", "Category.objects.create( name = category[0], default = category[0] in DEFAULTS ) except IntegrityError: pass", "('hobbies', _('Hobby / Activity')), ('uniforms', _('People in uniform')), ('literary', _('Work of literature')) )", "'surname','plant', 'animal', 'location', 'film', 'object', 'brand' ] def initialize_categories(apps, schema_editor): Category = apps.get_model('basta',", "uniform')), ('literary', _('Work of literature')) ) DEFAULTS = [ 'name', 'surname','plant', 'animal', 'location',", "name')), ('transportation', _('Means of transportation')), ('furniture', _('Furniture')), ('disease', _('Disease / Illness')), ('genres', _('Musical", "DEFAULTS = [ 'name', 'surname','plant', 'animal', 'location', 'film', 'object', 'brand' ] def initialize_categories(apps,", "CATEGORIES = ( ('elements', _('Chemical element')), ('petnames', _('Pet name')), ('transportation', _('Means of transportation')),", "_('Chemical element')), ('petnames', _('Pet name')), ('transportation', _('Means of transportation')), ('furniture', _('Furniture')), ('disease', _('Disease", "] def initialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category in CATEGORIES: try:", "[ 'name', 'surname','plant', 'animal', 'location', 'film', 'object', 'brand' ] def initialize_categories(apps, schema_editor): Category", "apps.get_model('basta', 'Category') for category in CATEGORIES: try: with transaction.atomic(): Category.objects.create( name = category[0],", "('elements', _('Chemical element')), ('petnames', _('Pet name')), ('transportation', _('Means of transportation')), ('furniture', _('Furniture')), ('disease',", "('villains', _('Villain')), ('excuses', _('Excuses not to go to a party')), ('reasonsquitjob',_('Reasons to quit", "Activity')), ('uniforms', _('People in uniform')), ('literary', _('Work of literature')) ) DEFAULTS = [", "'film', 'object', 'brand' ] def initialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category", "except IntegrityError: pass class Migration(migrations.Migration): dependencies = [ ('basta', '0017_auto_20200503_2155') ] operations =", "not to go to a party')), ('reasonsquitjob',_('Reasons to quit your job')), ('doatdate', _('Things", "'object', 'brand' ] def initialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category') for category in", "CATEGORIES: try: with transaction.atomic(): Category.objects.create( name = category[0], default = category[0] in DEFAULTS", "in DEFAULTS ) except IntegrityError: pass def uninitialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category')", "= ( ('elements', _('Chemical element')), ('petnames', _('Pet name')), ('transportation', _('Means of transportation')), ('furniture',", "element')), ('petnames', _('Pet name')), ('transportation', _('Means of transportation')), ('furniture', _('Furniture')), ('disease', _('Disease /", "Category = apps.get_model('basta', 'Category') for category in CATEGORIES: try: with transaction.atomic(): Category.objects.get( name", "name = category[0], default = category[0] in DEFAULTS ) except IntegrityError: pass def", "<filename>basta/migrations/0018_initialize_categories.py from django.db import migrations, transaction, IntegrityError from django.utils.translation import gettext_lazy as _", "_ CATEGORIES = ( ('elements', _('Chemical element')), ('petnames', _('Pet name')), ('transportation', _('Means of", "category in CATEGORIES: try: with transaction.atomic(): Category.objects.get( name = category[0], ).delete() except IntegrityError:", "_('Things to do on a date')), ('hobbies', _('Hobby / Activity')), ('uniforms', _('People in", "transaction.atomic(): Category.objects.create( name = category[0], default = category[0] in DEFAULTS ) except IntegrityError:", "with transaction.atomic(): Category.objects.create( name = category[0], default = category[0] in DEFAULTS ) except", "quit your job')), ('doatdate', _('Things to do on a date')), ('hobbies', _('Hobby /", "('literary', _('Work of literature')) ) DEFAULTS = [ 'name', 'surname','plant', 'animal', 'location', 'film',", "on a date')), ('hobbies', _('Hobby / Activity')), ('uniforms', _('People in uniform')), ('literary', _('Work", "transportation')), ('furniture', _('Furniture')), ('disease', _('Disease / Illness')), ('genres', _('Musical genre')), ('villains', _('Villain')), ('excuses',", "with transaction.atomic(): Category.objects.get( name = category[0], ).delete() except IntegrityError: pass class Migration(migrations.Migration): dependencies", "= apps.get_model('basta', 'Category') for category in CATEGORIES: try: with transaction.atomic(): Category.objects.get( name =", "try: with transaction.atomic(): Category.objects.get( name = category[0], ).delete() except IntegrityError: pass class Migration(migrations.Migration):", "'animal', 'location', 'film', 'object', 'brand' ] def initialize_categories(apps, schema_editor): Category = apps.get_model('basta', 'Category')", "category[0], ).delete() except IntegrityError: pass class Migration(migrations.Migration): dependencies = [ ('basta', '0017_auto_20200503_2155') ]", "name = category[0], ).delete() except IntegrityError: pass class Migration(migrations.Migration): dependencies = [ ('basta',", "CATEGORIES: try: with transaction.atomic(): Category.objects.get( name = category[0], ).delete() except IntegrityError: pass class", "genre')), ('villains', _('Villain')), ('excuses', _('Excuses not to go to a party')), ('reasonsquitjob',_('Reasons to", "_('Hobby / Activity')), ('uniforms', _('People in uniform')), ('literary', _('Work of literature')) ) DEFAULTS" ]
[ "import Interpreter class FontValue(Interpreter[Font]): def __init__(self) -> None: super().__init__( key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT,", "SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5, SelectGraphicRendition.FONT_ALT_6: Font.ALT_6, SelectGraphicRendition.FONT_ALT_7: Font.ALT_7, SelectGraphicRendition.FONT_ALT_8: Font.ALT_8, SelectGraphicRendition.FONT_DEFAULT:", "ansiscape.enums import Font, InterpretationKey, SelectGraphicRendition from ansiscape.interpreter import Interpreter class FontValue(Interpreter[Font]): def __init__(self)", "-> None: super().__init__( key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2,", "SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5, SelectGraphicRendition.FONT_ALT_6: Font.ALT_6, SelectGraphicRendition.FONT_ALT_7: Font.ALT_7, SelectGraphicRendition.FONT_ALT_8:", "def __init__(self) -> None: super().__init__( key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1,", "Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5,", "super().__init__( key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3,", "SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5, SelectGraphicRendition.FONT_ALT_6:", "ansiscape.interpreter import Interpreter class FontValue(Interpreter[Font]): def __init__(self) -> None: super().__init__( key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT:", "SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5, SelectGraphicRendition.FONT_ALT_6: Font.ALT_6, SelectGraphicRendition.FONT_ALT_7: Font.ALT_7, SelectGraphicRendition.FONT_ALT_8: Font.ALT_8, SelectGraphicRendition.FONT_DEFAULT: Font.DEFAULT, },", "Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5, SelectGraphicRendition.FONT_ALT_6: Font.ALT_6, SelectGraphicRendition.FONT_ALT_7: Font.ALT_7,", "key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4:", "from ansiscape.interpreter import Interpreter class FontValue(Interpreter[Font]): def __init__(self) -> None: super().__init__( key=InterpretationKey.FONT, lookup={", "SelectGraphicRendition from ansiscape.interpreter import Interpreter class FontValue(Interpreter[Font]): def __init__(self) -> None: super().__init__( key=InterpretationKey.FONT,", "Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5, SelectGraphicRendition.FONT_ALT_6: Font.ALT_6, SelectGraphicRendition.FONT_ALT_7: Font.ALT_7, SelectGraphicRendition.FONT_ALT_8: Font.ALT_8, SelectGraphicRendition.FONT_DEFAULT: Font.DEFAULT, }, )", "FontValue(Interpreter[Font]): def __init__(self) -> None: super().__init__( key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1:", "Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5, SelectGraphicRendition.FONT_ALT_6: Font.ALT_6, SelectGraphicRendition.FONT_ALT_7: Font.ALT_7, SelectGraphicRendition.FONT_ALT_8: Font.ALT_8, SelectGraphicRendition.FONT_DEFAULT: Font.DEFAULT,", "Font, InterpretationKey, SelectGraphicRendition from ansiscape.interpreter import Interpreter class FontValue(Interpreter[Font]): def __init__(self) -> None:", "lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4,", "SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5, SelectGraphicRendition.FONT_ALT_6: Font.ALT_6, SelectGraphicRendition.FONT_ALT_7:", "None: super().__init__( key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3:", "Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5, SelectGraphicRendition.FONT_ALT_6: Font.ALT_6,", "Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5: Font.ALT_5, SelectGraphicRendition.FONT_ALT_6: Font.ALT_6, SelectGraphicRendition.FONT_ALT_7: Font.ALT_7, SelectGraphicRendition.FONT_ALT_8: Font.ALT_8,", "class FontValue(Interpreter[Font]): def __init__(self) -> None: super().__init__( key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0,", "Interpreter class FontValue(Interpreter[Font]): def __init__(self) -> None: super().__init__( key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0:", "SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2: Font.ALT_2, SelectGraphicRendition.FONT_ALT_3: Font.ALT_3, SelectGraphicRendition.FONT_ALT_4: Font.ALT_4, SelectGraphicRendition.FONT_ALT_5:", "from ansiscape.enums import Font, InterpretationKey, SelectGraphicRendition from ansiscape.interpreter import Interpreter class FontValue(Interpreter[Font]): def", "import Font, InterpretationKey, SelectGraphicRendition from ansiscape.interpreter import Interpreter class FontValue(Interpreter[Font]): def __init__(self) ->", "InterpretationKey, SelectGraphicRendition from ansiscape.interpreter import Interpreter class FontValue(Interpreter[Font]): def __init__(self) -> None: super().__init__(", "__init__(self) -> None: super().__init__( key=InterpretationKey.FONT, lookup={ SelectGraphicRendition.DEFAULT: Font.DEFAULT, SelectGraphicRendition.FONT_ALT_0: Font.ALT_0, SelectGraphicRendition.FONT_ALT_1: Font.ALT_1, SelectGraphicRendition.FONT_ALT_2:" ]
[]
[ "utf-8 -*- from __future__ import unicode_literals from rest_framework import generics from rest_framework.views import", "import RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset", "Response from .models import RiskType, RiskField from .serializers import RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView): queryset", "queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RiskType.objects.all() serializer_class =", "from rest_framework import generics from rest_framework.views import APIView from rest_framework.response import Response from", "of RiskField.FIELD_TYPES. \"\"\" data = [{'field_type': k, 'name': v} for k, v in", "**kwargs): \"\"\" Return a list of RiskField.FIELD_TYPES. \"\"\" data = [{'field_type': k, 'name':", "FieldTypes(APIView): def get(self, request, **kwargs): \"\"\" Return a list of RiskField.FIELD_TYPES. \"\"\" data", "from __future__ import unicode_literals from rest_framework import generics from rest_framework.views import APIView from", "from .serializers import RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class", "\"\"\" data = [{'field_type': k, 'name': v} for k, v in RiskField.FIELD_TYPES] return", "= RiskTypeSerializer class FieldTypes(APIView): def get(self, request, **kwargs): \"\"\" Return a list of", "= RiskType.objects.all() serializer_class = RiskTypeSerializer class FieldTypes(APIView): def get(self, request, **kwargs): \"\"\" Return", "from rest_framework.response import Response from .models import RiskType, RiskField from .serializers import RiskTypeSerializer", "request, **kwargs): \"\"\" Return a list of RiskField.FIELD_TYPES. \"\"\" data = [{'field_type': k,", "import APIView from rest_framework.response import Response from .models import RiskType, RiskField from .serializers", "__future__ import unicode_literals from rest_framework import generics from rest_framework.views import APIView from rest_framework.response", "RiskTypeSerializer class FieldTypes(APIView): def get(self, request, **kwargs): \"\"\" Return a list of RiskField.FIELD_TYPES.", "import unicode_literals from rest_framework import generics from rest_framework.views import APIView from rest_framework.response import", "RiskField.FIELD_TYPES. \"\"\" data = [{'field_type': k, 'name': v} for k, v in RiskField.FIELD_TYPES]", "serializer_class = RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class FieldTypes(APIView):", "RiskTypeList(generics.ListCreateAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RiskType.objects.all() serializer_class", "RiskType, RiskField from .serializers import RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView): queryset = RiskType.objects.all() serializer_class =", ".serializers import RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView):", "rest_framework import generics from rest_framework.views import APIView from rest_framework.response import Response from .models", "= RiskType.objects.all() serializer_class = RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer", "-*- from __future__ import unicode_literals from rest_framework import generics from rest_framework.views import APIView", "<filename>backend/apps/risks/views.py<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import unicode_literals from rest_framework import", "\"\"\" Return a list of RiskField.FIELD_TYPES. \"\"\" data = [{'field_type': k, 'name': v}", "unicode_literals from rest_framework import generics from rest_framework.views import APIView from rest_framework.response import Response", "serializer_class = RiskTypeSerializer class FieldTypes(APIView): def get(self, request, **kwargs): \"\"\" Return a list", "-*- coding: utf-8 -*- from __future__ import unicode_literals from rest_framework import generics from", "coding: utf-8 -*- from __future__ import unicode_literals from rest_framework import generics from rest_framework.views", "rest_framework.response import Response from .models import RiskType, RiskField from .serializers import RiskTypeSerializer class", "class RiskTypeList(generics.ListCreateAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RiskType.objects.all()", "def get(self, request, **kwargs): \"\"\" Return a list of RiskField.FIELD_TYPES. \"\"\" data =", "import generics from rest_framework.views import APIView from rest_framework.response import Response from .models import", "from rest_framework.views import APIView from rest_framework.response import Response from .models import RiskType, RiskField", ".models import RiskType, RiskField from .serializers import RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView): queryset = RiskType.objects.all()", "generics from rest_framework.views import APIView from rest_framework.response import Response from .models import RiskType,", "rest_framework.views import APIView from rest_framework.response import Response from .models import RiskType, RiskField from", "APIView from rest_framework.response import Response from .models import RiskType, RiskField from .serializers import", "RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class FieldTypes(APIView): def get(self,", "data = [{'field_type': k, 'name': v} for k, v in RiskField.FIELD_TYPES] return Response(data)", "# -*- coding: utf-8 -*- from __future__ import unicode_literals from rest_framework import generics", "RiskType.objects.all() serializer_class = RiskTypeSerializer class FieldTypes(APIView): def get(self, request, **kwargs): \"\"\" Return a", "class FieldTypes(APIView): def get(self, request, **kwargs): \"\"\" Return a list of RiskField.FIELD_TYPES. \"\"\"", "import RiskType, RiskField from .serializers import RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView): queryset = RiskType.objects.all() serializer_class", "import Response from .models import RiskType, RiskField from .serializers import RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView):", "from .models import RiskType, RiskField from .serializers import RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView): queryset =", "a list of RiskField.FIELD_TYPES. \"\"\" data = [{'field_type': k, 'name': v} for k,", "RiskType.objects.all() serializer_class = RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class", "RiskField from .serializers import RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer", "= RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class FieldTypes(APIView): def", "list of RiskField.FIELD_TYPES. \"\"\" data = [{'field_type': k, 'name': v} for k, v", "RiskTypeSerializer class RiskTypeList(generics.ListCreateAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset =", "class RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class FieldTypes(APIView): def get(self, request,", "get(self, request, **kwargs): \"\"\" Return a list of RiskField.FIELD_TYPES. \"\"\" data = [{'field_type':", "queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class FieldTypes(APIView): def get(self, request, **kwargs): \"\"\"", "RiskTypeDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RiskType.objects.all() serializer_class = RiskTypeSerializer class FieldTypes(APIView): def get(self, request, **kwargs):", "Return a list of RiskField.FIELD_TYPES. \"\"\" data = [{'field_type': k, 'name': v} for" ]
[ "from core.renderer.renderer import get_renderer from config import REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT class Grid5kRunner(Runner):", "os.path.exists(log_root_path): os.makedirs(log_root_path) elif os.path.exists(stderr_log): os.remove(stderr_log) if os.path.exists(stdout_log): os.remove(stdout_log) bug_id = task.bug.project if task.bug.bug_id", "None: parameters.append(current_parameter) node_cmd_args = \"%s %s --id %s\" % ( os.path.join(REPAIR_ROOT, 'script', 'repair.py'),", "'-': if current_parameter is not None: parameters.append(current_parameter) param = a[1:] if param[0] ==", "json.load(fd) if 'patches' in task.results and len(task.results['patches']) > 0: task.status = \"PATCHED\" else:", "core.renderer.renderer import get_renderer from config import REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT class Grid5kRunner(Runner): def", "param[\"parameter\"] == \"id\": continue node_cmd_args += \" %s%s%s\" % (param[\"separator\"], param[\"parameter\"], param[\"value\"]) node_cmd", "Exception: task.status = \"ERROR\" pass else: task.status = \"ERROR\" self.finished.append(task) for task in", "= time.time() self.running.append(task) except subprocess.CalledProcessError: pass finally: return self.running def start_task(self, task): \"\"\"", "if a[0] == '-': if current_parameter is not None: parameters.append(current_parameter) param = a[1:]", "+ len(self.waiting) < GRID5K_MAX_NODE: task = to_run.pop() if task.bug is not None: self.start_task(task)", "if len(param) == 1 else '--', \"parameter\": param, \"value\": \"\" } elif current_parameter", "= \"oarsub -l nodes=1,walltime=%s -O %s -E %s \\\"%s\\\"\" % ( GRID5K_TIME_OUT, stdout_log,", "from core.runner.RepairTask import RepairTask from core.runner.Runner import Runner from core.renderer.renderer import get_renderer from", "or param[\"parameter\"] == \"id\": continue node_cmd_args += \" %s%s%s\" % (param[\"separator\"], param[\"parameter\"], param[\"value\"])", "self.waiting.remove(task) if task.id in running_ids: task.status = \"STARTED\" task.starting_date = time.time() self.running.append(task) except", "task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed)) stdout_log = os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log = os.path.join(log_root_path, 'grid5k.stderr.log')", "%s -E %s \\\"%s\\\"\" % ( GRID5K_TIME_OUT, stdout_log, stderr_log, node_cmd) devnull = open('/dev/null',", "if task.id not in waiting_ids: self.waiting.remove(task) if task.id in running_ids: task.status = \"STARTED\"", "in jobs: if jobs[job_id]['state'] == \"Running\": running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id)) for task in self.running:", "'grid5k.stderr.log') if not os.path.exists(log_root_path): os.makedirs(log_root_path) elif os.path.exists(stderr_log): os.remove(stderr_log) if os.path.exists(stdout_log): os.remove(stdout_log) bug_id =", "task.id not in running_ids: self.running.remove(task) task.end_date = time.time() result_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project,", "__init__(self, tasks, args): \"\"\" :type tasks: list of RepairTask \"\"\" super(Grid5kRunner, self).__init__(tasks, args)", "task.results and len(task.results['patches']) > 0: task.status = \"PATCHED\" else: task.status = \"DONE\" except", "finally: return self.running def start_task(self, task): \"\"\" :param task: :type task: RepairTask :return:", "'w') try: cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) jobs = json.loads(cmd_output) running_ids =", "'oarstat --json -u `whoami`' devnull = open('/dev/null', 'w') try: cmd_output = subprocess.check_output(cmd, shell=True,", "= get_renderer(self) to_run = self.tasks[:] while (len(to_run) > 0 or len(self.running) > 0", "task.bug.bug_id != \"\" and task.bug.bug_id is not None: bug_id = \"%s_%s\" % (task.bug.project,", "task.status = \"ERROR\" pass else: task.status = \"ERROR\" self.finished.append(task) for task in self.waiting:", "waiting_ids: self.waiting.remove(task) if task.id in running_ids: task.status = \"STARTED\" task.starting_date = time.time() self.running.append(task)", "\"\"\" :param task: :type task: RepairTask :return: \"\"\" log_root_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project,", "= \"WAITING\" self.waiting.append(task) def execute(self): renderer = get_renderer(self) to_run = self.tasks[:] while (len(to_run)", "for task in self.running: if task.id not in running_ids: self.running.remove(task) task.end_date = time.time()", "else: task.status = \"ERROR\" self.finished.append(task) for task in self.waiting: if task.id not in", "while (len(to_run) > 0 or len(self.running) > 0 or len(self.waiting) > 0) and", "param = a[1:] if param[0] == '-': param = param[1:] current_parameter = {", "node_cmd_args cmd = \"oarsub -l nodes=1,walltime=%s -O %s -E %s \\\"%s\\\"\" % (", "if task.id in running_ids: task.status = \"STARTED\" task.starting_date = time.time() self.running.append(task) except subprocess.CalledProcessError:", "%s \\\"%s\\\"\" % ( GRID5K_TIME_OUT, stdout_log, stderr_log, node_cmd) devnull = open('/dev/null', 'w') cmd_output", "\"value\": \"\" } elif current_parameter is not None: current_parameter['value'] += \" \" +", "waiting_ids.append(int(job_id)) for task in self.running: if task.id not in running_ids: self.running.remove(task) task.end_date =", "task.status = \"STARTED\" task.starting_date = time.time() self.running.append(task) except subprocess.CalledProcessError: pass finally: return self.running", "param, \"value\": \"\" } elif current_parameter is not None: current_parameter['value'] += \" \"", "execute(self): renderer = get_renderer(self) to_run = self.tasks[:] while (len(to_run) > 0 or len(self.running)", "if os.path.exists(result_path): try: with open(result_path) as fd: task.results = json.load(fd) if 'patches' in", "import get_renderer from config import REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT class Grid5kRunner(Runner): def __init__(self,", "[] current_parameter = None for a in sys.argv: if a[0] == '-': if", "--id %s\" % ( os.path.join(REPAIR_ROOT, 'script', 'repair.py'), task.tool.name, bug_id ) for param in", "= \"ERROR\" pass else: task.status = \"ERROR\" self.finished.append(task) for task in self.waiting: if", "str(task.bug.bug_id), task.tool.name, str(task.tool.seed), \"result.json\") if os.path.exists(result_path): try: with open(result_path) as fd: task.results =", "is not None: bug_id = \"%s_%s\" % (task.bug.project, task.bug.bug_id) parameters = [] current_parameter", "in self.running: if task.id not in running_ids: self.running.remove(task) task.end_date = time.time() result_path =", "if param[0] == '-': param = param[1:] current_parameter = { \"separator\": '-' if", "0 and len(self.running) + len(self.waiting) < GRID5K_MAX_NODE: task = to_run.pop() if task.bug is", "for task in self.waiting: if task.id not in waiting_ids: self.waiting.remove(task) if task.id in", "str(task.bug.bug_id), task.tool.name, str(task.tool.seed)) stdout_log = os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log = os.path.join(log_root_path, 'grid5k.stderr.log') if not", "= param[1:] current_parameter = { \"separator\": '-' if len(param) == 1 else '--',", "task.id not in waiting_ids: self.waiting.remove(task) if task.id in running_ids: task.status = \"STARTED\" task.starting_date", "(len(to_run) > 0 or len(self.running) > 0 or len(self.waiting) > 0) and not", "m: task.id = int(m.group(1)) task.status = \"WAITING\" self.waiting.append(task) def execute(self): renderer = get_renderer(self)", "not os.path.exists(log_root_path): os.makedirs(log_root_path) elif os.path.exists(stderr_log): os.remove(stderr_log) if os.path.exists(stdout_log): os.remove(stdout_log) bug_id = task.bug.project if", "'-': param = param[1:] current_parameter = { \"separator\": '-' if len(param) == 1", "subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) m = re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if m: task.id = int(m.group(1))", "param = param[1:] current_parameter = { \"separator\": '-' if len(param) == 1 else", "% (param[\"separator\"], param[\"parameter\"], param[\"value\"]) node_cmd = \"python %s\" % node_cmd_args cmd = \"oarsub", "re import sys from core.runner.RepairTask import RepairTask from core.runner.Runner import Runner from core.renderer.renderer", "> 0 or len(self.waiting) > 0) and not self.is_end_time(): if len(to_run) > 0", "if task.bug.bug_id != \"\" and task.bug.bug_id is not None: bug_id = \"%s_%s\" %", "from config import REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT class Grid5kRunner(Runner): def __init__(self, tasks, args):", "elif os.path.exists(stderr_log): os.remove(stderr_log) if os.path.exists(stdout_log): os.remove(stdout_log) bug_id = task.bug.project if task.bug.bug_id != \"\"", "os.makedirs(log_root_path) elif os.path.exists(stderr_log): os.remove(stderr_log) if os.path.exists(stdout_log): os.remove(stdout_log) bug_id = task.bug.project if task.bug.bug_id !=", "not None: bug_id = \"%s_%s\" % (task.bug.project, task.bug.bug_id) parameters = [] current_parameter =", "`whoami`' devnull = open('/dev/null', 'w') try: cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) jobs", "def start_task(self, task): \"\"\" :param task: :type task: RepairTask :return: \"\"\" log_root_path =", "import REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT class Grid5kRunner(Runner): def __init__(self, tasks, args): \"\"\" :type", "result_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed), \"result.json\") if os.path.exists(result_path): try: with", "try: cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) jobs = json.loads(cmd_output) running_ids = []", "= \"DONE\" except Exception: task.status = \"ERROR\" pass else: task.status = \"ERROR\" self.finished.append(task)", "os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log = os.path.join(log_root_path, 'grid5k.stderr.log') if not os.path.exists(log_root_path): os.makedirs(log_root_path) elif os.path.exists(stderr_log): os.remove(stderr_log)", "cmd = 'oarstat --json -u `whoami`' devnull = open('/dev/null', 'w') try: cmd_output =", "task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed), \"result.json\") if os.path.exists(result_path): try: with open(result_path) as fd: task.results", "if os.path.exists(stdout_log): os.remove(stdout_log) bug_id = task.bug.project if task.bug.bug_id != \"\" and task.bug.bug_id is", "waiting_ids = [] for job_id in jobs: if jobs[job_id]['state'] == \"Running\": running_ids.append(int(job_id)) else:", "current_parameter = { \"separator\": '-' if len(param) == 1 else '--', \"parameter\": param,", "not None: current_parameter['value'] += \" \" + a if current_parameter is not None:", "task.status = \"WAITING\" self.waiting.append(task) def execute(self): renderer = get_renderer(self) to_run = self.tasks[:] while", "continue node_cmd_args += \" %s%s%s\" % (param[\"separator\"], param[\"parameter\"], param[\"value\"]) node_cmd = \"python %s\"", "param[\"parameter\"], param[\"value\"]) node_cmd = \"python %s\" % node_cmd_args cmd = \"oarsub -l nodes=1,walltime=%s", "bug_id = task.bug.project if task.bug.bug_id != \"\" and task.bug.bug_id is not None: bug_id", "m = re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if m: task.id = int(m.group(1)) task.status = \"WAITING\" self.waiting.append(task)", "+ a if current_parameter is not None: parameters.append(current_parameter) node_cmd_args = \"%s %s --id", "import re import sys from core.runner.RepairTask import RepairTask from core.runner.Runner import Runner from", "= a[1:] if param[0] == '-': param = param[1:] current_parameter = { \"separator\":", "\"DONE\" except Exception: task.status = \"ERROR\" pass else: task.status = \"ERROR\" self.finished.append(task) for", "task.id in running_ids: task.status = \"STARTED\" task.starting_date = time.time() self.running.append(task) except subprocess.CalledProcessError: pass", "bug_id = \"%s_%s\" % (task.bug.project, task.bug.bug_id) parameters = [] current_parameter = None for", "None: current_parameter['value'] += \" \" + a if current_parameter is not None: parameters.append(current_parameter)", "'repair.py'), task.tool.name, bug_id ) for param in parameters: if param[\"parameter\"] == \"i\" or", "not in waiting_ids: self.waiting.remove(task) if task.id in running_ids: task.status = \"STARTED\" task.starting_date =", "= task.bug.project if task.bug.bug_id != \"\" and task.bug.bug_id is not None: bug_id =", "current_parameter['value'] += \" \" + a if current_parameter is not None: parameters.append(current_parameter) node_cmd_args", "\"id\": continue node_cmd_args += \" %s%s%s\" % (param[\"separator\"], param[\"parameter\"], param[\"value\"]) node_cmd = \"python", "task: RepairTask :return: \"\"\" log_root_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed)) stdout_log", "for param in parameters: if param[\"parameter\"] == \"i\" or param[\"parameter\"] == \"id\": continue", "import subprocess import json import os import re import sys from core.runner.RepairTask import", "else: task.status = \"DONE\" except Exception: task.status = \"ERROR\" pass else: task.status =", "os.path.exists(stdout_log): os.remove(stdout_log) bug_id = task.bug.project if task.bug.bug_id != \"\" and task.bug.bug_id is not", "sys from core.runner.RepairTask import RepairTask from core.runner.Runner import Runner from core.renderer.renderer import get_renderer", "GRID5K_TIME_OUT class Grid5kRunner(Runner): def __init__(self, tasks, args): \"\"\" :type tasks: list of RepairTask", "time.time() result_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed), \"result.json\") if os.path.exists(result_path): try:", "is not None: parameters.append(current_parameter) param = a[1:] if param[0] == '-': param =", "pass finally: return self.running def start_task(self, task): \"\"\" :param task: :type task: RepairTask", "except subprocess.CalledProcessError: pass finally: return self.running def start_task(self, task): \"\"\" :param task: :type", "task.id = int(m.group(1)) task.status = \"WAITING\" self.waiting.append(task) def execute(self): renderer = get_renderer(self) to_run", "% ( GRID5K_TIME_OUT, stdout_log, stderr_log, node_cmd) devnull = open('/dev/null', 'w') cmd_output = subprocess.check_output(cmd,", "import os import re import sys from core.runner.RepairTask import RepairTask from core.runner.Runner import", "if jobs[job_id]['state'] == \"Running\": running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id)) for task in self.running: if task.id", "renderer = get_renderer(self) to_run = self.tasks[:] while (len(to_run) > 0 or len(self.running) >", "OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT class Grid5kRunner(Runner): def __init__(self, tasks, args): \"\"\" :type tasks: list", "> 0 or len(self.running) > 0 or len(self.waiting) > 0) and not self.is_end_time():", "else: waiting_ids.append(int(job_id)) for task in self.running: if task.id not in running_ids: self.running.remove(task) task.end_date", "--json -u `whoami`' devnull = open('/dev/null', 'w') try: cmd_output = subprocess.check_output(cmd, shell=True, stdin=None,", ":return: \"\"\" log_root_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed)) stdout_log = os.path.join(log_root_path,", "nodes=1,walltime=%s -O %s -E %s \\\"%s\\\"\" % ( GRID5K_TIME_OUT, stdout_log, stderr_log, node_cmd) devnull", "list of RepairTask \"\"\" super(Grid5kRunner, self).__init__(tasks, args) def get_running(self): cmd = 'oarstat --json", "self.running.remove(task) task.end_date = time.time() result_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed), \"result.json\")", "( os.path.join(REPAIR_ROOT, 'script', 'repair.py'), task.tool.name, bug_id ) for param in parameters: if param[\"parameter\"]", "RepairTask :return: \"\"\" log_root_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed)) stdout_log =", "and len(self.running) + len(self.waiting) < GRID5K_MAX_NODE: task = to_run.pop() if task.bug is not", "in self.waiting: if task.id not in waiting_ids: self.waiting.remove(task) if task.id in running_ids: task.status", "os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed), \"result.json\") if os.path.exists(result_path): try: with open(result_path) as", "get_running(self): cmd = 'oarstat --json -u `whoami`' devnull = open('/dev/null', 'w') try: cmd_output", "core.runner.RepairTask import RepairTask from core.runner.Runner import Runner from core.renderer.renderer import get_renderer from config", ") for param in parameters: if param[\"parameter\"] == \"i\" or param[\"parameter\"] == \"id\":", "= \"PATCHED\" else: task.status = \"DONE\" except Exception: task.status = \"ERROR\" pass else:", "parameters = [] current_parameter = None for a in sys.argv: if a[0] ==", "for job_id in jobs: if jobs[job_id]['state'] == \"Running\": running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id)) for task", "task.end_date = time.time() result_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed), \"result.json\") if", "if current_parameter is not None: parameters.append(current_parameter) node_cmd_args = \"%s %s --id %s\" %", "stderr_log = os.path.join(log_root_path, 'grid5k.stderr.log') if not os.path.exists(log_root_path): os.makedirs(log_root_path) elif os.path.exists(stderr_log): os.remove(stderr_log) if os.path.exists(stdout_log):", "% (task.bug.project, task.bug.bug_id) parameters = [] current_parameter = None for a in sys.argv:", "\\\"%s\\\"\" % ( GRID5K_TIME_OUT, stdout_log, stderr_log, node_cmd) devnull = open('/dev/null', 'w') cmd_output =", "self.running def start_task(self, task): \"\"\" :param task: :type task: RepairTask :return: \"\"\" log_root_path", "running_ids: task.status = \"STARTED\" task.starting_date = time.time() self.running.append(task) except subprocess.CalledProcessError: pass finally: return", "open(result_path) as fd: task.results = json.load(fd) if 'patches' in task.results and len(task.results['patches']) >", "running_ids: self.running.remove(task) task.end_date = time.time() result_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed),", "cmd_output) if m: task.id = int(m.group(1)) task.status = \"WAITING\" self.waiting.append(task) def execute(self): renderer", "\"%s_%s\" % (task.bug.project, task.bug.bug_id) parameters = [] current_parameter = None for a in", "str(task.tool.seed)) stdout_log = os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log = os.path.join(log_root_path, 'grid5k.stderr.log') if not os.path.exists(log_root_path): os.makedirs(log_root_path)", "\"\"\" :type tasks: list of RepairTask \"\"\" super(Grid5kRunner, self).__init__(tasks, args) def get_running(self): cmd", "<filename>script/core/runner/grid5k/Grid5kRunner.py import time import subprocess import json import os import re import sys", "os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed)) stdout_log = os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log = os.path.join(log_root_path,", "= time.time() result_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed), \"result.json\") if os.path.exists(result_path):", "= int(m.group(1)) task.status = \"WAITING\" self.waiting.append(task) def execute(self): renderer = get_renderer(self) to_run =", "param[0] == '-': param = param[1:] current_parameter = { \"separator\": '-' if len(param)", "%s --id %s\" % ( os.path.join(REPAIR_ROOT, 'script', 'repair.py'), task.tool.name, bug_id ) for param", "current_parameter is not None: parameters.append(current_parameter) node_cmd_args = \"%s %s --id %s\" % (", "stdin=None, stderr=devnull) jobs = json.loads(cmd_output) running_ids = [] waiting_ids = [] for job_id", "-O %s -E %s \\\"%s\\\"\" % ( GRID5K_TIME_OUT, stdout_log, stderr_log, node_cmd) devnull =", "and not self.is_end_time(): if len(to_run) > 0 and len(self.running) + len(self.waiting) < GRID5K_MAX_NODE:", "%s%s%s\" % (param[\"separator\"], param[\"parameter\"], param[\"value\"]) node_cmd = \"python %s\" % node_cmd_args cmd =", "task.status = \"DONE\" except Exception: task.status = \"ERROR\" pass else: task.status = \"ERROR\"", "open('/dev/null', 'w') try: cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) jobs = json.loads(cmd_output) running_ids", "if current_parameter is not None: parameters.append(current_parameter) param = a[1:] if param[0] == '-':", "len(task.results['patches']) > 0: task.status = \"PATCHED\" else: task.status = \"DONE\" except Exception: task.status", "shell=True, stdin=None, stderr=devnull) m = re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if m: task.id = int(m.group(1)) task.status", "in sys.argv: if a[0] == '-': if current_parameter is not None: parameters.append(current_parameter) param", "a if current_parameter is not None: parameters.append(current_parameter) node_cmd_args = \"%s %s --id %s\"", "not None: parameters.append(current_parameter) param = a[1:] if param[0] == '-': param = param[1:]", "in running_ids: self.running.remove(task) task.end_date = time.time() result_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name,", "subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) jobs = json.loads(cmd_output) running_ids = [] waiting_ids = []", "str(task.tool.seed), \"result.json\") if os.path.exists(result_path): try: with open(result_path) as fd: task.results = json.load(fd) if", "task.starting_date = time.time() self.running.append(task) except subprocess.CalledProcessError: pass finally: return self.running def start_task(self, task):", "and task.bug.bug_id is not None: bug_id = \"%s_%s\" % (task.bug.project, task.bug.bug_id) parameters =", "import Runner from core.renderer.renderer import get_renderer from config import REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT", "job_id in jobs: if jobs[job_id]['state'] == \"Running\": running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id)) for task in", "len(self.waiting) < GRID5K_MAX_NODE: task = to_run.pop() if task.bug is not None: self.start_task(task) time.sleep(1)", "devnull = open('/dev/null', 'w') cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) m = re.search('OAR_JOB_ID=([0-9]+)',", "\"\"\" log_root_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed)) stdout_log = os.path.join(log_root_path, 'grid5k.stdout.log')", "tasks, args): \"\"\" :type tasks: list of RepairTask \"\"\" super(Grid5kRunner, self).__init__(tasks, args) def", "super(Grid5kRunner, self).__init__(tasks, args) def get_running(self): cmd = 'oarstat --json -u `whoami`' devnull =", "\"PATCHED\" else: task.status = \"DONE\" except Exception: task.status = \"ERROR\" pass else: task.status", "parameters.append(current_parameter) param = a[1:] if param[0] == '-': param = param[1:] current_parameter =", "os.path.exists(result_path): try: with open(result_path) as fd: task.results = json.load(fd) if 'patches' in task.results", "if not os.path.exists(log_root_path): os.makedirs(log_root_path) elif os.path.exists(stderr_log): os.remove(stderr_log) if os.path.exists(stdout_log): os.remove(stdout_log) bug_id = task.bug.project", "task.bug.project if task.bug.bug_id != \"\" and task.bug.bug_id is not None: bug_id = \"%s_%s\"", "cmd = \"oarsub -l nodes=1,walltime=%s -O %s -E %s \\\"%s\\\"\" % ( GRID5K_TIME_OUT,", "None: parameters.append(current_parameter) param = a[1:] if param[0] == '-': param = param[1:] current_parameter", "= 'oarstat --json -u `whoami`' devnull = open('/dev/null', 'w') try: cmd_output = subprocess.check_output(cmd,", "self).__init__(tasks, args) def get_running(self): cmd = 'oarstat --json -u `whoami`' devnull = open('/dev/null',", "open('/dev/null', 'w') cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) m = re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if", "def execute(self): renderer = get_renderer(self) to_run = self.tasks[:] while (len(to_run) > 0 or", "= subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) jobs = json.loads(cmd_output) running_ids = [] waiting_ids =", "import json import os import re import sys from core.runner.RepairTask import RepairTask from", "-u `whoami`' devnull = open('/dev/null', 'w') try: cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull)", "a in sys.argv: if a[0] == '-': if current_parameter is not None: parameters.append(current_parameter)", "node_cmd_args += \" %s%s%s\" % (param[\"separator\"], param[\"parameter\"], param[\"value\"]) node_cmd = \"python %s\" %", "< GRID5K_MAX_NODE: task = to_run.pop() if task.bug is not None: self.start_task(task) time.sleep(1) renderer.render()", "running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id)) for task in self.running: if task.id not in running_ids: self.running.remove(task)", "task.tool.name, bug_id ) for param in parameters: if param[\"parameter\"] == \"i\" or param[\"parameter\"]", "os.remove(stderr_log) if os.path.exists(stdout_log): os.remove(stdout_log) bug_id = task.bug.project if task.bug.bug_id != \"\" and task.bug.bug_id", "get_renderer from config import REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT class Grid5kRunner(Runner): def __init__(self, tasks,", "jobs[job_id]['state'] == \"Running\": running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id)) for task in self.running: if task.id not", "self.waiting.append(task) def execute(self): renderer = get_renderer(self) to_run = self.tasks[:] while (len(to_run) > 0", "= open('/dev/null', 'w') try: cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) jobs = json.loads(cmd_output)", "in task.results and len(task.results['patches']) > 0: task.status = \"PATCHED\" else: task.status = \"DONE\"", "jobs = json.loads(cmd_output) running_ids = [] waiting_ids = [] for job_id in jobs:", "jobs: if jobs[job_id]['state'] == \"Running\": running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id)) for task in self.running: if", "param[\"value\"]) node_cmd = \"python %s\" % node_cmd_args cmd = \"oarsub -l nodes=1,walltime=%s -O", "os.remove(stdout_log) bug_id = task.bug.project if task.bug.bug_id != \"\" and task.bug.bug_id is not None:", "(param[\"separator\"], param[\"parameter\"], param[\"value\"]) node_cmd = \"python %s\" % node_cmd_args cmd = \"oarsub -l", "\"WAITING\" self.waiting.append(task) def execute(self): renderer = get_renderer(self) to_run = self.tasks[:] while (len(to_run) >", "json import os import re import sys from core.runner.RepairTask import RepairTask from core.runner.Runner", "task in self.running: if task.id not in running_ids: self.running.remove(task) task.end_date = time.time() result_path", "to_run = self.tasks[:] while (len(to_run) > 0 or len(self.running) > 0 or len(self.waiting)", "node_cmd) devnull = open('/dev/null', 'w') cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) m =", "of RepairTask \"\"\" super(Grid5kRunner, self).__init__(tasks, args) def get_running(self): cmd = 'oarstat --json -u", "[] for job_id in jobs: if jobs[job_id]['state'] == \"Running\": running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id)) for", "= \"python %s\" % node_cmd_args cmd = \"oarsub -l nodes=1,walltime=%s -O %s -E", "%s\" % node_cmd_args cmd = \"oarsub -l nodes=1,walltime=%s -O %s -E %s \\\"%s\\\"\"", "REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT class Grid5kRunner(Runner): def __init__(self, tasks, args): \"\"\" :type tasks:", "subprocess.CalledProcessError: pass finally: return self.running def start_task(self, task): \"\"\" :param task: :type task:", "0) and not self.is_end_time(): if len(to_run) > 0 and len(self.running) + len(self.waiting) <", "args): \"\"\" :type tasks: list of RepairTask \"\"\" super(Grid5kRunner, self).__init__(tasks, args) def get_running(self):", "0: task.status = \"PATCHED\" else: task.status = \"DONE\" except Exception: task.status = \"ERROR\"", "get_renderer(self) to_run = self.tasks[:] while (len(to_run) > 0 or len(self.running) > 0 or", "not self.is_end_time(): if len(to_run) > 0 and len(self.running) + len(self.waiting) < GRID5K_MAX_NODE: task", "\"oarsub -l nodes=1,walltime=%s -O %s -E %s \\\"%s\\\"\" % ( GRID5K_TIME_OUT, stdout_log, stderr_log,", "GRID5K_MAX_NODE, GRID5K_TIME_OUT class Grid5kRunner(Runner): def __init__(self, tasks, args): \"\"\" :type tasks: list of", "a[1:] if param[0] == '-': param = param[1:] current_parameter = { \"separator\": '-'", "%s\" % ( os.path.join(REPAIR_ROOT, 'script', 'repair.py'), task.tool.name, bug_id ) for param in parameters:", "elif current_parameter is not None: current_parameter['value'] += \" \" + a if current_parameter", "parameters.append(current_parameter) node_cmd_args = \"%s %s --id %s\" % ( os.path.join(REPAIR_ROOT, 'script', 'repair.py'), task.tool.name,", "core.runner.Runner import Runner from core.renderer.renderer import get_renderer from config import REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE,", "'script', 'repair.py'), task.tool.name, bug_id ) for param in parameters: if param[\"parameter\"] == \"i\"", "task.tool.name, str(task.tool.seed)) stdout_log = os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log = os.path.join(log_root_path, 'grid5k.stderr.log') if not os.path.exists(log_root_path):", "json.loads(cmd_output) running_ids = [] waiting_ids = [] for job_id in jobs: if jobs[job_id]['state']", "with open(result_path) as fd: task.results = json.load(fd) if 'patches' in task.results and len(task.results['patches'])", "RepairTask \"\"\" super(Grid5kRunner, self).__init__(tasks, args) def get_running(self): cmd = 'oarstat --json -u `whoami`'", "'grid5k.stdout.log') stderr_log = os.path.join(log_root_path, 'grid5k.stderr.log') if not os.path.exists(log_root_path): os.makedirs(log_root_path) elif os.path.exists(stderr_log): os.remove(stderr_log) if", "sys.argv: if a[0] == '-': if current_parameter is not None: parameters.append(current_parameter) param =", "\" %s%s%s\" % (param[\"separator\"], param[\"parameter\"], param[\"value\"]) node_cmd = \"python %s\" % node_cmd_args cmd", "a[0] == '-': if current_parameter is not None: parameters.append(current_parameter) param = a[1:] if", "= open('/dev/null', 'w') cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) m = re.search('OAR_JOB_ID=([0-9]+)', cmd_output)", "task.tool.name, str(task.tool.seed), \"result.json\") if os.path.exists(result_path): try: with open(result_path) as fd: task.results = json.load(fd)", "subprocess import json import os import re import sys from core.runner.RepairTask import RepairTask", "not in running_ids: self.running.remove(task) task.end_date = time.time() result_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id),", "pass else: task.status = \"ERROR\" self.finished.append(task) for task in self.waiting: if task.id not", "and len(task.results['patches']) > 0: task.status = \"PATCHED\" else: task.status = \"DONE\" except Exception:", "else '--', \"parameter\": param, \"value\": \"\" } elif current_parameter is not None: current_parameter['value']", "\"i\" or param[\"parameter\"] == \"id\": continue node_cmd_args += \" %s%s%s\" % (param[\"separator\"], param[\"parameter\"],", "1 else '--', \"parameter\": param, \"value\": \"\" } elif current_parameter is not None:", "None for a in sys.argv: if a[0] == '-': if current_parameter is not", "\" \" + a if current_parameter is not None: parameters.append(current_parameter) node_cmd_args = \"%s", "running_ids = [] waiting_ids = [] for job_id in jobs: if jobs[job_id]['state'] ==", "\"separator\": '-' if len(param) == 1 else '--', \"parameter\": param, \"value\": \"\" }", "return self.running def start_task(self, task): \"\"\" :param task: :type task: RepairTask :return: \"\"\"", "!= \"\" and task.bug.bug_id is not None: bug_id = \"%s_%s\" % (task.bug.project, task.bug.bug_id)", "stdout_log, stderr_log, node_cmd) devnull = open('/dev/null', 'w') cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull)", "tasks: list of RepairTask \"\"\" super(Grid5kRunner, self).__init__(tasks, args) def get_running(self): cmd = 'oarstat", "os.path.join(REPAIR_ROOT, 'script', 'repair.py'), task.tool.name, bug_id ) for param in parameters: if param[\"parameter\"] ==", "args) def get_running(self): cmd = 'oarstat --json -u `whoami`' devnull = open('/dev/null', 'w')", "as fd: task.results = json.load(fd) if 'patches' in task.results and len(task.results['patches']) > 0:", "= json.loads(cmd_output) running_ids = [] waiting_ids = [] for job_id in jobs: if", "import sys from core.runner.RepairTask import RepairTask from core.runner.Runner import Runner from core.renderer.renderer import", "\"python %s\" % node_cmd_args cmd = \"oarsub -l nodes=1,walltime=%s -O %s -E %s", "-l nodes=1,walltime=%s -O %s -E %s \\\"%s\\\"\" % ( GRID5K_TIME_OUT, stdout_log, stderr_log, node_cmd)", "task.bug.bug_id) parameters = [] current_parameter = None for a in sys.argv: if a[0]", "% node_cmd_args cmd = \"oarsub -l nodes=1,walltime=%s -O %s -E %s \\\"%s\\\"\" %", "param[\"parameter\"] == \"i\" or param[\"parameter\"] == \"id\": continue node_cmd_args += \" %s%s%s\" %", "self.is_end_time(): if len(to_run) > 0 and len(self.running) + len(self.waiting) < GRID5K_MAX_NODE: task =", "node_cmd_args = \"%s %s --id %s\" % ( os.path.join(REPAIR_ROOT, 'script', 'repair.py'), task.tool.name, bug_id", "= os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed), \"result.json\") if os.path.exists(result_path): try: with open(result_path)", "Grid5kRunner(Runner): def __init__(self, tasks, args): \"\"\" :type tasks: list of RepairTask \"\"\" super(Grid5kRunner,", "task: :type task: RepairTask :return: \"\"\" log_root_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name,", ":param task: :type task: RepairTask :return: \"\"\" log_root_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id),", "Runner from core.renderer.renderer import get_renderer from config import REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT class", "'patches' in task.results and len(task.results['patches']) > 0: task.status = \"PATCHED\" else: task.status =", "= self.tasks[:] while (len(to_run) > 0 or len(self.running) > 0 or len(self.waiting) >", "{ \"separator\": '-' if len(param) == 1 else '--', \"parameter\": param, \"value\": \"\"", "if task.id not in running_ids: self.running.remove(task) task.end_date = time.time() result_path = os.path.join(OUTPUT_PATH, task.benchmark.name,", "0 or len(self.running) > 0 or len(self.waiting) > 0) and not self.is_end_time(): if", "\"result.json\") if os.path.exists(result_path): try: with open(result_path) as fd: task.results = json.load(fd) if 'patches'", "stderr_log, node_cmd) devnull = open('/dev/null', 'w') cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) m", "'-' if len(param) == 1 else '--', \"parameter\": param, \"value\": \"\" } elif", "'--', \"parameter\": param, \"value\": \"\" } elif current_parameter is not None: current_parameter['value'] +=", "> 0) and not self.is_end_time(): if len(to_run) > 0 and len(self.running) + len(self.waiting)", "task.status = \"ERROR\" self.finished.append(task) for task in self.waiting: if task.id not in waiting_ids:", "= os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log = os.path.join(log_root_path, 'grid5k.stderr.log') if not os.path.exists(log_root_path): os.makedirs(log_root_path) elif os.path.exists(stderr_log):", "= [] current_parameter = None for a in sys.argv: if a[0] == '-':", "task.results = json.load(fd) if 'patches' in task.results and len(task.results['patches']) > 0: task.status =", "self.finished.append(task) for task in self.waiting: if task.id not in waiting_ids: self.waiting.remove(task) if task.id", "start_task(self, task): \"\"\" :param task: :type task: RepairTask :return: \"\"\" log_root_path = os.path.join(OUTPUT_PATH,", "= os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed)) stdout_log = os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log =", "or len(self.running) > 0 or len(self.waiting) > 0) and not self.is_end_time(): if len(to_run)", "in waiting_ids: self.waiting.remove(task) if task.id in running_ids: task.status = \"STARTED\" task.starting_date = time.time()", "time.time() self.running.append(task) except subprocess.CalledProcessError: pass finally: return self.running def start_task(self, task): \"\"\" :param", "= [] for job_id in jobs: if jobs[job_id]['state'] == \"Running\": running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id))", "0 or len(self.waiting) > 0) and not self.is_end_time(): if len(to_run) > 0 and", "= re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if m: task.id = int(m.group(1)) task.status = \"WAITING\" self.waiting.append(task) def", "cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) jobs = json.loads(cmd_output) running_ids = [] waiting_ids", "len(to_run) > 0 and len(self.running) + len(self.waiting) < GRID5K_MAX_NODE: task = to_run.pop() if", "\"\" and task.bug.bug_id is not None: bug_id = \"%s_%s\" % (task.bug.project, task.bug.bug_id) parameters", "= \"%s_%s\" % (task.bug.project, task.bug.bug_id) parameters = [] current_parameter = None for a", "if m: task.id = int(m.group(1)) task.status = \"WAITING\" self.waiting.append(task) def execute(self): renderer =", "self.waiting: if task.id not in waiting_ids: self.waiting.remove(task) if task.id in running_ids: task.status =", "== \"i\" or param[\"parameter\"] == \"id\": continue node_cmd_args += \" %s%s%s\" % (param[\"separator\"],", "log_root_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed)) stdout_log = os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log", "or len(self.waiting) > 0) and not self.is_end_time(): if len(to_run) > 0 and len(self.running)", "(task.bug.project, task.bug.bug_id) parameters = [] current_parameter = None for a in sys.argv: if", "except Exception: task.status = \"ERROR\" pass else: task.status = \"ERROR\" self.finished.append(task) for task", "= \"%s %s --id %s\" % ( os.path.join(REPAIR_ROOT, 'script', 'repair.py'), task.tool.name, bug_id )", "\"ERROR\" self.finished.append(task) for task in self.waiting: if task.id not in waiting_ids: self.waiting.remove(task) if", "= \"STARTED\" task.starting_date = time.time() self.running.append(task) except subprocess.CalledProcessError: pass finally: return self.running def", "= { \"separator\": '-' if len(param) == 1 else '--', \"parameter\": param, \"value\":", "os.path.join(log_root_path, 'grid5k.stderr.log') if not os.path.exists(log_root_path): os.makedirs(log_root_path) elif os.path.exists(stderr_log): os.remove(stderr_log) if os.path.exists(stdout_log): os.remove(stdout_log) bug_id", "-E %s \\\"%s\\\"\" % ( GRID5K_TIME_OUT, stdout_log, stderr_log, node_cmd) devnull = open('/dev/null', 'w')", "os.path.exists(stderr_log): os.remove(stderr_log) if os.path.exists(stdout_log): os.remove(stdout_log) bug_id = task.bug.project if task.bug.bug_id != \"\" and", "self.tasks[:] while (len(to_run) > 0 or len(self.running) > 0 or len(self.waiting) > 0)", "cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) m = re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if m: task.id", "parameters: if param[\"parameter\"] == \"i\" or param[\"parameter\"] == \"id\": continue node_cmd_args += \"", "shell=True, stdin=None, stderr=devnull) jobs = json.loads(cmd_output) running_ids = [] waiting_ids = [] for", "\" + a if current_parameter is not None: parameters.append(current_parameter) node_cmd_args = \"%s %s", "in running_ids: task.status = \"STARTED\" task.starting_date = time.time() self.running.append(task) except subprocess.CalledProcessError: pass finally:", "\"\" } elif current_parameter is not None: current_parameter['value'] += \" \" + a", "\"STARTED\" task.starting_date = time.time() self.running.append(task) except subprocess.CalledProcessError: pass finally: return self.running def start_task(self,", "for a in sys.argv: if a[0] == '-': if current_parameter is not None:", "== '-': param = param[1:] current_parameter = { \"separator\": '-' if len(param) ==", "def get_running(self): cmd = 'oarstat --json -u `whoami`' devnull = open('/dev/null', 'w') try:", "= None for a in sys.argv: if a[0] == '-': if current_parameter is", "RepairTask from core.runner.Runner import Runner from core.renderer.renderer import get_renderer from config import REPAIR_ROOT,", "== 1 else '--', \"parameter\": param, \"value\": \"\" } elif current_parameter is not", "== \"id\": continue node_cmd_args += \" %s%s%s\" % (param[\"separator\"], param[\"parameter\"], param[\"value\"]) node_cmd =", "re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if m: task.id = int(m.group(1)) task.status = \"WAITING\" self.waiting.append(task) def execute(self):", "class Grid5kRunner(Runner): def __init__(self, tasks, args): \"\"\" :type tasks: list of RepairTask \"\"\"", "not None: parameters.append(current_parameter) node_cmd_args = \"%s %s --id %s\" % ( os.path.join(REPAIR_ROOT, 'script',", "if 'patches' in task.results and len(task.results['patches']) > 0: task.status = \"PATCHED\" else: task.status", "task = to_run.pop() if task.bug is not None: self.start_task(task) time.sleep(1) renderer.render() self.get_running() renderer.render_final_result()", "fd: task.results = json.load(fd) if 'patches' in task.results and len(task.results['patches']) > 0: task.status", "import RepairTask from core.runner.Runner import Runner from core.renderer.renderer import get_renderer from config import", "= os.path.join(log_root_path, 'grid5k.stderr.log') if not os.path.exists(log_root_path): os.makedirs(log_root_path) elif os.path.exists(stderr_log): os.remove(stderr_log) if os.path.exists(stdout_log): os.remove(stdout_log)", "task.status = \"PATCHED\" else: task.status = \"DONE\" except Exception: task.status = \"ERROR\" pass", "> 0 and len(self.running) + len(self.waiting) < GRID5K_MAX_NODE: task = to_run.pop() if task.bug", "is not None: current_parameter['value'] += \" \" + a if current_parameter is not", "len(param) == 1 else '--', \"parameter\": param, \"value\": \"\" } elif current_parameter is", "if len(to_run) > 0 and len(self.running) + len(self.waiting) < GRID5K_MAX_NODE: task = to_run.pop()", "stderr=devnull) jobs = json.loads(cmd_output) running_ids = [] waiting_ids = [] for job_id in", "task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed), \"result.json\") if os.path.exists(result_path): try: with open(result_path) as fd:", "\"parameter\": param, \"value\": \"\" } elif current_parameter is not None: current_parameter['value'] += \"", "int(m.group(1)) task.status = \"WAITING\" self.waiting.append(task) def execute(self): renderer = get_renderer(self) to_run = self.tasks[:]", "node_cmd = \"python %s\" % node_cmd_args cmd = \"oarsub -l nodes=1,walltime=%s -O %s", "stderr=devnull) m = re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if m: task.id = int(m.group(1)) task.status = \"WAITING\"", "len(self.waiting) > 0) and not self.is_end_time(): if len(to_run) > 0 and len(self.running) +", "from core.runner.Runner import Runner from core.renderer.renderer import get_renderer from config import REPAIR_ROOT, OUTPUT_PATH,", "None: bug_id = \"%s_%s\" % (task.bug.project, task.bug.bug_id) parameters = [] current_parameter = None", "in parameters: if param[\"parameter\"] == \"i\" or param[\"parameter\"] == \"id\": continue node_cmd_args +=", "= [] waiting_ids = [] for job_id in jobs: if jobs[job_id]['state'] == \"Running\":", "time import subprocess import json import os import re import sys from core.runner.RepairTask", "= \"ERROR\" self.finished.append(task) for task in self.waiting: if task.id not in waiting_ids: self.waiting.remove(task)", "+= \" %s%s%s\" % (param[\"separator\"], param[\"parameter\"], param[\"value\"]) node_cmd = \"python %s\" % node_cmd_args", "task): \"\"\" :param task: :type task: RepairTask :return: \"\"\" log_root_path = os.path.join(OUTPUT_PATH, task.benchmark.name,", "== \"Running\": running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id)) for task in self.running: if task.id not in", "devnull = open('/dev/null', 'w') try: cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) jobs =", "task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed)) stdout_log = os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log = os.path.join(log_root_path, 'grid5k.stderr.log') if", "GRID5K_MAX_NODE: task = to_run.pop() if task.bug is not None: self.start_task(task) time.sleep(1) renderer.render() self.get_running()", "try: with open(result_path) as fd: task.results = json.load(fd) if 'patches' in task.results and", "GRID5K_TIME_OUT, stdout_log, stderr_log, node_cmd) devnull = open('/dev/null', 'w') cmd_output = subprocess.check_output(cmd, shell=True, stdin=None,", "+= \" \" + a if current_parameter is not None: parameters.append(current_parameter) node_cmd_args =", "[] waiting_ids = [] for job_id in jobs: if jobs[job_id]['state'] == \"Running\": running_ids.append(int(job_id))", "% ( os.path.join(REPAIR_ROOT, 'script', 'repair.py'), task.tool.name, bug_id ) for param in parameters: if", "param[1:] current_parameter = { \"separator\": '-' if len(param) == 1 else '--', \"parameter\":", "( GRID5K_TIME_OUT, stdout_log, stderr_log, node_cmd) devnull = open('/dev/null', 'w') cmd_output = subprocess.check_output(cmd, shell=True,", "config import REPAIR_ROOT, OUTPUT_PATH, GRID5K_MAX_NODE, GRID5K_TIME_OUT class Grid5kRunner(Runner): def __init__(self, tasks, args): \"\"\"", "current_parameter is not None: current_parameter['value'] += \" \" + a if current_parameter is", "current_parameter = None for a in sys.argv: if a[0] == '-': if current_parameter", "\"Running\": running_ids.append(int(job_id)) else: waiting_ids.append(int(job_id)) for task in self.running: if task.id not in running_ids:", "task.bug.bug_id is not None: bug_id = \"%s_%s\" % (task.bug.project, task.bug.bug_id) parameters = []", "self.running.append(task) except subprocess.CalledProcessError: pass finally: return self.running def start_task(self, task): \"\"\" :param task:", "'w') cmd_output = subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) m = re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if m:", "if param[\"parameter\"] == \"i\" or param[\"parameter\"] == \"id\": continue node_cmd_args += \" %s%s%s\"", "} elif current_parameter is not None: current_parameter['value'] += \" \" + a if", "bug_id ) for param in parameters: if param[\"parameter\"] == \"i\" or param[\"parameter\"] ==", "def __init__(self, tasks, args): \"\"\" :type tasks: list of RepairTask \"\"\" super(Grid5kRunner, self).__init__(tasks,", "param in parameters: if param[\"parameter\"] == \"i\" or param[\"parameter\"] == \"id\": continue node_cmd_args", "task in self.waiting: if task.id not in waiting_ids: self.waiting.remove(task) if task.id in running_ids:", "stdout_log = os.path.join(log_root_path, 'grid5k.stdout.log') stderr_log = os.path.join(log_root_path, 'grid5k.stderr.log') if not os.path.exists(log_root_path): os.makedirs(log_root_path) elif", "> 0: task.status = \"PATCHED\" else: task.status = \"DONE\" except Exception: task.status =", "stdin=None, stderr=devnull) m = re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if m: task.id = int(m.group(1)) task.status =", "\"ERROR\" pass else: task.status = \"ERROR\" self.finished.append(task) for task in self.waiting: if task.id", ":type tasks: list of RepairTask \"\"\" super(Grid5kRunner, self).__init__(tasks, args) def get_running(self): cmd =", ":type task: RepairTask :return: \"\"\" log_root_path = os.path.join(OUTPUT_PATH, task.benchmark.name, task.bug.project, str(task.bug.bug_id), task.tool.name, str(task.tool.seed))", "== '-': if current_parameter is not None: parameters.append(current_parameter) param = a[1:] if param[0]", "\"%s %s --id %s\" % ( os.path.join(REPAIR_ROOT, 'script', 'repair.py'), task.tool.name, bug_id ) for", "len(self.running) > 0 or len(self.waiting) > 0) and not self.is_end_time(): if len(to_run) >", "self.running: if task.id not in running_ids: self.running.remove(task) task.end_date = time.time() result_path = os.path.join(OUTPUT_PATH,", "os import re import sys from core.runner.RepairTask import RepairTask from core.runner.Runner import Runner", "is not None: parameters.append(current_parameter) node_cmd_args = \"%s %s --id %s\" % ( os.path.join(REPAIR_ROOT,", "current_parameter is not None: parameters.append(current_parameter) param = a[1:] if param[0] == '-': param", "= subprocess.check_output(cmd, shell=True, stdin=None, stderr=devnull) m = re.search('OAR_JOB_ID=([0-9]+)', cmd_output) if m: task.id =", "\"\"\" super(Grid5kRunner, self).__init__(tasks, args) def get_running(self): cmd = 'oarstat --json -u `whoami`' devnull", "= json.load(fd) if 'patches' in task.results and len(task.results['patches']) > 0: task.status = \"PATCHED\"", "len(self.running) + len(self.waiting) < GRID5K_MAX_NODE: task = to_run.pop() if task.bug is not None:", "import time import subprocess import json import os import re import sys from" ]
[ "\"parameters\": {\"language\": \"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\": 25282}, }, \"java\": {", "40492}, }, \"javascript\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available", "\"ClozeTesting-all\", \"name\": \"java\", \"parameters\": {\"language\": \"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\": 40492},", "https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"ruby\", \"parameters\": {\"language\": \"ruby\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/ruby\", \"sizes\":", "\"dir_name\": \"ClozeTesting-all\", \"name\": \"ruby\", \"parameters\": {\"language\": \"ruby\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/ruby\", \"sizes\": {\"train\":", "\"go\", \"parameters\": {\"language\": \"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\": 25282}, }, \"java\":", "\"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\": 40137}, }, \"ruby\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\":", "\"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"java\", \"parameters\": {\"language\":", "{\"language\": \"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\": 40137}, }, \"ruby\": { \"class_name\":", "{\"train\": 51930}, }, \"python\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset,", "available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"javascript\", \"parameters\": {\"language\": \"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\":", "{\"language\": \"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\": 25282}, }, \"java\": { \"class_name\":", "51930}, }, \"python\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available", "\"php\", \"parameters\": {\"language\": \"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\": 51930}, }, \"python\":", "\"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"java\",", "\"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\": 40492}, }, \"javascript\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE", "\"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"go\", \"parameters\": {\"language\": \"go\"},", "\"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\": 51930}, }, \"python\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\":", "\"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"python\",", "\"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"ruby\", \"parameters\": {\"language\":", "}, \"java\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at", "13837}, }, \"php\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available", "\"ruby\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "\"sizes\": {\"train\": 40137}, }, \"ruby\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all", "= { \"go\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available", "\"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"php\", \"parameters\": {\"language\": \"php\"},", "\"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\": 40137}, }, \"ruby\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\":", "\"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\": 40492}, }, \"javascript\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\":", "\"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\": 40137}, }, \"ruby\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE", "\"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\": 13837}, }, \"php\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\":", "\"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\": 40492}, }, \"javascript\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\":", "\"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"go\",", "\"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\": 25282}, }, \"java\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE", "\"name\": \"go\", \"parameters\": {\"language\": \"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\": 25282}, },", "\"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\": 51930}, }, \"python\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE", "\"name\": \"php\", \"parameters\": {\"language\": \"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\": 51930}, },", "at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"php\", \"parameters\": {\"language\": \"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\",", "dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"python\", \"parameters\": {\"language\": \"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "\"ClozeTesting-all\", \"name\": \"go\", \"parameters\": {\"language\": \"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\": 25282},", "available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"go\", \"parameters\": {\"language\": \"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\":", "at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"java\", \"parameters\": {\"language\": \"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\",", "ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"php\", \"parameters\": {\"language\": \"php\"}, \"project_url\":", "\"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\": 51930}, }, \"python\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\":", "\"python\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "\"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\": 40137}, }, \"ruby\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\",", "\"python\", \"parameters\": {\"language\": \"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\": 40137}, }, \"ruby\":", "\"parameters\": {\"language\": \"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\": 40137}, }, \"ruby\": {", "\"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\": 51930}, }, \"python\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\",", "{ \"go\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at", "https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"python\", \"parameters\": {\"language\": \"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\":", "\"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"javascript\", \"parameters\": {\"language\":", "}, \"python\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at", "https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"java\", \"parameters\": {\"language\": \"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\":", "\"parameters\": {\"language\": \"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\": 51930}, }, \"python\": {", "}, \"ruby\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at", "\"parameters\": {\"language\": \"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\": 40492}, }, \"javascript\": {", "\"dir_name\": \"ClozeTesting-all\", \"name\": \"python\", \"parameters\": {\"language\": \"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\":", "ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"ruby\", \"parameters\": {\"language\": \"ruby\"}, \"project_url\":", "dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"java\", \"parameters\": {\"language\": \"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "\"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\",", "\"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\": 51930}, }, \"python\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\",", "\"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\": 25282}, }, \"java\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\",", "\"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\": 40492}, }, \"javascript\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\",", "\"dir_name\": \"ClozeTesting-all\", \"name\": \"php\", \"parameters\": {\"language\": \"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\":", "\"name\": \"java\", \"parameters\": {\"language\": \"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\": 40492}, },", "\"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\": 25282}, }, \"java\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\":", "available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"python\", \"parameters\": {\"language\": \"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\":", "\"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\": 13837}, }, \"php\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\",", "available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"ruby\", \"parameters\": {\"language\": \"ruby\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\":", "\"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\":", "\"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\": 13837}, }, \"php\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE", "\"javascript\", \"parameters\": {\"language\": \"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\": 13837}, }, \"php\":", "25282}, }, \"java\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available", "\"dir_name\": \"ClozeTesting-all\", \"name\": \"java\", \"parameters\": {\"language\": \"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\":", "at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"javascript\", \"parameters\": {\"language\": \"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\",", "\"ClozeTesting-all\", \"name\": \"python\", \"parameters\": {\"language\": \"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\": 40137},", "\"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\": 25282}, }, \"java\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\":", "dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"go\", \"parameters\": {\"language\": \"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"javascript\", \"parameters\": {\"language\": \"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\":", "dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"php\", \"parameters\": {\"language\": \"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "\"sizes\": {\"train\": 51930}, }, \"python\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all", "\"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"php\", \"parameters\": {\"language\":", "\"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\": 25282}, }, \"java\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\",", "}, \"javascript\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at", "\"parameters\": {\"language\": \"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\": 13837}, }, \"php\": {", "{\"train\": 25282}, }, \"java\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset,", "\"php\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"ruby\", \"parameters\": {\"language\": \"ruby\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/ruby\",", "\"dir_name\": \"ClozeTesting-all\", \"name\": \"go\", \"parameters\": {\"language\": \"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\": {\"train\":", "}, \"php\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at", "40137}, }, \"ruby\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available", "\"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"java\", \"parameters\":", "\"go\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "\"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"go\", \"parameters\":", "at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"go\", \"parameters\": {\"language\": \"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\",", "available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"php\", \"parameters\": {\"language\": \"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\":", "{ \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\":", "\"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"php\",", "\"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\": 40492}, }, \"javascript\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\",", "dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"ruby\", \"parameters\": {\"language\": \"ruby\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "\"sizes\": {\"train\": 13837}, }, \"php\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all", "https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"go\", \"parameters\": {\"language\": \"go\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\", \"sizes\":", "\"name\": \"ruby\", \"parameters\": {\"language\": \"ruby\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/ruby\", \"sizes\": {\"train\": 4437}, },", "ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"python\", \"parameters\": {\"language\": \"python\"}, \"project_url\":", "ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"javascript\", \"parameters\": {\"language\": \"javascript\"}, \"project_url\":", "\"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"go\", \"parameters\": {\"language\":", "\"name\": \"python\", \"parameters\": {\"language\": \"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\": 40137}, },", "\"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\": 13837}, }, \"php\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\",", "{\"language\": \"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\": 13837}, }, \"php\": { \"class_name\":", "\"ClozeTesting-all\", \"name\": \"javascript\", \"parameters\": {\"language\": \"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\": 13837},", "{\"language\": \"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\": 40492}, }, \"javascript\": { \"class_name\":", "\"dir_name\": \"ClozeTesting-all\", \"name\": \"javascript\", \"parameters\": {\"language\": \"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\":", "\"javascript\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "\"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"javascript\", \"parameters\":", "\"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"ruby\", \"parameters\": {\"language\": \"ruby\"},", "{\"language\": \"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\": 51930}, }, \"python\": { \"class_name\":", "\"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"python\", \"parameters\": {\"language\": \"python\"},", "\"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"javascript\", \"parameters\": {\"language\": \"javascript\"},", "\"ruby\", \"parameters\": {\"language\": \"ruby\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/ruby\", \"sizes\": {\"train\": 4437}, }, }", "\"sizes\": {\"train\": 25282}, }, \"java\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all", "available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"java\", \"parameters\": {\"language\": \"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\":", "\"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"java\", \"parameters\": {\"language\": \"java\"},", "\"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"ruby\", \"parameters\":", "\"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"python\", \"parameters\": {\"language\":", "\"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"ruby\",", "\"ClozeTesting-all\", \"name\": \"php\", \"parameters\": {\"language\": \"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\": {\"train\": 51930},", "\"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"python\", \"parameters\":", "DEFINITIONS = { \"go\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset,", "\"java\", \"parameters\": {\"language\": \"java\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\", \"sizes\": {\"train\": 40492}, }, \"javascript\":", "{\"train\": 40492}, }, \"javascript\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset,", "\"name\": \"javascript\", \"parameters\": {\"language\": \"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\": 13837}, },", "dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"javascript\", \"parameters\": {\"language\": \"javascript\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "{\"train\": 40137}, }, \"ruby\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset,", "\"ClozeTesting-all\", \"name\": \"ruby\", \"parameters\": {\"language\": \"ruby\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/ruby\", \"sizes\": {\"train\": 4437},", "\"java\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",", "\"sizes\": {\"train\": 40492}, }, \"javascript\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all", "at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"python\", \"parameters\": {\"language\": \"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\",", "ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"go\", \"parameters\": {\"language\": \"go\"}, \"project_url\":", "{\"train\": 13837}, }, \"php\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset,", "\"python\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\", \"sizes\": {\"train\": 40137}, }, \"ruby\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\",", "\"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"php\", \"parameters\":", "\"dataset_type\": \"Code-Code\", \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"javascript\",", "https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"php\", \"parameters\": {\"language\": \"php\"}, \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\", \"sizes\":", "ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\", \"dir_name\": \"ClozeTesting-all\", \"name\": \"java\", \"parameters\": {\"language\": \"java\"}, \"project_url\":", "\"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\", \"sizes\": {\"train\": 13837}, }, \"php\": { \"class_name\": \"CodeXGlueCcClozeTestingAll\", \"dataset_type\": \"Code-Code\", \"description\":" ]
[ "Hdot # 5. X 13. Xdot # 6. Y 14. Ydot # 7.", "5000, 1: 5000, 2: 2500, 3: 1000, 4: 1000, 5: 1000, 6: 500,", "12. Hdot # 5. X 13. Xdot # 6. Y 14. Ydot #", "Shapefile').CreateDataSource(filename) ogr_lyr = ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('elev', ogr.OFTReal)", "\"\"\"if not os.path.exists(\"WMM.COF\"): raise Exception( \"Coefficient file missing: %s\" % os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\"", "uuid4().hex[:10] # generate geotransform values geotransform = [ lonmin, deg_interval, 0, latmax, 0,", "2), \"Z\":(7, 2) #\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16 }", "line_array = line.split( ) values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize = len(xvalues) rasterysize = len(yvalues)", "print >>proc.stdin, timestart print >>proc.stdin, timeend print >>proc.stdin, time_interval print >>proc.stdin, product_id print", "timeend print >>proc.stdin, time_interval print >>proc.stdin, product_id print >>proc.stdin, output print >>proc.stdin, tempfile", "time timeend = time # time step size time_interval = \"0\" # geomagnetic", "ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0, [], 0,", "\"/tmp/%s\" % uuid4().hex[:10] # generate geotransform values geotransform = [ lonmin, deg_interval, 0,", "#print rasterxsize, rasterysize driver = gdal.GetDriverByName('GTiff') ds = driver.Create( filename, rasterxsize, rasterysize, 1,", "output (1 for file) output = \"1\" # output filename tempfile = \"/tmp/%s\"", "4: 1000, 5: 1000, 6: 500, 7: 500, 8: 100 } } def", "Xdot # 6. Y 14. Ydot # 7. Z 15. Zdot # 8.", "2), \"X\":(5, 2), \"Y\":(6, 2), \"Z\":(7, 2) #\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13,", "nargs=1, type=float) parser.add_argument(\"product\", nargs=1, type=str) parser.add_argument(\"--contour\", action=\"store_true\", default=False) #parser.add_argument(\"interval\", nargs=1, type=float) parsed =", "# height step size (in km) height_interval = 0 # decimal year starting", "geotransform = [ lonmin, deg_interval, 0, latmax, 0, -deg_interval ] wmmxmin = lonmin-deg_interval/2", "WGS-84 Ellipsoid (in km) heightmin = height # height step size (in km)", "1), \"F\":(3, 2), \"H\":(4, 2), \"X\":(5, 2), \"Y\":(6, 2), \"Z\":(7, 2) #\"GV\":{8, #\"Ddot\":{9.,", "time_interval print >>proc.stdin, product_id print >>proc.stdin, output print >>proc.stdin, tempfile print >>proc.stdin status", ">>proc.stdin, wmmxmax print >>proc.stdin, deg_interval print >>proc.stdin, height print >>proc.stdin, heightmax print >>proc.stdin,", "(in km) heightmax = height # Maximum Height above the WGS-84 Ellipsoid (in", "values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize = len(xvalues) rasterysize = len(yvalues) logger.info(\"size %d %d \"", "parser.add_argument(\"pixelsize\", nargs=1, type=int) parser.add_argument(\"height\", nargs=1, type=int) parser.add_argument(\"time\", nargs=1, type=float) parser.add_argument(\"product\", nargs=1, type=str) parser.add_argument(\"--contour\",", "# time step size time_interval = \"0\" # geomagnetic element to print. Your", "parsed.interval[0] \"\"\" zoom = round(deg_interval, 8) contour_steps = iso_intervals[ products[product][1] ][zoomresolution[zoom]] #print \"zoomlevel:", "#!/usr/bin/env python import sys import argparse import os import os.path import subprocess import", "\" %(rasterxsize, rasterysize)) os.remove(tempfile) # create 1d numpy array, reshape to 2d, and", "= lonmin-deg_interval/2 wmmxmax = lonmax+deg_interval/2 wmmymin = latmin-deg_interval/2 wmmymax = latmax+deg_interval/2 print >>proc.stdin,", "(in degrees) per zoom level for EPSG 4326 exe = os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if", "= parsed.interval[0] \"\"\" zoom = round(deg_interval, 8) contour_steps = iso_intervals[ products[product][1] ][zoomresolution[zoom]] #print", ">>proc.stdin, wmmxmin print >>proc.stdin, wmmxmax print >>proc.stdin, deg_interval print >>proc.stdin, height print >>proc.stdin,", "= sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4, type=float) #parser.add_argument(\"resolution\", nargs=1, type=float) parser.add_argument(\"pixelsize\", nargs=1,", "f: for line in f: line_array = line.split( ) values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize", "reshape to 2d, and flip to correct order raster_out = numpy.fromiter(values, \"float32\") raster_2d", "step size (in km) height_interval = 0 # decimal year starting time timestart", "nargs=1, type=str) parser.add_argument(\"--contour\", action=\"store_true\", default=False) #parser.add_argument(\"interval\", nargs=1, type=float) parsed = parser.parse_args(args) main( \"contour.shp\",", "%(rasterxsize, rasterysize)) os.remove(tempfile) # create 1d numpy array, reshape to 2d, and flip", "wmmymin print >>proc.stdin, wmmymax print >>proc.stdin, wmmxmin print >>proc.stdin, wmmxmax print >>proc.stdin, deg_interval", "round(deg_interval, 8) contour_steps = iso_intervals[ products[product][1] ][zoomresolution[zoom]] #print \"zoomlevel: \" + zoomresolution[deg_interval] #print", "print \"STATUS:\", status proc.stdin.close() values = [] xvalues = set() yvalues = set()", "1d numpy array, reshape to 2d, and flip to correct order raster_out =", "wmmxmax print >>proc.stdin, deg_interval print >>proc.stdin, height print >>proc.stdin, heightmax print >>proc.stdin, heightmin", "{ 1:{ 0: 10, 1: 10, 2: 5, 3: 5, 4: 1, 5:", "step size time_interval = \"0\" # geomagnetic element to print. Your options are", "create 1d numpy array, reshape to 2d, and flip to correct order raster_out", "rasterxsize, rasterysize driver = gdal.GetDriverByName('GTiff') ds = driver.Create( filename, rasterxsize, rasterysize, 1, gdal.GDT_Float32", "subprocess.STDOUT, cwd=os.path.dirname(__file__) ) latmin, lonmin, latmax, lonmax = bbox # Step Size (in", "= products[product][0] # select output (1 for file) output = \"1\" # output", "lonmax+deg_interval/2 wmmymin = latmin-deg_interval/2 wmmymax = latmax+deg_interval/2 print >>proc.stdin, wmmymin print >>proc.stdin, wmmymax", "srs = osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return ds #contour_steps = parsed.interval[0] \"\"\" zoom =", "os.path.exists(\"WMM.COF\"): raise Exception( \"Coefficient file missing: %s\" % os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\" proc =", "in f: line_array = line.split( ) values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize = len(xvalues) rasterysize", "proc.stdin.close() values = [] xvalues = set() yvalues = set() with open(tempfile) as", "zoom level for EPSG 4326 exe = os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if not os.path.exists(\"WMM.COF\"): raise", "Ellipsoid (in km) heightmax = height # Maximum Height above the WGS-84 Ellipsoid", "(in km) heightmin = height # height step size (in km) height_interval =", "= height # height step size (in km) height_interval = 0 # decimal", "\"1\" # output filename tempfile = \"/tmp/%s\" % uuid4().hex[:10] # generate geotransform values", "max(raster_out) \"\"\" if __name__ == \"__main__\": args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(\"bbox\",", "driver.Create( filename, rasterxsize, rasterysize, 1, gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs = osr.SpatialReference() srs.ImportFromEPSG(4326)", "import logging logger = logging.getLogger(__name__) zoomresolution = { 0.70312500:0, 0.35156250:1, 0.17578125:2, 0.08789063:3, 0.04394531:4,", "Fdot # 4. H 12. Hdot # 5. X 13. Xdot # 6.", "## resolutions (in degrees) per zoom level for EPSG 4326 exe = os.path.join(os.path.dirname(__file__),", "\"0\" # geomagnetic element to print. Your options are : # 1. Declination", "# clean up from previous runs try: os.remove('contour.shp') except: pass try: os.remove('contour.dbf') except:", "# 3. F 11. Fdot # 4. H 12. Hdot # 5. X", "% os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\" proc = subprocess.Popen( [exe], 1, exe, subprocess.PIPE, open(os.devnull), subprocess.STDOUT,", "\"\"\" if __name__ == \"__main__\": args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4,", "= [] xvalues = set() yvalues = set() with open(tempfile) as f: for", "uuid4 import logging logger = logging.getLogger(__name__) zoomresolution = { 0.70312500:0, 0.35156250:1, 0.17578125:2, 0.08789063:3,", "numpy.fromiter(values, \"float32\") raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape #print rasterxsize, rasterysize driver = gdal.GetDriverByName('GTiff')", "# 5. X 13. Xdot # 6. Y 14. Ydot # 7. Z", "km) heightmin = height # height step size (in km) height_interval = 0", "products[product][1] ][zoomresolution[zoom]] #print \"zoomlevel: \" + zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean up from", "# 7. Z 15. Zdot # 8. GV 16. GVdot product_id = products[product][0]", "iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean up from previous runs try: os.remove('contour.shp') except: pass try: os.remove('contour.dbf')", "values geotransform = [ lonmin, deg_interval, 0, latmax, 0, -deg_interval ] wmmxmin =", "set() with open(tempfile) as f: for line in f: line_array = line.split( )", "10, 2: 5, 3: 5, 4: 1, 5: 1, 6: 0.5, 7: 0.5,", "logging.getLogger(__name__) zoomresolution = { 0.70312500:0, 0.35156250:1, 0.17578125:2, 0.08789063:3, 0.04394531:4, 0.02197266:5, 0.01098633:6, 0.00549316:7, 0.00274658:8,", "wmmymin = latmin-deg_interval/2 wmmymax = latmax+deg_interval/2 print >>proc.stdin, wmmymin print >>proc.stdin, wmmymax print", "6: 500, 7: 500, 8: 100 } } def main(filename, product, bbox, pixelsize,", "decimal degrees) #deg_interval = resolution deg_interval = (latmax-latmin)/pixelsize # Minimum Height above the", "2) #\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16 } iso_intervals =", "wmmxmin = lonmin-deg_interval/2 wmmxmax = lonmax+deg_interval/2 wmmymin = latmin-deg_interval/2 wmmymax = latmax+deg_interval/2 print", "zoom = round(deg_interval, 8) contour_steps = iso_intervals[ products[product][1] ][zoomresolution[zoom]] #print \"zoomlevel: \" +", "\"\"\" zoom = round(deg_interval, 8) contour_steps = iso_intervals[ products[product][1] ][zoomresolution[zoom]] #print \"zoomlevel: \"", "\"F\":(3, 2), \"H\":(4, 2), \"X\":(5, 2), \"Y\":(6, 2), \"Z\":(7, 2) #\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10,", "with open(tempfile) as f: for line in f: line_array = line.split( ) values.append(str(line_array[4]))", ">>proc.stdin, deg_interval print >>proc.stdin, height print >>proc.stdin, heightmax print >>proc.stdin, heightmin print >>proc.stdin,", ">>proc.stdin, time_interval print >>proc.stdin, product_id print >>proc.stdin, output print >>proc.stdin, tempfile print >>proc.stdin", "#\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16 } iso_intervals = { 1:{ 0:", "time # decimal year ending time timeend = time # time step size", "height_interval print >>proc.stdin, timestart print >>proc.stdin, timeend print >>proc.stdin, time_interval print >>proc.stdin, product_id", "Height above the WGS-84 Ellipsoid (in km) heightmin = height # height step", "= set() yvalues = set() with open(tempfile) as f: for line in f:", "resolutions (in degrees) per zoom level for EPSG 4326 exe = os.path.join(os.path.dirname(__file__), 'wmm_grid.exe')", "above the WGS-84 Ellipsoid (in km) heightmin = height # height step size", "2: 5, 3: 5, 4: 1, 5: 1, 6: 0.5, 7: 0.5, 8:", "[ lonmin, deg_interval, 0, latmax, 0, -deg_interval ] wmmxmin = lonmin-deg_interval/2 wmmxmax =", "0.00137329:9, 0.00068665:10 } # product names:(id, iso_interval flavor) products = { \"Decl\":(1, 1),", "main(filename, product, bbox, pixelsize, height, time): # configuration ## resolutions (in degrees) per", "% uuid4().hex[:10] # generate geotransform values geotransform = [ lonmin, deg_interval, 0, latmax,", "Y 14. Ydot # 7. Z 15. Zdot # 8. GV 16. GVdot", "= subprocess.Popen( [exe], 1, exe, subprocess.PIPE, open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__) ) latmin, lonmin, latmax,", "[] xvalues = set() yvalues = set() with open(tempfile) as f: for line", "{ \"Decl\":(1, 1), \"Incl\":(2, 1), \"F\":(3, 2), \"H\":(4, 2), \"X\":(5, 2), \"Y\":(6, 2),", "pass try: os.remove('contour.dbf') except: pass try: os.remove('contour.shx') except: pass ogr_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename)", "to print. Your options are : # 1. Declination 9. Ddot # 2.", "uuid import uuid4 import logging logger = logging.getLogger(__name__) zoomresolution = { 0.70312500:0, 0.35156250:1,", "nargs=1, type=float) parsed = parser.parse_args(args) main( \"contour.shp\", parsed.product[0], parsed.bbox, parsed.pixelsize[0], parsed.height[0], parsed.time[0], parsed.contour", "8. GV 16. GVdot product_id = products[product][0] # select output (1 for file)", "0, latmax, 0, -deg_interval ] wmmxmin = lonmin-deg_interval/2 wmmxmax = lonmax+deg_interval/2 wmmymin =", "2), \"H\":(4, 2), \"X\":(5, 2), \"Y\":(6, 2), \"Z\":(7, 2) #\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11,", "#print min(raster_out), max(raster_out) \"\"\" if __name__ == \"__main__\": args = sys.argv[1:] parser =", "options are : # 1. Declination 9. Ddot # 2. Inclination 10. Idot", "return ds #contour_steps = parsed.interval[0] \"\"\" zoom = round(deg_interval, 8) contour_steps = iso_intervals[", "\"zoomlevel: \" + zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean up from previous runs try:", "timestart print >>proc.stdin, timeend print >>proc.stdin, time_interval print >>proc.stdin, product_id print >>proc.stdin, output", "\"Y\":(6, 2), \"Z\":(7, 2) #\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16", "\"Coefficient file missing: %s\" % os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\" proc = subprocess.Popen( [exe], 1,", "5. X 13. Xdot # 6. Y 14. Ydot # 7. Z 15.", "5: 1, 6: 0.5, 7: 0.5, 8: 0.1 }, 2:{ 0: 5000, 1:", "0, -deg_interval ] wmmxmin = lonmin-deg_interval/2 wmmxmax = lonmax+deg_interval/2 wmmymin = latmin-deg_interval/2 wmmymax", "print >>proc.stdin, wmmxmax print >>proc.stdin, deg_interval print >>proc.stdin, height print >>proc.stdin, heightmax print", "#\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16 } iso_intervals = { 1:{", "= set() with open(tempfile) as f: for line in f: line_array = line.split(", "ogr from uuid import uuid4 import logging logger = logging.getLogger(__name__) zoomresolution = {", "'wmm_grid.exe') \"\"\"if not os.path.exists(\"WMM.COF\"): raise Exception( \"Coefficient file missing: %s\" % os.path.join(os.path.dirname(__file__), \"WMM.COF\")", "\"float32\") raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape #print rasterxsize, rasterysize driver = gdal.GetDriverByName('GTiff') ds", "5: 1000, 6: 500, 7: 500, 8: 100 } } def main(filename, product,", "= ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0, [], 0, 0, ogr_lyr, 0, 1)", "python import sys import argparse import os import os.path import subprocess import numpy", "1, gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return ds #contour_steps", "2:{ 0: 5000, 1: 5000, 2: 2500, 3: 1000, 4: 1000, 5: 1000,", "%d %d \" %(rasterxsize, rasterysize)) os.remove(tempfile) # create 1d numpy array, reshape to", "2d, and flip to correct order raster_out = numpy.fromiter(values, \"float32\") raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize))", "\"X\":(5, 2), \"Y\":(6, 2), \"Z\":(7, 2) #\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14,", ")\"\"\" proc = subprocess.Popen( [exe], 1, exe, subprocess.PIPE, open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__) ) latmin,", "resolution deg_interval = (latmax-latmin)/pixelsize # Minimum Height above the WGS-84 Ellipsoid (in km)", "size time_interval = \"0\" # geomagnetic element to print. Your options are :", "gdal.GetDriverByName('GTiff') ds = driver.Create( filename, rasterxsize, rasterysize, 1, gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs", "osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return ds #contour_steps = parsed.interval[0] \"\"\" zoom = round(deg_interval, 8)", "0.01098633:6, 0.00549316:7, 0.00274658:8, 0.00137329:9, 0.00068665:10 } # product names:(id, iso_interval flavor) products =", "# generate geotransform values geotransform = [ lonmin, deg_interval, 0, latmax, 0, -deg_interval", "ogr_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr = ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn", "heightmax print >>proc.stdin, heightmin print >>proc.stdin, height_interval print >>proc.stdin, timestart print >>proc.stdin, timeend", "runs try: os.remove('contour.shp') except: pass try: os.remove('contour.dbf') except: pass try: os.remove('contour.shx') except: pass", "%s\" % os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\" proc = subprocess.Popen( [exe], 1, exe, subprocess.PIPE, open(os.devnull),", "\"STATUS:\", status proc.stdin.close() values = [] xvalues = set() yvalues = set() with", "1: 5000, 2: 2500, 3: 1000, 4: 1000, 5: 1000, 6: 500, 7:", "year ending time timeend = time # time step size time_interval = \"0\"", "per zoom level for EPSG 4326 exe = os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if not os.path.exists(\"WMM.COF\"):", "Your options are : # 1. Declination 9. Ddot # 2. Inclination 10.", "print >>proc.stdin, timeend print >>proc.stdin, time_interval print >>proc.stdin, product_id print >>proc.stdin, output print", "deg_interval = (latmax-latmin)/pixelsize # Minimum Height above the WGS-84 Ellipsoid (in km) heightmax", "} def main(filename, product, bbox, pixelsize, height, time): # configuration ## resolutions (in", "rasterysize driver = gdal.GetDriverByName('GTiff') ds = driver.Create( filename, rasterxsize, rasterysize, 1, gdal.GDT_Float32 )", "except: pass try: os.remove('contour.shx') except: pass ogr_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr = ogr_ds.CreateLayer('contour')", "status = proc.wait() print \"STATUS:\", status proc.stdin.close() values = [] xvalues = set()", "logging logger = logging.getLogger(__name__) zoomresolution = { 0.70312500:0, 0.35156250:1, 0.17578125:2, 0.08789063:3, 0.04394531:4, 0.02197266:5,", "500, 8: 100 } } def main(filename, product, bbox, pixelsize, height, time): #", "Inclination 10. Idot # 3. F 11. Fdot # 4. H 12. Hdot", "min(raster_out), max(raster_out) \"\"\" if __name__ == \"__main__\": args = sys.argv[1:] parser = argparse.ArgumentParser()", "type=int) parser.add_argument(\"time\", nargs=1, type=float) parser.add_argument(\"product\", nargs=1, type=str) parser.add_argument(\"--contour\", action=\"store_true\", default=False) #parser.add_argument(\"interval\", nargs=1, type=float)", "][zoomresolution[zoom]] #print \"zoomlevel: \" + zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean up from previous", "decimal year starting time timestart = time # decimal year ending time timeend", "type=float) parser.add_argument(\"product\", nargs=1, type=str) parser.add_argument(\"--contour\", action=\"store_true\", default=False) #parser.add_argument(\"interval\", nargs=1, type=float) parsed = parser.parse_args(args)", "= line.split( ) values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize = len(xvalues) rasterysize = len(yvalues) logger.info(\"size", "= bbox # Step Size (in decimal degrees) #deg_interval = resolution deg_interval =", "Exception( \"Coefficient file missing: %s\" % os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\" proc = subprocess.Popen( [exe],", "0.00068665:10 } # product names:(id, iso_interval flavor) products = { \"Decl\":(1, 1), \"Incl\":(2,", "GVdot product_id = products[product][0] # select output (1 for file) output = \"1\"", "4. H 12. Hdot # 5. X 13. Xdot # 6. Y 14.", "ds.SetGeoTransform(geotransform) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return ds #contour_steps = parsed.interval[0] \"\"\" zoom", "= ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0, [],", "wmmymax print >>proc.stdin, wmmxmin print >>proc.stdin, wmmxmax print >>proc.stdin, deg_interval print >>proc.stdin, height", "sys import argparse import os import os.path import subprocess import numpy import gdal", "flip to correct order raster_out = numpy.fromiter(values, \"float32\") raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape", "args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4, type=float) #parser.add_argument(\"resolution\", nargs=1, type=float) parser.add_argument(\"pixelsize\",", "ds #contour_steps = parsed.interval[0] \"\"\" zoom = round(deg_interval, 8) contour_steps = iso_intervals[ products[product][1]", "6. Y 14. Ydot # 7. Z 15. Zdot # 8. GV 16.", "clean up from previous runs try: os.remove('contour.shp') except: pass try: os.remove('contour.dbf') except: pass", "the WGS-84 Ellipsoid (in km) heightmax = height # Maximum Height above the", "import numpy import gdal import osr import ogr from uuid import uuid4 import", "from previous runs try: os.remove('contour.shp') except: pass try: os.remove('contour.dbf') except: pass try: os.remove('contour.shx')", "zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean up from previous runs try: os.remove('contour.shp') except: pass", "1000, 6: 500, 7: 500, 8: 100 } } def main(filename, product, bbox,", "previous runs try: os.remove('contour.shp') except: pass try: os.remove('contour.dbf') except: pass try: os.remove('contour.shx') except:", "latmin-deg_interval/2 wmmymax = latmax+deg_interval/2 print >>proc.stdin, wmmymin print >>proc.stdin, wmmymax print >>proc.stdin, wmmxmin", "= iso_intervals[ products[product][1] ][zoomresolution[zoom]] #print \"zoomlevel: \" + zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean", "os.remove('contour.dbf') except: pass try: os.remove('contour.shx') except: pass ogr_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr =", "gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return ds #contour_steps =", "= len(yvalues) logger.info(\"size %d %d \" %(rasterxsize, rasterysize)) os.remove(tempfile) # create 1d numpy", "height, time): # configuration ## resolutions (in degrees) per zoom level for EPSG", "are : # 1. Declination 9. Ddot # 2. Inclination 10. Idot #", "exe, subprocess.PIPE, open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__) ) latmin, lonmin, latmax, lonmax = bbox #", "tempfile print >>proc.stdin status = proc.wait() print \"STATUS:\", status proc.stdin.close() values = []", "type=int) parser.add_argument(\"height\", nargs=1, type=int) parser.add_argument(\"time\", nargs=1, type=float) parser.add_argument(\"product\", nargs=1, type=str) parser.add_argument(\"--contour\", action=\"store_true\", default=False)", "set() yvalues = set() with open(tempfile) as f: for line in f: line_array", "for EPSG 4326 exe = os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if not os.path.exists(\"WMM.COF\"): raise Exception( \"Coefficient", "# create 1d numpy array, reshape to 2d, and flip to correct order", "print >>proc.stdin, deg_interval print >>proc.stdin, height print >>proc.stdin, heightmax print >>proc.stdin, heightmin print", "# 1. Declination 9. Ddot # 2. Inclination 10. Idot # 3. F", "srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return ds #contour_steps = parsed.interval[0] \"\"\" zoom = round(deg_interval, 8) contour_steps", "bbox # Step Size (in decimal degrees) #deg_interval = resolution deg_interval = (latmax-latmin)/pixelsize", "except: pass try: os.remove('contour.dbf') except: pass try: os.remove('contour.shx') except: pass ogr_ds = ogr.GetDriverByName('ESRI", "= ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1),", "type=str) parser.add_argument(\"--contour\", action=\"store_true\", default=False) #parser.add_argument(\"interval\", nargs=1, type=float) parsed = parser.parse_args(args) main( \"contour.shp\", parsed.product[0],", "EPSG 4326 exe = os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if not os.path.exists(\"WMM.COF\"): raise Exception( \"Coefficient file", "= { 1:{ 0: 10, 1: 10, 2: 5, 3: 5, 4: 1,", "500, 7: 500, 8: 100 } } def main(filename, product, bbox, pixelsize, height,", "numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape #print rasterxsize, rasterysize driver = gdal.GetDriverByName('GTiff') ds = driver.Create( filename,", "# Step Size (in decimal degrees) #deg_interval = resolution deg_interval = (latmax-latmin)/pixelsize #", "print >>proc.stdin, height print >>proc.stdin, heightmax print >>proc.stdin, heightmin print >>proc.stdin, height_interval print", "argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4, type=float) #parser.add_argument(\"resolution\", nargs=1, type=float) parser.add_argument(\"pixelsize\", nargs=1, type=int) parser.add_argument(\"height\", nargs=1, type=int)", "# configuration ## resolutions (in degrees) per zoom level for EPSG 4326 exe", "numpy import gdal import osr import ogr from uuid import uuid4 import logging", "1000, 4: 1000, 5: 1000, 6: 500, 7: 500, 8: 100 } }", ">>proc.stdin, product_id print >>proc.stdin, output print >>proc.stdin, tempfile print >>proc.stdin status = proc.wait()", "= logging.getLogger(__name__) zoomresolution = { 0.70312500:0, 0.35156250:1, 0.17578125:2, 0.08789063:3, 0.04394531:4, 0.02197266:5, 0.01098633:6, 0.00549316:7,", "#deg_interval = resolution deg_interval = (latmax-latmin)/pixelsize # Minimum Height above the WGS-84 Ellipsoid", "generate geotransform values geotransform = [ lonmin, deg_interval, 0, latmax, 0, -deg_interval ]", "1. Declination 9. Ddot # 2. Inclination 10. Idot # 3. F 11.", "zoomresolution = { 0.70312500:0, 0.35156250:1, 0.17578125:2, 0.08789063:3, 0.04394531:4, 0.02197266:5, 0.01098633:6, 0.00549316:7, 0.00274658:8, 0.00137329:9,", "= (latmax-latmin)/pixelsize # Minimum Height above the WGS-84 Ellipsoid (in km) heightmax =", "8: 100 } } def main(filename, product, bbox, pixelsize, height, time): # configuration", "and flip to correct order raster_out = numpy.fromiter(values, \"float32\") raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print", "except: pass ogr_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr = ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn('ID', ogr.OFTInteger)", "logger.info(\"size %d %d \" %(rasterxsize, rasterysize)) os.remove(tempfile) # create 1d numpy array, reshape", "8: 0.1 }, 2:{ 0: 5000, 1: 5000, 2: 2500, 3: 1000, 4:", "7. Z 15. Zdot # 8. GV 16. GVdot product_id = products[product][0] #", "2500, 3: 1000, 4: 1000, 5: 1000, 6: 500, 7: 500, 8: 100", "gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0, [], 0, 0, ogr_lyr, 0, 1) #print min(raster_out), max(raster_out) \"\"\"", "#\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16 } iso_intervals = { 1:{ 0: 10, 1: 10,", "pass try: os.remove('contour.shx') except: pass ogr_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr = ogr_ds.CreateLayer('contour') field_defn", "= { 0.70312500:0, 0.35156250:1, 0.17578125:2, 0.08789063:3, 0.04394531:4, 0.02197266:5, 0.01098633:6, 0.00549316:7, 0.00274658:8, 0.00137329:9, 0.00068665:10", "raster_2d.shape #print rasterxsize, rasterysize driver = gdal.GetDriverByName('GTiff') ds = driver.Create( filename, rasterxsize, rasterysize,", "line.split( ) values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize = len(xvalues) rasterysize = len(yvalues) logger.info(\"size %d", "5, 3: 5, 4: 1, 5: 1, 6: 0.5, 7: 0.5, 8: 0.1", "products = { \"Decl\":(1, 1), \"Incl\":(2, 1), \"F\":(3, 2), \"H\":(4, 2), \"X\":(5, 2),", "driver = gdal.GetDriverByName('GTiff') ds = driver.Create( filename, rasterxsize, rasterysize, 1, gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d)", "type=float) #parser.add_argument(\"resolution\", nargs=1, type=float) parser.add_argument(\"pixelsize\", nargs=1, type=int) parser.add_argument(\"height\", nargs=1, type=int) parser.add_argument(\"time\", nargs=1, type=float)", ">>proc.stdin, wmmymax print >>proc.stdin, wmmxmin print >>proc.stdin, wmmxmax print >>proc.stdin, deg_interval print >>proc.stdin,", "nargs=4, type=float) #parser.add_argument(\"resolution\", nargs=1, type=float) parser.add_argument(\"pixelsize\", nargs=1, type=int) parser.add_argument(\"height\", nargs=1, type=int) parser.add_argument(\"time\", nargs=1,", "lonmax = bbox # Step Size (in decimal degrees) #deg_interval = resolution deg_interval", "parser.add_argument(\"height\", nargs=1, type=int) parser.add_argument(\"time\", nargs=1, type=float) parser.add_argument(\"product\", nargs=1, type=str) parser.add_argument(\"--contour\", action=\"store_true\", default=False) #parser.add_argument(\"interval\",", "print >>proc.stdin, time_interval print >>proc.stdin, product_id print >>proc.stdin, output print >>proc.stdin, tempfile print", "to correct order raster_out = numpy.fromiter(values, \"float32\") raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape #print", "geomagnetic element to print. Your options are : # 1. Declination 9. Ddot", "lonmin, latmax, lonmax = bbox # Step Size (in decimal degrees) #deg_interval =", "degrees) #deg_interval = resolution deg_interval = (latmax-latmin)/pixelsize # Minimum Height above the WGS-84", "= numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape #print rasterxsize, rasterysize driver = gdal.GetDriverByName('GTiff') ds = driver.Create(", "GV 16. GVdot product_id = products[product][0] # select output (1 for file) output", "level for EPSG 4326 exe = os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if not os.path.exists(\"WMM.COF\"): raise Exception(", "#\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16 } iso_intervals = { 1:{ 0: 10, 1:", "= gdal.GetDriverByName('GTiff') ds = driver.Create( filename, rasterxsize, rasterysize, 1, gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform)", "timeend = time # time step size time_interval = \"0\" # geomagnetic element", "# 6. Y 14. Ydot # 7. Z 15. Zdot # 8. GV", "= time # time step size time_interval = \"0\" # geomagnetic element to", "proc = subprocess.Popen( [exe], 1, exe, subprocess.PIPE, open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__) ) latmin, lonmin,", "# 8. GV 16. GVdot product_id = products[product][0] # select output (1 for", "raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape #print rasterxsize, rasterysize driver = gdal.GetDriverByName('GTiff') ds =", "default=False) #parser.add_argument(\"interval\", nargs=1, type=float) parsed = parser.parse_args(args) main( \"contour.shp\", parsed.product[0], parsed.bbox, parsed.pixelsize[0], parsed.height[0],", "ending time timeend = time # time step size time_interval = \"0\" #", "6: 0.5, 7: 0.5, 8: 0.1 }, 2:{ 0: 5000, 1: 5000, 2:", "# select output (1 for file) output = \"1\" # output filename tempfile", "output = \"1\" # output filename tempfile = \"/tmp/%s\" % uuid4().hex[:10] # generate", "-deg_interval ] wmmxmin = lonmin-deg_interval/2 wmmxmax = lonmax+deg_interval/2 wmmymin = latmin-deg_interval/2 wmmymax =", "= ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr = ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn =", "os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if not os.path.exists(\"WMM.COF\"): raise Exception( \"Coefficient file missing: %s\" % os.path.join(os.path.dirname(__file__),", "to 2d, and flip to correct order raster_out = numpy.fromiter(values, \"float32\") raster_2d =", "1:{ 0: 10, 1: 10, 2: 5, 3: 5, 4: 1, 5: 1,", "import sys import argparse import os import os.path import subprocess import numpy import", "= osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return ds #contour_steps = parsed.interval[0] \"\"\" zoom = round(deg_interval,", "0, 1) #print min(raster_out), max(raster_out) \"\"\" if __name__ == \"__main__\": args = sys.argv[1:]", "0: 10, 1: 10, 2: 5, 3: 5, 4: 1, 5: 1, 6:", "\"Incl\":(2, 1), \"F\":(3, 2), \"H\":(4, 2), \"X\":(5, 2), \"Y\":(6, 2), \"Z\":(7, 2) #\"GV\":{8,", "file missing: %s\" % os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\" proc = subprocess.Popen( [exe], 1, exe,", "subprocess.Popen( [exe], 1, exe, subprocess.PIPE, open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__) ) latmin, lonmin, latmax, lonmax", "xvalues = set() yvalues = set() with open(tempfile) as f: for line in", "# output filename tempfile = \"/tmp/%s\" % uuid4().hex[:10] # generate geotransform values geotransform", "print >>proc.stdin, heightmin print >>proc.stdin, height_interval print >>proc.stdin, timestart print >>proc.stdin, timeend print", "= latmin-deg_interval/2 wmmymax = latmax+deg_interval/2 print >>proc.stdin, wmmymin print >>proc.stdin, wmmymax print >>proc.stdin,", "degrees) per zoom level for EPSG 4326 exe = os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if not", ">>proc.stdin, heightmax print >>proc.stdin, heightmin print >>proc.stdin, height_interval print >>proc.stdin, timestart print >>proc.stdin,", "import uuid4 import logging logger = logging.getLogger(__name__) zoomresolution = { 0.70312500:0, 0.35156250:1, 0.17578125:2,", "# Maximum Height above the WGS-84 Ellipsoid (in km) heightmin = height #", ">>proc.stdin, output print >>proc.stdin, tempfile print >>proc.stdin status = proc.wait() print \"STATUS:\", status", "1: 10, 2: 5, 3: 5, 4: 1, 5: 1, 6: 0.5, 7:", "product, bbox, pixelsize, height, time): # configuration ## resolutions (in degrees) per zoom", "import gdal import osr import ogr from uuid import uuid4 import logging logger", "open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__) ) latmin, lonmin, latmax, lonmax = bbox # Step Size", "deg_interval, 0, latmax, 0, -deg_interval ] wmmxmin = lonmin-deg_interval/2 wmmxmax = lonmax+deg_interval/2 wmmymin", "not os.path.exists(\"WMM.COF\"): raise Exception( \"Coefficient file missing: %s\" % os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\" proc", "bbox, pixelsize, height, time): # configuration ## resolutions (in degrees) per zoom level", "latmax, lonmax = bbox # Step Size (in decimal degrees) #deg_interval = resolution", "configuration ## resolutions (in degrees) per zoom level for EPSG 4326 exe =", ": # 1. Declination 9. Ddot # 2. Inclination 10. Idot # 3.", "print >>proc.stdin, wmmymax print >>proc.stdin, wmmxmin print >>proc.stdin, wmmxmax print >>proc.stdin, deg_interval print", "ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return ds #contour_steps = parsed.interval[0] \"\"\"", "contour_steps = iso_intervals[ products[product][1] ][zoomresolution[zoom]] #print \"zoomlevel: \" + zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] #", ") latmin, lonmin, latmax, lonmax = bbox # Step Size (in decimal degrees)", "os.remove(tempfile) # create 1d numpy array, reshape to 2d, and flip to correct", "= lonmax+deg_interval/2 wmmymin = latmin-deg_interval/2 wmmymax = latmax+deg_interval/2 print >>proc.stdin, wmmymin print >>proc.stdin,", "from uuid import uuid4 import logging logger = logging.getLogger(__name__) zoomresolution = { 0.70312500:0,", "the WGS-84 Ellipsoid (in km) heightmin = height # height step size (in", "time step size time_interval = \"0\" # geomagnetic element to print. Your options", "height # height step size (in km) height_interval = 0 # decimal year", "#parser.add_argument(\"resolution\", nargs=1, type=float) parser.add_argument(\"pixelsize\", nargs=1, type=int) parser.add_argument(\"height\", nargs=1, type=int) parser.add_argument(\"time\", nargs=1, type=float) parser.add_argument(\"product\",", "ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0, [], 0, 0, ogr_lyr, 0, 1) #print min(raster_out), max(raster_out)", "#\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16 } iso_intervals = { 1:{ 0: 10, 1: 10, 2:", "3: 1000, 4: 1000, 5: 1000, 6: 500, 7: 500, 8: 100 }", ">>proc.stdin, timestart print >>proc.stdin, timeend print >>proc.stdin, time_interval print >>proc.stdin, product_id print >>proc.stdin,", "(in decimal degrees) #deg_interval = resolution deg_interval = (latmax-latmin)/pixelsize # Minimum Height above", "14. Ydot # 7. Z 15. Zdot # 8. GV 16. GVdot product_id", "heightmin print >>proc.stdin, height_interval print >>proc.stdin, timestart print >>proc.stdin, timeend print >>proc.stdin, time_interval", "raise Exception( \"Coefficient file missing: %s\" % os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\" proc = subprocess.Popen(", "xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize = len(xvalues) rasterysize = len(yvalues) logger.info(\"size %d %d \" %(rasterxsize,", "16. GVdot product_id = products[product][0] # select output (1 for file) output =", "for file) output = \"1\" # output filename tempfile = \"/tmp/%s\" % uuid4().hex[:10]", "time): # configuration ## resolutions (in degrees) per zoom level for EPSG 4326", "15. Zdot # 8. GV 16. GVdot product_id = products[product][0] # select output", "print >>proc.stdin, product_id print >>proc.stdin, output print >>proc.stdin, tempfile print >>proc.stdin status =", "contour_steps, 0, [], 0, 0, ogr_lyr, 0, 1) #print min(raster_out), max(raster_out) \"\"\" if", "try: os.remove('contour.shp') except: pass try: os.remove('contour.dbf') except: pass try: os.remove('contour.shx') except: pass ogr_ds", "ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0, [], 0, 0, ogr_lyr, 0, 1) #print", "0: 5000, 1: 5000, 2: 2500, 3: 1000, 4: 1000, 5: 1000, 6:", "= time # decimal year ending time timeend = time # time step", "deg_interval print >>proc.stdin, height print >>proc.stdin, heightmax print >>proc.stdin, heightmin print >>proc.stdin, height_interval", "%d \" %(rasterxsize, rasterysize)) os.remove(tempfile) # create 1d numpy array, reshape to 2d,", "array, reshape to 2d, and flip to correct order raster_out = numpy.fromiter(values, \"float32\")", "= argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4, type=float) #parser.add_argument(\"resolution\", nargs=1, type=float) parser.add_argument(\"pixelsize\", nargs=1, type=int) parser.add_argument(\"height\", nargs=1,", "pixelsize, height, time): # configuration ## resolutions (in degrees) per zoom level for", "subprocess import numpy import gdal import osr import ogr from uuid import uuid4", "wmmxmax = lonmax+deg_interval/2 wmmymin = latmin-deg_interval/2 wmmymax = latmax+deg_interval/2 print >>proc.stdin, wmmymin print", "product names:(id, iso_interval flavor) products = { \"Decl\":(1, 1), \"Incl\":(2, 1), \"F\":(3, 2),", "Step Size (in decimal degrees) #deg_interval = resolution deg_interval = (latmax-latmin)/pixelsize # Minimum", "4326 exe = os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if not os.path.exists(\"WMM.COF\"): raise Exception( \"Coefficient file missing:", "= 0 # decimal year starting time timestart = time # decimal year", "# decimal year ending time timeend = time # time step size time_interval", "= \"1\" # output filename tempfile = \"/tmp/%s\" % uuid4().hex[:10] # generate geotransform", "#print \"zoomlevel: \" + zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean up from previous runs", "0 # decimal year starting time timestart = time # decimal year ending", "5, 4: 1, 5: 1, 6: 0.5, 7: 0.5, 8: 0.1 }, 2:{", "= driver.Create( filename, rasterxsize, rasterysize, 1, gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs = osr.SpatialReference()", "proc.wait() print \"STATUS:\", status proc.stdin.close() values = [] xvalues = set() yvalues =", "km) heightmax = height # Maximum Height above the WGS-84 Ellipsoid (in km)", "#\"GVdot\":{16 } iso_intervals = { 1:{ 0: 10, 1: 10, 2: 5, 3:", "3: 5, 4: 1, 5: 1, 6: 0.5, 7: 0.5, 8: 0.1 },", "1) #print min(raster_out), max(raster_out) \"\"\" if __name__ == \"__main__\": args = sys.argv[1:] parser", "7: 0.5, 8: 0.1 }, 2:{ 0: 5000, 1: 5000, 2: 2500, 3:", "import subprocess import numpy import gdal import osr import ogr from uuid import", "\" + zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean up from previous runs try: os.remove('contour.shp')", "WGS-84 Ellipsoid (in km) heightmax = height # Maximum Height above the WGS-84", "\"Z\":(7, 2) #\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16 } iso_intervals", "0.1 }, 2:{ 0: 5000, 1: 5000, 2: 2500, 3: 1000, 4: 1000,", "5000, 2: 2500, 3: 1000, 4: 1000, 5: 1000, 6: 500, 7: 500,", "= { \"Decl\":(1, 1), \"Incl\":(2, 1), \"F\":(3, 2), \"H\":(4, 2), \"X\":(5, 2), \"Y\":(6,", "Ydot # 7. Z 15. Zdot # 8. GV 16. GVdot product_id =", "== \"__main__\": args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4, type=float) #parser.add_argument(\"resolution\", nargs=1,", "Minimum Height above the WGS-84 Ellipsoid (in km) heightmax = height # Maximum", "cwd=os.path.dirname(__file__) ) latmin, lonmin, latmax, lonmax = bbox # Step Size (in decimal", "km) height_interval = 0 # decimal year starting time timestart = time #", "2), \"Y\":(6, 2), \"Z\":(7, 2) #\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15,", "= latmax+deg_interval/2 print >>proc.stdin, wmmymin print >>proc.stdin, wmmymax print >>proc.stdin, wmmxmin print >>proc.stdin,", "\"__main__\": args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4, type=float) #parser.add_argument(\"resolution\", nargs=1, type=float)", "} # product names:(id, iso_interval flavor) products = { \"Decl\":(1, 1), \"Incl\":(2, 1),", "height_interval = 0 # decimal year starting time timestart = time # decimal", "} } def main(filename, product, bbox, pixelsize, height, time): # configuration ## resolutions", ">>proc.stdin, tempfile print >>proc.stdin status = proc.wait() print \"STATUS:\", status proc.stdin.close() values =", "wmmymax = latmax+deg_interval/2 print >>proc.stdin, wmmymin print >>proc.stdin, wmmymax print >>proc.stdin, wmmxmin print", "year starting time timestart = time # decimal year ending time timeend =", "0.02197266:5, 0.01098633:6, 0.00549316:7, 0.00274658:8, 0.00137329:9, 0.00068665:10 } # product names:(id, iso_interval flavor) products", "nargs=1, type=int) parser.add_argument(\"time\", nargs=1, type=float) parser.add_argument(\"product\", nargs=1, type=str) parser.add_argument(\"--contour\", action=\"store_true\", default=False) #parser.add_argument(\"interval\", nargs=1,", "= [ lonmin, deg_interval, 0, latmax, 0, -deg_interval ] wmmxmin = lonmin-deg_interval/2 wmmxmax", "height step size (in km) height_interval = 0 # decimal year starting time", "latmax+deg_interval/2 print >>proc.stdin, wmmymin print >>proc.stdin, wmmymax print >>proc.stdin, wmmxmin print >>proc.stdin, wmmxmax", "1, exe, subprocess.PIPE, open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__) ) latmin, lonmin, latmax, lonmax = bbox", ">>proc.stdin, heightmin print >>proc.stdin, height_interval print >>proc.stdin, timestart print >>proc.stdin, timeend print >>proc.stdin,", "#print raster_2d.shape #print rasterxsize, rasterysize driver = gdal.GetDriverByName('GTiff') ds = driver.Create( filename, rasterxsize,", "parser.add_argument(\"--contour\", action=\"store_true\", default=False) #parser.add_argument(\"interval\", nargs=1, type=float) parsed = parser.parse_args(args) main( \"contour.shp\", parsed.product[0], parsed.bbox,", "os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\" proc = subprocess.Popen( [exe], 1, exe, subprocess.PIPE, open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__)", "timestart = time # decimal year ending time timeend = time # time", "F 11. Fdot # 4. H 12. Hdot # 5. X 13. Xdot", ">>proc.stdin, height_interval print >>proc.stdin, timestart print >>proc.stdin, timeend print >>proc.stdin, time_interval print >>proc.stdin,", "0.00549316:7, 0.00274658:8, 0.00137329:9, 0.00068665:10 } # product names:(id, iso_interval flavor) products = {", "latmax, 0, -deg_interval ] wmmxmin = lonmin-deg_interval/2 wmmxmax = lonmax+deg_interval/2 wmmymin = latmin-deg_interval/2", "rasterysize)) os.remove(tempfile) # create 1d numpy array, reshape to 2d, and flip to", "iso_intervals = { 1:{ 0: 10, 1: 10, 2: 5, 3: 5, 4:", "logger = logging.getLogger(__name__) zoomresolution = { 0.70312500:0, 0.35156250:1, 0.17578125:2, 0.08789063:3, 0.04394531:4, 0.02197266:5, 0.01098633:6,", "0.70312500:0, 0.35156250:1, 0.17578125:2, 0.08789063:3, 0.04394531:4, 0.02197266:5, 0.01098633:6, 0.00549316:7, 0.00274658:8, 0.00137329:9, 0.00068665:10 } #", "yvalues.add(str(line_array[0])) rasterxsize = len(xvalues) rasterysize = len(yvalues) logger.info(\"size %d %d \" %(rasterxsize, rasterysize))", "8) contour_steps = iso_intervals[ products[product][1] ][zoomresolution[zoom]] #print \"zoomlevel: \" + zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]]", "# product names:(id, iso_interval flavor) products = { \"Decl\":(1, 1), \"Incl\":(2, 1), \"F\":(3,", "100 } } def main(filename, product, bbox, pixelsize, height, time): # configuration ##", "decimal year ending time timeend = time # time step size time_interval =", "0, 0, ogr_lyr, 0, 1) #print min(raster_out), max(raster_out) \"\"\" if __name__ == \"__main__\":", "select output (1 for file) output = \"1\" # output filename tempfile =", "{ 0.70312500:0, 0.35156250:1, 0.17578125:2, 0.08789063:3, 0.04394531:4, 0.02197266:5, 0.01098633:6, 0.00549316:7, 0.00274658:8, 0.00137329:9, 0.00068665:10 }", "print >>proc.stdin, output print >>proc.stdin, tempfile print >>proc.stdin status = proc.wait() print \"STATUS:\",", "size (in km) height_interval = 0 # decimal year starting time timestart =", "os.remove('contour.shp') except: pass try: os.remove('contour.dbf') except: pass try: os.remove('contour.shx') except: pass ogr_ds =", "] wmmxmin = lonmin-deg_interval/2 wmmxmax = lonmax+deg_interval/2 wmmymin = latmin-deg_interval/2 wmmymax = latmax+deg_interval/2", "ds.SetProjection(srs.ExportToWkt()) return ds #contour_steps = parsed.interval[0] \"\"\" zoom = round(deg_interval, 8) contour_steps =", "parser = argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4, type=float) #parser.add_argument(\"resolution\", nargs=1, type=float) parser.add_argument(\"pixelsize\", nargs=1, type=int) parser.add_argument(\"height\",", "ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr = ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('elev',", "0.00274658:8, 0.00137329:9, 0.00068665:10 } # product names:(id, iso_interval flavor) products = { \"Decl\":(1,", "import os.path import subprocess import numpy import gdal import osr import ogr from", "output filename tempfile = \"/tmp/%s\" % uuid4().hex[:10] # generate geotransform values geotransform =", "import ogr from uuid import uuid4 import logging logger = logging.getLogger(__name__) zoomresolution =", "import argparse import os import os.path import subprocess import numpy import gdal import", "os.remove('contour.shx') except: pass ogr_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr = ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn('ID',", "parser.add_argument(\"time\", nargs=1, type=float) parser.add_argument(\"product\", nargs=1, type=str) parser.add_argument(\"--contour\", action=\"store_true\", default=False) #parser.add_argument(\"interval\", nargs=1, type=float) parsed", "nargs=1, type=float) parser.add_argument(\"pixelsize\", nargs=1, type=int) parser.add_argument(\"height\", nargs=1, type=int) parser.add_argument(\"time\", nargs=1, type=float) parser.add_argument(\"product\", nargs=1,", "print >>proc.stdin, wmmymin print >>proc.stdin, wmmymax print >>proc.stdin, wmmxmin print >>proc.stdin, wmmxmax print", "subprocess.PIPE, open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__) ) latmin, lonmin, latmax, lonmax = bbox # Step", "# Minimum Height above the WGS-84 Ellipsoid (in km) heightmax = height #", "= round(deg_interval, 8) contour_steps = iso_intervals[ products[product][1] ][zoomresolution[zoom]] #print \"zoomlevel: \" + zoomresolution[deg_interval]", ">>proc.stdin status = proc.wait() print \"STATUS:\", status proc.stdin.close() values = [] xvalues =", "print >>proc.stdin status = proc.wait() print \"STATUS:\", status proc.stdin.close() values = [] xvalues", "= proc.wait() print \"STATUS:\", status proc.stdin.close() values = [] xvalues = set() yvalues", "1, 6: 0.5, 7: 0.5, 8: 0.1 }, 2:{ 0: 5000, 1: 5000,", ">>proc.stdin, wmmymin print >>proc.stdin, wmmymax print >>proc.stdin, wmmxmin print >>proc.stdin, wmmxmax print >>proc.stdin,", "product_id = products[product][0] # select output (1 for file) output = \"1\" #", "as f: for line in f: line_array = line.split( ) values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0]))", "latmin, lonmin, latmax, lonmax = bbox # Step Size (in decimal degrees) #deg_interval", "element to print. Your options are : # 1. Declination 9. Ddot #", "ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps,", "nargs=1, type=int) parser.add_argument(\"height\", nargs=1, type=int) parser.add_argument(\"time\", nargs=1, type=float) parser.add_argument(\"product\", nargs=1, type=str) parser.add_argument(\"--contour\", action=\"store_true\",", "starting time timestart = time # decimal year ending time timeend = time", "field_defn = ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0,", "heightmax = height # Maximum Height above the WGS-84 Ellipsoid (in km) heightmin", "file) output = \"1\" # output filename tempfile = \"/tmp/%s\" % uuid4().hex[:10] #", "open(tempfile) as f: for line in f: line_array = line.split( ) values.append(str(line_array[4])) xvalues.add(str(line_array[1]))", "+ zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean up from previous runs try: os.remove('contour.shp') except:", "sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4, type=float) #parser.add_argument(\"resolution\", nargs=1, type=float) parser.add_argument(\"pixelsize\", nargs=1, type=int)", "Ddot # 2. Inclination 10. Idot # 3. F 11. Fdot # 4.", "print >>proc.stdin, height_interval print >>proc.stdin, timestart print >>proc.stdin, timeend print >>proc.stdin, time_interval print", "X 13. Xdot # 6. Y 14. Ydot # 7. Z 15. Zdot", "= len(xvalues) rasterysize = len(yvalues) logger.info(\"size %d %d \" %(rasterxsize, rasterysize)) os.remove(tempfile) #", "type=float) parsed = parser.parse_args(args) main( \"contour.shp\", parsed.product[0], parsed.bbox, parsed.pixelsize[0], parsed.height[0], parsed.time[0], parsed.contour )", "ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0, [], 0, 0, ogr_lyr, 0, 1) #print min(raster_out),", "9. Ddot # 2. Inclination 10. Idot # 3. F 11. Fdot #", "status proc.stdin.close() values = [] xvalues = set() yvalues = set() with open(tempfile)", "product_id print >>proc.stdin, output print >>proc.stdin, tempfile print >>proc.stdin status = proc.wait() print", "raster_out = numpy.fromiter(values, \"float32\") raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape #print rasterxsize, rasterysize driver", "0.08789063:3, 0.04394531:4, 0.02197266:5, 0.01098633:6, 0.00549316:7, 0.00274658:8, 0.00137329:9, 0.00068665:10 } # product names:(id, iso_interval", "#\"Zdot\":{15, #\"GVdot\":{16 } iso_intervals = { 1:{ 0: 10, 1: 10, 2: 5,", "ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0, [], 0, 0,", "Zdot # 8. GV 16. GVdot product_id = products[product][0] # select output (1", "len(xvalues) rasterysize = len(yvalues) logger.info(\"size %d %d \" %(rasterxsize, rasterysize)) os.remove(tempfile) # create", "exe = os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if not os.path.exists(\"WMM.COF\"): raise Exception( \"Coefficient file missing: %s\"", "heightmin = height # height step size (in km) height_interval = 0 #", "above the WGS-84 Ellipsoid (in km) heightmax = height # Maximum Height above", "rasterxsize = len(xvalues) rasterysize = len(yvalues) logger.info(\"size %d %d \" %(rasterxsize, rasterysize)) os.remove(tempfile)", ") ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return ds #contour_steps = parsed.interval[0]", "try: os.remove('contour.shx') except: pass ogr_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr = ogr_ds.CreateLayer('contour') field_defn =", "(1 for file) output = \"1\" # output filename tempfile = \"/tmp/%s\" %", "ogr_lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0, [], 0, 0, ogr_lyr,", "(latmax-latmin)/pixelsize # Minimum Height above the WGS-84 Ellipsoid (in km) heightmax = height", "\"Decl\":(1, 1), \"Incl\":(2, 1), \"F\":(3, 2), \"H\":(4, 2), \"X\":(5, 2), \"Y\":(6, 2), \"Z\":(7,", "# 2. Inclination 10. Idot # 3. F 11. Fdot # 4. H", "iso_intervals[ products[product][1] ][zoomresolution[zoom]] #print \"zoomlevel: \" + zoomresolution[deg_interval] #print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean up", "\"WMM.COF\") )\"\"\" proc = subprocess.Popen( [exe], 1, exe, subprocess.PIPE, open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__) )", "10. Idot # 3. F 11. Fdot # 4. H 12. Hdot #", "products[product][0] # select output (1 for file) output = \"1\" # output filename", "7: 500, 8: 100 } } def main(filename, product, bbox, pixelsize, height, time):", "missing: %s\" % os.path.join(os.path.dirname(__file__), \"WMM.COF\") )\"\"\" proc = subprocess.Popen( [exe], 1, exe, subprocess.PIPE,", "names:(id, iso_interval flavor) products = { \"Decl\":(1, 1), \"Incl\":(2, 1), \"F\":(3, 2), \"H\":(4,", "print >>proc.stdin, tempfile print >>proc.stdin status = proc.wait() print \"STATUS:\", status proc.stdin.close() values", "lonmin-deg_interval/2 wmmxmax = lonmax+deg_interval/2 wmmymin = latmin-deg_interval/2 wmmymax = latmax+deg_interval/2 print >>proc.stdin, wmmymin", "} iso_intervals = { 1:{ 0: 10, 1: 10, 2: 5, 3: 5,", "geotransform values geotransform = [ lonmin, deg_interval, 0, latmax, 0, -deg_interval ] wmmxmin", "parser.add_argument(\"product\", nargs=1, type=str) parser.add_argument(\"--contour\", action=\"store_true\", default=False) #parser.add_argument(\"interval\", nargs=1, type=float) parsed = parser.parse_args(args) main(", "action=\"store_true\", default=False) #parser.add_argument(\"interval\", nargs=1, type=float) parsed = parser.parse_args(args) main( \"contour.shp\", parsed.product[0], parsed.bbox, parsed.pixelsize[0],", "0.5, 8: 0.1 }, 2:{ 0: 5000, 1: 5000, 2: 2500, 3: 1000,", "= numpy.fromiter(values, \"float32\") raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape #print rasterxsize, rasterysize driver =", "Idot # 3. F 11. Fdot # 4. H 12. Hdot # 5.", "= \"0\" # geomagnetic element to print. Your options are : # 1.", "tempfile = \"/tmp/%s\" % uuid4().hex[:10] # generate geotransform values geotransform = [ lonmin,", "lonmin, deg_interval, 0, latmax, 0, -deg_interval ] wmmxmin = lonmin-deg_interval/2 wmmxmax = lonmax+deg_interval/2", "Maximum Height above the WGS-84 Ellipsoid (in km) heightmin = height # height", "#print iso_intervals[products[parsed.product[0]][1]][zoomresolution[deg_interval]] # clean up from previous runs try: os.remove('contour.shp') except: pass try:", "#contour_steps = parsed.interval[0] \"\"\" zoom = round(deg_interval, 8) contour_steps = iso_intervals[ products[product][1] ][zoomresolution[zoom]]", "parser.add_argument(\"bbox\", nargs=4, type=float) #parser.add_argument(\"resolution\", nargs=1, type=float) parser.add_argument(\"pixelsize\", nargs=1, type=int) parser.add_argument(\"height\", nargs=1, type=int) parser.add_argument(\"time\",", "1), \"Incl\":(2, 1), \"F\":(3, 2), \"H\":(4, 2), \"X\":(5, 2), \"Y\":(6, 2), \"Z\":(7, 2)", "(in km) height_interval = 0 # decimal year starting time timestart = time", "gdal import osr import ogr from uuid import uuid4 import logging logger =", "}, 2:{ 0: 5000, 1: 5000, 2: 2500, 3: 1000, 4: 1000, 5:", "0, [], 0, 0, ogr_lyr, 0, 1) #print min(raster_out), max(raster_out) \"\"\" if __name__", "= \"/tmp/%s\" % uuid4().hex[:10] # generate geotransform values geotransform = [ lonmin, deg_interval,", "wmmxmin print >>proc.stdin, wmmxmax print >>proc.stdin, deg_interval print >>proc.stdin, height print >>proc.stdin, heightmax", "Height above the WGS-84 Ellipsoid (in km) heightmax = height # Maximum Height", "4: 1, 5: 1, 6: 0.5, 7: 0.5, 8: 0.1 }, 2:{ 0:", "11. Fdot # 4. H 12. Hdot # 5. X 13. Xdot #", "\"H\":(4, 2), \"X\":(5, 2), \"Y\":(6, 2), \"Z\":(7, 2) #\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12,", "os import os.path import subprocess import numpy import gdal import osr import ogr", "def main(filename, product, bbox, pixelsize, height, time): # configuration ## resolutions (in degrees)", "values = [] xvalues = set() yvalues = set() with open(tempfile) as f:", "correct order raster_out = numpy.fromiter(values, \"float32\") raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape #print rasterxsize,", "= height # Maximum Height above the WGS-84 Ellipsoid (in km) heightmin =", "0.35156250:1, 0.17578125:2, 0.08789063:3, 0.04394531:4, 0.02197266:5, 0.01098633:6, 0.00549316:7, 0.00274658:8, 0.00137329:9, 0.00068665:10 } # product", "1000, 5: 1000, 6: 500, 7: 500, 8: 100 } } def main(filename,", "10, 1: 10, 2: 5, 3: 5, 4: 1, 5: 1, 6: 0.5,", "0.5, 7: 0.5, 8: 0.1 }, 2:{ 0: 5000, 1: 5000, 2: 2500,", "iso_interval flavor) products = { \"Decl\":(1, 1), \"Incl\":(2, 1), \"F\":(3, 2), \"H\":(4, 2),", "yvalues = set() with open(tempfile) as f: for line in f: line_array =", "type=float) parser.add_argument(\"pixelsize\", nargs=1, type=int) parser.add_argument(\"height\", nargs=1, type=int) parser.add_argument(\"time\", nargs=1, type=float) parser.add_argument(\"product\", nargs=1, type=str)", "0.17578125:2, 0.08789063:3, 0.04394531:4, 0.02197266:5, 0.01098633:6, 0.00549316:7, 0.00274658:8, 0.00137329:9, 0.00068665:10 } # product names:(id,", "1, 5: 1, 6: 0.5, 7: 0.5, 8: 0.1 }, 2:{ 0: 5000,", "os.path import subprocess import numpy import gdal import osr import ogr from uuid", "Z 15. Zdot # 8. GV 16. GVdot product_id = products[product][0] # select", "f: line_array = line.split( ) values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize = len(xvalues) rasterysize =", ">>proc.stdin, timeend print >>proc.stdin, time_interval print >>proc.stdin, product_id print >>proc.stdin, output print >>proc.stdin,", ") values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize = len(xvalues) rasterysize = len(yvalues) logger.info(\"size %d %d", "pass ogr_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr = ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn)", "# geomagnetic element to print. Your options are : # 1. Declination 9.", "print. Your options are : # 1. Declination 9. Ddot # 2. Inclination", "[], 0, 0, ogr_lyr, 0, 1) #print min(raster_out), max(raster_out) \"\"\" if __name__ ==", "height print >>proc.stdin, heightmax print >>proc.stdin, heightmin print >>proc.stdin, height_interval print >>proc.stdin, timestart", "for line in f: line_array = line.split( ) values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize =", "#parser.add_argument(\"interval\", nargs=1, type=float) parsed = parser.parse_args(args) main( \"contour.shp\", parsed.product[0], parsed.bbox, parsed.pixelsize[0], parsed.height[0], parsed.time[0],", "import osr import ogr from uuid import uuid4 import logging logger = logging.getLogger(__name__)", "ds = driver.Create( filename, rasterxsize, rasterysize, 1, gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs =", "Ellipsoid (in km) heightmin = height # height step size (in km) height_interval", "print >>proc.stdin, wmmxmin print >>proc.stdin, wmmxmax print >>proc.stdin, deg_interval print >>proc.stdin, height print", "0.04394531:4, 0.02197266:5, 0.01098633:6, 0.00549316:7, 0.00274658:8, 0.00137329:9, 0.00068665:10 } # product names:(id, iso_interval flavor)", "0, ogr_lyr, 0, 1) #print min(raster_out), max(raster_out) \"\"\" if __name__ == \"__main__\": args", "__name__ == \"__main__\": args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4, type=float) #parser.add_argument(\"resolution\",", "Declination 9. Ddot # 2. Inclination 10. Idot # 3. F 11. Fdot", "flavor) products = { \"Decl\":(1, 1), \"Incl\":(2, 1), \"F\":(3, 2), \"H\":(4, 2), \"X\":(5,", "2: 2500, 3: 1000, 4: 1000, 5: 1000, 6: 500, 7: 500, 8:", "filename, rasterxsize, rasterysize, 1, gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt())", "if __name__ == \"__main__\": args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(\"bbox\", nargs=4, type=float)", "argparse import os import os.path import subprocess import numpy import gdal import osr", "time timestart = time # decimal year ending time timeend = time #", "osr import ogr from uuid import uuid4 import logging logger = logging.getLogger(__name__) zoomresolution", "height # Maximum Height above the WGS-84 Ellipsoid (in km) heightmin = height", "Size (in decimal degrees) #deg_interval = resolution deg_interval = (latmax-latmin)/pixelsize # Minimum Height", "rasterysize, 1, gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return ds", "ogr_lyr, 0, 1) #print min(raster_out), max(raster_out) \"\"\" if __name__ == \"__main__\": args =", "filename tempfile = \"/tmp/%s\" % uuid4().hex[:10] # generate geotransform values geotransform = [", "field_defn = ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn) gdal.ContourGenerate(mem_ds.GetRasterBand(1), contour_steps, 0, [], 0, 0, ogr_lyr, 0,", "2. Inclination 10. Idot # 3. F 11. Fdot # 4. H 12.", "import os import os.path import subprocess import numpy import gdal import osr import", "#\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16 } iso_intervals = { 1:{ 0: 10,", ">>proc.stdin, height print >>proc.stdin, heightmax print >>proc.stdin, heightmin print >>proc.stdin, height_interval print >>proc.stdin,", "order raster_out = numpy.fromiter(values, \"float32\") raster_2d = numpy.flipud(raster_out.reshape(rasterysize,rasterxsize)) #print raster_2d.shape #print rasterxsize, rasterysize", "output print >>proc.stdin, tempfile print >>proc.stdin status = proc.wait() print \"STATUS:\", status proc.stdin.close()", "rasterysize = len(yvalues) logger.info(\"size %d %d \" %(rasterxsize, rasterysize)) os.remove(tempfile) # create 1d", "numpy array, reshape to 2d, and flip to correct order raster_out = numpy.fromiter(values,", "time_interval = \"0\" # geomagnetic element to print. Your options are : #", "#\"GV\":{8, #\"Ddot\":{9., #\"Idot\":{10, #\"Fdot\":{11, #\"Hdot\":{12, #\"Xdot\":{13, #\"Ydot\":{14, #\"Zdot\":{15, #\"GVdot\":{16 } iso_intervals = {", "= resolution deg_interval = (latmax-latmin)/pixelsize # Minimum Height above the WGS-84 Ellipsoid (in", "rasterxsize, rasterysize, 1, gdal.GDT_Float32 ) ds.GetRasterBand(1).WriteArray(raster_2d) ds.SetGeoTransform(geotransform) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) ds.SetProjection(srs.ExportToWkt()) return", "line in f: line_array = line.split( ) values.append(str(line_array[4])) xvalues.add(str(line_array[1])) yvalues.add(str(line_array[0])) rasterxsize = len(xvalues)", "len(yvalues) logger.info(\"size %d %d \" %(rasterxsize, rasterysize)) os.remove(tempfile) # create 1d numpy array,", "H 12. Hdot # 5. X 13. Xdot # 6. Y 14. Ydot", "time # time step size time_interval = \"0\" # geomagnetic element to print.", "try: os.remove('contour.dbf') except: pass try: os.remove('contour.shx') except: pass ogr_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(filename) ogr_lyr", "[exe], 1, exe, subprocess.PIPE, open(os.devnull), subprocess.STDOUT, cwd=os.path.dirname(__file__) ) latmin, lonmin, latmax, lonmax =", "ogr_lyr = ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn('ID', ogr.OFTInteger) ogr_lyr.CreateField(field_defn) field_defn = ogr.FieldDefn('elev', ogr.OFTReal) ogr_lyr.CreateField(field_defn)", "= os.path.join(os.path.dirname(__file__), 'wmm_grid.exe') \"\"\"if not os.path.exists(\"WMM.COF\"): raise Exception( \"Coefficient file missing: %s\" %", "13. Xdot # 6. Y 14. Ydot # 7. Z 15. Zdot #", "up from previous runs try: os.remove('contour.shp') except: pass try: os.remove('contour.dbf') except: pass try:", "print >>proc.stdin, heightmax print >>proc.stdin, heightmin print >>proc.stdin, height_interval print >>proc.stdin, timestart print", "3. F 11. Fdot # 4. H 12. Hdot # 5. X 13.", "# decimal year starting time timestart = time # decimal year ending time", "# 4. H 12. Hdot # 5. X 13. Xdot # 6. Y" ]
[ "\"month\": mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'), \"second\": mars_interimm_now_hms.get('second') } } self.wfile.write(json.dumps(res).encode(\"utf-8\"))", "self.send_response(200) self.send_header(\"Content-type\", \"application/json\") self.end_headers() url = self.path parsed_url = urlparse(url) path = parsed_url.path", "self.send_header(\"Content-type\", \"application/json\") self.end_headers() url = self.path parsed_url = urlparse(url) path = parsed_url.path epoch_time", "urlparse import json import debugserver import datetime from functions.mars import CoordinatedMarsTime from functions.interimm", "from functions.mars import CoordinatedMarsTime from functions.interimm import MartianTime class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200)", "= MartianTime() mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd) dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat() res =", "\"application/json\") self.end_headers() url = self.path parsed_url = urlparse(url) path = parsed_url.path epoch_time =", "parsed_url.path epoch_time = path.split('/')[-1] epoch_time = int(float(epoch_time)) mars_time = CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now = MartianTime()", "'second': mars_time.seconds, 'millisecond': mars_time.milliseconds }, \"interimm\": { \"msd\": mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'),", "= parsed_url.path epoch_time = path.split('/')[-1] epoch_time = int(float(epoch_time)) mars_time = CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now =", "= mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd) dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat() res = { \"earth_utc_time\": dt_time,", "datetime from functions.mars import CoordinatedMarsTime from functions.interimm import MartianTime class handler(BaseHTTPRequestHandler): def do_GET(self):", "datetime.datetime.fromtimestamp(epoch_time).isoformat() res = { \"earth_utc_time\": dt_time, \"mars_timezone\": 0, \"mars24\": { 'msd': mars_time.msd, 'day':", "def do_GET(self): self.send_response(200) self.send_header(\"Content-type\", \"application/json\") self.end_headers() url = self.path parsed_url = urlparse(url) path", "epoch_time = int(float(epoch_time)) mars_time = CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now = MartianTime() mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal", "url = self.path parsed_url = urlparse(url) path = parsed_url.path epoch_time = path.split('/')[-1] epoch_time", "functions.interimm import MartianTime class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header(\"Content-type\", \"application/json\") self.end_headers() url =", "self.end_headers() url = self.path parsed_url = urlparse(url) path = parsed_url.path epoch_time = path.split('/')[-1]", "'day': mars_time.days, 'hour': mars_time.hours, 'minute': mars_time.minutes, 'second': mars_time.seconds, 'millisecond': mars_time.milliseconds }, \"interimm\": {", "'hour': mars_time.hours, 'minute': mars_time.minutes, 'second': mars_time.seconds, 'millisecond': mars_time.milliseconds }, \"interimm\": { \"msd\": mars_interimm_now_hms.get('msd'),", "= urlparse(url) path = parsed_url.path epoch_time = path.split('/')[-1] epoch_time = int(float(epoch_time)) mars_time =", "from functions.interimm import MartianTime class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header(\"Content-type\", \"application/json\") self.end_headers() url", "do_GET(self): self.send_response(200) self.send_header(\"Content-type\", \"application/json\") self.end_headers() url = self.path parsed_url = urlparse(url) path =", "\"year\": mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'), \"second\": mars_interimm_now_hms.get('second') }", "\"mars_timezone\": 0, \"mars24\": { 'msd': mars_time.msd, 'day': mars_time.days, 'hour': mars_time.hours, 'minute': mars_time.minutes, 'second':", "debugserver import datetime from functions.mars import CoordinatedMarsTime from functions.interimm import MartianTime class handler(BaseHTTPRequestHandler):", "import debugserver import datetime from functions.mars import CoordinatedMarsTime from functions.interimm import MartianTime class", "'minute': mars_time.minutes, 'second': mars_time.seconds, 'millisecond': mars_time.milliseconds }, \"interimm\": { \"msd\": mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'),", "mars_time.minutes, 'second': mars_time.seconds, 'millisecond': mars_time.milliseconds }, \"interimm\": { \"msd\": mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'), \"month\":", "urlparse(url) path = parsed_url.path epoch_time = path.split('/')[-1] epoch_time = int(float(epoch_time)) mars_time = CoordinatedMarsTime.from_unix_time(epoch_time)", "0, \"mars24\": { 'msd': mars_time.msd, 'day': mars_time.days, 'hour': mars_time.hours, 'minute': mars_time.minutes, 'second': mars_time.seconds,", "mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'), \"second\": mars_interimm_now_hms.get('second')", "int(float(epoch_time)) mars_time = CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now = MartianTime() mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd)", "{ 'msd': mars_time.msd, 'day': mars_time.days, 'hour': mars_time.hours, 'minute': mars_time.minutes, 'second': mars_time.seconds, 'millisecond': mars_time.milliseconds", "json import debugserver import datetime from functions.mars import CoordinatedMarsTime from functions.interimm import MartianTime", "import BaseHTTPRequestHandler from urllib.parse import urlparse import json import debugserver import datetime from", "MartianTime() mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd) dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat() res = {", "mars_time.milliseconds }, \"interimm\": { \"msd\": mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'), \"hour\":", "= datetime.datetime.fromtimestamp(epoch_time).isoformat() res = { \"earth_utc_time\": dt_time, \"mars_timezone\": 0, \"mars24\": { 'msd': mars_time.msd,", "\"earth_utc_time\": dt_time, \"mars_timezone\": 0, \"mars24\": { 'msd': mars_time.msd, 'day': mars_time.days, 'hour': mars_time.hours, 'minute':", "'millisecond': mars_time.milliseconds }, \"interimm\": { \"msd\": mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'),", "mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'), \"second\": mars_interimm_now_hms.get('second') } }", "\"day\": mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'), \"second\": mars_interimm_now_hms.get('second') } } self.wfile.write(json.dumps(res).encode(\"utf-8\")) return if", "\"hour\": mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'), \"second\": mars_interimm_now_hms.get('second') } } self.wfile.write(json.dumps(res).encode(\"utf-8\")) return if __name__ ==", "http.server import BaseHTTPRequestHandler from urllib.parse import urlparse import json import debugserver import datetime", "mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'), \"second\": mars_interimm_now_hms.get('second') } } self.wfile.write(json.dumps(res).encode(\"utf-8\")) return if __name__", "CoordinatedMarsTime from functions.interimm import MartianTime class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header(\"Content-type\", \"application/json\") self.end_headers()", "}, \"interimm\": { \"msd\": mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'),", "epoch_time = path.split('/')[-1] epoch_time = int(float(epoch_time)) mars_time = CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now = MartianTime() mars_interimm_now_hms", "mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd) dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat() res = { \"earth_utc_time\":", "mars_time.seconds, 'millisecond': mars_time.milliseconds }, \"interimm\": { \"msd\": mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'), \"day\":", "\"msd\": mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'), \"second\":", "import MartianTime class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header(\"Content-type\", \"application/json\") self.end_headers() url = self.path", "mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd) dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat() res = { \"earth_utc_time\": dt_time, \"mars_timezone\": 0,", "import datetime from functions.mars import CoordinatedMarsTime from functions.interimm import MartianTime class handler(BaseHTTPRequestHandler): def", "{ \"msd\": mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'),", "functions.mars import CoordinatedMarsTime from functions.interimm import MartianTime class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header(\"Content-type\",", "self.path parsed_url = urlparse(url) path = parsed_url.path epoch_time = path.split('/')[-1] epoch_time = int(float(epoch_time))", "= int(float(epoch_time)) mars_time = CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now = MartianTime() mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal =", "import CoordinatedMarsTime from functions.interimm import MartianTime class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header(\"Content-type\", \"application/json\")", "\"interimm\": { \"msd\": mars_interimm_now_hms.get('msd'), \"year\": mars_interimm_now_cal.get('year'), \"month\": mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'), \"minute\":", "= mars_interimm_now.interimm_calendar(mars_time.msd) dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat() res = { \"earth_utc_time\": dt_time, \"mars_timezone\": 0, \"mars24\":", "= CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now = MartianTime() mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd) dt_time =", "dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat() res = { \"earth_utc_time\": dt_time, \"mars_timezone\": 0, \"mars24\": { 'msd':", "\"mars24\": { 'msd': mars_time.msd, 'day': mars_time.days, 'hour': mars_time.hours, 'minute': mars_time.minutes, 'second': mars_time.seconds, 'millisecond':", "mars_time.hours, 'minute': mars_time.minutes, 'second': mars_time.seconds, 'millisecond': mars_time.milliseconds }, \"interimm\": { \"msd\": mars_interimm_now_hms.get('msd'), \"year\":", "mars_interimm_now = MartianTime() mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd) dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat() res", "mars_interimm_now.interimm_calendar(mars_time.msd) dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat() res = { \"earth_utc_time\": dt_time, \"mars_timezone\": 0, \"mars24\": {", "<gh_stars>1-10 from http.server import BaseHTTPRequestHandler from urllib.parse import urlparse import json import debugserver", "mars_time.days, 'hour': mars_time.hours, 'minute': mars_time.minutes, 'second': mars_time.seconds, 'millisecond': mars_time.milliseconds }, \"interimm\": { \"msd\":", "mars_interimm_now_cal.get('month'), \"day\": mars_interimm_now_cal.get('day'), \"hour\": mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'), \"second\": mars_interimm_now_hms.get('second') } } self.wfile.write(json.dumps(res).encode(\"utf-8\")) return", "= { \"earth_utc_time\": dt_time, \"mars_timezone\": 0, \"mars24\": { 'msd': mars_time.msd, 'day': mars_time.days, 'hour':", "handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header(\"Content-type\", \"application/json\") self.end_headers() url = self.path parsed_url = urlparse(url)", "path.split('/')[-1] epoch_time = int(float(epoch_time)) mars_time = CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now = MartianTime() mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd)", "CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now = MartianTime() mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd) dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat()", "parsed_url = urlparse(url) path = parsed_url.path epoch_time = path.split('/')[-1] epoch_time = int(float(epoch_time)) mars_time", "urllib.parse import urlparse import json import debugserver import datetime from functions.mars import CoordinatedMarsTime", "= self.path parsed_url = urlparse(url) path = parsed_url.path epoch_time = path.split('/')[-1] epoch_time =", "\"minute\": mars_interimm_now_hms.get('minute'), \"second\": mars_interimm_now_hms.get('second') } } self.wfile.write(json.dumps(res).encode(\"utf-8\")) return if __name__ == '__main__': debugserver.serve(handler)", "{ \"earth_utc_time\": dt_time, \"mars_timezone\": 0, \"mars24\": { 'msd': mars_time.msd, 'day': mars_time.days, 'hour': mars_time.hours,", "from http.server import BaseHTTPRequestHandler from urllib.parse import urlparse import json import debugserver import", "= path.split('/')[-1] epoch_time = int(float(epoch_time)) mars_time = CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now = MartianTime() mars_interimm_now_hms =", "class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header(\"Content-type\", \"application/json\") self.end_headers() url = self.path parsed_url =", "import urlparse import json import debugserver import datetime from functions.mars import CoordinatedMarsTime from", "from urllib.parse import urlparse import json import debugserver import datetime from functions.mars import", "mars_time = CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now = MartianTime() mars_interimm_now_hms = mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd) dt_time", "res = { \"earth_utc_time\": dt_time, \"mars_timezone\": 0, \"mars24\": { 'msd': mars_time.msd, 'day': mars_time.days,", "'msd': mars_time.msd, 'day': mars_time.days, 'hour': mars_time.hours, 'minute': mars_time.minutes, 'second': mars_time.seconds, 'millisecond': mars_time.milliseconds },", "import json import debugserver import datetime from functions.mars import CoordinatedMarsTime from functions.interimm import", "path = parsed_url.path epoch_time = path.split('/')[-1] epoch_time = int(float(epoch_time)) mars_time = CoordinatedMarsTime.from_unix_time(epoch_time) mars_interimm_now", "mars_interimm_now_hms.get('hour'), \"minute\": mars_interimm_now_hms.get('minute'), \"second\": mars_interimm_now_hms.get('second') } } self.wfile.write(json.dumps(res).encode(\"utf-8\")) return if __name__ == '__main__':", "MartianTime class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header(\"Content-type\", \"application/json\") self.end_headers() url = self.path parsed_url", "mars_interimm_now.interimm_clock(mars_time.msd) mars_interimm_now_cal = mars_interimm_now.interimm_calendar(mars_time.msd) dt_time = datetime.datetime.fromtimestamp(epoch_time).isoformat() res = { \"earth_utc_time\": dt_time, \"mars_timezone\":", "BaseHTTPRequestHandler from urllib.parse import urlparse import json import debugserver import datetime from functions.mars", "mars_time.msd, 'day': mars_time.days, 'hour': mars_time.hours, 'minute': mars_time.minutes, 'second': mars_time.seconds, 'millisecond': mars_time.milliseconds }, \"interimm\":", "dt_time, \"mars_timezone\": 0, \"mars24\": { 'msd': mars_time.msd, 'day': mars_time.days, 'hour': mars_time.hours, 'minute': mars_time.minutes," ]
[ "coding: utf-8 # MultiPerceptron # queueを使った学習 # 学習step数を記録 # 学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更 #", "MultiPerceptron # queueを使った学習 # 学習step数を記録 # 学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更 # scoreを追加 import os", "placeholder_input_target:batch_target}) except tf.errors.CancelledError as e: break print(\"finished enqueueing\") def weight_variable(shape): initial = tf.truncated_normal(shape,", "_, batch_loss, w_summary = sess.run([train_op, loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size}) if step % 1000 ==", "(step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000 step毎にsaveする if step % 1000000 == 0: _step = sess.run(step_op,feed_dict={placeholder_step:step})", "#FRONT = np.random.randint(0,20,batch_size) #RIGHT45 = np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT =", "_FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import tensorflow as tf import threading from sklearn.utils import shuffle", "return batch_data, batch_target def load_and_enqueue(sess): while True: try: batch_data, batch_target = generate_random_train_data(batch_size) sess.run(enqueue_op,", "n_classes = 4 # 予測結果の数。stop,left,forward,right batch_size = 100 # バッチサイズは10〜100前後に chunk_size = 100", "# check batch_size's data # テストデータでの精度を確認する test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if step %", "= np.random.randint(0,100,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる sensors = np.random.randint(0,200,[batch_size,3]) #sensors = np.c_[LEFT45,FRONT,RIGHT45]", "enqueue_thread = threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start() threads = tf.train.start_queue_runners(coord=coord, sess=sess) step = 0", "# Report exceptions to the coodinator. print(e) coord.request_stop(e) finally: coord.request_stop() coord.join(threads) # ステップ学習時、保存する", "1m以内の判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(0,100,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる sensors", "tf.train.Saver(max_to_keep=1000) test_data, test_target =generate_random_train_data(TEST_NUM) with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(MODEL_DIR) if ckpt:", "= tf.placeholder(tf.int32, name='batch_size') # need feed_dict in training sess.run(). don't need for prediction.", "step:{}\".format(_step)) for step in range(_step+1, target_step+1): batch_loss=0 w_summary=None _, batch_loss, w_summary = sess.run([train_op,", "tf.train.start_queue_runners(coord=coord, sess=sess) step = 0 # 最後にstep数をモデルに記録するために変数を用意しておく try: # check the accuracy before", "import numpy as np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1 =", "#RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる sensors = np.random.randint(0,200,[batch_size,3]) #sensors = np.c_[LEFT45,FRONT,RIGHT45] for i", "= tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy') tf.summary.scalar('accuracy', accuracy) summary_op = tf.summary.merge_all() train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op')", "data asynchronously, and hide I/O latency. coord = tf.train.Coordinator() enqueue_thread = threading.Thread(target=load_and_enqueue, args=[sess])", "+ '/model-'+str(step)+'.ckpt') # テストデータを新たに生成し、精度を確認する test_data, test_target =generate_random_train_data(TEST_NUM) print('Accuracy:',accuracy.eval({dequeue_data_op:test_data, dequeue_target_op:test_target})) # 総step数を表示する print('step:{}'.format(sess.run(variable_step))) print(\"end\")", "before training (without feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) # check batch_size's data # step取得 _step", "= np.random.randint(0,200,[batch_size,3]) #sensors = np.c_[LEFT45,FRONT,RIGHT45] for i in range(batch_size): GENERATOR_RESULT = generator.driving_instruction(sensors[i]) CSVROW", "= np.c_[LEFT45,FRONT,RIGHT45] for i in range(batch_size): GENERATOR_RESULT = generator.driving_instruction(sensors[i]) CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW)", "sklearn.utils import shuffle import sys sys.path.append(_FILE_DIR+'/..') from generator import SensorGenerator import numpy as", "# ステップ学習時、保存する if step > _step: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR", "check batch_size's data # テストデータでの精度を確認する test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if step % 10000", "accuracy) summary_op = tf.summary.merge_all() train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver = tf.train.Saver(max_to_keep=1000) test_data, test_target", "tf.global_variables_initializer() sess.run(init_op) writer = tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time, start_clock = time.time(), time.clock() # Start", "== 0: print(\"Step:%d accuracy:%.8f test_accuracy:%.8f loss:%.8f time:%.8f clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000 step毎にsaveする", "# 初期化処理 init_op = tf.global_variables_initializer() sess.run(init_op) writer = tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time, start_clock =", "#RIGHT45 = np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(0,100,batch_size) #RIGHT45 =", "ckpt.model_checkpoint_path print(\"load {0}\".format(last_model)) # 学習済みモデルを読み込む saver.restore(sess, last_model) LOAD_MODEL = True else: print(\"initialization\") #", "tf.constant(0.1, shape=shape) return tf.Variable(initial) with tf.variable_scope(\"input\"): placeholder_input_data = tf.placeholder('float', [None, data_cols], name='input_data') #", "= tf.train.Saver(max_to_keep=1000) test_data, test_target =generate_random_train_data(TEST_NUM) with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(MODEL_DIR) if", "= generator.driving_instruction(sensors[i]) CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA = np.array(CSVDATA) batch_data = CSVDATA[0:batch_size,0:data_cols] batch_target", "with tf.variable_scope(\"input\"): placeholder_input_data = tf.placeholder('float', [None, data_cols], name='input_data') # for load_and_enqueue. use dequeue_data_op", "name='dequeue_op') # instead of data/target placeholder with tf.variable_scope('neural_network_model'): hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))}", "'float'], shapes=[[data_cols], [n_classes]], name='FIFOQueue' ) # Enqueue and dequeue operations enqueue_op = queue.enqueue_many([placeholder_input_data,", "start_clock = time.time(), time.clock() # Start a thread to enqueue data asynchronously, and", "= tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver = tf.train.Saver(max_to_keep=1000) test_data, test_target =generate_random_train_data(TEST_NUM) with tf.Session() as sess:", "hide I/O latency. coord = tf.train.Coordinator() enqueue_thread = threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start() threads", "name='input_target') # for load_and_enqueue. use dequeue_target_op for prediction placeholder_batch_size = tf.placeholder(tf.int32, name='batch_size') #", "tf.summary.merge_all() train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver = tf.train.Saver(max_to_keep=1000) test_data, test_target =generate_random_train_data(TEST_NUM) with tf.Session()", "as e: break print(\"finished enqueueing\") def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial)", "prediction = tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y') # スコア score = tf.nn.softmax(prediction, name='score') with tf.variable_scope('loss'):", "= np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(0,100,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size)", "ckpt = tf.train.get_checkpoint_state(MODEL_DIR) if ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する last_model = ckpt.model_checkpoint_path print(\"load {0}\".format(last_model)) #", "= 0 # 最後にstep数をモデルに記録するために変数を用意しておく try: # check the accuracy before training (without feed_dict!)", "with tf.variable_scope('neural_network_model'): hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1", "% 1000000 == 0: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt')", "= np.array(CSVDATA) batch_data = CSVDATA[0:batch_size,0:data_cols] batch_target = CSVDATA[0:batch_size,data_cols:] return batch_data, batch_target def load_and_enqueue(sess):", "finally: coord.request_stop() coord.join(threads) # ステップ学習時、保存する if step > _step: _step = sess.run(step_op,feed_dict={placeholder_step:step}) #", "# for load_and_enqueue. use dequeue_data_op for prediction placeholder_input_target = tf.placeholder('float', name='input_target') # for", "scoreを追加 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import tensorflow as tf import threading from", "tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver = tf.train.Saver(max_to_keep=1000) test_data, test_target =generate_random_train_data(TEST_NUM) with tf.Session() as sess: ckpt", "variable_step = tf.Variable(initial_value=0, name=\"step\") # step記録用 step_op = variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"): queue =", "=generate_random_train_data(TEST_NUM) with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(MODEL_DIR) if ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する last_model", "placeholder with tf.variable_scope('neural_network_model'): hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),}", "tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time, start_clock = time.time(), time.clock() # Start a thread to enqueue", "np.array(CSVDATA) batch_data = CSVDATA[0:batch_size,0:data_cols] batch_target = CSVDATA[0:batch_size,data_cols:] return batch_data, batch_target def load_and_enqueue(sess): while", "import sys sys.path.append(_FILE_DIR+'/..') from generator import SensorGenerator import numpy as np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\"", "prediction. with tf.variable_scope(\"step\"): placeholder_step = tf.placeholder(tf.int32, name='input_step') # step値入力用 variable_step = tf.Variable(initial_value=0, name=\"step\")", "= sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) # check batch_size's data # テストデータでの精度を確認する test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target})", "# step値入力用 variable_step = tf.Variable(initial_value=0, name=\"step\") # step記録用 step_op = variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"):", "I/O latency. coord = tf.train.Coordinator() enqueue_thread = threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start() threads =", "= tf.train.start_queue_runners(coord=coord, sess=sess) step = 0 # 最後にstep数をモデルに記録するために変数を用意しておく try: # check the accuracy", "placeholder_input_target = tf.placeholder('float', name='input_target') # for load_and_enqueue. use dequeue_target_op for prediction placeholder_batch_size =", "11 data_cols = 3 # センサーの数。left45,front,right45 n_classes = 4 # 予測結果の数。stop,left,forward,right batch_size =", "# for load_and_enqueue. use dequeue_target_op for prediction placeholder_batch_size = tf.placeholder(tf.int32, name='batch_size') # need", "with tf.variable_scope(\"step\"): placeholder_step = tf.placeholder(tf.int32, name='input_step') # step値入力用 variable_step = tf.Variable(initial_value=0, name=\"step\") #", "tf.variable_scope('accuracy'): correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy') tf.summary.scalar('accuracy',", "10000 == 0: print(\"Step:%d accuracy:%.8f test_accuracy:%.8f loss:%.8f time:%.8f clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000", "= np.random.randint(0,200,batch_size) #RIGHT45 = np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(0,100,batch_size)", "if ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する last_model = ckpt.model_checkpoint_path print(\"load {0}\".format(last_model)) # 学習済みモデルを読み込む saver.restore(sess, last_model)", "shuffle import sys sys.path.append(_FILE_DIR+'/..') from generator import SensorGenerator import numpy as np tf.reset_default_graph()", "前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(20,200,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる #LEFT45", "# FIFOQueueのcapacity target_step = 10000000 # ステップ数 TEST_NUM = 10000 # テストデータ件数 generator", "np.random.randint(0,200,batch_size) #FRONT = np.random.randint(0,200,batch_size) #RIGHT45 = np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT", "tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1 = 11 data_cols = 3", "and hide I/O latency. coord = tf.train.Coordinator() enqueue_thread = threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start()", "for step in range(_step+1, target_step+1): batch_loss=0 w_summary=None _, batch_loss, w_summary = sess.run([train_op, loss_op,", "threading from sklearn.utils import shuffle import sys sys.path.append(_FILE_DIR+'/..') from generator import SensorGenerator import", "queueを使った学習 # 学習step数を記録 # 学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更 # scoreを追加 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import", "前方20cm以内の判定を学習させる #LEFT45 = np.random.randint(0,1000,batch_size) #FRONT = np.random.randint(0,20,batch_size) #RIGHT45 = np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45", "queue = tf.FIFOQueue( capacity=chunk_size, # enqueue size dtypes=['float', 'float'], shapes=[[data_cols], [n_classes]], name='FIFOQueue' )", "feed_dict={placeholder_batch_size:chunk_size})) # check batch_size's data # step取得 _step = sess.run(variable_step) print(\"learned step:{}\".format(_step)) for", "enqueue size dtypes=['float', 'float'], shapes=[[data_cols], [n_classes]], name='FIFOQueue' ) # Enqueue and dequeue operations", "ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する last_model = ckpt.model_checkpoint_path print(\"load {0}\".format(last_model)) # 学習済みモデルを読み込む saver.restore(sess, last_model) LOAD_MODEL", "accuracy before training (without feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) # check batch_size's data # step取得", "== 0: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except", "10m以内の判定を学習させる #sensors = np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる #LEFT45 = np.random.randint(0,1000,batch_size) #FRONT = np.random.randint(0,20,batch_size) #RIGHT45", "name='output_y') # スコア score = tf.nn.softmax(prediction, name='score') with tf.variable_scope('loss'): losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op)", "= CSVDATA[0:batch_size,data_cols:] return batch_data, batch_target def load_and_enqueue(sess): while True: try: batch_data, batch_target =", "labels=dequeue_target_op) loss_op = tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss', loss_op) with tf.variable_scope('accuracy'): correct = tf.equal(tf.argmax(prediction, 1),", "MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1 = 11 data_cols = 3 #", "0: print(\"Step:%d accuracy:%.8f test_accuracy:%.8f loss:%.8f time:%.8f clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000 step毎にsaveする if", "2m以内の判定を学習させる #LEFT45 = np.random.randint(0,200,batch_size) #FRONT = np.random.randint(0,200,batch_size) #RIGHT45 = np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる #LEFT45", "1), tf.argmax(dequeue_target_op, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy') tf.summary.scalar('accuracy', accuracy) summary_op = tf.summary.merge_all()", "as e: # Report exceptions to the coodinator. print(e) coord.request_stop(e) finally: coord.request_stop() coord.join(threads)", "tf.Variable(initial_value=0, name=\"step\") # step記録用 step_op = variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"): queue = tf.FIFOQueue( capacity=chunk_size,", "def load_and_enqueue(sess): while True: try: batch_data, batch_target = generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except", "= np.random.randint(0,100,batch_size) #FRONT = np.random.randint(0,100,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる sensors = np.random.randint(0,200,[batch_size,3])", "CSVDATA[0:batch_size,data_cols:] return batch_data, batch_target def load_and_enqueue(sess): while True: try: batch_data, batch_target = generate_random_train_data(batch_size)", "Start a thread to enqueue data asynchronously, and hide I/O latency. coord =", "variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except Exception as e: # Report exceptions", "step取得 _step = sess.run(variable_step) print(\"learned step:{}\".format(_step)) for step in range(_step+1, target_step+1): batch_loss=0 w_summary=None", "name='enqueue_op') dequeue_data_op, dequeue_target_op = queue.dequeue_many(placeholder_batch_size, name='dequeue_op') # instead of data/target placeholder with tf.variable_scope('neural_network_model'):", "MODEL_DIR + '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except Exception as e: # Report exceptions to the", "coodinator. print(e) coord.request_stop(e) finally: coord.request_stop() coord.join(threads) # ステップ学習時、保存する if step > _step: _step", "generator = SensorGenerator() def generate_random_train_data(batch_size): CSVDATA=[] # 10m以内の判定を学習させる #sensors = np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる", "# instead of data/target placeholder with tf.variable_scope('neural_network_model'): hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer", "import time import tensorflow as tf import threading from sklearn.utils import shuffle import", "time import tensorflow as tf import threading from sklearn.utils import shuffle import sys", "w_summary=None _, batch_loss, w_summary = sess.run([train_op, loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size}) if step % 1000", "shapes=[[data_cols], [n_classes]], name='FIFOQueue' ) # Enqueue and dequeue operations enqueue_op = queue.enqueue_many([placeholder_input_data, placeholder_input_target],", "import tensorflow as tf import threading from sklearn.utils import shuffle import sys sys.path.append(_FILE_DIR+'/..')", "(without feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) # check batch_size's data # step取得 _step = sess.run(variable_step)", "tf.placeholder(tf.int32, name='input_step') # step値入力用 variable_step = tf.Variable(initial_value=0, name=\"step\") # step記録用 step_op = variable_step.assign(placeholder_step)", "# need feed_dict in training sess.run(). don't need for prediction. with tf.variable_scope(\"step\"): placeholder_step", "# 1m以内の判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(0,100,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる", "= tf.FIFOQueue( capacity=chunk_size, # enqueue size dtypes=['float', 'float'], shapes=[[data_cols], [n_classes]], name='FIFOQueue' ) #", "with tf.variable_scope(\"queue\"): queue = tf.FIFOQueue( capacity=chunk_size, # enqueue size dtypes=['float', 'float'], shapes=[[data_cols], [n_classes]],", "GENERATOR_RESULT = generator.driving_instruction(sensors[i]) CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA = np.array(CSVDATA) batch_data = CSVDATA[0:batch_size,0:data_cols]", "enqueue_thread.start() threads = tf.train.start_queue_runners(coord=coord, sess=sess) step = 0 # 最後にstep数をモデルに記録するために変数を用意しておく try: # check", "with tf.variable_scope('accuracy'): correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy')", "sys sys.path.append(_FILE_DIR+'/..') from generator import SensorGenerator import numpy as np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\"", "#LEFT45 = np.random.randint(0,1000,batch_size) #FRONT = np.random.randint(0,20,batch_size) #RIGHT45 = np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 =", "print(\"finished enqueueing\") def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial", "np.random.randint(0,100,batch_size) #FRONT = np.random.randint(0,100,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる sensors = np.random.randint(0,200,[batch_size,3]) #sensors", "= tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy') tf.summary.scalar('accuracy', accuracy) summary_op", "tf.nn.relu(l1) # 予測結果 prediction = tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y') # スコア score = tf.nn.softmax(prediction,", "batch_target def load_and_enqueue(sess): while True: try: batch_data, batch_target = generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target})", "CSVDATA[0:batch_size,0:data_cols] batch_target = CSVDATA[0:batch_size,data_cols:] return batch_data, batch_target def load_and_enqueue(sess): while True: try: batch_data,", "sensors = np.random.randint(0,200,[batch_size,3]) #sensors = np.c_[LEFT45,FRONT,RIGHT45] for i in range(batch_size): GENERATOR_RESULT = generator.driving_instruction(sensors[i])", "SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1 = 11 data_cols = 3 # センサーの数。left45,front,right45", "with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(MODEL_DIR) if ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する last_model =", "[n_classes]], name='FIFOQueue' ) # Enqueue and dequeue operations enqueue_op = queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op')", "need for prediction. with tf.variable_scope(\"step\"): placeholder_step = tf.placeholder(tf.int32, name='input_step') # step値入力用 variable_step =", "= np.random.randint(0,20,batch_size) #RIGHT45 = np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(20,200,batch_size)", "enqueue_thread.isDaemon() enqueue_thread.start() threads = tf.train.start_queue_runners(coord=coord, sess=sess) step = 0 # 最後にstep数をモデルに記録するために変数を用意しておく try: #", "batch_size's data # テストデータでの精度を確認する test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if step % 10000 ==", "sess.graph) start_time, start_clock = time.time(), time.clock() # Start a thread to enqueue data", "tensorflow as tf import threading from sklearn.utils import shuffle import sys sys.path.append(_FILE_DIR+'/..') from", "accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if step % 10000 == 0: print(\"Step:%d accuracy:%.8f test_accuracy:%.8f loss:%.8f time:%.8f", "batch_data, batch_target = generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except tf.errors.CancelledError as e: break print(\"finished", "return tf.Variable(initial) with tf.variable_scope(\"input\"): placeholder_input_data = tf.placeholder('float', [None, data_cols], name='input_data') # for load_and_enqueue.", "0: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except Exception", "tf.summary.scalar('loss', loss_op) with tf.variable_scope('accuracy'): correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op, 1)) accuracy = tf.reduce_mean(tf.cast(correct,", "= tf.summary.merge_all() train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver = tf.train.Saver(max_to_keep=1000) test_data, test_target =generate_random_train_data(TEST_NUM) with", "= queue.dequeue_many(placeholder_batch_size, name='dequeue_op') # instead of data/target placeholder with tf.variable_scope('neural_network_model'): hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols,", "TEST_NUM = 10000 # テストデータ件数 generator = SensorGenerator() def generate_random_train_data(batch_size): CSVDATA=[] # 10m以内の判定を学習させる", "10000 # テストデータ件数 generator = SensorGenerator() def generate_random_train_data(batch_size): CSVDATA=[] # 10m以内の判定を学習させる #sensors =", "'queue/dequeue_op:1':test_target}) if step % 10000 == 0: print(\"Step:%d accuracy:%.8f test_accuracy:%.8f loss:%.8f time:%.8f clock:%.14f\"", "# 学習済みモデルを読み込む saver.restore(sess, last_model) LOAD_MODEL = True else: print(\"initialization\") # 初期化処理 init_op =", "ステップ数 TEST_NUM = 10000 # テストデータ件数 generator = SensorGenerator() def generate_random_train_data(batch_size): CSVDATA=[] #", "{'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) # 予測結果 prediction", "tf.variable_scope(\"step\"): placeholder_step = tf.placeholder(tf.int32, name='input_step') # step値入力用 variable_step = tf.Variable(initial_value=0, name=\"step\") # step記録用", "バッチサイズは10〜100前後に chunk_size = 100 # FIFOQueueのcapacity target_step = 10000000 # ステップ数 TEST_NUM =", "coord.request_stop() coord.join(threads) # ステップ学習時、保存する if step > _step: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する", "target_step+1): batch_loss=0 w_summary=None _, batch_loss, w_summary = sess.run([train_op, loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size}) if step", "range(_step+1, target_step+1): batch_loss=0 w_summary=None _, batch_loss, w_summary = sess.run([train_op, loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size}) if", "print(\"load {0}\".format(last_model)) # 学習済みモデルを読み込む saver.restore(sess, last_model) LOAD_MODEL = True else: print(\"initialization\") # 初期化処理", "test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if step % 10000 == 0: print(\"Step:%d accuracy:%.8f test_accuracy:%.8f", "loss:%.8f time:%.8f clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000 step毎にsaveする if step % 1000000 ==", "= tf.placeholder('float', [None, data_cols], name='input_data') # for load_and_enqueue. use dequeue_data_op for prediction placeholder_input_target", "tf.errors.CancelledError as e: break print(\"finished enqueueing\") def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return", "dequeue operations enqueue_op = queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op') dequeue_data_op, dequeue_target_op = queue.dequeue_many(placeholder_batch_size, name='dequeue_op') #", "time.clock() # Start a thread to enqueue data asynchronously, and hide I/O latency.", "sess.run(init_op) writer = tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time, start_clock = time.time(), time.clock() # Start a", "#RIGHT45 = np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(20,200,batch_size) #RIGHT45 =", "load_and_enqueue. use dequeue_target_op for prediction placeholder_batch_size = tf.placeholder(tf.int32, name='batch_size') # need feed_dict in", "tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) with", "# MultiPerceptron # queueを使った学習 # 学習step数を記録 # 学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更 # scoreを追加 import", "if step % 1000 == 0: if not w_summary is None: writer.add_summary(w_summary, step)", "= variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"): queue = tf.FIFOQueue( capacity=chunk_size, # enqueue size dtypes=['float', 'float'],", "for load_and_enqueue. use dequeue_data_op for prediction placeholder_input_target = tf.placeholder('float', name='input_target') # for load_and_enqueue.", "tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op = tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss', loss_op) with tf.variable_scope('accuracy'): correct = tf.equal(tf.argmax(prediction,", "step > _step: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') #", "exceptions to the coodinator. print(e) coord.request_stop(e) finally: coord.request_stop() coord.join(threads) # ステップ学習時、保存する if step", "np.random.randint(0,200,batch_size) #RIGHT45 = np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(0,100,batch_size) #RIGHT45", "#LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(20,200,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる #LEFT45 =", "FIFOQueueのcapacity target_step = 10000000 # ステップ数 TEST_NUM = 10000 # テストデータ件数 generator =", "np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(0,100,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) #", "l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) # 予測結果 prediction = tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'],", "tf.argmax(dequeue_target_op, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy') tf.summary.scalar('accuracy', accuracy) summary_op = tf.summary.merge_all() train_op", "hidden_1_layer['biases']) l1 = tf.nn.relu(l1) # 予測結果 prediction = tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y') # スコア", "break print(\"finished enqueueing\") def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape):", "generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except tf.errors.CancelledError as e: break print(\"finished enqueueing\") def weight_variable(shape):", "True: try: batch_data, batch_target = generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except tf.errors.CancelledError as e:", "import shuffle import sys sys.path.append(_FILE_DIR+'/..') from generator import SensorGenerator import numpy as np", "#FRONT = np.random.randint(20,200,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる #LEFT45 = np.random.randint(0,200,batch_size) #FRONT =", "for load_and_enqueue. use dequeue_target_op for prediction placeholder_batch_size = tf.placeholder(tf.int32, name='batch_size') # need feed_dict", "'float'), name='accuracy') tf.summary.scalar('accuracy', accuracy) summary_op = tf.summary.merge_all() train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver =", "# queueを使った学習 # 学習step数を記録 # 学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更 # scoreを追加 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__))", "latency. coord = tf.train.Coordinator() enqueue_thread = threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start() threads = tf.train.start_queue_runners(coord=coord,", "# 最後にstep数をモデルに記録するために変数を用意しておく try: # check the accuracy before training (without feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}))", "in range(_step+1, target_step+1): batch_loss=0 w_summary=None _, batch_loss, w_summary = sess.run([train_op, loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size})", "np.random.randint(0,100,batch_size) #FRONT = np.random.randint(20,200,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる #LEFT45 = np.random.randint(0,200,batch_size) #FRONT", "print(e) coord.request_stop(e) finally: coord.request_stop() coord.join(threads) # ステップ学習時、保存する if step > _step: _step =", "os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import tensorflow as tf import threading from sklearn.utils import", "SensorGenerator import numpy as np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1", "loss_op = tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss', loss_op) with tf.variable_scope('accuracy'): correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op,", "= tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss', loss_op) with tf.variable_scope('accuracy'): correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op, 1))", "clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000 step毎にsaveする if step % 1000000 == 0: _step", "# バッチサイズは10〜100前後に chunk_size = 100 # FIFOQueueのcapacity target_step = 10000000 # ステップ数 TEST_NUM", "# variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') # テストデータを新たに生成し、精度を確認する test_data, test_target =generate_random_train_data(TEST_NUM) print('Accuracy:',accuracy.eval({dequeue_data_op:test_data, dequeue_target_op:test_target}))", "= tf.global_variables_initializer() sess.run(init_op) writer = tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time, start_clock = time.time(), time.clock() #", "# scoreを追加 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import tensorflow as tf import threading", "CSVDATA.append(CSVROW) CSVDATA = np.array(CSVDATA) batch_data = CSVDATA[0:batch_size,0:data_cols] batch_target = CSVDATA[0:batch_size,data_cols:] return batch_data, batch_target", "{'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1", "as sess: ckpt = tf.train.get_checkpoint_state(MODEL_DIR) if ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する last_model = ckpt.model_checkpoint_path print(\"load", "batch_loss, w_summary = sess.run([train_op, loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size}) if step % 1000 == 0:", "#LEFT45 = np.random.randint(0,200,batch_size) #FRONT = np.random.randint(0,200,batch_size) #RIGHT45 = np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる #LEFT45 =", "e: break print(\"finished enqueueing\") def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def", "#FRONT = np.random.randint(0,200,batch_size) #RIGHT45 = np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT =", "args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start() threads = tf.train.start_queue_runners(coord=coord, sess=sess) step = 0 # 最後にstep数をモデルに記録するために変数を用意しておく try:", "train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver = tf.train.Saver(max_to_keep=1000) test_data, test_target =generate_random_train_data(TEST_NUM) with tf.Session() as", "step % 1000 == 0: if not w_summary is None: writer.add_summary(w_summary, step) ac", "try: batch_data, batch_target = generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except tf.errors.CancelledError as e: break", "= np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる #LEFT45 = np.random.randint(0,1000,batch_size) #FRONT = np.random.randint(0,20,batch_size) #RIGHT45 = np.random.randint(0,1000,batch_size)", "instead of data/target placeholder with tf.variable_scope('neural_network_model'): hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer =", "= 100 # バッチサイズは10〜100前後に chunk_size = 100 # FIFOQueueのcapacity target_step = 10000000 #", "print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) # check batch_size's data # step取得 _step = sess.run(variable_step) print(\"learned step:{}\".format(_step))", "saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') # テストデータを新たに生成し、精度を確認する test_data, test_target =generate_random_train_data(TEST_NUM) print('Accuracy:',accuracy.eval({dequeue_data_op:test_data, dequeue_target_op:test_target})) # 総step数を表示する", "最後にstep数をモデルに記録するために変数を用意しておく try: # check the accuracy before training (without feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) #", "テストデータでの精度を確認する test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if step % 10000 == 0: print(\"Step:%d accuracy:%.8f", "the accuracy before training (without feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) # check batch_size's data #", "sess.run(). don't need for prediction. with tf.variable_scope(\"step\"): placeholder_step = tf.placeholder(tf.int32, name='input_step') # step値入力用", "batch_data, batch_target def load_and_enqueue(sess): while True: try: batch_data, batch_target = generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data,", "sess.run([train_op, loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size}) if step % 1000 == 0: if not w_summary", "sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except Exception as e: #", "is None: writer.add_summary(w_summary, step) ac = sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) # check batch_size's data #", "batch_target = CSVDATA[0:batch_size,data_cols:] return batch_data, batch_target def load_and_enqueue(sess): while True: try: batch_data, batch_target", "ステップ学習時、保存する if step > _step: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR +", "ac = sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) # check batch_size's data # テストデータでの精度を確認する test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data,", "need feed_dict in training sess.run(). don't need for prediction. with tf.variable_scope(\"step\"): placeholder_step =", "name=\"step\") # step記録用 step_op = variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"): queue = tf.FIFOQueue( capacity=chunk_size, #", "np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(20,200,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) #", "print(\"Step:%d accuracy:%.8f test_accuracy:%.8f loss:%.8f time:%.8f clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000 step毎にsaveする if step", "_step = sess.run(variable_step) print(\"learned step:{}\".format(_step)) for step in range(_step+1, target_step+1): batch_loss=0 w_summary=None _,", "% 10000 == 0: print(\"Step:%d accuracy:%.8f test_accuracy:%.8f loss:%.8f time:%.8f clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) #", "name='input_step') # step値入力用 variable_step = tf.Variable(initial_value=0, name=\"step\") # step記録用 step_op = variable_step.assign(placeholder_step) with", "tf.placeholder('float', name='input_target') # for load_and_enqueue. use dequeue_target_op for prediction placeholder_batch_size = tf.placeholder(tf.int32, name='batch_size')", "= tf.train.Coordinator() enqueue_thread = threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start() threads = tf.train.start_queue_runners(coord=coord, sess=sess) step", "dequeue_target_op for prediction placeholder_batch_size = tf.placeholder(tf.int32, name='batch_size') # need feed_dict in training sess.run().", "data # テストデータでの精度を確認する test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if step % 10000 == 0:", "1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy') tf.summary.scalar('accuracy', accuracy) summary_op = tf.summary.merge_all() train_op =", "0 # 最後にstep数をモデルに記録するために変数を用意しておく try: # check the accuracy before training (without feed_dict!) print(sess.run(accuracy,", "time.time(), time.clock() # Start a thread to enqueue data asynchronously, and hide I/O", "# センサーの数。left45,front,right45 n_classes = 4 # 予測結果の数。stop,left,forward,right batch_size = 100 # バッチサイズは10〜100前後に chunk_size", "operations enqueue_op = queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op') dequeue_data_op, dequeue_target_op = queue.dequeue_many(placeholder_batch_size, name='dequeue_op') # instead", "sess: ckpt = tf.train.get_checkpoint_state(MODEL_DIR) if ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する last_model = ckpt.model_checkpoint_path print(\"load {0}\".format(last_model))", "in training sess.run(). don't need for prediction. with tf.variable_scope(\"step\"): placeholder_step = tf.placeholder(tf.int32, name='input_step')", "tf.summary.scalar('accuracy', accuracy) summary_op = tf.summary.merge_all() train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver = tf.train.Saver(max_to_keep=1000) test_data,", "check the accuracy before training (without feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) # check batch_size's data", "#RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる #LEFT45 = np.random.randint(0,200,batch_size) #FRONT = np.random.randint(0,200,batch_size) #RIGHT45 =", "for prediction. with tf.variable_scope(\"step\"): placeholder_step = tf.placeholder(tf.int32, name='input_step') # step値入力用 variable_step = tf.Variable(initial_value=0,", "if step % 1000000 == 0: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR", "generate_random_train_data(batch_size): CSVDATA=[] # 10m以内の判定を学習させる #sensors = np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる #LEFT45 = np.random.randint(0,1000,batch_size) #FRONT", "100 # FIFOQueueのcapacity target_step = 10000000 # ステップ数 TEST_NUM = 10000 # テストデータ件数", "if step > _step: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt')", "= sess.run([train_op, loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size}) if step % 1000 == 0: if not", "accuracy:%.8f test_accuracy:%.8f loss:%.8f time:%.8f clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000 step毎にsaveする if step %", "CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA = np.array(CSVDATA) batch_data = CSVDATA[0:batch_size,0:data_cols] batch_target = CSVDATA[0:batch_size,data_cols:]", "last_model) LOAD_MODEL = True else: print(\"initialization\") # 初期化処理 init_op = tf.global_variables_initializer() sess.run(init_op) writer", "#sensors = np.c_[LEFT45,FRONT,RIGHT45] for i in range(batch_size): GENERATOR_RESULT = generator.driving_instruction(sensors[i]) CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4]))", "enqueue_op = queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op') dequeue_data_op, dequeue_target_op = queue.dequeue_many(placeholder_batch_size, name='dequeue_op') # instead of", "= sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except Exception as e:", "step in range(_step+1, target_step+1): batch_loss=0 w_summary=None _, batch_loss, w_summary = sess.run([train_op, loss_op, summary_op],", "test_accuracy:%.8f loss:%.8f time:%.8f clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000 step毎にsaveする if step % 1000000", "chunk_size = 100 # FIFOQueueのcapacity target_step = 10000000 # ステップ数 TEST_NUM = 10000", "= {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) # 予測結果", "placeholder_input_data = tf.placeholder('float', [None, data_cols], name='input_data') # for load_and_enqueue. use dequeue_data_op for prediction", "data_cols], name='input_data') # for load_and_enqueue. use dequeue_data_op for prediction placeholder_input_target = tf.placeholder('float', name='input_target')", "prediction placeholder_input_target = tf.placeholder('float', name='input_target') # for load_and_enqueue. use dequeue_target_op for prediction placeholder_batch_size", "+ '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except Exception as e: # Report exceptions to the coodinator.", "= np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる #LEFT45 = np.random.randint(0,200,batch_size) #FRONT = np.random.randint(0,200,batch_size) #RIGHT45 = np.random.randint(0,200,batch_size)", "don't need for prediction. with tf.variable_scope(\"step\"): placeholder_step = tf.placeholder(tf.int32, name='input_step') # step値入力用 variable_step", "tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y') # スコア score = tf.nn.softmax(prediction, name='score') with tf.variable_scope('loss'): losses =", "# 学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更 # scoreを追加 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import tensorflow", "to the coodinator. print(e) coord.request_stop(e) finally: coord.request_stop() coord.join(threads) # ステップ学習時、保存する if step >", "# 学習step数を記録 # 学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更 # scoreを追加 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time", "# スコア score = tf.nn.softmax(prediction, name='score') with tf.variable_scope('loss'): losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op", "np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1 = 11 data_cols =", "# step取得 _step = sess.run(variable_step) print(\"learned step:{}\".format(_step)) for step in range(_step+1, target_step+1): batch_loss=0", "1000000 == 0: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True))", "for prediction placeholder_batch_size = tf.placeholder(tf.int32, name='batch_size') # need feed_dict in training sess.run(). don't", "name='cost') tf.summary.scalar('loss', loss_op) with tf.variable_scope('accuracy'): correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op, 1)) accuracy =", "tf.variable_scope('neural_network_model'): hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1 =", "4 # 予測結果の数。stop,left,forward,right batch_size = 100 # バッチサイズは10〜100前後に chunk_size = 100 # FIFOQueueのcapacity", "training (without feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) # check batch_size's data # step取得 _step =", "placeholder_input_target], name='enqueue_op') dequeue_data_op, dequeue_target_op = queue.dequeue_many(placeholder_batch_size, name='dequeue_op') # instead of data/target placeholder with", "range(batch_size): GENERATOR_RESULT = generator.driving_instruction(sensors[i]) CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA = np.array(CSVDATA) batch_data =", "= accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if step % 10000 == 0: print(\"Step:%d accuracy:%.8f test_accuracy:%.8f loss:%.8f", "学習step数を記録 # 学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更 # scoreを追加 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import", "tf.nn.softmax(prediction, name='score') with tf.variable_scope('loss'): losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op = tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss',", "10000000 # ステップ数 TEST_NUM = 10000 # テストデータ件数 generator = SensorGenerator() def generate_random_train_data(batch_size):", "# 予測結果の数。stop,left,forward,right batch_size = 100 # バッチサイズは10〜100前後に chunk_size = 100 # FIFOQueueのcapacity target_step", "学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更 # scoreを追加 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import tensorflow as", "sys.path.append(_FILE_DIR+'/..') from generator import SensorGenerator import numpy as np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if", "np.random.randint(20,200,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる #LEFT45 = np.random.randint(0,200,batch_size) #FRONT = np.random.randint(0,200,batch_size) #RIGHT45", "prediction placeholder_batch_size = tf.placeholder(tf.int32, name='batch_size') # need feed_dict in training sess.run(). don't need", "dtypes=['float', 'float'], shapes=[[data_cols], [n_classes]], name='FIFOQueue' ) # Enqueue and dequeue operations enqueue_op =", "# ステップ数 TEST_NUM = 10000 # テストデータ件数 generator = SensorGenerator() def generate_random_train_data(batch_size): CSVDATA=[]", "2m以内の判定を学習させる sensors = np.random.randint(0,200,[batch_size,3]) #sensors = np.c_[LEFT45,FRONT,RIGHT45] for i in range(batch_size): GENERATOR_RESULT =", "variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"): queue = tf.FIFOQueue( capacity=chunk_size, # enqueue size dtypes=['float', 'float'], shapes=[[data_cols],", "data/target placeholder with tf.variable_scope('neural_network_model'): hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])),", "= ckpt.model_checkpoint_path print(\"load {0}\".format(last_model)) # 学習済みモデルを読み込む saver.restore(sess, last_model) LOAD_MODEL = True else: print(\"initialization\")", "tf.placeholder(tf.int32, name='batch_size') # need feed_dict in training sess.run(). don't need for prediction. with", "enqueue data asynchronously, and hide I/O latency. coord = tf.train.Coordinator() enqueue_thread = threading.Thread(target=load_and_enqueue,", "output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) #", "feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except tf.errors.CancelledError as e: break print(\"finished enqueueing\") def weight_variable(shape): initial =", "dequeue_data_op, dequeue_target_op = queue.dequeue_many(placeholder_batch_size, name='dequeue_op') # instead of data/target placeholder with tf.variable_scope('neural_network_model'): hidden_1_layer", "capacity=chunk_size, # enqueue size dtypes=['float', 'float'], shapes=[[data_cols], [n_classes]], name='FIFOQueue' ) # Enqueue and", "np.random.randint(0,1000,batch_size) #FRONT = np.random.randint(0,20,batch_size) #RIGHT45 = np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT", "generator import SensorGenerator import numpy as np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not os.path.exists(MODEL_DIR):", "tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) with tf.variable_scope(\"input\"): placeholder_input_data =", "学習済みモデルを読み込む saver.restore(sess, last_model) LOAD_MODEL = True else: print(\"initialization\") # 初期化処理 init_op = tf.global_variables_initializer()", "> _step: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') # テストデータを新たに生成し、精度を確認する", "the coodinator. print(e) coord.request_stop(e) finally: coord.request_stop() coord.join(threads) # ステップ学習時、保存する if step > _step:", "= np.random.randint(0,200,batch_size) #FRONT = np.random.randint(0,200,batch_size) #RIGHT45 = np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size)", "test_target =generate_random_train_data(TEST_NUM) with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(MODEL_DIR) if ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する", "tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(MODEL_DIR) if ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する last_model = ckpt.model_checkpoint_path", "summary_op = tf.summary.merge_all() train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver = tf.train.Saver(max_to_keep=1000) test_data, test_target =generate_random_train_data(TEST_NUM)", "_step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except Exception as", "sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') # テストデータを新たに生成し、精度を確認する test_data, test_target =generate_random_train_data(TEST_NUM) print('Accuracy:',accuracy.eval({dequeue_data_op:test_data,", "# checkpointファイルから最後に保存したモデルへのパスを取得する last_model = ckpt.model_checkpoint_path print(\"load {0}\".format(last_model)) # 学習済みモデルを読み込む saver.restore(sess, last_model) LOAD_MODEL =", "3x11x4のNNモデルに変更 # scoreを追加 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import tensorflow as tf import", "= tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial)", "name='batch_size') # need feed_dict in training sess.run(). don't need for prediction. with tf.variable_scope(\"step\"):", "'/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except Exception as e: # Report exceptions to the coodinator. print(e)", "for prediction placeholder_input_target = tf.placeholder('float', name='input_target') # for load_and_enqueue. use dequeue_target_op for prediction", "スコア score = tf.nn.softmax(prediction, name='score') with tf.variable_scope('loss'): losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op =", "weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape)", "n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) # 予測結果 prediction =", "step) ac = sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) # check batch_size's data # テストデータでの精度を確認する test_accuracy =", "not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1 = 11 data_cols = 3 # センサーの数。left45,front,right45 n_classes =", "with tf.variable_scope('loss'): losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op = tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss', loss_op) with", "= 4 # 予測結果の数。stop,left,forward,right batch_size = 100 # バッチサイズは10〜100前後に chunk_size = 100 #", "loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size}) if step % 1000 == 0: if not w_summary is", "w_summary is None: writer.add_summary(w_summary, step) ac = sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) # check batch_size's data", ") # Enqueue and dequeue operations enqueue_op = queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op') dequeue_data_op, dequeue_target_op", "load_and_enqueue(sess): while True: try: batch_data, batch_target = generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except tf.errors.CancelledError", "losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op = tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss', loss_op) with tf.variable_scope('accuracy'): correct", "dequeue_target_op = queue.dequeue_many(placeholder_batch_size, name='dequeue_op') # instead of data/target placeholder with tf.variable_scope('neural_network_model'): hidden_1_layer =", "threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start() threads = tf.train.start_queue_runners(coord=coord, sess=sess) step = 0 # 最後にstep数をモデルに記録するために変数を用意しておく", "saver.restore(sess, last_model) LOAD_MODEL = True else: print(\"initialization\") # 初期化処理 init_op = tf.global_variables_initializer() sess.run(init_op)", "variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') # テストデータを新たに生成し、精度を確認する test_data, test_target =generate_random_train_data(TEST_NUM) print('Accuracy:',accuracy.eval({dequeue_data_op:test_data, dequeue_target_op:test_target})) #", "in range(batch_size): GENERATOR_RESULT = generator.driving_instruction(sensors[i]) CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA = np.array(CSVDATA) batch_data", "batch_size = 100 # バッチサイズは10〜100前後に chunk_size = 100 # FIFOQueueのcapacity target_step = 10000000", "last_model = ckpt.model_checkpoint_path print(\"load {0}\".format(last_model)) # 学習済みモデルを読み込む saver.restore(sess, last_model) LOAD_MODEL = True else:", "start_time, start_clock = time.time(), time.clock() # Start a thread to enqueue data asynchronously,", "import SensorGenerator import numpy as np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR)", "sess.run(variable_step) print(\"learned step:{}\".format(_step)) for step in range(_step+1, target_step+1): batch_loss=0 w_summary=None _, batch_loss, w_summary", "for i in range(batch_size): GENERATOR_RESULT = generator.driving_instruction(sensors[i]) CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA =", "name='accuracy') tf.summary.scalar('accuracy', accuracy) summary_op = tf.summary.merge_all() train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver = tf.train.Saver(max_to_keep=1000)", "= generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except tf.errors.CancelledError as e: break print(\"finished enqueueing\") def", "try: # check the accuracy before training (without feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) # check", "= 10000 # テストデータ件数 generator = SensorGenerator() def generate_random_train_data(batch_size): CSVDATA=[] # 10m以内の判定を学習させる #sensors", "センサーの数。left45,front,right45 n_classes = 4 # 予測結果の数。stop,left,forward,right batch_size = 100 # バッチサイズは10〜100前後に chunk_size =", "# 予測結果 prediction = tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y') # スコア score = tf.nn.softmax(prediction, name='score')", "threads = tf.train.start_queue_runners(coord=coord, sess=sess) step = 0 # 最後にstep数をモデルに記録するために変数を用意しておく try: # check the", "step_op = variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"): queue = tf.FIFOQueue( capacity=chunk_size, # enqueue size dtypes=['float',", "step値入力用 variable_step = tf.Variable(initial_value=0, name=\"step\") # step記録用 step_op = variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"): queue", "= np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA = np.array(CSVDATA) batch_data = CSVDATA[0:batch_size,0:data_cols] batch_target = CSVDATA[0:batch_size,data_cols:] return", "# step記録用 step_op = variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"): queue = tf.FIFOQueue( capacity=chunk_size, # enqueue", "sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except tf.errors.CancelledError as e: break print(\"finished enqueueing\") def weight_variable(shape): initial", "= tf.nn.relu(l1) # 予測結果 prediction = tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y') # スコア score =", "# 2m以内の判定を学習させる sensors = np.random.randint(0,200,[batch_size,3]) #sensors = np.c_[LEFT45,FRONT,RIGHT45] for i in range(batch_size): GENERATOR_RESULT", "asynchronously, and hide I/O latency. coord = tf.train.Coordinator() enqueue_thread = threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon()", "except tf.errors.CancelledError as e: break print(\"finished enqueueing\") def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1)", "# Enqueue and dequeue operations enqueue_op = queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op') dequeue_data_op, dequeue_target_op =", "# check batch_size's data # step取得 _step = sess.run(variable_step) print(\"learned step:{}\".format(_step)) for step", "print(\"initialization\") # 初期化処理 init_op = tf.global_variables_initializer() sess.run(init_op) writer = tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time, start_clock", "return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) with tf.variable_scope(\"input\"): placeholder_input_data", "coord.request_stop(e) finally: coord.request_stop() coord.join(threads) # ステップ学習時、保存する if step > _step: _step = sess.run(step_op,feed_dict={placeholder_step:step})", "Exception as e: # Report exceptions to the coodinator. print(e) coord.request_stop(e) finally: coord.request_stop()", "= CSVDATA[0:batch_size,0:data_cols] batch_target = CSVDATA[0:batch_size,data_cols:] return batch_data, batch_target def load_and_enqueue(sess): while True: try:", "data # step取得 _step = sess.run(variable_step) print(\"learned step:{}\".format(_step)) for step in range(_step+1, target_step+1):", "def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1,", "None: writer.add_summary(w_summary, step) ac = sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) # check batch_size's data # テストデータでの精度を確認する", "CSVDATA=[] # 10m以内の判定を学習させる #sensors = np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる #LEFT45 = np.random.randint(0,1000,batch_size) #FRONT =", "= tf.constant(0.1, shape=shape) return tf.Variable(initial) with tf.variable_scope(\"input\"): placeholder_input_data = tf.placeholder('float', [None, data_cols], name='input_data')", "coord = tf.train.Coordinator() enqueue_thread = threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start() threads = tf.train.start_queue_runners(coord=coord, sess=sess)", "{0}\".format(last_model)) # 学習済みモデルを読み込む saver.restore(sess, last_model) LOAD_MODEL = True else: print(\"initialization\") # 初期化処理 init_op", "'biases':tf.Variable(bias_variable([n_classes])),} l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) # 予測結果 prediction = tf.add(tf.matmul(l1,output_layer['weights']),", "予測結果の数。stop,left,forward,right batch_size = 100 # バッチサイズは10〜100前後に chunk_size = 100 # FIFOQueueのcapacity target_step =", "if step % 10000 == 0: print(\"Step:%d accuracy:%.8f test_accuracy:%.8f loss:%.8f time:%.8f clock:%.14f\" %", "_step: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') # テストデータを新たに生成し、精度を確認する test_data,", "name='FIFOQueue' ) # Enqueue and dequeue operations enqueue_op = queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op') dequeue_data_op,", "= {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases'])", "l1 = tf.nn.relu(l1) # 予測結果 prediction = tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y') # スコア score", "= tf.placeholder(tf.int32, name='input_step') # step値入力用 variable_step = tf.Variable(initial_value=0, name=\"step\") # step記録用 step_op =", "use dequeue_target_op for prediction placeholder_batch_size = tf.placeholder(tf.int32, name='batch_size') # need feed_dict in training", "= tf.train.get_checkpoint_state(MODEL_DIR) if ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する last_model = ckpt.model_checkpoint_path print(\"load {0}\".format(last_model)) # 学習済みモデルを読み込む", "import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import tensorflow as tf import threading from sklearn.utils", "tf.Variable(initial) with tf.variable_scope(\"input\"): placeholder_input_data = tf.placeholder('float', [None, data_cols], name='input_data') # for load_and_enqueue. use", "use dequeue_data_op for prediction placeholder_input_target = tf.placeholder('float', name='input_target') # for load_and_enqueue. use dequeue_target_op", "batch_loss=0 w_summary=None _, batch_loss, w_summary = sess.run([train_op, loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size}) if step %", "step = 0 # 最後にstep数をモデルに記録するために変数を用意しておく try: # check the accuracy before training (without", "1000000 step毎にsaveする if step % 1000000 == 0: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する", "np.random.randint(0,100,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる sensors = np.random.randint(0,200,[batch_size,3]) #sensors = np.c_[LEFT45,FRONT,RIGHT45] for", "初期化処理 init_op = tf.global_variables_initializer() sess.run(init_op) writer = tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time, start_clock = time.time(),", "from generator import SensorGenerator import numpy as np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not", "= 3 # センサーの数。left45,front,right45 n_classes = 4 # 予測結果の数。stop,left,forward,right batch_size = 100 #", "% (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000 step毎にsaveする if step % 1000000 == 0: _step =", "tf.FIFOQueue( capacity=chunk_size, # enqueue size dtypes=['float', 'float'], shapes=[[data_cols], [n_classes]], name='FIFOQueue' ) # Enqueue", "= 100 # FIFOQueueのcapacity target_step = 10000000 # ステップ数 TEST_NUM = 10000 #", "checkpointファイルから最後に保存したモデルへのパスを取得する last_model = ckpt.model_checkpoint_path print(\"load {0}\".format(last_model)) # 学習済みモデルを読み込む saver.restore(sess, last_model) LOAD_MODEL = True", "= tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y') # スコア score = tf.nn.softmax(prediction, name='score') with tf.variable_scope('loss'): losses", "initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) with tf.variable_scope(\"input\"): placeholder_input_data = tf.placeholder('float', [None, data_cols],", "= 11 data_cols = 3 # センサーの数。left45,front,right45 n_classes = 4 # 予測結果の数。stop,left,forward,right batch_size", "予測結果 prediction = tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y') # スコア score = tf.nn.softmax(prediction, name='score') with", "= sess.run(variable_step) print(\"learned step:{}\".format(_step)) for step in range(_step+1, target_step+1): batch_loss=0 w_summary=None _, batch_loss,", "step記録用 step_op = variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"): queue = tf.FIFOQueue( capacity=chunk_size, # enqueue size", "as np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1 = 11 data_cols", "batch_target = generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except tf.errors.CancelledError as e: break print(\"finished enqueueing\")", "queue.dequeue_many(placeholder_batch_size, name='dequeue_op') # instead of data/target placeholder with tf.variable_scope('neural_network_model'): hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])),", "batch_size's data # step取得 _step = sess.run(variable_step) print(\"learned step:{}\".format(_step)) for step in range(_step+1,", "sess.run(queue.close(cancel_pending_enqueues=True)) except Exception as e: # Report exceptions to the coodinator. print(e) coord.request_stop(e)", "placeholder_batch_size = tf.placeholder(tf.int32, name='batch_size') # need feed_dict in training sess.run(). don't need for", "= 10000000 # ステップ数 TEST_NUM = 10000 # テストデータ件数 generator = SensorGenerator() def", "queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op') dequeue_data_op, dequeue_target_op = queue.dequeue_many(placeholder_batch_size, name='dequeue_op') # instead of data/target placeholder", "n_nodes_hl1 = 11 data_cols = 3 # センサーの数。left45,front,right45 n_classes = 4 # 予測結果の数。stop,left,forward,right", "# 前方20cm以内の判定を学習させる #LEFT45 = np.random.randint(0,1000,batch_size) #FRONT = np.random.randint(0,20,batch_size) #RIGHT45 = np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる", "and dequeue operations enqueue_op = queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op') dequeue_data_op, dequeue_target_op = queue.dequeue_many(placeholder_batch_size, name='dequeue_op')", "tf.placeholder('float', [None, data_cols], name='input_data') # for load_and_enqueue. use dequeue_data_op for prediction placeholder_input_target =", "sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) # check batch_size's data # テストデータでの精度を確認する test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if", "% 1000 == 0: if not w_summary is None: writer.add_summary(w_summary, step) ac =", "load_and_enqueue. use dequeue_data_op for prediction placeholder_input_target = tf.placeholder('float', name='input_target') # for load_and_enqueue. use", "size dtypes=['float', 'float'], shapes=[[data_cols], [n_classes]], name='FIFOQueue' ) # Enqueue and dequeue operations enqueue_op", "w_summary = sess.run([train_op, loss_op, summary_op], feed_dict={placeholder_batch_size:batch_size}) if step % 1000 == 0: if", "_step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') # テストデータを新たに生成し、精度を確認する test_data, test_target", "tf.variable_scope(\"input\"): placeholder_input_data = tf.placeholder('float', [None, data_cols], name='input_data') # for load_and_enqueue. use dequeue_data_op for", "# 10m以内の判定を学習させる #sensors = np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる #LEFT45 = np.random.randint(0,1000,batch_size) #FRONT = np.random.randint(0,20,batch_size)", "= True else: print(\"initialization\") # 初期化処理 init_op = tf.global_variables_initializer() sess.run(init_op) writer = tf.summary.FileWriter(SUMMARY_LOG_DIR,", "thread to enqueue data asynchronously, and hide I/O latency. coord = tf.train.Coordinator() enqueue_thread", "writer = tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time, start_clock = time.time(), time.clock() # Start a thread", "feed_dict in training sess.run(). don't need for prediction. with tf.variable_scope(\"step\"): placeholder_step = tf.placeholder(tf.int32,", "if not w_summary is None: writer.add_summary(w_summary, step) ac = sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) # check", "os.makedirs(MODEL_DIR) n_nodes_hl1 = 11 data_cols = 3 # センサーの数。left45,front,right45 n_classes = 4 #", "# 3x11x4のNNモデルに変更 # scoreを追加 import os _FILE_DIR=os.path.abspath(os.path.dirname(__file__)) import time import tensorflow as tf", "e: # Report exceptions to the coodinator. print(e) coord.request_stop(e) finally: coord.request_stop() coord.join(threads) #", "= threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start() threads = tf.train.start_queue_runners(coord=coord, sess=sess) step = 0 #", "# 1000000 step毎にsaveする if step % 1000000 == 0: _step = sess.run(step_op,feed_dict={placeholder_step:step}) #", "CSVDATA = np.array(CSVDATA) batch_data = CSVDATA[0:batch_size,0:data_cols] batch_target = CSVDATA[0:batch_size,data_cols:] return batch_data, batch_target def", "= np.random.randint(0,100,batch_size) #FRONT = np.random.randint(20,200,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる #LEFT45 = np.random.randint(0,200,batch_size)", "name='train_op') saver = tf.train.Saver(max_to_keep=1000) test_data, test_target =generate_random_train_data(TEST_NUM) with tf.Session() as sess: ckpt =", "utf-8 # MultiPerceptron # queueを使った学習 # 学習step数を記録 # 学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更 # scoreを追加", "name='score') with tf.variable_scope('loss'): losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op = tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss', loss_op)", "True else: print(\"initialization\") # 初期化処理 init_op = tf.global_variables_initializer() sess.run(init_op) writer = tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph)", "# coding: utf-8 # MultiPerceptron # queueを使った学習 # 学習step数を記録 # 学習データはCSVの代わりにジェネレータを搭載 # 3x11x4のNNモデルに変更", "SensorGenerator() def generate_random_train_data(batch_size): CSVDATA=[] # 10m以内の判定を学習させる #sensors = np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる #LEFT45 =", "[None, data_cols], name='input_data') # for load_and_enqueue. use dequeue_data_op for prediction placeholder_input_target = tf.placeholder('float',", "tf.variable_scope(\"queue\"): queue = tf.FIFOQueue( capacity=chunk_size, # enqueue size dtypes=['float', 'float'], shapes=[[data_cols], [n_classes]], name='FIFOQueue'", "== 0: if not w_summary is None: writer.add_summary(w_summary, step) ac = sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})", "'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1)", "3 # センサーの数。left45,front,right45 n_classes = 4 # 予測結果の数。stop,left,forward,right batch_size = 100 # バッチサイズは10〜100前後に", "score = tf.nn.softmax(prediction, name='score') with tf.variable_scope('loss'): losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op = tf.reduce_mean(losses,", "except Exception as e: # Report exceptions to the coodinator. print(e) coord.request_stop(e) finally:", "import threading from sklearn.utils import shuffle import sys sys.path.append(_FILE_DIR+'/..') from generator import SensorGenerator", "np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる #LEFT45 = np.random.randint(0,1000,batch_size) #FRONT = np.random.randint(0,20,batch_size) #RIGHT45 = np.random.randint(0,1000,batch_size) #", "def generate_random_train_data(batch_size): CSVDATA=[] # 10m以内の判定を学習させる #sensors = np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる #LEFT45 = np.random.randint(0,1000,batch_size)", "generator.driving_instruction(sensors[i]) CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA = np.array(CSVDATA) batch_data = CSVDATA[0:batch_size,0:data_cols] batch_target =", "check batch_size's data # step取得 _step = sess.run(variable_step) print(\"learned step:{}\".format(_step)) for step in", "= tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time, start_clock = time.time(), time.clock() # Start a thread to", "step % 10000 == 0: print(\"Step:%d accuracy:%.8f test_accuracy:%.8f loss:%.8f time:%.8f clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock))", "coord.join(threads) # ステップ学習時、保存する if step > _step: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess,", "np.random.randint(0,20,batch_size) #RIGHT45 = np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(20,200,batch_size) #RIGHT45", "saver = tf.train.Saver(max_to_keep=1000) test_data, test_target =generate_random_train_data(TEST_NUM) with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(MODEL_DIR)", "step % 1000000 == 0: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR +", "= np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる sensors = np.random.randint(0,200,[batch_size,3]) #sensors = np.c_[LEFT45,FRONT,RIGHT45] for i in", "# テストデータでの精度を確認する test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if step % 10000 == 0: print(\"Step:%d", "os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1 = 11 data_cols = 3 # センサーの数。left45,front,right45 n_classes = 4", "else: print(\"initialization\") # 初期化処理 init_op = tf.global_variables_initializer() sess.run(init_op) writer = tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time,", "np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる #LEFT45 = np.random.randint(0,200,batch_size) #FRONT = np.random.randint(0,200,batch_size) #RIGHT45 = np.random.randint(0,200,batch_size) #", "batch_data = CSVDATA[0:batch_size,0:data_cols] batch_target = CSVDATA[0:batch_size,data_cols:] return batch_data, batch_target def load_and_enqueue(sess): while True:", "feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) # check batch_size's data # step取得 _step = sess.run(variable_step) print(\"learned", "# variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except Exception as e: # Report", "test_data, test_target =generate_random_train_data(TEST_NUM) with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(MODEL_DIR) if ckpt: #", "feed_dict={placeholder_batch_size:batch_size}) if step % 1000 == 0: if not w_summary is None: writer.add_summary(w_summary,", "feed_dict={placeholder_batch_size:chunk_size}) # check batch_size's data # テストデータでの精度を確認する test_accuracy = accuracy.eval({'queue/dequeue_op:0':test_data, 'queue/dequeue_op:1':test_target}) if step", "LOAD_MODEL = True else: print(\"initialization\") # 初期化処理 init_op = tf.global_variables_initializer() sess.run(init_op) writer =", "tf import threading from sklearn.utils import shuffle import sys sys.path.append(_FILE_DIR+'/..') from generator import", "tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy') tf.summary.scalar('accuracy', accuracy) summary_op = tf.summary.merge_all() train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op, name='train_op') saver", "shape=shape) return tf.Variable(initial) with tf.variable_scope(\"input\"): placeholder_input_data = tf.placeholder('float', [None, data_cols], name='input_data') # for", "a thread to enqueue data asynchronously, and hide I/O latency. coord = tf.train.Coordinator()", "np.c_[LEFT45,FRONT,RIGHT45] for i in range(batch_size): GENERATOR_RESULT = generator.driving_instruction(sensors[i]) CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA", "tf.train.Coordinator() enqueue_thread = threading.Thread(target=load_and_enqueue, args=[sess]) enqueue_thread.isDaemon() enqueue_thread.start() threads = tf.train.start_queue_runners(coord=coord, sess=sess) step =", "#sensors = np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる #LEFT45 = np.random.randint(0,1000,batch_size) #FRONT = np.random.randint(0,20,batch_size) #RIGHT45 =", "target_step = 10000000 # ステップ数 TEST_NUM = 10000 # テストデータ件数 generator = SensorGenerator()", "# enqueue size dtypes=['float', 'float'], shapes=[[data_cols], [n_classes]], name='FIFOQueue' ) # Enqueue and dequeue", "0: if not w_summary is None: writer.add_summary(w_summary, step) ac = sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) #", "= tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op = tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss', loss_op) with tf.variable_scope('accuracy'): correct =", "to enqueue data asynchronously, and hide I/O latency. coord = tf.train.Coordinator() enqueue_thread =", "enqueueing\") def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial =", "= tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) # 予測結果 prediction = tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y')", "Report exceptions to the coodinator. print(e) coord.request_stop(e) finally: coord.request_stop() coord.join(threads) # ステップ学習時、保存する if", "= np.random.randint(20,200,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる #LEFT45 = np.random.randint(0,200,batch_size) #FRONT = np.random.randint(0,200,batch_size)", "saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') sess.run(queue.close(cancel_pending_enqueues=True)) except Exception as e: # Report exceptions to", "= np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(20,200,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size)", "#FRONT = np.random.randint(0,100,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる sensors = np.random.randint(0,200,[batch_size,3]) #sensors =", "= tf.placeholder('float', name='input_target') # for load_and_enqueue. use dequeue_target_op for prediction placeholder_batch_size = tf.placeholder(tf.int32,", "accuracy = tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy') tf.summary.scalar('accuracy', accuracy) summary_op = tf.summary.merge_all() train_op = tf.train.AdamOptimizer(0.0001).minimize(loss_op,", "np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる sensors = np.random.randint(0,200,[batch_size,3]) #sensors = np.c_[LEFT45,FRONT,RIGHT45] for i in range(batch_size):", "= SensorGenerator() def generate_random_train_data(batch_size): CSVDATA=[] # 10m以内の判定を学習させる #sensors = np.random.randint(0,1000,[batch_size,3]) # 前方20cm以内の判定を学習させる #LEFT45", "tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1 = tf.nn.relu(l1) # 予測結果 prediction = tf.add(tf.matmul(l1,output_layer['weights']), output_layer['biases'], name='output_y') #", "correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy') tf.summary.scalar('accuracy', accuracy)", "Enqueue and dequeue operations enqueue_op = queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op') dequeue_data_op, dequeue_target_op = queue.dequeue_many(placeholder_batch_size,", "from sklearn.utils import shuffle import sys sys.path.append(_FILE_DIR+'/..') from generator import SensorGenerator import numpy", "= sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess, MODEL_DIR + '/model-'+str(step)+'.ckpt') # テストデータを新たに生成し、精度を確認する test_data, test_target =generate_random_train_data(TEST_NUM)", "initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return", "# check the accuracy before training (without feed_dict!) print(sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size})) # check batch_size's", "= np.random.randint(0,1000,batch_size) #FRONT = np.random.randint(0,20,batch_size) #RIGHT45 = np.random.randint(0,1000,batch_size) # 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size)", "numpy as np tf.reset_default_graph() MODEL_DIR=_FILE_DIR+\"/model\" SUMMARY_LOG_DIR=_FILE_DIR+\"/log\" if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1 = 11", "as tf import threading from sklearn.utils import shuffle import sys sys.path.append(_FILE_DIR+'/..') from generator", "np.random.randint(0,200,[batch_size,3]) #sensors = np.c_[LEFT45,FRONT,RIGHT45] for i in range(batch_size): GENERATOR_RESULT = generator.driving_instruction(sensors[i]) CSVROW =", "n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']), hidden_1_layer['biases']) l1 =", "# 前方20cm-100cm、左右100cm以内のの判定を学習させる #LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(20,200,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる", "if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR) n_nodes_hl1 = 11 data_cols = 3 # センサーの数。left45,front,right45 n_classes", "#LEFT45 = np.random.randint(0,100,batch_size) #FRONT = np.random.randint(0,100,batch_size) #RIGHT45 = np.random.randint(0,100,batch_size) # 2m以内の判定を学習させる sensors =", "1000 == 0: if not w_summary is None: writer.add_summary(w_summary, step) ac = sess.run(accuracy,", "bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) with tf.variable_scope(\"input\"): placeholder_input_data = tf.placeholder('float', [None,", "MODEL_DIR + '/model-'+str(step)+'.ckpt') # テストデータを新たに生成し、精度を確認する test_data, test_target =generate_random_train_data(TEST_NUM) print('Accuracy:',accuracy.eval({dequeue_data_op:test_data, dequeue_target_op:test_target})) # 総step数を表示する print('step:{}'.format(sess.run(variable_step)))", "テストデータ件数 generator = SensorGenerator() def generate_random_train_data(batch_size): CSVDATA=[] # 10m以内の判定を学習させる #sensors = np.random.randint(0,1000,[batch_size,3]) #", "output_layer['biases'], name='output_y') # スコア score = tf.nn.softmax(prediction, name='score') with tf.variable_scope('loss'): losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction,", "# 2m以内の判定を学習させる #LEFT45 = np.random.randint(0,200,batch_size) #FRONT = np.random.randint(0,200,batch_size) #RIGHT45 = np.random.randint(0,200,batch_size) # 1m以内の判定を学習させる", "sess=sess) step = 0 # 最後にstep数をモデルに記録するために変数を用意しておく try: # check the accuracy before training", "100 # バッチサイズは10〜100前後に chunk_size = 100 # FIFOQueueのcapacity target_step = 10000000 # ステップ数", "while True: try: batch_data, batch_target = generate_random_train_data(batch_size) sess.run(enqueue_op, feed_dict={placeholder_input_data:batch_data, placeholder_input_target:batch_target}) except tf.errors.CancelledError as", "tf.train.get_checkpoint_state(MODEL_DIR) if ckpt: # checkpointファイルから最後に保存したモデルへのパスを取得する last_model = ckpt.model_checkpoint_path print(\"load {0}\".format(last_model)) # 学習済みモデルを読み込む saver.restore(sess,", "name='input_data') # for load_and_enqueue. use dequeue_data_op for prediction placeholder_input_target = tf.placeholder('float', name='input_target') #", "not w_summary is None: writer.add_summary(w_summary, step) ac = sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) # check batch_size's", "print(\"learned step:{}\".format(_step)) for step in range(_step+1, target_step+1): batch_loss=0 w_summary=None _, batch_loss, w_summary =", "tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float'), name='accuracy') tf.summary.scalar('accuracy', accuracy) summary_op =", "= queue.enqueue_many([placeholder_input_data, placeholder_input_target], name='enqueue_op') dequeue_data_op, dequeue_target_op = queue.dequeue_many(placeholder_batch_size, name='dequeue_op') # instead of data/target", "time:%.8f clock:%.14f\" % (step,ac,test_accuracy,batch_loss,time.time()-start_time,time.clock()-start_clock)) # 1000000 step毎にsaveする if step % 1000000 == 0:", "i in range(batch_size): GENERATOR_RESULT = generator.driving_instruction(sensors[i]) CSVROW = np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA = np.array(CSVDATA)", "# テストデータ件数 generator = SensorGenerator() def generate_random_train_data(batch_size): CSVDATA=[] # 10m以内の判定を学習させる #sensors = np.random.randint(0,1000,[batch_size,3])", "tf.variable_scope('loss'): losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op = tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss', loss_op) with tf.variable_scope('accuracy'):", "training sess.run(). don't need for prediction. with tf.variable_scope(\"step\"): placeholder_step = tf.placeholder(tf.int32, name='input_step') #", "= tf.Variable(initial_value=0, name=\"step\") # step記録用 step_op = variable_step.assign(placeholder_step) with tf.variable_scope(\"queue\"): queue = tf.FIFOQueue(", "stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) with tf.variable_scope(\"input\"):", "dequeue_data_op for prediction placeholder_input_target = tf.placeholder('float', name='input_target') # for load_and_enqueue. use dequeue_target_op for", "step毎にsaveする if step % 1000000 == 0: _step = sess.run(step_op,feed_dict={placeholder_step:step}) # variable_stepにstepを記録する saver.save(sess,", "loss_op) with tf.variable_scope('accuracy'): correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float'),", "of data/target placeholder with tf.variable_scope('neural_network_model'): hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1,", "# Start a thread to enqueue data asynchronously, and hide I/O latency. coord", "placeholder_step = tf.placeholder(tf.int32, name='input_step') # step値入力用 variable_step = tf.Variable(initial_value=0, name=\"step\") # step記録用 step_op", "hidden_1_layer = {'weights':tf.Variable(weight_variable([data_cols, n_nodes_hl1])), 'biases':tf.Variable(bias_variable([n_nodes_hl1]))} output_layer = {'weights':tf.Variable(weight_variable([n_nodes_hl1, n_classes])), 'biases':tf.Variable(bias_variable([n_classes])),} l1 = tf.add(tf.matmul(dequeue_data_op,hidden_1_layer['weights']),", "np.hstack((sensors[i],GENERATOR_RESULT[0:4])) CSVDATA.append(CSVROW) CSVDATA = np.array(CSVDATA) batch_data = CSVDATA[0:batch_size,0:data_cols] batch_target = CSVDATA[0:batch_size,data_cols:] return batch_data,", "tf.reduce_mean(losses, name='cost') tf.summary.scalar('loss', loss_op) with tf.variable_scope('accuracy'): correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(dequeue_target_op, 1)) accuracy", "= tf.nn.softmax(prediction, name='score') with tf.variable_scope('loss'): losses = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=dequeue_target_op) loss_op = tf.reduce_mean(losses, name='cost')", "init_op = tf.global_variables_initializer() sess.run(init_op) writer = tf.summary.FileWriter(SUMMARY_LOG_DIR, sess.graph) start_time, start_clock = time.time(), time.clock()", "= time.time(), time.clock() # Start a thread to enqueue data asynchronously, and hide", "writer.add_summary(w_summary, step) ac = sess.run(accuracy, feed_dict={placeholder_batch_size:chunk_size}) # check batch_size's data # テストデータでの精度を確認する test_accuracy", "data_cols = 3 # センサーの数。left45,front,right45 n_classes = 4 # 予測結果の数。stop,left,forward,right batch_size = 100", "def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) with tf.variable_scope(\"input\"): placeholder_input_data = tf.placeholder('float',", "summary_op], feed_dict={placeholder_batch_size:batch_size}) if step % 1000 == 0: if not w_summary is None:" ]
[ "TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self, svc, factories, db_session): annotation = factories.Annotation() svc.hide(annotation) mod = db_session.query(models.AnnotationModeration)", "= db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation) \\ .count() assert count == 1 @pytest.fixture def svc(self,", "= db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation) \\ .first() assert mod is not None def test_it_skips_creating_moderation_when_already_exists(self,", "unicode_literals import pytest from h import models from h.services.annotation_moderation import AnnotationModerationService from h.services.annotation_moderation", "def test_it_returns_service(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert isinstance(svc, AnnotationModerationService) def test_it_provides_request_db_as_session(self, pyramid_request):", "from __future__ import unicode_literals import pytest from h import models from h.services.annotation_moderation import", "is not None def test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session): existing = factories.AnnotationModeration() svc.hide(existing.annotation) count", ".first() assert mod is not None def test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session): existing =", "from h.services.annotation_moderation import AnnotationModerationService from h.services.annotation_moderation import annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self, svc,", "@pytest.fixture def svc(self, db_session): return AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self, pyramid_request): svc =", "h.services.annotation_moderation import annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self, svc, factories, db_session): annotation = factories.Annotation()", "annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self, svc, factories, db_session): annotation = factories.Annotation() svc.hide(annotation) mod", "assert count == 1 @pytest.fixture def svc(self, db_session): return AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object): def", "test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session): existing = factories.AnnotationModeration() svc.hide(existing.annotation) count = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation)", "count = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation) \\ .count() assert count == 1 @pytest.fixture def", ".count() assert count == 1 @pytest.fixture def svc(self, db_session): return AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object):", "class TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert isinstance(svc, AnnotationModerationService) def", "def test_it_creates_annotation_moderation(self, svc, factories, db_session): annotation = factories.Annotation() svc.hide(annotation) mod = db_session.query(models.AnnotationModeration) \\", "factories.Annotation() svc.hide(annotation) mod = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation) \\ .first() assert mod is not", "db_session): existing = factories.AnnotationModeration() svc.hide(existing.annotation) count = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation) \\ .count() assert", "svc, factories, db_session): existing = factories.AnnotationModeration() svc.hide(existing.annotation) count = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation) \\", "# -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest from h", "None def test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session): existing = factories.AnnotationModeration() svc.hide(existing.annotation) count = db_session.query(models.AnnotationModeration)", "db_session): annotation = factories.Annotation() svc.hide(annotation) mod = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation) \\ .first() assert", "from h.services.annotation_moderation import annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self, svc, factories, db_session): annotation =", "import annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self, svc, factories, db_session): annotation = factories.Annotation() svc.hide(annotation)", "def svc(self, db_session): return AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self, pyramid_request): svc = annotation_moderation_service_factory(None,", "test_it_returns_service(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert isinstance(svc, AnnotationModerationService) def test_it_provides_request_db_as_session(self, pyramid_request): svc", "\\ .filter_by(annotation=annotation) \\ .first() assert mod is not None def test_it_skips_creating_moderation_when_already_exists(self, svc, factories,", "\\ .filter_by(annotation=existing.annotation) \\ .count() assert count == 1 @pytest.fixture def svc(self, db_session): return", "isinstance(svc, AnnotationModerationService) def test_it_provides_request_db_as_session(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert svc.session == pyramid_request.db", "= factories.Annotation() svc.hide(annotation) mod = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation) \\ .first() assert mod is", "svc.hide(annotation) mod = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation) \\ .first() assert mod is not None", "= annotation_moderation_service_factory(None, pyramid_request) assert isinstance(svc, AnnotationModerationService) def test_it_provides_request_db_as_session(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request)", "h.services.annotation_moderation import AnnotationModerationService from h.services.annotation_moderation import annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self, svc, factories,", ".filter_by(annotation=annotation) \\ .first() assert mod is not None def test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session):", "AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert isinstance(svc, AnnotationModerationService)", "not None def test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session): existing = factories.AnnotationModeration() svc.hide(existing.annotation) count =", "AnnotationModerationService from h.services.annotation_moderation import annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self, svc, factories, db_session): annotation", "svc = annotation_moderation_service_factory(None, pyramid_request) assert isinstance(svc, AnnotationModerationService) def test_it_provides_request_db_as_session(self, pyramid_request): svc = annotation_moderation_service_factory(None,", "annotation = factories.Annotation() svc.hide(annotation) mod = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation) \\ .first() assert mod", "db_session): return AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert", "factories, db_session): existing = factories.AnnotationModeration() svc.hide(existing.annotation) count = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation) \\ .count()", "-*- coding: utf-8 -*- from __future__ import unicode_literals import pytest from h import", "\\ .first() assert mod is not None def test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session): existing", "TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert isinstance(svc, AnnotationModerationService) def test_it_provides_request_db_as_session(self,", "pytest from h import models from h.services.annotation_moderation import AnnotationModerationService from h.services.annotation_moderation import annotation_moderation_service_factory", "factories, db_session): annotation = factories.Annotation() svc.hide(annotation) mod = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation) \\ .first()", "db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation) \\ .count() assert count == 1 @pytest.fixture def svc(self, db_session):", "count == 1 @pytest.fixture def svc(self, db_session): return AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self,", "test_it_creates_annotation_moderation(self, svc, factories, db_session): annotation = factories.Annotation() svc.hide(annotation) mod = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation)", "svc(self, db_session): return AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request)", ".filter_by(annotation=existing.annotation) \\ .count() assert count == 1 @pytest.fixture def svc(self, db_session): return AnnotationModerationService(db_session)", "-*- from __future__ import unicode_literals import pytest from h import models from h.services.annotation_moderation", "== 1 @pytest.fixture def svc(self, db_session): return AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self, pyramid_request):", "from h import models from h.services.annotation_moderation import AnnotationModerationService from h.services.annotation_moderation import annotation_moderation_service_factory class", "h import models from h.services.annotation_moderation import AnnotationModerationService from h.services.annotation_moderation import annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object):", "db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation) \\ .first() assert mod is not None def test_it_skips_creating_moderation_when_already_exists(self, svc,", "factories.AnnotationModeration() svc.hide(existing.annotation) count = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation) \\ .count() assert count == 1", "models from h.services.annotation_moderation import AnnotationModerationService from h.services.annotation_moderation import annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self,", "import models from h.services.annotation_moderation import AnnotationModerationService from h.services.annotation_moderation import annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object): def", "svc.hide(existing.annotation) count = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation) \\ .count() assert count == 1 @pytest.fixture", "import pytest from h import models from h.services.annotation_moderation import AnnotationModerationService from h.services.annotation_moderation import", "import unicode_literals import pytest from h import models from h.services.annotation_moderation import AnnotationModerationService from", "pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert isinstance(svc, AnnotationModerationService) def test_it_provides_request_db_as_session(self, pyramid_request): svc =", "= factories.AnnotationModeration() svc.hide(existing.annotation) count = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation) \\ .count() assert count ==", "existing = factories.AnnotationModeration() svc.hide(existing.annotation) count = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=existing.annotation) \\ .count() assert count", "__future__ import unicode_literals import pytest from h import models from h.services.annotation_moderation import AnnotationModerationService", "1 @pytest.fixture def svc(self, db_session): return AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self, pyramid_request): svc", "assert isinstance(svc, AnnotationModerationService) def test_it_provides_request_db_as_session(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert svc.session ==", "annotation_moderation_service_factory(None, pyramid_request) assert isinstance(svc, AnnotationModerationService) def test_it_provides_request_db_as_session(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert", "mod is not None def test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session): existing = factories.AnnotationModeration() svc.hide(existing.annotation)", "pyramid_request) assert isinstance(svc, AnnotationModerationService) def test_it_provides_request_db_as_session(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert svc.session", "utf-8 -*- from __future__ import unicode_literals import pytest from h import models from", "coding: utf-8 -*- from __future__ import unicode_literals import pytest from h import models", "svc, factories, db_session): annotation = factories.Annotation() svc.hide(annotation) mod = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation) \\", "mod = db_session.query(models.AnnotationModeration) \\ .filter_by(annotation=annotation) \\ .first() assert mod is not None def", "def test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session): existing = factories.AnnotationModeration() svc.hide(existing.annotation) count = db_session.query(models.AnnotationModeration) \\", "\\ .count() assert count == 1 @pytest.fixture def svc(self, db_session): return AnnotationModerationService(db_session) class", "<filename>tests/h/services/annotation_moderation_test.py # -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest from", "import AnnotationModerationService from h.services.annotation_moderation import annotation_moderation_service_factory class TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self, svc, factories, db_session):", "class TestAnnotationModerationServiceHide(object): def test_it_creates_annotation_moderation(self, svc, factories, db_session): annotation = factories.Annotation() svc.hide(annotation) mod =", "return AnnotationModerationService(db_session) class TestAnnotationNipsaServiceFactory(object): def test_it_returns_service(self, pyramid_request): svc = annotation_moderation_service_factory(None, pyramid_request) assert isinstance(svc,", "assert mod is not None def test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session): existing = factories.AnnotationModeration()" ]
[ "on 2020-02-14 10:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "dependencies = [ ('questions', '0050_data_migration'), ] operations = [ migrations.AlterField( model_name='catalog', name='sites', field=models.ManyToManyField(blank=True,", "help_text='The sites this catalog belongs to (in a multi site setup).', to='sites.Site', verbose_name='Sites'),", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('questions', '0050_data_migration'), ]", "models class Migration(migrations.Migration): dependencies = [ ('questions', '0050_data_migration'), ] operations = [ migrations.AlterField(", "[ ('questions', '0050_data_migration'), ] operations = [ migrations.AlterField( model_name='catalog', name='sites', field=models.ManyToManyField(blank=True, help_text='The sites", "2.2.9 on 2020-02-14 10:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "# Generated by Django 2.2.9 on 2020-02-14 10:33 from django.db import migrations, models", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('questions', '0050_data_migration'), ] operations =", "migrations.AlterField( model_name='catalog', name='sites', field=models.ManyToManyField(blank=True, help_text='The sites this catalog belongs to (in a multi", "('questions', '0050_data_migration'), ] operations = [ migrations.AlterField( model_name='catalog', name='sites', field=models.ManyToManyField(blank=True, help_text='The sites this", "] operations = [ migrations.AlterField( model_name='catalog', name='sites', field=models.ManyToManyField(blank=True, help_text='The sites this catalog belongs", "'0050_data_migration'), ] operations = [ migrations.AlterField( model_name='catalog', name='sites', field=models.ManyToManyField(blank=True, help_text='The sites this catalog", "field=models.ManyToManyField(blank=True, help_text='The sites this catalog belongs to (in a multi site setup).', to='sites.Site',", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('questions', '0050_data_migration'), ] operations", "Migration(migrations.Migration): dependencies = [ ('questions', '0050_data_migration'), ] operations = [ migrations.AlterField( model_name='catalog', name='sites',", "[ migrations.AlterField( model_name='catalog', name='sites', field=models.ManyToManyField(blank=True, help_text='The sites this catalog belongs to (in a", "Generated by Django 2.2.9 on 2020-02-14 10:33 from django.db import migrations, models class", "operations = [ migrations.AlterField( model_name='catalog', name='sites', field=models.ManyToManyField(blank=True, help_text='The sites this catalog belongs to", "= [ ('questions', '0050_data_migration'), ] operations = [ migrations.AlterField( model_name='catalog', name='sites', field=models.ManyToManyField(blank=True, help_text='The", "10:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('questions', '0050_data_migration'),", "Django 2.2.9 on 2020-02-14 10:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "this catalog belongs to (in a multi site setup).', to='sites.Site', verbose_name='Sites'), ), ]", "migrations, models class Migration(migrations.Migration): dependencies = [ ('questions', '0050_data_migration'), ] operations = [", "class Migration(migrations.Migration): dependencies = [ ('questions', '0050_data_migration'), ] operations = [ migrations.AlterField( model_name='catalog',", "model_name='catalog', name='sites', field=models.ManyToManyField(blank=True, help_text='The sites this catalog belongs to (in a multi site", "name='sites', field=models.ManyToManyField(blank=True, help_text='The sites this catalog belongs to (in a multi site setup).',", "2020-02-14 10:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('questions',", "by Django 2.2.9 on 2020-02-14 10:33 from django.db import migrations, models class Migration(migrations.Migration):", "= [ migrations.AlterField( model_name='catalog', name='sites', field=models.ManyToManyField(blank=True, help_text='The sites this catalog belongs to (in", "sites this catalog belongs to (in a multi site setup).', to='sites.Site', verbose_name='Sites'), )," ]
[ "'admin' in request.path: return {} else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart object in the", "from .models import Category,PledgeItem,Pledge from .views import pledge_id_fn def counter(request): item_count=0 if 'admin'", "only a single pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item in pledge_items: item_count+=pledge_item.quantity except Pledge.DoesNotExist:", "pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item in pledge_items: item_count+=pledge_item.quantity except Pledge.DoesNotExist: item_count=0 return dict(item_count=item_count)", "a single pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item in pledge_items: item_count+=pledge_item.quantity except Pledge.DoesNotExist: item_count=0", "in the current session #find the current pledged_item in the session and return", "#find the current pledged_item in the session and return only a single pledge_items", "def counter(request): item_count=0 if 'admin' in request.path: return {} else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify", ".views import pledge_id_fn def counter(request): item_count=0 if 'admin' in request.path: return {} else:", "try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart object in the current session #find the current pledged_item", "else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart object in the current session #find the current", "item_count=0 if 'admin' in request.path: return {} else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart object", "if 'admin' in request.path: return {} else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart object in", "object in the current session #find the current pledged_item in the session and", "pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart object in the current session #find the current pledged_item in", "current pledged_item in the session and return only a single pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1])", "return {} else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart object in the current session #find", "in request.path: return {} else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart object in the current", "<filename>members/context_processors.py from .models import Category,PledgeItem,Pledge from .views import pledge_id_fn def counter(request): item_count=0 if", "pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item in pledge_items: item_count+=pledge_item.quantity except Pledge.DoesNotExist: item_count=0 return dict(item_count=item_count) def menu_links(request):", ".models import Category,PledgeItem,Pledge from .views import pledge_id_fn def counter(request): item_count=0 if 'admin' in", "current session #find the current pledged_item in the session and return only a", "pledge_id_fn def counter(request): item_count=0 if 'admin' in request.path: return {} else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request))", "the current session #find the current pledged_item in the session and return only", "request.path: return {} else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart object in the current session", "and return only a single pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item in pledge_items: item_count+=pledge_item.quantity", "in the session and return only a single pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item", "return only a single pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item in pledge_items: item_count+=pledge_item.quantity except", "object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item in pledge_items: item_count+=pledge_item.quantity except Pledge.DoesNotExist: item_count=0 return dict(item_count=item_count) def", "for pledge_item in pledge_items: item_count+=pledge_item.quantity except Pledge.DoesNotExist: item_count=0 return dict(item_count=item_count) def menu_links(request): links=Category.objects.all()", "import Category,PledgeItem,Pledge from .views import pledge_id_fn def counter(request): item_count=0 if 'admin' in request.path:", "session and return only a single pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item in pledge_items:", "counter(request): item_count=0 if 'admin' in request.path: return {} else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart", "the session and return only a single pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item in", "import pledge_id_fn def counter(request): item_count=0 if 'admin' in request.path: return {} else: try:", "#specify cart object in the current session #find the current pledged_item in the", "from .views import pledge_id_fn def counter(request): item_count=0 if 'admin' in request.path: return {}", "single pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for pledge_item in pledge_items: item_count+=pledge_item.quantity except Pledge.DoesNotExist: item_count=0 return", "Category,PledgeItem,Pledge from .views import pledge_id_fn def counter(request): item_count=0 if 'admin' in request.path: return", "pledge_item in pledge_items: item_count+=pledge_item.quantity except Pledge.DoesNotExist: item_count=0 return dict(item_count=item_count) def menu_links(request): links=Category.objects.all() return", "{} else: try: pledge=Pledge.objects.filter(pledge_id=pledge_id_fn(request)) #specify cart object in the current session #find the", "session #find the current pledged_item in the session and return only a single", "cart object in the current session #find the current pledged_item in the session", "the current pledged_item in the session and return only a single pledge_items object", "in pledge_items: item_count+=pledge_item.quantity except Pledge.DoesNotExist: item_count=0 return dict(item_count=item_count) def menu_links(request): links=Category.objects.all() return dict(links=links)", "pledged_item in the session and return only a single pledge_items object pledge_items=PledgeItem.objects.all().filter(pledge=pledge[:1]) for" ]
[ "import COPPER_API_TOKEN, COPPER_API_EMAIL from copper_sdk.copper import Copper @pytest.fixture(scope='session') def copper(): return Copper(COPPER_API_TOKEN, COPPER_API_EMAIL)", "copper_sdk import COPPER_API_TOKEN, COPPER_API_EMAIL from copper_sdk.copper import Copper @pytest.fixture(scope='session') def copper(): return Copper(COPPER_API_TOKEN,", "pytest from copper_sdk import COPPER_API_TOKEN, COPPER_API_EMAIL from copper_sdk.copper import Copper @pytest.fixture(scope='session') def copper():", "from copper_sdk import COPPER_API_TOKEN, COPPER_API_EMAIL from copper_sdk.copper import Copper @pytest.fixture(scope='session') def copper(): return", "import pytest from copper_sdk import COPPER_API_TOKEN, COPPER_API_EMAIL from copper_sdk.copper import Copper @pytest.fixture(scope='session') def" ]
[ "get_absolute_path(file_name) wb = openpyxl.load_workbook(excel_file_path) sheet = wb.active max_col = sheet.max_column column_map = []", "sheet.max_column column_map = [] for i in range(1,max_col+1): cell_obj = sheet.cell(row=1,column=i) column_map.append({ \"excel_column\"", "\"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if is_private else 'public', 'files', file_name)[1:] @frappe.whitelist() def get_column_names(file_name): excel_file_path =", "get_column_names(file_name): excel_file_path = get_absolute_path(file_name) wb = openpyxl.load_workbook(excel_file_path) sheet = wb.active max_col = sheet.max_column", "= openpyxl.load_workbook(excel_file_path) sheet = wb.active max_col = sheet.max_column column_map = [] for i", "get_files_path, get_site_path, get_site_base_path import openpyxl,re def get_absolute_path(file_name, is_private=False): site_name = get_site_base_path() if(file_name.startswith('/files/')): file_name", "import openpyxl,re def get_absolute_path(file_name, is_private=False): site_name = get_site_base_path() if(file_name.startswith('/files/')): file_name = file_name[7:] return", "file_name)[1:] @frappe.whitelist() def get_column_names(file_name): excel_file_path = get_absolute_path(file_name) wb = openpyxl.load_workbook(excel_file_path) sheet = wb.active", "[] for i in range(1,max_col+1): cell_obj = sheet.cell(row=1,column=i) column_map.append({ \"excel_column\" : cell_obj.value, \"import_column\":", "if is_private else 'public', 'files', file_name)[1:] @frappe.whitelist() def get_column_names(file_name): excel_file_path = get_absolute_path(file_name) wb", "for i in range(1,max_col+1): cell_obj = sheet.cell(row=1,column=i) column_map.append({ \"excel_column\" : cell_obj.value, \"import_column\": \"\"", "openpyxl,re def get_absolute_path(file_name, is_private=False): site_name = get_site_base_path() if(file_name.startswith('/files/')): file_name = file_name[7:] return frappe.utils.get_bench_path()+", "@frappe.whitelist() def get_column_names(file_name): excel_file_path = get_absolute_path(file_name) wb = openpyxl.load_workbook(excel_file_path) sheet = wb.active max_col", "get_site_base_path import openpyxl,re def get_absolute_path(file_name, is_private=False): site_name = get_site_base_path() if(file_name.startswith('/files/')): file_name = file_name[7:]", "column_map = [] for i in range(1,max_col+1): cell_obj = sheet.cell(row=1,column=i) column_map.append({ \"excel_column\" :", "'files', file_name)[1:] @frappe.whitelist() def get_column_names(file_name): excel_file_path = get_absolute_path(file_name) wb = openpyxl.load_workbook(excel_file_path) sheet =", "else 'public', 'files', file_name)[1:] @frappe.whitelist() def get_column_names(file_name): excel_file_path = get_absolute_path(file_name) wb = openpyxl.load_workbook(excel_file_path)", "frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if is_private else 'public', 'files', file_name)[1:] @frappe.whitelist() def get_column_names(file_name): excel_file_path", "def get_absolute_path(file_name, is_private=False): site_name = get_site_base_path() if(file_name.startswith('/files/')): file_name = file_name[7:] return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+", "import frappe from frappe.utils import get_files_path, get_site_path, get_site_base_path import openpyxl,re def get_absolute_path(file_name, is_private=False):", "get_site_base_path() if(file_name.startswith('/files/')): file_name = file_name[7:] return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if is_private else 'public',", "frappe.utils.get_path('private' if is_private else 'public', 'files', file_name)[1:] @frappe.whitelist() def get_column_names(file_name): excel_file_path = get_absolute_path(file_name)", "site_name = get_site_base_path() if(file_name.startswith('/files/')): file_name = file_name[7:] return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if is_private", "file_name = file_name[7:] return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if is_private else 'public', 'files', file_name)[1:]", "wb.active max_col = sheet.max_column column_map = [] for i in range(1,max_col+1): cell_obj =", "i in range(1,max_col+1): cell_obj = sheet.cell(row=1,column=i) column_map.append({ \"excel_column\" : cell_obj.value, \"import_column\": \"\" })", "is_private=False): site_name = get_site_base_path() if(file_name.startswith('/files/')): file_name = file_name[7:] return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if", "'public', 'files', file_name)[1:] @frappe.whitelist() def get_column_names(file_name): excel_file_path = get_absolute_path(file_name) wb = openpyxl.load_workbook(excel_file_path) sheet", "get_site_path, get_site_base_path import openpyxl,re def get_absolute_path(file_name, is_private=False): site_name = get_site_base_path() if(file_name.startswith('/files/')): file_name =", "get_absolute_path(file_name, is_private=False): site_name = get_site_base_path() if(file_name.startswith('/files/')): file_name = file_name[7:] return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private'", "= sheet.max_column column_map = [] for i in range(1,max_col+1): cell_obj = sheet.cell(row=1,column=i) column_map.append({", "sheet = wb.active max_col = sheet.max_column column_map = [] for i in range(1,max_col+1):", "wb = openpyxl.load_workbook(excel_file_path) sheet = wb.active max_col = sheet.max_column column_map = [] for", "is_private else 'public', 'files', file_name)[1:] @frappe.whitelist() def get_column_names(file_name): excel_file_path = get_absolute_path(file_name) wb =", "= file_name[7:] return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if is_private else 'public', 'files', file_name)[1:] @frappe.whitelist()", "return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if is_private else 'public', 'files', file_name)[1:] @frappe.whitelist() def get_column_names(file_name):", "import get_files_path, get_site_path, get_site_base_path import openpyxl,re def get_absolute_path(file_name, is_private=False): site_name = get_site_base_path() if(file_name.startswith('/files/')):", "if(file_name.startswith('/files/')): file_name = file_name[7:] return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if is_private else 'public', 'files',", "= wb.active max_col = sheet.max_column column_map = [] for i in range(1,max_col+1): cell_obj", "frappe.utils import get_files_path, get_site_path, get_site_base_path import openpyxl,re def get_absolute_path(file_name, is_private=False): site_name = get_site_base_path()", "in range(1,max_col+1): cell_obj = sheet.cell(row=1,column=i) column_map.append({ \"excel_column\" : cell_obj.value, \"import_column\": \"\" }) return", "def get_column_names(file_name): excel_file_path = get_absolute_path(file_name) wb = openpyxl.load_workbook(excel_file_path) sheet = wb.active max_col =", "excel_file_path = get_absolute_path(file_name) wb = openpyxl.load_workbook(excel_file_path) sheet = wb.active max_col = sheet.max_column column_map", "range(1,max_col+1): cell_obj = sheet.cell(row=1,column=i) column_map.append({ \"excel_column\" : cell_obj.value, \"import_column\": \"\" }) return column_map", "frappe from frappe.utils import get_files_path, get_site_path, get_site_base_path import openpyxl,re def get_absolute_path(file_name, is_private=False): site_name", "= get_site_base_path() if(file_name.startswith('/files/')): file_name = file_name[7:] return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if is_private else", "openpyxl.load_workbook(excel_file_path) sheet = wb.active max_col = sheet.max_column column_map = [] for i in", "max_col = sheet.max_column column_map = [] for i in range(1,max_col+1): cell_obj = sheet.cell(row=1,column=i)", "= get_absolute_path(file_name) wb = openpyxl.load_workbook(excel_file_path) sheet = wb.active max_col = sheet.max_column column_map =", "<reponame>saeedkola/cefiro_customizations import frappe from frappe.utils import get_files_path, get_site_path, get_site_base_path import openpyxl,re def get_absolute_path(file_name,", "from frappe.utils import get_files_path, get_site_path, get_site_base_path import openpyxl,re def get_absolute_path(file_name, is_private=False): site_name =", "file_name[7:] return frappe.utils.get_bench_path()+ \"/sites/\"+site_name[2:]+\"/\"+ frappe.utils.get_path('private' if is_private else 'public', 'files', file_name)[1:] @frappe.whitelist() def", "= [] for i in range(1,max_col+1): cell_obj = sheet.cell(row=1,column=i) column_map.append({ \"excel_column\" : cell_obj.value," ]
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "# See the License for the specific language governing permissions and # limitations", "License. # You may obtain a copy of the License at # #", "embedding_dim=50) def get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list)", "# Copyright 2021 PaddleFSL Authors # # Licensed under the Apache License, Version", "rc_init_vector_test(): vector = vector_initializer( tokens=['yes', 'it', 'is', '*9*', '6$'], head_position=[0], tail_position=[2], max_len=6 )", "= vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list) def search_tokens_test(): vector = vector_initializer.search_tokens(['i', 'love', 'robin', '[PAD]'])", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list) def search_tokens_test():", "compliance with the License. # You may obtain a copy of the License", "def search_tokens_test(): vector = vector_initializer.search_tokens(['i', 'love', 'robin', '[PAD]']) print(vector) print(vector.shape) def rc_init_vector_test(): vector", "print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list) def search_tokens_test(): vector = vector_initializer.search_tokens(['i', 'love',", "Authors # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "the specific language governing permissions and # limitations under the License. from paddlefsl.backbones", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "this file except in compliance with the License. # You may obtain a", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "vector = vector_initializer( tokens=['yes', 'it', 'is', '*9*', '6$'], head_position=[0], tail_position=[2], max_len=6 ) print(len(vector_initializer))", "def get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list) def", "you may not use this file except in compliance with the License. #", "= RCInitVector(corpus='glove-wiki', embedding_dim=50) def get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i', 'love',", "tokens=['yes', 'it', 'is', '*9*', '6$'], head_position=[0], tail_position=[2], max_len=6 ) print(len(vector_initializer)) print(vector) print(vector.shape) if", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "ANY KIND, either express or implied. # See the License for the specific", "permissions and # limitations under the License. from paddlefsl.backbones import RCInitVector vector_initializer =", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "= vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list) def search_tokens_test(): vector =", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "use this file except in compliance with the License. # You may obtain", "'it', 'is', '*9*', '6$'], head_position=[0], tail_position=[2], max_len=6 ) print(len(vector_initializer)) print(vector) print(vector.shape) if __name__", "print(vector.shape) def rc_init_vector_test(): vector = vector_initializer( tokens=['yes', 'it', 'is', '*9*', '6$'], head_position=[0], tail_position=[2],", "vector = vector_initializer.search_tokens(['i', 'love', 'robin', '[PAD]']) print(vector) print(vector.shape) def rc_init_vector_test(): vector = vector_initializer(", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "not use this file except in compliance with the License. # You may", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "RCInitVector(corpus='glove-wiki', embedding_dim=50) def get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i', 'love', 'you'])", "See the License for the specific language governing permissions and # limitations under", "RCInitVector vector_initializer = RCInitVector(corpus='glove-wiki', embedding_dim=50) def get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list =", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "License, Version 2.0 (the \"License\"); # you may not use this file except", "and # limitations under the License. from paddlefsl.backbones import RCInitVector vector_initializer = RCInitVector(corpus='glove-wiki',", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list) def search_tokens_test(): vector = vector_initializer.search_tokens(['i', 'love', 'robin', '[PAD]']) print(vector)", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "from paddlefsl.backbones import RCInitVector vector_initializer = RCInitVector(corpus='glove-wiki', embedding_dim=50) def get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]')", "OF ANY KIND, either express or implied. # See the License for the", "PaddleFSL Authors # # Licensed under the Apache License, Version 2.0 (the \"License\");", "License. from paddlefsl.backbones import RCInitVector vector_initializer = RCInitVector(corpus='glove-wiki', embedding_dim=50) def get_idx_list_from_words_test(): idx_list =", "'is', '*9*', '6$'], head_position=[0], tail_position=[2], max_len=6 ) print(len(vector_initializer)) print(vector) print(vector.shape) if __name__ ==", "2.0 (the \"License\"); # you may not use this file except in compliance", "tail_position=[2], max_len=6 ) print(len(vector_initializer)) print(vector) print(vector.shape) if __name__ == '__main__': get_idx_list_from_words_test() search_tokens_test() rc_init_vector_test()", "# you may not use this file except in compliance with the License.", "agreed to in writing, software # distributed under the License is distributed on", "Copyright 2021 PaddleFSL Authors # # Licensed under the Apache License, Version 2.0", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "paddlefsl.backbones import RCInitVector vector_initializer = RCInitVector(corpus='glove-wiki', embedding_dim=50) def get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list)", "(the \"License\"); # you may not use this file except in compliance with", "specific language governing permissions and # limitations under the License. from paddlefsl.backbones import", "'love', 'you']) print(idx_list) def search_tokens_test(): vector = vector_initializer.search_tokens(['i', 'love', 'robin', '[PAD]']) print(vector) print(vector.shape)", "# # Unless required by applicable law or agreed to in writing, software", "express or implied. # See the License for the specific language governing permissions", "Version 2.0 (the \"License\"); # you may not use this file except in", "# Unless required by applicable law or agreed to in writing, software #", "for the specific language governing permissions and # limitations under the License. from", "except in compliance with the License. # You may obtain a copy of", "by applicable law or agreed to in writing, software # distributed under the", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "either express or implied. # See the License for the specific language governing", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "= vector_initializer( tokens=['yes', 'it', 'is', '*9*', '6$'], head_position=[0], tail_position=[2], max_len=6 ) print(len(vector_initializer)) print(vector)", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "2021 PaddleFSL Authors # # Licensed under the Apache License, Version 2.0 (the", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "governing permissions and # limitations under the License. from paddlefsl.backbones import RCInitVector vector_initializer", "file except in compliance with the License. # You may obtain a copy", "print(idx_list) def search_tokens_test(): vector = vector_initializer.search_tokens(['i', 'love', 'robin', '[PAD]']) print(vector) print(vector.shape) def rc_init_vector_test():", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list) def search_tokens_test(): vector", "vector_initializer = RCInitVector(corpus='glove-wiki', embedding_dim=50) def get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i',", "License for the specific language governing permissions and # limitations under the License.", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "the License. # You may obtain a copy of the License at #", "language governing permissions and # limitations under the License. from paddlefsl.backbones import RCInitVector", "vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list) def search_tokens_test(): vector = vector_initializer.search_tokens(['i',", "to in writing, software # distributed under the License is distributed on an", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "vector_initializer.search_tokens(['i', 'love', 'robin', '[PAD]']) print(vector) print(vector.shape) def rc_init_vector_test(): vector = vector_initializer( tokens=['yes', 'it',", "implied. # See the License for the specific language governing permissions and #", "\"License\"); # you may not use this file except in compliance with the", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "= vector_initializer.search_tokens(['i', 'love', 'robin', '[PAD]']) print(vector) print(vector.shape) def rc_init_vector_test(): vector = vector_initializer( tokens=['yes',", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "vector_initializer( tokens=['yes', 'it', 'is', '*9*', '6$'], head_position=[0], tail_position=[2], max_len=6 ) print(len(vector_initializer)) print(vector) print(vector.shape)", "required by applicable law or agreed to in writing, software # distributed under", "head_position=[0], tail_position=[2], max_len=6 ) print(len(vector_initializer)) print(vector) print(vector.shape) if __name__ == '__main__': get_idx_list_from_words_test() search_tokens_test()", "applicable law or agreed to in writing, software # distributed under the License", "'6$'], head_position=[0], tail_position=[2], max_len=6 ) print(len(vector_initializer)) print(vector) print(vector.shape) if __name__ == '__main__': get_idx_list_from_words_test()", "the License. from paddlefsl.backbones import RCInitVector vector_initializer = RCInitVector(corpus='glove-wiki', embedding_dim=50) def get_idx_list_from_words_test(): idx_list", "search_tokens_test(): vector = vector_initializer.search_tokens(['i', 'love', 'robin', '[PAD]']) print(vector) print(vector.shape) def rc_init_vector_test(): vector =", "print(vector) print(vector.shape) def rc_init_vector_test(): vector = vector_initializer( tokens=['yes', 'it', 'is', '*9*', '6$'], head_position=[0],", "under the License. from paddlefsl.backbones import RCInitVector vector_initializer = RCInitVector(corpus='glove-wiki', embedding_dim=50) def get_idx_list_from_words_test():", "'robin', '[PAD]']) print(vector) print(vector.shape) def rc_init_vector_test(): vector = vector_initializer( tokens=['yes', 'it', 'is', '*9*',", "idx_list = vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list) def search_tokens_test(): vector = vector_initializer.search_tokens(['i', 'love', 'robin',", "'love', 'robin', '[PAD]']) print(vector) print(vector.shape) def rc_init_vector_test(): vector = vector_initializer( tokens=['yes', 'it', 'is',", "or agreed to in writing, software # distributed under the License is distributed", "'you']) print(idx_list) def search_tokens_test(): vector = vector_initializer.search_tokens(['i', 'love', 'robin', '[PAD]']) print(vector) print(vector.shape) def", "or implied. # See the License for the specific language governing permissions and", "# limitations under the License. from paddlefsl.backbones import RCInitVector vector_initializer = RCInitVector(corpus='glove-wiki', embedding_dim=50)", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "def rc_init_vector_test(): vector = vector_initializer( tokens=['yes', 'it', 'is', '*9*', '6$'], head_position=[0], tail_position=[2], max_len=6", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "limitations under the License. from paddlefsl.backbones import RCInitVector vector_initializer = RCInitVector(corpus='glove-wiki', embedding_dim=50) def", "import RCInitVector vector_initializer = RCInitVector(corpus='glove-wiki', embedding_dim=50) def get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list", "with the License. # You may obtain a copy of the License at", "'[PAD]']) print(vector) print(vector.shape) def rc_init_vector_test(): vector = vector_initializer( tokens=['yes', 'it', 'is', '*9*', '6$'],", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "'*9*', '6$'], head_position=[0], tail_position=[2], max_len=6 ) print(len(vector_initializer)) print(vector) print(vector.shape) if __name__ == '__main__':", "under the Apache License, Version 2.0 (the \"License\"); # you may not use" ]
[]
[ "accounts not cracked by john are displayed\") parser.add_argument('-v', '--verbose', action=\"store_true\", dest=\"verbose\", default=False, help=\"display", "john_result_file: f = open(john_result_file) john = f.read().lower() f.close() if output: f = open(output,", "Default is stdout') parser.add_argument('HASH_FILE', action=\"store\", help=\"The result file of impacket-secretsdump\") parser.add_argument('-j', '--john', action=\"store\",", "+= 1 del(ntlm[\"safe\"][line[:-1]]) if verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\", file=sys.stderr) leak.close() def export(ntlm,", "output: f = open(output, \"a+\") cpt = 0 for c in ntlm[\"cracked\"]: line", "return hashes, ntlm def searchLeaked(leakfile, ntlm, verbose): leak = open(leakfile,\"r\") cpt = 0", "file=sys.stderr) for line in leak: if line[:-1] in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]] cpt", "print(f\"New {cpt} compromised\") if output: f.close() def main(): parser = argparse.ArgumentParser(description='List accounts compromised", "john_result_file='', output=''): john = '' if john_result_file: f = open(john_result_file) john = f.read().lower()", "(long) ...\", file=sys.stderr) for line in leak: if line[:-1] in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] =", "parser.add_argument('-j', '--john', action=\"store\", dest=\"john_file\", default='', help=\"If used, only the accounts not cracked by", "john = f.read().lower() f.close() if output: f = open(output, \"a+\") cpt = 0", "h = i.split(':') ntlm[\"safe\"][h[3].upper()] = h[0].lower() except Exception as e: pass return hashes,", "action=\"store\", help=\"The result file of impacket-secretsdump\") parser.add_argument('-j', '--john', action=\"store\", dest=\"john_file\", default='', help=\"If used,", "default='', help='A path to store the results. Default is stdout') parser.add_argument('HASH_FILE', action=\"store\", help=\"The", "for line in leak: if line[:-1] in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]] cpt +=", "sys def readHashFile(hashfile): f = open(hashfile) hashes = f.read().split('\\n')[:-1] ntlm ={\"cracked\":{}, \"safe\":{}} f.close()", "not cracked by john are displayed\") parser.add_argument('-v', '--verbose', action=\"store_true\", dest=\"verbose\", default=False, help=\"display the", "0 for c in ntlm[\"cracked\"]: line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c] not in john:", "cpt += 1 del(ntlm[\"safe\"][line[:-1]]) if verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\", file=sys.stderr) leak.close() def", "if verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\", file=sys.stderr) leak.close() def export(ntlm, john_result_file='', output=''): john", "help=\"The wordlist containing the NTLM leaked\") args = parser.parse_args() hashes, ntlm = readHashFile(args.HASH_FILE)", "i.split(':') ntlm[\"safe\"][h[3].upper()] = h[0].lower() except Exception as e: pass return hashes, ntlm def", "args = parser.parse_args() hashes, ntlm = readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE, ntlm, args.verbose) export(ntlm, args.john_file, args.path)", "main(): parser = argparse.ArgumentParser(description='List accounts compromised in public leaked NTLMs', add_help=True) parser.add_argument('-w', '--write',", "if output : f.write(line+'\\n') else: print(line) cpt += 1 if john_result_file: print(f\"New {cpt}", "the accounts not cracked by john are displayed\") parser.add_argument('-v', '--verbose', action=\"store_true\", dest=\"verbose\", default=False,", "print(f\"{cpt} compromised\", file=sys.stderr) leak.close() def export(ntlm, john_result_file='', output=''): john = '' if john_result_file:", "h[0].lower() except Exception as e: pass return hashes, ntlm def searchLeaked(leakfile, ntlm, verbose):", "if output: f = open(output, \"a+\") cpt = 0 for c in ntlm[\"cracked\"]:", "open(hashfile) hashes = f.read().split('\\n')[:-1] ntlm ={\"cracked\":{}, \"safe\":{}} f.close() for i in hashes: try:", "in hashes: try: h = i.split(':') ntlm[\"safe\"][h[3].upper()] = h[0].lower() except Exception as e:", ": f.write(line+'\\n') else: print(line) cpt += 1 if john_result_file: print(f\"New {cpt} compromised\") if", "action=\"store\", help=\"The wordlist containing the NTLM leaked\") args = parser.parse_args() hashes, ntlm =", "ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\", file=sys.stderr) leak.close() def export(ntlm, john_result_file='', output=''): john = '' if", "if ntlm[\"cracked\"][c] not in john: if output : f.write(line+'\\n') else: print(line) cpt +=", "= open(output, \"a+\") cpt = 0 for c in ntlm[\"cracked\"]: line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\"", "against hashes (long) ...\", file=sys.stderr) for line in leak: if line[:-1] in ntlm[\"safe\"]:", "line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c] not in john: if output : f.write(line+'\\n') else:", "not in john: if output : f.write(line+'\\n') else: print(line) cpt += 1 if", "the cracked accounts in real time\") parser.add_argument('LEAK_FILE', action=\"store\", help=\"The wordlist containing the NTLM", "= parser.parse_args() hashes, ntlm = readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE, ntlm, args.verbose) export(ntlm, args.john_file, args.path) if", "leak: if line[:-1] in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]] cpt += 1 del(ntlm[\"safe\"][line[:-1]]) if", "= open(hashfile) hashes = f.read().split('\\n')[:-1] ntlm ={\"cracked\":{}, \"safe\":{}} f.close() for i in hashes:", "f = open(output, \"a+\") cpt = 0 for c in ntlm[\"cracked\"]: line =", "i in hashes: try: h = i.split(':') ntlm[\"safe\"][h[3].upper()] = h[0].lower() except Exception as", "def readHashFile(hashfile): f = open(hashfile) hashes = f.read().split('\\n')[:-1] ntlm ={\"cracked\":{}, \"safe\":{}} f.close() for", "open(output, \"a+\") cpt = 0 for c in ntlm[\"cracked\"]: line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if", "{cpt} compromised\") if output: f.close() def main(): parser = argparse.ArgumentParser(description='List accounts compromised in", "cpt = 0 print(\"[*] Checking leaked database against hashes (long) ...\", file=sys.stderr) for", "file of impacket-secretsdump\") parser.add_argument('-j', '--john', action=\"store\", dest=\"john_file\", default='', help=\"If used, only the accounts", "hashes, ntlm def searchLeaked(leakfile, ntlm, verbose): leak = open(leakfile,\"r\") cpt = 0 print(\"[*]", "cracked by john are displayed\") parser.add_argument('-v', '--verbose', action=\"store_true\", dest=\"verbose\", default=False, help=\"display the cracked", "the NTLM leaked\") args = parser.parse_args() hashes, ntlm = readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE, ntlm, args.verbose)", "= f.read().split('\\n')[:-1] ntlm ={\"cracked\":{}, \"safe\":{}} f.close() for i in hashes: try: h =", "john_result_file: print(f\"New {cpt} compromised\") if output: f.close() def main(): parser = argparse.ArgumentParser(description='List accounts", "of impacket-secretsdump\") parser.add_argument('-j', '--john', action=\"store\", dest=\"john_file\", default='', help=\"If used, only the accounts not", "f.read().split('\\n')[:-1] ntlm ={\"cracked\":{}, \"safe\":{}} f.close() for i in hashes: try: h = i.split(':')", "def searchLeaked(leakfile, ntlm, verbose): leak = open(leakfile,\"r\") cpt = 0 print(\"[*] Checking leaked", "if john_result_file: print(f\"New {cpt} compromised\") if output: f.close() def main(): parser = argparse.ArgumentParser(description='List", "real time\") parser.add_argument('LEAK_FILE', action=\"store\", help=\"The wordlist containing the NTLM leaked\") args = parser.parse_args()", "ntlm[\"cracked\"][c] not in john: if output : f.write(line+'\\n') else: print(line) cpt += 1", "action=\"store\", dest=\"john_file\", default='', help=\"If used, only the accounts not cracked by john are", "verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\", file=sys.stderr) leak.close() def export(ntlm, john_result_file='', output=''): john =", "default=False, help=\"display the cracked accounts in real time\") parser.add_argument('LEAK_FILE', action=\"store\", help=\"The wordlist containing", "hashes, ntlm = readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE, ntlm, args.verbose) export(ntlm, args.john_file, args.path) if __name__ ==", "= '' if john_result_file: f = open(john_result_file) john = f.read().lower() f.close() if output:", "= open(leakfile,\"r\") cpt = 0 print(\"[*] Checking leaked database against hashes (long) ...\",", "f.close() def main(): parser = argparse.ArgumentParser(description='List accounts compromised in public leaked NTLMs', add_help=True)", "cracked accounts in real time\") parser.add_argument('LEAK_FILE', action=\"store\", help=\"The wordlist containing the NTLM leaked\")", "in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]] cpt += 1 del(ntlm[\"safe\"][line[:-1]]) if verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]])", "except Exception as e: pass return hashes, ntlm def searchLeaked(leakfile, ntlm, verbose): leak", "+= 1 if john_result_file: print(f\"New {cpt} compromised\") if output: f.close() def main(): parser", "action=\"store_true\", dest=\"verbose\", default=False, help=\"display the cracked accounts in real time\") parser.add_argument('LEAK_FILE', action=\"store\", help=\"The", "hashes = f.read().split('\\n')[:-1] ntlm ={\"cracked\":{}, \"safe\":{}} f.close() for i in hashes: try: h", "leak.close() def export(ntlm, john_result_file='', output=''): john = '' if john_result_file: f = open(john_result_file)", "'' if john_result_file: f = open(john_result_file) john = f.read().lower() f.close() if output: f", "leak = open(leakfile,\"r\") cpt = 0 print(\"[*] Checking leaked database against hashes (long)", "database against hashes (long) ...\", file=sys.stderr) for line in leak: if line[:-1] in", "compromised\", file=sys.stderr) leak.close() def export(ntlm, john_result_file='', output=''): john = '' if john_result_file: f", "= open(john_result_file) john = f.read().lower() f.close() if output: f = open(output, \"a+\") cpt", "'--john', action=\"store\", dest=\"john_file\", default='', help=\"If used, only the accounts not cracked by john", "ntlm[\"safe\"][h[3].upper()] = h[0].lower() except Exception as e: pass return hashes, ntlm def searchLeaked(leakfile,", "ntlm = readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE, ntlm, args.verbose) export(ntlm, args.john_file, args.path) if __name__ == '__main__':", "in public leaked NTLMs', add_help=True) parser.add_argument('-w', '--write', action=\"store\", dest=\"path\", default='', help='A path to", "f.close() for i in hashes: try: h = i.split(':') ntlm[\"safe\"][h[3].upper()] = h[0].lower() except", "results. Default is stdout') parser.add_argument('HASH_FILE', action=\"store\", help=\"The result file of impacket-secretsdump\") parser.add_argument('-j', '--john',", "c in ntlm[\"cracked\"]: line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c] not in john: if output", "in ntlm[\"cracked\"]: line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c] not in john: if output :", "public leaked NTLMs', add_help=True) parser.add_argument('-w', '--write', action=\"store\", dest=\"path\", default='', help='A path to store", "store the results. Default is stdout') parser.add_argument('HASH_FILE', action=\"store\", help=\"The result file of impacket-secretsdump\")", "if output: f.close() def main(): parser = argparse.ArgumentParser(description='List accounts compromised in public leaked", "= i.split(':') ntlm[\"safe\"][h[3].upper()] = h[0].lower() except Exception as e: pass return hashes, ntlm", "output : f.write(line+'\\n') else: print(line) cpt += 1 if john_result_file: print(f\"New {cpt} compromised\")", "f.write(line+'\\n') else: print(line) cpt += 1 if john_result_file: print(f\"New {cpt} compromised\") if output:", "help=\"The result file of impacket-secretsdump\") parser.add_argument('-j', '--john', action=\"store\", dest=\"john_file\", default='', help=\"If used, only", "pass return hashes, ntlm def searchLeaked(leakfile, ntlm, verbose): leak = open(leakfile,\"r\") cpt =", "\"safe\":{}} f.close() for i in hashes: try: h = i.split(':') ntlm[\"safe\"][h[3].upper()] = h[0].lower()", "in john: if output : f.write(line+'\\n') else: print(line) cpt += 1 if john_result_file:", "ntlm, verbose): leak = open(leakfile,\"r\") cpt = 0 print(\"[*] Checking leaked database against", "'--write', action=\"store\", dest=\"path\", default='', help='A path to store the results. Default is stdout')", "f = open(john_result_file) john = f.read().lower() f.close() if output: f = open(output, \"a+\")", "dest=\"verbose\", default=False, help=\"display the cracked accounts in real time\") parser.add_argument('LEAK_FILE', action=\"store\", help=\"The wordlist", "argparse.ArgumentParser(description='List accounts compromised in public leaked NTLMs', add_help=True) parser.add_argument('-w', '--write', action=\"store\", dest=\"path\", default='',", "...\", file=sys.stderr) for line in leak: if line[:-1] in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]]", "f.read().lower() f.close() if output: f = open(output, \"a+\") cpt = 0 for c", "file=sys.stderr) leak.close() def export(ntlm, john_result_file='', output=''): john = '' if john_result_file: f =", "to store the results. Default is stdout') parser.add_argument('HASH_FILE', action=\"store\", help=\"The result file of", "used, only the accounts not cracked by john are displayed\") parser.add_argument('-v', '--verbose', action=\"store_true\",", "john are displayed\") parser.add_argument('-v', '--verbose', action=\"store_true\", dest=\"verbose\", default=False, help=\"display the cracked accounts in", "dest=\"path\", default='', help='A path to store the results. Default is stdout') parser.add_argument('HASH_FILE', action=\"store\",", "e: pass return hashes, ntlm def searchLeaked(leakfile, ntlm, verbose): leak = open(leakfile,\"r\") cpt", "print(\"[*] Checking leaked database against hashes (long) ...\", file=sys.stderr) for line in leak:", "line in leak: if line[:-1] in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]] cpt += 1", "= ntlm[\"safe\"][line[:-1]] cpt += 1 del(ntlm[\"safe\"][line[:-1]]) if verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\", file=sys.stderr)", "ntlm[\"cracked\"]: line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c] not in john: if output : f.write(line+'\\n')", "path to store the results. Default is stdout') parser.add_argument('HASH_FILE', action=\"store\", help=\"The result file", "stdout') parser.add_argument('HASH_FILE', action=\"store\", help=\"The result file of impacket-secretsdump\") parser.add_argument('-j', '--john', action=\"store\", dest=\"john_file\", default='',", "NTLMs', add_help=True) parser.add_argument('-w', '--write', action=\"store\", dest=\"path\", default='', help='A path to store the results.", "for c in ntlm[\"cracked\"]: line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c] not in john: if", "parser.parse_args() hashes, ntlm = readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE, ntlm, args.verbose) export(ntlm, args.john_file, args.path) if __name__", "= argparse.ArgumentParser(description='List accounts compromised in public leaked NTLMs', add_help=True) parser.add_argument('-w', '--write', action=\"store\", dest=\"path\",", "the results. Default is stdout') parser.add_argument('HASH_FILE', action=\"store\", help=\"The result file of impacket-secretsdump\") parser.add_argument('-j',", "john = '' if john_result_file: f = open(john_result_file) john = f.read().lower() f.close() if", "ntlm ={\"cracked\":{}, \"safe\":{}} f.close() for i in hashes: try: h = i.split(':') ntlm[\"safe\"][h[3].upper()]", "by john are displayed\") parser.add_argument('-v', '--verbose', action=\"store_true\", dest=\"verbose\", default=False, help=\"display the cracked accounts", "result file of impacket-secretsdump\") parser.add_argument('-j', '--john', action=\"store\", dest=\"john_file\", default='', help=\"If used, only the", "dest=\"john_file\", default='', help=\"If used, only the accounts not cracked by john are displayed\")", "readHashFile(hashfile): f = open(hashfile) hashes = f.read().split('\\n')[:-1] ntlm ={\"cracked\":{}, \"safe\":{}} f.close() for i", "add_help=True) parser.add_argument('-w', '--write', action=\"store\", dest=\"path\", default='', help='A path to store the results. Default", "parser.add_argument('-v', '--verbose', action=\"store_true\", dest=\"verbose\", default=False, help=\"display the cracked accounts in real time\") parser.add_argument('LEAK_FILE',", "def main(): parser = argparse.ArgumentParser(description='List accounts compromised in public leaked NTLMs', add_help=True) parser.add_argument('-w',", "verbose): leak = open(leakfile,\"r\") cpt = 0 print(\"[*] Checking leaked database against hashes", "= 0 print(\"[*] Checking leaked database against hashes (long) ...\", file=sys.stderr) for line", "john: if output : f.write(line+'\\n') else: print(line) cpt += 1 if john_result_file: print(f\"New", "compromised\") if output: f.close() def main(): parser = argparse.ArgumentParser(description='List accounts compromised in public", "try: h = i.split(':') ntlm[\"safe\"][h[3].upper()] = h[0].lower() except Exception as e: pass return", "accounts in real time\") parser.add_argument('LEAK_FILE', action=\"store\", help=\"The wordlist containing the NTLM leaked\") args", "import argparse import sys def readHashFile(hashfile): f = open(hashfile) hashes = f.read().split('\\n')[:-1] ntlm", "else: print(line) cpt += 1 if john_result_file: print(f\"New {cpt} compromised\") if output: f.close()", "def export(ntlm, john_result_file='', output=''): john = '' if john_result_file: f = open(john_result_file) john", "import sys def readHashFile(hashfile): f = open(hashfile) hashes = f.read().split('\\n')[:-1] ntlm ={\"cracked\":{}, \"safe\":{}}", "leaked database against hashes (long) ...\", file=sys.stderr) for line in leak: if line[:-1]", "line[:-1] in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]] cpt += 1 del(ntlm[\"safe\"][line[:-1]]) if verbose: print(line[:-1],", "parser = argparse.ArgumentParser(description='List accounts compromised in public leaked NTLMs', add_help=True) parser.add_argument('-w', '--write', action=\"store\",", "={\"cracked\":{}, \"safe\":{}} f.close() for i in hashes: try: h = i.split(':') ntlm[\"safe\"][h[3].upper()] =", "ntlm def searchLeaked(leakfile, ntlm, verbose): leak = open(leakfile,\"r\") cpt = 0 print(\"[*] Checking", "ntlm[\"safe\"][line[:-1]] cpt += 1 del(ntlm[\"safe\"][line[:-1]]) if verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\", file=sys.stderr) leak.close()", "= 0 for c in ntlm[\"cracked\"]: line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c] not in", "wordlist containing the NTLM leaked\") args = parser.parse_args() hashes, ntlm = readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE,", "print(line) cpt += 1 if john_result_file: print(f\"New {cpt} compromised\") if output: f.close() def", "parser.add_argument('LEAK_FILE', action=\"store\", help=\"The wordlist containing the NTLM leaked\") args = parser.parse_args() hashes, ntlm", "is stdout') parser.add_argument('HASH_FILE', action=\"store\", help=\"The result file of impacket-secretsdump\") parser.add_argument('-j', '--john', action=\"store\", dest=\"john_file\",", "= readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE, ntlm, args.verbose) export(ntlm, args.john_file, args.path) if __name__ == '__main__': main()", "= h[0].lower() except Exception as e: pass return hashes, ntlm def searchLeaked(leakfile, ntlm,", "hashes: try: h = i.split(':') ntlm[\"safe\"][h[3].upper()] = h[0].lower() except Exception as e: pass", "help=\"If used, only the accounts not cracked by john are displayed\") parser.add_argument('-v', '--verbose',", "print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\", file=sys.stderr) leak.close() def export(ntlm, john_result_file='', output=''): john = ''", "1 del(ntlm[\"safe\"][line[:-1]]) if verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\", file=sys.stderr) leak.close() def export(ntlm, john_result_file='',", "open(leakfile,\"r\") cpt = 0 print(\"[*] Checking leaked database against hashes (long) ...\", file=sys.stderr)", "0 print(\"[*] Checking leaked database against hashes (long) ...\", file=sys.stderr) for line in", "= f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c] not in john: if output : f.write(line+'\\n') else: print(line)", "argparse import sys def readHashFile(hashfile): f = open(hashfile) hashes = f.read().split('\\n')[:-1] ntlm ={\"cracked\":{},", "searchLeaked(leakfile, ntlm, verbose): leak = open(leakfile,\"r\") cpt = 0 print(\"[*] Checking leaked database", "= f.read().lower() f.close() if output: f = open(output, \"a+\") cpt = 0 for", "only the accounts not cracked by john are displayed\") parser.add_argument('-v', '--verbose', action=\"store_true\", dest=\"verbose\",", "for i in hashes: try: h = i.split(':') ntlm[\"safe\"][h[3].upper()] = h[0].lower() except Exception", "ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]] cpt += 1 del(ntlm[\"safe\"][line[:-1]]) if verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\",", "compromised in public leaked NTLMs', add_help=True) parser.add_argument('-w', '--write', action=\"store\", dest=\"path\", default='', help='A path", "in leak: if line[:-1] in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]] cpt += 1 del(ntlm[\"safe\"][line[:-1]])", "del(ntlm[\"safe\"][line[:-1]]) if verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt} compromised\", file=sys.stderr) leak.close() def export(ntlm, john_result_file='', output=''):", "cpt += 1 if john_result_file: print(f\"New {cpt} compromised\") if output: f.close() def main():", "output: f.close() def main(): parser = argparse.ArgumentParser(description='List accounts compromised in public leaked NTLMs',", "parser.add_argument('HASH_FILE', action=\"store\", help=\"The result file of impacket-secretsdump\") parser.add_argument('-j', '--john', action=\"store\", dest=\"john_file\", default='', help=\"If", "f = open(hashfile) hashes = f.read().split('\\n')[:-1] ntlm ={\"cracked\":{}, \"safe\":{}} f.close() for i in", "output=''): john = '' if john_result_file: f = open(john_result_file) john = f.read().lower() f.close()", "containing the NTLM leaked\") args = parser.parse_args() hashes, ntlm = readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE, ntlm,", "\"a+\") cpt = 0 for c in ntlm[\"cracked\"]: line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c]", "if line[:-1] in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]] cpt += 1 del(ntlm[\"safe\"][line[:-1]]) if verbose:", "ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]] = ntlm[\"safe\"][line[:-1]] cpt += 1 del(ntlm[\"safe\"][line[:-1]]) if verbose: print(line[:-1], ntlm[\"cracked\"][line[:-1]]) print(f\"{cpt}", "if john_result_file: f = open(john_result_file) john = f.read().lower() f.close() if output: f =", "help='A path to store the results. Default is stdout') parser.add_argument('HASH_FILE', action=\"store\", help=\"The result", "action=\"store\", dest=\"path\", default='', help='A path to store the results. Default is stdout') parser.add_argument('HASH_FILE',", "parser.add_argument('-w', '--write', action=\"store\", dest=\"path\", default='', help='A path to store the results. Default is", "leaked\") args = parser.parse_args() hashes, ntlm = readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE, ntlm, args.verbose) export(ntlm, args.john_file,", "1 if john_result_file: print(f\"New {cpt} compromised\") if output: f.close() def main(): parser =", "help=\"display the cracked accounts in real time\") parser.add_argument('LEAK_FILE', action=\"store\", help=\"The wordlist containing the", "'--verbose', action=\"store_true\", dest=\"verbose\", default=False, help=\"display the cracked accounts in real time\") parser.add_argument('LEAK_FILE', action=\"store\",", "in real time\") parser.add_argument('LEAK_FILE', action=\"store\", help=\"The wordlist containing the NTLM leaked\") args =", "are displayed\") parser.add_argument('-v', '--verbose', action=\"store_true\", dest=\"verbose\", default=False, help=\"display the cracked accounts in real", "displayed\") parser.add_argument('-v', '--verbose', action=\"store_true\", dest=\"verbose\", default=False, help=\"display the cracked accounts in real time\")", "#!/usr/bin/python3 import argparse import sys def readHashFile(hashfile): f = open(hashfile) hashes = f.read().split('\\n')[:-1]", "time\") parser.add_argument('LEAK_FILE', action=\"store\", help=\"The wordlist containing the NTLM leaked\") args = parser.parse_args() hashes,", "hashes (long) ...\", file=sys.stderr) for line in leak: if line[:-1] in ntlm[\"safe\"]: ntlm[\"cracked\"][line[:-1]]", "open(john_result_file) john = f.read().lower() f.close() if output: f = open(output, \"a+\") cpt =", "f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c] not in john: if output : f.write(line+'\\n') else: print(line) cpt", "accounts compromised in public leaked NTLMs', add_help=True) parser.add_argument('-w', '--write', action=\"store\", dest=\"path\", default='', help='A", "default='', help=\"If used, only the accounts not cracked by john are displayed\") parser.add_argument('-v',", "NTLM leaked\") args = parser.parse_args() hashes, ntlm = readHashFile(args.HASH_FILE) searchLeaked(args.LEAK_FILE, ntlm, args.verbose) export(ntlm,", "export(ntlm, john_result_file='', output=''): john = '' if john_result_file: f = open(john_result_file) john =", "cpt = 0 for c in ntlm[\"cracked\"]: line = f\"{ntlm['cracked'][c]}:<LeakTheWeak>:LEAK:NOLM:{c}:::\" if ntlm[\"cracked\"][c] not", "as e: pass return hashes, ntlm def searchLeaked(leakfile, ntlm, verbose): leak = open(leakfile,\"r\")", "Exception as e: pass return hashes, ntlm def searchLeaked(leakfile, ntlm, verbose): leak =", "f.close() if output: f = open(output, \"a+\") cpt = 0 for c in", "leaked NTLMs', add_help=True) parser.add_argument('-w', '--write', action=\"store\", dest=\"path\", default='', help='A path to store the", "Checking leaked database against hashes (long) ...\", file=sys.stderr) for line in leak: if", "impacket-secretsdump\") parser.add_argument('-j', '--john', action=\"store\", dest=\"john_file\", default='', help=\"If used, only the accounts not cracked" ]
[ "import read_file_by_lines inlines = read_file_by_lines(fastq, 1000 * 1000 * 1000, 4) count =", "print(\"[info] The barcode for {} is {}\".format(info[0], info[1])) path = os.path.join(outdir, sample) +", "inlines: count += 1 barcode = line[0].strip().split(\":\")[-1] if barcode in bc_files: bc_buffers[barcode].append(\"\".join(line)) if", "in buffer.keys(): filehandles[key].writelines(buffer[key]) buffer[key] = [] def write_and_close(buffer, filehandles): for key in buffer.keys():", "= info[0] barcode = info[1] print(\"[info] The barcode for {} is {}\".format(info[0], info[1]))", "reads... from baseq.utils.file_reader import read_file_by_lines inlines = read_file_by_lines(fastq, 1000 * 1000 * 1000,", "buffer.keys(): filehandles[key].writelines(buffer[key]) buffer[key] = [] def write_and_close(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key])", "def split_barcode(barcode_file, fastq, outdir, suffix): \"\"\" barcode_file: tsv: samplename barcode_string... \"\"\" with open(barcode_file,", "+ \".\" + suffix print(\"[info] File for '{}' is '{}'\".format(sample, path)) bc_files[barcode] =", "barcode for {} is {}\".format(info[0], info[1])) path = os.path.join(outdir, sample) + \".\" +", "{}\".format(info[0], info[1])) path = os.path.join(outdir, sample) + \".\" + suffix print(\"[info] File for", "file: barcodes = file.readlines() bc_files = {} bc_buffers = {} for bc in", "is {}\".format(info[0], info[1])) path = os.path.join(outdir, sample) + \".\" + suffix print(\"[info] File", "+= 1 barcode = line[0].strip().split(\":\")[-1] if barcode in bc_files: bc_buffers[barcode].append(\"\".join(line)) if count %", "line[0].strip().split(\":\")[-1] if barcode in bc_files: bc_buffers[barcode].append(\"\".join(line)) if count % 1000000 == 1: write_buffer(bc_buffers,", "* 1000, 4) count = 0 for line in inlines: count += 1", "* 1000 * 1000, 4) count = 0 for line in inlines: count", "os def write_buffer(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) buffer[key] = [] def", "[] def write_and_close(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close() def split_barcode(barcode_file, fastq,", "0 for line in inlines: count += 1 barcode = line[0].strip().split(\":\")[-1] if barcode", "write_buffer(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) buffer[key] = [] def write_and_close(buffer, filehandles):", "read_file_by_lines(fastq, 1000 * 1000 * 1000, 4) count = 0 for line in", "open(barcode_file, 'r') as file: barcodes = file.readlines() bc_files = {} bc_buffers = {}", "= [] def write_and_close(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close() def split_barcode(barcode_file,", "open(path, \"w\") bc_buffers[barcode] = [] #Iterating the reads... from baseq.utils.file_reader import read_file_by_lines inlines", "filehandles[key].close() def split_barcode(barcode_file, fastq, outdir, suffix): \"\"\" barcode_file: tsv: samplename barcode_string... \"\"\" with", "for '{}' is '{}'\".format(sample, path)) bc_files[barcode] = open(path, \"w\") bc_buffers[barcode] = [] #Iterating", "in barcodes: info = [x.strip() for x in bc.split()] if len(info) == 2:", "= file.readlines() bc_files = {} bc_buffers = {} for bc in barcodes: info", "key in buffer.keys(): filehandles[key].writelines(buffer[key]) buffer[key] = [] def write_and_close(buffer, filehandles): for key in", "filehandles[key].writelines(buffer[key]) buffer[key] = [] def write_and_close(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close()", "'r') as file: barcodes = file.readlines() bc_files = {} bc_buffers = {} for", "suffix print(\"[info] File for '{}' is '{}'\".format(sample, path)) bc_files[barcode] = open(path, \"w\") bc_buffers[barcode]", "is '{}'\".format(sample, path)) bc_files[barcode] = open(path, \"w\") bc_buffers[barcode] = [] #Iterating the reads...", "x in bc.split()] if len(info) == 2: sample = info[0] barcode = info[1]", "info[0] barcode = info[1] print(\"[info] The barcode for {} is {}\".format(info[0], info[1])) path", "barcodes = file.readlines() bc_files = {} bc_buffers = {} for bc in barcodes:", "4) count = 0 for line in inlines: count += 1 barcode =", "print(\"[info] File for '{}' is '{}'\".format(sample, path)) bc_files[barcode] = open(path, \"w\") bc_buffers[barcode] =", "[x.strip() for x in bc.split()] if len(info) == 2: sample = info[0] barcode", "{} bc_buffers = {} for bc in barcodes: info = [x.strip() for x", "line in inlines: count += 1 barcode = line[0].strip().split(\":\")[-1] if barcode in bc_files:", "{} is {}\".format(info[0], info[1])) path = os.path.join(outdir, sample) + \".\" + suffix print(\"[info]", "in bc.split()] if len(info) == 2: sample = info[0] barcode = info[1] print(\"[info]", "#Iterating the reads... from baseq.utils.file_reader import read_file_by_lines inlines = read_file_by_lines(fastq, 1000 * 1000", "from baseq.utils.file_reader import read_file_by_lines inlines = read_file_by_lines(fastq, 1000 * 1000 * 1000, 4)", "<gh_stars>1-10 import os def write_buffer(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) buffer[key] =", "suffix): \"\"\" barcode_file: tsv: samplename barcode_string... \"\"\" with open(barcode_file, 'r') as file: barcodes", "the reads... from baseq.utils.file_reader import read_file_by_lines inlines = read_file_by_lines(fastq, 1000 * 1000 *", "path = os.path.join(outdir, sample) + \".\" + suffix print(\"[info] File for '{}' is", "def write_and_close(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close() def split_barcode(barcode_file, fastq, outdir,", "== 2: sample = info[0] barcode = info[1] print(\"[info] The barcode for {}", "for x in bc.split()] if len(info) == 2: sample = info[0] barcode =", "for key in buffer.keys(): filehandles[key].writelines(buffer[key]) buffer[key] = [] def write_and_close(buffer, filehandles): for key", "baseq.utils.file_reader import read_file_by_lines inlines = read_file_by_lines(fastq, 1000 * 1000 * 1000, 4) count", "= info[1] print(\"[info] The barcode for {} is {}\".format(info[0], info[1])) path = os.path.join(outdir,", "os.path.join(outdir, sample) + \".\" + suffix print(\"[info] File for '{}' is '{}'\".format(sample, path))", "as file: barcodes = file.readlines() bc_files = {} bc_buffers = {} for bc", "barcode in bc_files: bc_buffers[barcode].append(\"\".join(line)) if count % 1000000 == 1: write_buffer(bc_buffers, bc_files) write_and_close(bc_buffers,", "1 barcode = line[0].strip().split(\":\")[-1] if barcode in bc_files: bc_buffers[barcode].append(\"\".join(line)) if count % 1000000", "= read_file_by_lines(fastq, 1000 * 1000 * 1000, 4) count = 0 for line", "{} for bc in barcodes: info = [x.strip() for x in bc.split()] if", "1000 * 1000 * 1000, 4) count = 0 for line in inlines:", "\"\"\" barcode_file: tsv: samplename barcode_string... \"\"\" with open(barcode_file, 'r') as file: barcodes =", "\"\"\" with open(barcode_file, 'r') as file: barcodes = file.readlines() bc_files = {} bc_buffers", "info = [x.strip() for x in bc.split()] if len(info) == 2: sample =", "if barcode in bc_files: bc_buffers[barcode].append(\"\".join(line)) if count % 1000000 == 1: write_buffer(bc_buffers, bc_files)", "bc_buffers = {} for bc in barcodes: info = [x.strip() for x in", "import os def write_buffer(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) buffer[key] = []", "barcode = info[1] print(\"[info] The barcode for {} is {}\".format(info[0], info[1])) path =", "inlines = read_file_by_lines(fastq, 1000 * 1000 * 1000, 4) count = 0 for", "def write_buffer(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) buffer[key] = [] def write_and_close(buffer,", "+ suffix print(\"[info] File for '{}' is '{}'\".format(sample, path)) bc_files[barcode] = open(path, \"w\")", "fastq, outdir, suffix): \"\"\" barcode_file: tsv: samplename barcode_string... \"\"\" with open(barcode_file, 'r') as", "= open(path, \"w\") bc_buffers[barcode] = [] #Iterating the reads... from baseq.utils.file_reader import read_file_by_lines", "2: sample = info[0] barcode = info[1] print(\"[info] The barcode for {} is", "outdir, suffix): \"\"\" barcode_file: tsv: samplename barcode_string... \"\"\" with open(barcode_file, 'r') as file:", "if len(info) == 2: sample = info[0] barcode = info[1] print(\"[info] The barcode", "= os.path.join(outdir, sample) + \".\" + suffix print(\"[info] File for '{}' is '{}'\".format(sample,", "for {} is {}\".format(info[0], info[1])) path = os.path.join(outdir, sample) + \".\" + suffix", "'{}' is '{}'\".format(sample, path)) bc_files[barcode] = open(path, \"w\") bc_buffers[barcode] = [] #Iterating the", "= [] #Iterating the reads... from baseq.utils.file_reader import read_file_by_lines inlines = read_file_by_lines(fastq, 1000", "bc_files[barcode] = open(path, \"w\") bc_buffers[barcode] = [] #Iterating the reads... from baseq.utils.file_reader import", "\".\" + suffix print(\"[info] File for '{}' is '{}'\".format(sample, path)) bc_files[barcode] = open(path,", "barcode_file: tsv: samplename barcode_string... \"\"\" with open(barcode_file, 'r') as file: barcodes = file.readlines()", "samplename barcode_string... \"\"\" with open(barcode_file, 'r') as file: barcodes = file.readlines() bc_files =", "\"w\") bc_buffers[barcode] = [] #Iterating the reads... from baseq.utils.file_reader import read_file_by_lines inlines =", "bc in barcodes: info = [x.strip() for x in bc.split()] if len(info) ==", "File for '{}' is '{}'\".format(sample, path)) bc_files[barcode] = open(path, \"w\") bc_buffers[barcode] = []", "= line[0].strip().split(\":\")[-1] if barcode in bc_files: bc_buffers[barcode].append(\"\".join(line)) if count % 1000000 == 1:", "sample = info[0] barcode = info[1] print(\"[info] The barcode for {} is {}\".format(info[0],", "buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close() def split_barcode(barcode_file, fastq, outdir, suffix): \"\"\" barcode_file: tsv: samplename barcode_string...", "len(info) == 2: sample = info[0] barcode = info[1] print(\"[info] The barcode for", "sample) + \".\" + suffix print(\"[info] File for '{}' is '{}'\".format(sample, path)) bc_files[barcode]", "for bc in barcodes: info = [x.strip() for x in bc.split()] if len(info)", "'{}'\".format(sample, path)) bc_files[barcode] = open(path, \"w\") bc_buffers[barcode] = [] #Iterating the reads... from", "with open(barcode_file, 'r') as file: barcodes = file.readlines() bc_files = {} bc_buffers =", "bc_files = {} bc_buffers = {} for bc in barcodes: info = [x.strip()", "filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) buffer[key] = [] def write_and_close(buffer, filehandles): for", "bc_buffers[barcode] = [] #Iterating the reads... from baseq.utils.file_reader import read_file_by_lines inlines = read_file_by_lines(fastq,", "for line in inlines: count += 1 barcode = line[0].strip().split(\":\")[-1] if barcode in", "split_barcode(barcode_file, fastq, outdir, suffix): \"\"\" barcode_file: tsv: samplename barcode_string... \"\"\" with open(barcode_file, 'r')", "count += 1 barcode = line[0].strip().split(\":\")[-1] if barcode in bc_files: bc_buffers[barcode].append(\"\".join(line)) if count", "in buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close() def split_barcode(barcode_file, fastq, outdir, suffix): \"\"\" barcode_file: tsv: samplename", "barcode = line[0].strip().split(\":\")[-1] if barcode in bc_files: bc_buffers[barcode].append(\"\".join(line)) if count % 1000000 ==", "count = 0 for line in inlines: count += 1 barcode = line[0].strip().split(\":\")[-1]", "for key in buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close() def split_barcode(barcode_file, fastq, outdir, suffix): \"\"\" barcode_file:", "buffer[key] = [] def write_and_close(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close() def", "filehandles[key].writelines(buffer[key]) filehandles[key].close() def split_barcode(barcode_file, fastq, outdir, suffix): \"\"\" barcode_file: tsv: samplename barcode_string... \"\"\"", "info[1] print(\"[info] The barcode for {} is {}\".format(info[0], info[1])) path = os.path.join(outdir, sample)", "info[1])) path = os.path.join(outdir, sample) + \".\" + suffix print(\"[info] File for '{}'", "key in buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close() def split_barcode(barcode_file, fastq, outdir, suffix): \"\"\" barcode_file: tsv:", "barcodes: info = [x.strip() for x in bc.split()] if len(info) == 2: sample", "tsv: samplename barcode_string... \"\"\" with open(barcode_file, 'r') as file: barcodes = file.readlines() bc_files", "read_file_by_lines inlines = read_file_by_lines(fastq, 1000 * 1000 * 1000, 4) count = 0", "= {} bc_buffers = {} for bc in barcodes: info = [x.strip() for", "[] #Iterating the reads... from baseq.utils.file_reader import read_file_by_lines inlines = read_file_by_lines(fastq, 1000 *", "write_and_close(buffer, filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close() def split_barcode(barcode_file, fastq, outdir, suffix):", "path)) bc_files[barcode] = open(path, \"w\") bc_buffers[barcode] = [] #Iterating the reads... from baseq.utils.file_reader", "barcode_string... \"\"\" with open(barcode_file, 'r') as file: barcodes = file.readlines() bc_files = {}", "= 0 for line in inlines: count += 1 barcode = line[0].strip().split(\":\")[-1] if", "file.readlines() bc_files = {} bc_buffers = {} for bc in barcodes: info =", "filehandles): for key in buffer.keys(): filehandles[key].writelines(buffer[key]) filehandles[key].close() def split_barcode(barcode_file, fastq, outdir, suffix): \"\"\"", "in inlines: count += 1 barcode = line[0].strip().split(\":\")[-1] if barcode in bc_files: bc_buffers[barcode].append(\"\".join(line))", "= [x.strip() for x in bc.split()] if len(info) == 2: sample = info[0]", "1000 * 1000, 4) count = 0 for line in inlines: count +=", "bc.split()] if len(info) == 2: sample = info[0] barcode = info[1] print(\"[info] The", "in bc_files: bc_buffers[barcode].append(\"\".join(line)) if count % 1000000 == 1: write_buffer(bc_buffers, bc_files) write_and_close(bc_buffers, bc_files)", "1000, 4) count = 0 for line in inlines: count += 1 barcode", "= {} for bc in barcodes: info = [x.strip() for x in bc.split()]", "The barcode for {} is {}\".format(info[0], info[1])) path = os.path.join(outdir, sample) + \".\"" ]
[ "int(selecao) <= 20: selecao = input('Tente Novamente informando um número válido. Informe um", "'Quartoze', 'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte') selecao = input('Informe um número entre", "'Dezoito', 'Dezenove', 'Vinte') selecao = input('Informe um número entre 0 ~ 20: ')", "informando um número válido. Informe um número entre 0 ~ 20: ') print(selecao)", "'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quartoze', 'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte') selecao", "= input('Tente Novamente informando um número válido. Informe um número entre 0 ~", "input('Informe um número entre 0 ~ 20: ') while not int(selecao) >= 0", "not int(selecao) >= 0 and int(selecao) <= 20: selecao = input('Tente Novamente informando", "= ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze',", "Novamente informando um número válido. Informe um número entre 0 ~ 20: ')", "int(selecao) >= 0 and int(selecao) <= 20: selecao = input('Tente Novamente informando um", "'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quartoze', 'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte')", "'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte') selecao = input('Informe um número entre 0 ~", "número entre 0 ~ 20: ') while not int(selecao) >= 0 and int(selecao)", "<= 20: selecao = input('Tente Novamente informando um número válido. Informe um número", "selecao = input('Informe um número entre 0 ~ 20: ') while not int(selecao)", "'Dezesete', 'Dezoito', 'Dezenove', 'Vinte') selecao = input('Informe um número entre 0 ~ 20:", "'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quartoze', 'Quinze', 'Dezesseis', 'Dezesete',", "'Dezenove', 'Vinte') selecao = input('Informe um número entre 0 ~ 20: ') while", "and int(selecao) <= 20: selecao = input('Tente Novamente informando um número válido. Informe", "('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze',", "'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quartoze', 'Quinze', 'Dezesseis',", "~ 20: ') while not int(selecao) >= 0 and int(selecao) <= 20: selecao", ">= 0 and int(selecao) <= 20: selecao = input('Tente Novamente informando um número", "20: ') while not int(selecao) >= 0 and int(selecao) <= 20: selecao =", "') while not int(selecao) >= 0 and int(selecao) <= 20: selecao = input('Tente", "contagem = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez',", "'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quartoze', 'Quinze',", "while not int(selecao) >= 0 and int(selecao) <= 20: selecao = input('Tente Novamente", "20: selecao = input('Tente Novamente informando um número válido. Informe um número entre", "um número entre 0 ~ 20: ') while not int(selecao) >= 0 and", "'Onze', 'Doze', 'Treze', 'Quartoze', 'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte') selecao = input('Informe", "'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte') selecao = input('Informe um número entre 0", "'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quartoze',", "selecao = input('Tente Novamente informando um número válido. Informe um número entre 0", "= input('Informe um número entre 0 ~ 20: ') while not int(selecao) >=", "'Vinte') selecao = input('Informe um número entre 0 ~ 20: ') while not", "entre 0 ~ 20: ') while not int(selecao) >= 0 and int(selecao) <=", "'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze',", "'Doze', 'Treze', 'Quartoze', 'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte') selecao = input('Informe um", "'Treze', 'Quartoze', 'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte') selecao = input('Informe um número", "0 ~ 20: ') while not int(selecao) >= 0 and int(selecao) <= 20:", "0 and int(selecao) <= 20: selecao = input('Tente Novamente informando um número válido.", "'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quartoze', 'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito',", "'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quartoze', 'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove',", "'Dez', 'Onze', 'Doze', 'Treze', 'Quartoze', 'Quinze', 'Dezesseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte') selecao =", "input('Tente Novamente informando um número válido. Informe um número entre 0 ~ 20:", "<filename>Exercicios/ex072.py contagem = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove'," ]
[ "save_type = convert_file.split(\".\")[-1] # Deleting all objects for scene in bpy.data.scenes: for obj", "bpy.ops.object.delete(use_global=False) for item in bpy.data.meshes: for scene in bpy.data.scenes: for obj in scene.objects:", "obj in scene.objects: scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item) print(\"Scene cleared\") # Open model and save", "\"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type == \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False) else: print(\"Incorrect save format\")", "for bpy_data_iter in ( bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, ): for id_data in bpy_data_iter:", "scene.objects: scene.objects.unlink(obj) for bpy_data_iter in ( bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, ): for id_data", "bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item) print(\"Scene cleared\") # Open model", "True, #import_vertcolors False, #skip_blank False, #use_layers 1.0) #mesh_scale print(\"Success\") except: print(\"Fail\") exit(1) print(\"\\nModel", "args[-1] save_type = convert_file.split(\".\")[-1] # Deleting all objects for scene in bpy.data.scenes: for", "Open model and save try: try: print(\"Try to use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except:", "bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type = \"MESH\") bpy.ops.object.delete(use_global=False) for item in bpy.data.meshes: for scene in bpy.data.scenes:", "#filepath bpy.context, #context False, #randomize_colors True, #import_vertcolors False, #skip_blank False, #use_layers 1.0) #mesh_scale", "use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except: try: print(\"Fail\") print(\"Try to use outer script...\") try:", "for obj in scene.objects: scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item) print(\"Scene cleared\") # Open model and", "print(\"Try to use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except: try: print(\"Fail\") print(\"Try to use outer", "= \"MESH\") bpy.ops.object.delete(use_global=False) for item in bpy.data.meshes: for scene in bpy.data.scenes: for obj", "= args[-1] save_type = convert_file.split(\".\")[-1] # Deleting all objects for scene in bpy.data.scenes:", "in bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type = \"MESH\") bpy.ops.object.delete(use_global=False) for item in bpy.data.meshes: for scene", "obj in scene.objects: scene.objects.unlink(obj) for bpy_data_iter in ( bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, ):", "to use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except: try: print(\"Fail\") print(\"Try to use outer script...\")", "print(\"Fail\") print(\"Try to use outer script...\") try: import import_DeusExMD except: print(\"Fail to import\")", "print(\"\\nModel opened\\n\") if save_type == \"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif save_type == \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif", "save_type == \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type == \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type == \"stl\":", "import bpy import sys # Names of folder and files args = sys.argv", "= convert_file.split(\".\")[-1] # Deleting all objects for scene in bpy.data.scenes: for obj in", "in scene.objects: scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item) print(\"Scene cleared\") # Open model and save try:", "and files args = sys.argv source_file = args[-2] convert_file = args[-1] save_type =", "model and save try: try: print(\"Try to use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except: try:", "# Names of folder and files args = sys.argv source_file = args[-2] convert_file", "#skip_blank False, #use_layers 1.0) #mesh_scale print(\"Success\") except: print(\"Fail\") exit(1) print(\"\\nModel opened\\n\") if save_type", "in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) for bpy_data_iter in ( bpy.data.objects, bpy.data.meshes,", "bpy.data.cameras, ): for id_data in bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type = \"MESH\") bpy.ops.object.delete(use_global=False) for item", "== \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type == \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type == \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file,", "model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context, #context False, #randomize_colors True, #import_vertcolors False, #skip_blank False, #use_layers", "if save_type == \"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif save_type == \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type ==", "\"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type == \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type == \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False,", "print(\"Fail to import\") exit(2) print(\"Successful module import; try to open model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath", "bpy.ops.export_scene.obj(filepath=convert_file) elif save_type == \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type == \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type", "save_type == \"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif save_type == \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type == \"3ds\":", "#import_vertcolors False, #skip_blank False, #use_layers 1.0) #mesh_scale print(\"Success\") except: print(\"Fail\") exit(1) print(\"\\nModel opened\\n\")", "all objects for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) for bpy_data_iter", "import_DeusExMD except: print(\"Fail to import\") exit(2) print(\"Successful module import; try to open model...\")", "# Deleting all objects for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj)", "#randomize_colors True, #import_vertcolors False, #skip_blank False, #use_layers 1.0) #mesh_scale print(\"Success\") except: print(\"Fail\") exit(1)", "\"MESH\") bpy.ops.object.delete(use_global=False) for item in bpy.data.meshes: for scene in bpy.data.scenes: for obj in", "print(\"Scene cleared\") # Open model and save try: try: print(\"Try to use plugin...\")", "# Open model and save try: try: print(\"Try to use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\")", "print(\"Successful module import; try to open model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context, #context False, #randomize_colors", "args = sys.argv source_file = args[-2] convert_file = args[-1] save_type = convert_file.split(\".\")[-1] #", "use outer script...\") try: import import_DeusExMD except: print(\"Fail to import\") exit(2) print(\"Successful module", "): for id_data in bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type = \"MESH\") bpy.ops.object.delete(use_global=False) for item in", "bpy_data_iter in ( bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, ): for id_data in bpy_data_iter: bpy_data_iter.remove(id_data)", "bpy import sys # Names of folder and files args = sys.argv source_file", "args[-2] convert_file = args[-1] save_type = convert_file.split(\".\")[-1] # Deleting all objects for scene", "import; try to open model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context, #context False, #randomize_colors True, #import_vertcolors", "#use_layers 1.0) #mesh_scale print(\"Success\") except: print(\"Fail\") exit(1) print(\"\\nModel opened\\n\") if save_type == \"obj\":", "import\") exit(2) print(\"Successful module import; try to open model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context, #context", "bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type == \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False) else: print(\"Incorrect save format\") print(\"\\nConvertions", "#context False, #randomize_colors True, #import_vertcolors False, #skip_blank False, #use_layers 1.0) #mesh_scale print(\"Success\") except:", "import import_DeusExMD except: print(\"Fail to import\") exit(2) print(\"Successful module import; try to open", "print(\"Fail\") exit(1) print(\"\\nModel opened\\n\") if save_type == \"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif save_type == \"fbx\":", "save format\") print(\"\\nConvertions done!\") exit(0) # In case of error except Exception: print(\"\\nSome", "os import bpy import sys # Names of folder and files args =", "format\") print(\"\\nConvertions done!\") exit(0) # In case of error except Exception: print(\"\\nSome errors", "scene.objects: scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item) print(\"Scene cleared\") # Open model and save try: try:", "bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False) else: print(\"Incorrect save format\") print(\"\\nConvertions done!\") exit(0) # In case", "else: print(\"Incorrect save format\") print(\"\\nConvertions done!\") exit(0) # In case of error except", "id_data in bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type = \"MESH\") bpy.ops.object.delete(use_global=False) for item in bpy.data.meshes: for", "script...\") try: import import_DeusExMD except: print(\"Fail to import\") exit(2) print(\"Successful module import; try", "exit(2) print(\"Successful module import; try to open model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context, #context False,", "files args = sys.argv source_file = args[-2] convert_file = args[-1] save_type = convert_file.split(\".\")[-1]", "outer script...\") try: import import_DeusExMD except: print(\"Fail to import\") exit(2) print(\"Successful module import;", "save_type == \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False) else: print(\"Incorrect save format\") print(\"\\nConvertions done!\") exit(0)", "print(\"Incorrect save format\") print(\"\\nConvertions done!\") exit(0) # In case of error except Exception:", "print(\"Success\") except: print(\"Fail\") exit(1) print(\"\\nModel opened\\n\") if save_type == \"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif save_type", "open model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context, #context False, #randomize_colors True, #import_vertcolors False, #skip_blank False,", "== \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False) else: print(\"Incorrect save format\") print(\"\\nConvertions done!\") exit(0) #", "objects for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) for bpy_data_iter in", "and save try: try: print(\"Try to use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except: try: print(\"Fail\")", "to open model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context, #context False, #randomize_colors True, #import_vertcolors False, #skip_blank", "module import; try to open model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context, #context False, #randomize_colors True,", "sys # Names of folder and files args = sys.argv source_file = args[-2]", "print(\"Success\") except: try: print(\"Fail\") print(\"Try to use outer script...\") try: import import_DeusExMD except:", "exit(1) print(\"\\nModel opened\\n\") if save_type == \"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif save_type == \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file)", "opened\\n\") if save_type == \"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif save_type == \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type", "bpy.data.lamps, bpy.data.cameras, ): for id_data in bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type = \"MESH\") bpy.ops.object.delete(use_global=False) for", "False, #randomize_colors True, #import_vertcolors False, #skip_blank False, #use_layers 1.0) #mesh_scale print(\"Success\") except: print(\"Fail\")", "save_type == \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type == \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False) else: print(\"Incorrect", "for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) for bpy_data_iter in (", "Names of folder and files args = sys.argv source_file = args[-2] convert_file =", "bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, ): for id_data in bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type = \"MESH\")", "import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context, #context False, #randomize_colors True, #import_vertcolors False, #skip_blank False, #use_layers 1.0)", "to import\") exit(2) print(\"Successful module import; try to open model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context,", "try: try: print(\"Try to use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except: try: print(\"Fail\") print(\"Try to", "sys.argv source_file = args[-2] convert_file = args[-1] save_type = convert_file.split(\".\")[-1] # Deleting all", "to use outer script...\") try: import import_DeusExMD except: print(\"Fail to import\") exit(2) print(\"Successful", "elif save_type == \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False) else: print(\"Incorrect save format\") print(\"\\nConvertions done!\")", "bpy.data.meshes: for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item) print(\"Scene", "bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, ): for id_data in bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type = \"MESH\") bpy.ops.object.delete(use_global=False)", "plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except: try: print(\"Fail\") print(\"Try to use outer script...\") try: import", "check_existing=False, ascii=False) else: print(\"Incorrect save format\") print(\"\\nConvertions done!\") exit(0) # In case of", "\"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif save_type == \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type == \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif", "elif save_type == \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type == \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type ==", "scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item) print(\"Scene cleared\") #", "try to open model...\") import_DeusExMD.import_DeusExMD(source_file, #filepath bpy.context, #context False, #randomize_colors True, #import_vertcolors False,", "item in bpy.data.meshes: for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) item.user_clear()", "False, #skip_blank False, #use_layers 1.0) #mesh_scale print(\"Success\") except: print(\"Fail\") exit(1) print(\"\\nModel opened\\n\") if", "scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) for bpy_data_iter in ( bpy.data.objects,", "cleared\") # Open model and save try: try: print(\"Try to use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file)", "for item in bpy.data.meshes: for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj)", "convert_file.split(\".\")[-1] # Deleting all objects for scene in bpy.data.scenes: for obj in scene.objects:", "for obj in scene.objects: scene.objects.unlink(obj) for bpy_data_iter in ( bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras,", "bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except: try: print(\"Fail\") print(\"Try to use outer script...\") try: import import_DeusExMD", "1.0) #mesh_scale print(\"Success\") except: print(\"Fail\") exit(1) print(\"\\nModel opened\\n\") if save_type == \"obj\": bpy.ops.export_scene.obj(filepath=convert_file)", "False, #use_layers 1.0) #mesh_scale print(\"Success\") except: print(\"Fail\") exit(1) print(\"\\nModel opened\\n\") if save_type ==", "= args[-2] convert_file = args[-1] save_type = convert_file.split(\".\")[-1] # Deleting all objects for", "== \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type == \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False) else: print(\"Incorrect save", "in bpy.data.meshes: for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item)", "import sys # Names of folder and files args = sys.argv source_file =", "scene.objects.unlink(obj) for bpy_data_iter in ( bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, ): for id_data in", "item.user_clear() bpy.data.meshes.remove(item) print(\"Scene cleared\") # Open model and save try: try: print(\"Try to", "source_file = args[-2] convert_file = args[-1] save_type = convert_file.split(\".\")[-1] # Deleting all objects", "try: import import_DeusExMD except: print(\"Fail to import\") exit(2) print(\"Successful module import; try to", "\"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False) else: print(\"Incorrect save format\") print(\"\\nConvertions done!\") exit(0) # In", "( bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, ): for id_data in bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type =", "print(\"\\nConvertions done!\") exit(0) # In case of error except Exception: print(\"\\nSome errors here\")", "bpy.context, #context False, #randomize_colors True, #import_vertcolors False, #skip_blank False, #use_layers 1.0) #mesh_scale print(\"Success\")", "bpy.data.meshes.remove(item) print(\"Scene cleared\") # Open model and save try: try: print(\"Try to use", "Deleting all objects for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) for", "of folder and files args = sys.argv source_file = args[-2] convert_file = args[-1]", "done!\") exit(0) # In case of error except Exception: print(\"\\nSome errors here\") exit(1)", "scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item) print(\"Scene cleared\") # Open model and save try: try: print(\"Try", "ascii=False) else: print(\"Incorrect save format\") print(\"\\nConvertions done!\") exit(0) # In case of error", "bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type == \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type == \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False)", "print(\"Try to use outer script...\") try: import import_DeusExMD except: print(\"Fail to import\") exit(2)", "except: print(\"Fail\") exit(1) print(\"\\nModel opened\\n\") if save_type == \"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif save_type ==", "= sys.argv source_file = args[-2] convert_file = args[-1] save_type = convert_file.split(\".\")[-1] # Deleting", "convert_file = args[-1] save_type = convert_file.split(\".\")[-1] # Deleting all objects for scene in", "in ( bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, ): for id_data in bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type", "elif save_type == \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file) elif save_type == \"stl\": bpy.ops.export_mesh.stl(filepath=convert_file, check_existing=False, ascii=False) else:", "for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item) print(\"Scene cleared\")", "for id_data in bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type = \"MESH\") bpy.ops.object.delete(use_global=False) for item in bpy.data.meshes:", "save try: try: print(\"Try to use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except: try: print(\"Fail\") print(\"Try", "except: try: print(\"Fail\") print(\"Try to use outer script...\") try: import import_DeusExMD except: print(\"Fail", "in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) item.user_clear() bpy.data.meshes.remove(item) print(\"Scene cleared\") # Open", "bpy.ops.object.select_by_type(type = \"MESH\") bpy.ops.object.delete(use_global=False) for item in bpy.data.meshes: for scene in bpy.data.scenes: for", "try: print(\"Fail\") print(\"Try to use outer script...\") try: import import_DeusExMD except: print(\"Fail to", "in scene.objects: scene.objects.unlink(obj) for bpy_data_iter in ( bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras, ): for", "bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) for bpy_data_iter in ( bpy.data.objects, bpy.data.meshes, bpy.data.lamps,", "folder and files args = sys.argv source_file = args[-2] convert_file = args[-1] save_type", "#mesh_scale print(\"Success\") except: print(\"Fail\") exit(1) print(\"\\nModel opened\\n\") if save_type == \"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif", "except: print(\"Fail to import\") exit(2) print(\"Successful module import; try to open model...\") import_DeusExMD.import_DeusExMD(source_file,", "== \"obj\": bpy.ops.export_scene.obj(filepath=convert_file) elif save_type == \"fbx\": bpy.ops.export_scene.fbx(filepath=convert_file) elif save_type == \"3ds\": bpy.ops.export_scene.autodesk_3ds(filepath=convert_file)", "try: print(\"Try to use plugin...\") bpy.ops.import_scene.deusexmd(filepath=source_file) print(\"Success\") except: try: print(\"Fail\") print(\"Try to use", "bpy_data_iter: bpy_data_iter.remove(id_data) bpy.ops.object.select_by_type(type = \"MESH\") bpy.ops.object.delete(use_global=False) for item in bpy.data.meshes: for scene in", "import os import bpy import sys # Names of folder and files args" ]
[ "'50' or i[3] == '50hz'): count += 1 fft_cnt += i[2] elif(base ==", "= pw_df.filter(\"outage != 0\") #record the duration of the outage def calculateDuration(startTime, endTime):", "value2): if(value1 == value2): return 0 else: return 1 udfDetectTransition = udf(detectTransition, IntegerType())", "if(base == 50): if abs((time - i[0]).total_seconds()) < 15 and i[2] is not", "50): if abs((time - i[0]).total_seconds()) < 15 and i[2] is not None and", "a list of all Powerwatch outages with an outage time #now we should", "of the outage def calculateDuration(startTime, endTime): delta = endTime-startTime seconds = delta.total_seconds() return", "IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df = pw_df.filter(\"outage_cluster_size > 1\") #now we need", "now have a list of all Powerwatch outages with an outage time #now", "i in imeiList: if(base == 50): if abs((time - i[0]).total_seconds()) < 15 and", "1 else: return 0 udfCountTransition = udf(countOutage, IntegerType()) is_powered_lead = lead(\"is_powered\",1).over(w) is_powered_lag =", "pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df = pw_df.filter(\"product_id = 7008 OR product_id= 7009\") #now we", "count udfFilterTransition = udf(filterOutage, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df = pw_df.filter(\"outage_cluster_size >", "joined_df = joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove all of the phone records joined_df =", "pyspark import SparkConf import yaml import datetime import os from math import isnan", "if(value1 == False and value2 == True and value3 == True): return 1", "pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we now have a list of all Powerwatch outages", "(i[3] == '50' or i[3] == '50hz'): count += 1 fft_cnt += i[2]", "pw_df.filter(\"outage_cluster_size > 1\") #now we need to collapse these individual outage events into", "pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag)) #now find all the exact outage and restore times", "and detects transitions #then we can filter out all data that is not", "udfFilterTransition = udf(filterOutage, IntegerType()) joined_df = joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the same window size", "\"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\") spark = SparkSession.builder \\ .config(conf=conf) \\", "\"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\") spark = SparkSession.builder \\ .config(conf=conf) \\ .master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI cluster", "config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis'])", "(fft_base = 50 OR fft_base = '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df = dw_df.filter(\"type =", "= lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag)) #now find all the exact", "time/outage time joined_df = pw_df.join(dw_df, col(\"outage_time\") == col(\"time\"), \"fullouter\") joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df", "the leading lagging edge of is powered and detects transitions #then we can", "== True): return 1 else: return 0 udfCountTransition = udf(countOutage, IntegerType()) is_powered_lead =", "= 150 w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time, core_id, timeList): count", "= pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df = pw_df.filter(\"outage_cluster = 1\") pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we", "pw_df.filter(\"outage != 0\") #record the duration of the outage def calculateDuration(startTime, endTime): delta", "each outage time we need to see how many DW unplug events occurred", "window_size: return window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType()) joined_df = joined_df.withColumn(\"phones_detecting\",", "udf(filterOutage, IntegerType()) joined_df = joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the same window size average the", "pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp = pw_df # ##now filter out all", "product_id= 7009\") #now we need to created a window function that looks at", "udf, hour, month, dayofmonth, collect_list, lit, year, coalesce, mean import pyspark.sql.functions as F", "\"fullouter\") joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run a similar metric as", "FloatType, IntegerType, DateType, TimestampType from pyspark import SparkConf import yaml import datetime import", "- i[0]).total_seconds()) < 15 and i[1] not in used: used.append(i[1]) count += 1", "count = 0 fft_cnt = 0 #we want phone imei to be none", "return float(-1) print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count))) if(return_count): return float(count) else: return float(float(fft_cnt)/float(count)) udfFilterTransition =", "conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\") spark = SparkSession.builder \\ .config(conf=conf)", "= 0 fft_cnt = 0 #we want phone imei to be none if", "and (i[3] == '50' or i[3] == '50hz'): count += 1 fft_cnt +=", "udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the same window size average the fft_cnt to see if there", "\"15g\") conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\") spark = SparkSession.builder \\ .config(conf=conf) \\ .master(\"local[4]\") \\", "= dw_df.filter(\"type = 'unplugged' OR type = 'plugged'\") #okay now we want the", "try per-plug differencing (although it may be better to take the averaged plug", "find all the exact outage and restore times using millis def timeCorrect(time, millis,", "1\") #pw_df = pw_df.select(\"month(time)\",\"sum(outage_duration)\",\"sum(outage_events)\",\"num_outages\") #pw_df = pw_df.groupBy(\"month(time)\").sum().orderBy(\"month(time)\") #pw_df = pw_df.show(200) # #pw_cp.repartition(1).write.format(\"com.databricks.spark.csv\").option(\"header\", \"true\").save(\"monthly_outages_aggregate_cluster_size_time_corrected\").groupBy(month(\"time\")).sum().orderBy(month(\"time\"))", "collapse these individual outage events into actual outages #we can use a similar", "fft_cnt > -1 AND (fft_base = 50 OR fft_base = '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count())", "see how many unplug events occur dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\": config['user'], \"password\":", "w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time, core_id, timeList): count = 1", "import FloatType, IntegerType, DateType, TimestampType from pyspark import SparkConf import yaml import datetime", "have a #pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df = pw_df.withColumn(\"outage_events\",lit(1)) #pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df =", "AND fft_cnt > -1 AND (fft_base = 50 OR fft_base = '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show()", "-1 AND (fft_base = 60 OR fft_base = '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) # #unplugged_50_df", "and i[2] is not None and (i[3] == '50' or i[3] == '50hz'):", "> -1 AND (fft_base = 50 OR fft_base = '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df", "lag_time): if(lag_time is not None): if((time - lag_time).total_seconds() < 120): return 0 else:", "udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out all transitions pw_df = pw_df.filter(\"transition != 0\") #now count each", "time #now we should take all DW unplug events and for each outage", "#read the data that we care about dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df = dw_df.filter(year(\"time\")", "'unplugged' AND fft_cnt > -1 AND (fft_base = 60 OR fft_base = '60hz')\")", "None or unplugMillis == None or isnan(millis) or isnan(unplugMillis)): return time elif unplugMillis", "phone imei #we will first try per-plug differencing (although it may be better", "restoration) def countOutage(value1, value2, value3): if(value1 == False and value2 == True and", "not None: return -1 used = [] for i in imeiList: if abs((time", "= Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag = lag(\"fft_cnt\",1).over(w) dw_df = dw_df.filter(\"type = 'unplugged'\") #now we need", "end time of the outage for saidi reasons time_lead = lead(\"r_time\",1).over(w) pw_df =", "created a window function that looks at the leading lagging edge of is", "import datetime import os from math import isnan conf = SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\")", "\"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df", "= '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df = dw_df.filter(\"type = 'unplugged' OR", "and for each outage see how many unplug events occur dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\",", "IntegerType()) w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out", "need to join the data on time/outage time joined_df = pw_df.join(dw_df, col(\"outage_time\") ==", "\"dumsorwatch\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about dw_df", "if there is a signal in that metric window_size = 100 w =", "the two datasets together so that we have a #pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df", "udf(timeCorrect, TimestampType()) pw_df = pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df = pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote the", "phone) #w = Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag = lag(\"fft_cnt\",1).over(w) dw_df = dw_df.filter(\"type = 'unplugged'\") #now", "signal in that metric window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w))", "times using millis def timeCorrect(time, millis, unplugMillis): if(unplugMillis == 0 or millis ==", "i[0]).total_seconds()) < 120 and i[1] not in used: used.append(i[1]) count += 1 if", "lag_time).total_seconds() < 120): return 0 else: return 1 else: return 1 udfFilterTransition =", "should have a time and end_time for every outage pw_df = pw_df.filter(\"outage !=", "= pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df = pw_df.filter(\"product_id = 7008 OR product_id= 7009\") #now we need", "events occur dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data", "need to created a window function that looks at the leading lagging edge", "elif unplugMillis > millis: return time else: return time - datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000)", "fft_cnt drop between plugged and unplugged for each phone imei #we will first", "differencing (although it may be better to take the averaged plug cnt for", "not an outage. We should have a time and end_time for every outage", "a similar metric as above #for each outage time we need to see", "to created a window function that looks at the leading lagging edge of", "OR fft_base = '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df = dw_df.filter(\"type = 'plugged' AND fft_cnt", "== None or unplugMillis == None or isnan(millis) or isnan(unplugMillis)): return time elif", "first try per-plug differencing (although it may be better to take the averaged", "== 0): return float(-1) print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count))) if(return_count): return float(count) else: return float(float(fft_cnt)/float(count))", "millis, unplugMillis): if(unplugMillis == 0 or millis == None or unplugMillis == None", "unplugMillis): if(unplugMillis == 0 or millis == None or unplugMillis == None or", "= '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) # #unplugged_50_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt >", "may be better to take the averaged plug cnt for each phone) #w", "config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df =", "udfFilterTransition = udf(filterOutage, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df = pw_df.filter(\"outage_cluster_size > 1\")", "pw_df = pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote the end time of the outage for", ".master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI cluster size\") \\ .getOrCreate() config = open('config.yaml') config = yaml.load(config)", "dayofmonth, collect_list, lit, year, coalesce, mean import pyspark.sql.functions as F from pyspark.sql.window import", "as a baseline #plugged_50_df = dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND", "#For the same window size average the fft_cnt to see if there is", "else: return float(float(fft_cnt)/float(count)) udfFilterTransition = udf(filterOutage, FloatType()) joined_df = joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df =", "0\") #now count each outage (really restoration) def countOutage(value1, value2, value3): if(value1 ==", "lead(\"is_powered\",1).over(w) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag)) #now find all", "-1 used = [] for i in imeiList: if abs((time - i[0]).total_seconds()) <", "Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag = lag(\"fft_cnt\",1).over(w) dw_df = dw_df.filter(\"type = 'unplugged'\") #now we need to", "= yaml.load(config) #connect to the database pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\": config['user'], \"password\":", "= pw_df.withColumn(\"outage_events\",lit(1)) #pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp", "#print(unplugged_60_df.count()) dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df = dw_df.filter(\"type = 'unplugged' OR type = 'plugged'\")", "within some time window window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w))", "powered and detects transitions #then we can filter out all data that is", "baseline #plugged_50_df = dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND (fft_base =", "endTime): delta = endTime-startTime seconds = delta.total_seconds() return int(seconds) udfcalculateDuration = udf(calculateDuration, IntegerType())", "AND (fft_base = 60 OR fft_base = '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\")", "conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\") spark = SparkSession.builder \\ .config(conf=conf) \\ .master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI", "value2, value3): if(value1 == False and value2 == True and value3 == True):", "value3): if(value1 == False and value2 == True and value3 == True): return", "#record the duration of the outage def calculateDuration(startTime, endTime): delta = endTime-startTime seconds", "dw_df.filter(\"type = 'unplugged'\") #now we need to join the data on time/outage time", "from math import isnan conf = SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\")", "phone imei to be none if phone_imei is not None: return -1 used", "OR fft_base = '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) # #unplugged_50_df = dw_df.filter(\"type = 'unplugged' AND", "pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df = pw_df.filter(\"product_id = 7008 OR product_id= 7009\") #now we need to", "not None): if((time - lag_time).total_seconds() < 120): return 0 else: return 1 else:", "and value2 == True and value3 == True): return 1 else: return 0", "dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND (fft_base = 50 OR fft_base", "#now remove all of the phone records joined_df = joined_df.filter(\"phones_detecting > -1\") joined_df", "= 'plugged' AND fft_cnt > -1 AND (fft_base = 60 OR fft_base =", "import os from math import isnan conf = SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\")", "time - datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000) udftimeCorrect = udf(timeCorrect, TimestampType()) pw_df = pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\"))", "def calculateDuration(startTime, endTime): delta = endTime-startTime seconds = delta.total_seconds() return int(seconds) udfcalculateDuration =", "want the fft_cnt drop between plugged and unplugged for each phone imei #we", "= joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the same window size average the fft_cnt to see", "data that we care about pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df = pw_df.filter(\"product_id = 7008", "is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag)) #now find all the", "a similar method of windowing as before but only look at the row", "TimestampType from pyspark import SparkConf import yaml import datetime import os from math", "= dw_df.filter(year(\"time\") == 2018) #get the avg fft_cnt as a baseline #plugged_50_df =", ".getOrCreate() config = open('config.yaml') config = yaml.load(config) #connect to the database pw_df =", "OR fft_base = '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt", "== None or isnan(millis) or isnan(unplugMillis)): return time elif unplugMillis > millis: return", "= Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time, phone_imei, imeiList, base, return_count): count =", "joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time, phone_imei, imeiList): count = 0 #we want phone", "pw_df.join(dw_df, col(\"outage_time\") == col(\"time\"), \"fullouter\") joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run", "Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time, core_id, timeList): count = 1 used =", "1 else: return 1 udfFilterTransition = udf(onlyOutages, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df", "events occurred within some time window window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df", "all the exact outage and restore times using millis def timeCorrect(time, millis, unplugMillis):", "joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run a similar metric as above #for each", "print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count))) if(return_count): return float(count) else: return float(float(fft_cnt)/float(count)) udfFilterTransition = udf(filterOutage, FloatType())", "+= 1 if count > window_size: return window_size else: return count udfFilterTransition =", "#w = Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag = lag(\"fft_cnt\",1).over(w) dw_df = dw_df.filter(\"type = 'unplugged'\") #now we", "joined_df = joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the same window size average the fft_cnt to", "the end time of the outage for saidi reasons time_lead = lead(\"r_time\",1).over(w) pw_df", "imeiList, base, return_count): count = 0 fft_cnt = 0 #we want phone imei", "'50hz'): count += 1 fft_cnt += i[2] elif(base == 60): if abs((time -", "i[2] elif(base == 60): if abs((time - i[0]).total_seconds()) < 15 and i[2] is", "records joined_df = joined_df.filter(\"phones_detecting > -1\") joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now join the", "time window window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time,", "pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out all transitions pw_df = pw_df.filter(\"transition != 0\") #now count", "unplugMillis == None or isnan(millis) or isnan(unplugMillis)): return time elif unplugMillis > millis:", "of is powered and detects transitions #then we can filter out all data", "for i in timeList: if abs((time - i[0]).total_seconds()) < 120 and i[1] not", "can filter out all data that is not a transition def detectTransition(value1, value2):", "only look at the row before w = Window.orderBy(asc(\"outage_time\")) outage_time_lag = lag(\"outage_time\",1).over(w) def", "#!/usr/bin/env python from pyspark.sql import SparkSession from pyspark.sql.functions import col, window, asc, desc,", "from pyspark.sql.window import Window from pyspark.sql.types import FloatType, IntegerType, DateType, TimestampType from pyspark", "a baseline #plugged_50_df = dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND (fft_base", "restore times using millis def timeCorrect(time, millis, unplugMillis): if(unplugMillis == 0 or millis", "Window from pyspark.sql.types import FloatType, IntegerType, DateType, TimestampType from pyspark import SparkConf import", "AND (fft_base = 50 OR fft_base = '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df = dw_df.filter(\"type", ".config(conf=conf) \\ .master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI cluster size\") \\ .getOrCreate() config = open('config.yaml') config", "< 120): return 0 else: return 1 else: return 1 udfFilterTransition = udf(onlyOutages,", "i[2] is not None and (i[3] == '60' or i[3] == '60hz'): count", "= pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df = pw_df.filter(\"outage_cluster_size > 1\") #now we need to collapse", "1 udfDetectTransition = udf(detectTransition, IntegerType()) w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df =", "metric window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time, phone_imei,", "pyspark.sql.window import Window from pyspark.sql.types import FloatType, IntegerType, DateType, TimestampType from pyspark import", "#now count each outage (really restoration) def countOutage(value1, value2, value3): if(value1 == False", "= 1\") pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we now have a list of all", "!= 0\") #now count each outage (really restoration) def countOutage(value1, value2, value3): if(value1", "'60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) # #unplugged_50_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1", "not None: return -1 for i in imeiList: if(base == 50): if abs((time", "pw_df = pw_df.filter(\"outage != 0\") #record the duration of the outage def calculateDuration(startTime,", "imeiList: if(base == 50): if abs((time - i[0]).total_seconds()) < 15 and i[2] is", "for each phone) #w = Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag = lag(\"fft_cnt\",1).over(w) dw_df = dw_df.filter(\"type =", "= udf(calculateDuration, IntegerType()) pw_df = pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size = 150 w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size)", "= pw_df.withColumn(\"restore_time\", time_lead) #now filter out everything that is not an outage. We", "row before w = Window.orderBy(asc(\"outage_time\")) outage_time_lag = lag(\"outage_time\",1).over(w) def onlyOutages(time, lag_time): if(lag_time is", "import yaml import datetime import os from math import isnan conf = SparkConf()", "pyspark.sql import SparkSession from pyspark.sql.functions import col, window, asc, desc, lead, lag, udf,", "lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag)) #now find all the exact outage", "= SparkSession.builder \\ .config(conf=conf) \\ .master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI cluster size\") \\ .getOrCreate() config", "= pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote the end time of the outage for saidi", "i[3] == '60hz'): count += 1 fft_cnt += i[2] if(count == 0): return", "= joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run a similar metric as above #for", "take the averaged plug cnt for each phone) #w = Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag =", "above #for each outage time we need to see how many DW unplug", "config = yaml.load(config) #connect to the database pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\": config['user'],", "pw_df = pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df = pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote the end time", "outage. We should have a time and end_time for every outage pw_df =", "return int(seconds) udfcalculateDuration = udf(calculateDuration, IntegerType()) pw_df = pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size = 150", "at the row before w = Window.orderBy(asc(\"outage_time\")) outage_time_lag = lag(\"outage_time\",1).over(w) def onlyOutages(time, lag_time):", "to see how many DW unplug events occurred within some time window window_size", "> -1 AND (fft_base = 50 OR fft_base = '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df", "as before but only look at the row before w = Window.orderBy(asc(\"outage_time\")) outage_time_lag", "end_time for every outage pw_df = pw_df.filter(\"outage != 0\") #record the duration of", "= 50 OR fft_base = '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df = dw_df.filter(\"type = 'unplugged'", "15 and i[2] is not None and (i[3] == '50' or i[3] ==", "phone_imei is not None: return -1 used = [] for i in imeiList:", "None or isnan(millis) or isnan(unplugMillis)): return time elif unplugMillis > millis: return time", "= pw_df.filter(\"product_id = 7008 OR product_id= 7009\") #now we need to created a", "phone records joined_df = joined_df.filter(\"phones_detecting > -1\") joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now join", "denote the end time of the outage for saidi reasons time_lead = lead(\"r_time\",1).over(w)", "= pw_df.filter(\"outage_cluster = 1\") pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we now have a list", "not None and (i[3] == '60' or i[3] == '60hz'): count += 1", "need to see how many DW unplug events occurred within some time window", "the row before w = Window.orderBy(asc(\"outage_time\")) outage_time_lag = lag(\"outage_time\",1).over(w) def onlyOutages(time, lag_time): if(lag_time", "lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out all transitions pw_df = pw_df.filter(\"transition !=", "= pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp = pw_df # ##now filter out all single outages", "outages #we can use a similar method of windowing as before but only", "each phone) #w = Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag = lag(\"fft_cnt\",1).over(w) dw_df = dw_df.filter(\"type = 'unplugged'\")", "lit, year, coalesce, mean import pyspark.sql.functions as F from pyspark.sql.window import Window from", "window function that looks at the leading lagging edge of is powered and", "os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\") spark =", "window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df", "can use a similar method of windowing as before but only look at", "#pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df = pw_df.withColumn(\"outage_events\",lit(1)) #pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df", "window_size: return window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster_size\",", "1 fft_cnt += i[2] elif(base == 60): if abs((time - i[0]).total_seconds()) < 15", "outage (really restoration) def countOutage(value1, value2, value3): if(value1 == False and value2 ==", "= pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df = pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote the end time of", "udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size = 150 w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time, core_id,", "return window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType()) joined_df = joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\"))", "return -1 used = [] for i in imeiList: if abs((time - i[0]).total_seconds())", "type = 'plugged'\") #okay now we want the fft_cnt drop between plugged and", "return time else: return time - datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000) udftimeCorrect = udf(timeCorrect, TimestampType())", "using millis def timeCorrect(time, millis, unplugMillis): if(unplugMillis == 0 or millis == None", "= 'unplugged' OR type = 'plugged'\") #okay now we want the fft_cnt drop", "each outage see how many unplug events occur dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\":", "lag(\"outage_time\",1).over(w) def onlyOutages(time, lag_time): if(lag_time is not None): if((time - lag_time).total_seconds() < 120):", "that metric window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time,", "that is not an outage. We should have a time and end_time for", "= spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care", "to take the averaged plug cnt for each phone) #w = Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag", "metric as above #for each outage time we need to see how many", "OR fft_base = '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df = dw_df.filter(\"type =", "the avg fft_cnt as a baseline #plugged_50_df = dw_df.filter(\"type = 'plugged' AND fft_cnt", "outage see how many unplug events occur dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\": config['user'],", "dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND (fft_base = 50 OR fft_base", "datetime import os from math import isnan conf = SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\") +", "leading lagging edge of is powered and detects transitions #then we can filter", "the outage for saidi reasons time_lead = lead(\"r_time\",1).over(w) pw_df = pw_df.withColumn(\"restore_time\", time_lead) #now", "pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote the end time of the outage for saidi reasons", "import isnan conf = SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\")", "in timeList: if abs((time - i[0]).total_seconds()) < 120 and i[1] not in used:", "events into actual outages #we can use a similar method of windowing as", "have a list of all Powerwatch outages with an outage time #now we", "we need to join the data on time/outage time joined_df = pw_df.join(dw_df, col(\"outage_time\")", "[] for i in imeiList: if abs((time - i[0]).total_seconds()) < 15 and i[1]", "fft_cnt += i[2] if(count == 0): return float(-1) print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count))) if(return_count): return", "look at the row before w = Window.orderBy(asc(\"outage_time\")) outage_time_lag = lag(\"outage_time\",1).over(w) def onlyOutages(time,", "lead(\"r_time\",1).over(w) pw_df = pw_df.withColumn(\"restore_time\", time_lead) #now filter out everything that is not an", "the exact outage and restore times using millis def timeCorrect(time, millis, unplugMillis): if(unplugMillis", "all DW unplug events and for each outage see how many unplug events", "col(\"outage_time\") == col(\"time\"), \"fullouter\") joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run a", "that we care about pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df = pw_df.filter(\"product_id = 7008 OR", "if(return_count): return float(count) else: return float(float(fft_cnt)/float(count)) udfFilterTransition = udf(filterOutage, FloatType()) joined_df = joined_df.withColumn(\"avg_50_fft_cnt\",", "return float(float(fft_cnt)/float(count)) udfFilterTransition = udf(filterOutage, FloatType()) joined_df = joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df = joined_df.withColumn(\"50_fft_cnt\",", "pw_df = pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out all transitions pw_df = pw_df.filter(\"transition != 0\")", "events and for each outage see how many unplug events occur dw_df =", "be none if phone_imei is not None: return -1 used = [] for", "+= i[2] if(count == 0): return float(-1) print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count))) if(return_count): return float(count)", "used.append(i[1]) count += 1 if count > window_size: return window_size else: return count", "abs((time - i[0]).total_seconds()) < 15 and i[2] is not None and (i[3] ==", "millis: return time else: return time - datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000) udftimeCorrect = udf(timeCorrect,", "== '60' or i[3] == '60hz'): count += 1 fft_cnt += i[2] if(count", "pw_df.filter(\"transition != 0\") #now count each outage (really restoration) def countOutage(value1, value2, value3):", "- lag_time).total_seconds() < 120): return 0 else: return 1 else: return 1 udfFilterTransition", "- datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000) udftimeCorrect = udf(timeCorrect, TimestampType()) pw_df = pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df", "== 2018) #get the avg fft_cnt as a baseline #plugged_50_df = dw_df.filter(\"type =", "fft_cnt > -1 AND (fft_base = 50 OR fft_base = '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count())", "udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df = joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df = joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df = joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True)))", "an outage time #now we should take all DW unplug events and for", "if abs((time - i[0]).total_seconds()) < 15 and i[2] is not None and (i[3]", "coalesce, mean import pyspark.sql.functions as F from pyspark.sql.window import Window from pyspark.sql.types import", "the database pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data", "timeCorrect(time, millis, unplugMillis): if(unplugMillis == 0 or millis == None or unplugMillis ==", "= endTime-startTime seconds = delta.total_seconds() return int(seconds) udfcalculateDuration = udf(calculateDuration, IntegerType()) pw_df =", "= 0 #we want phone imei to be none if phone_imei is not", "count = 0 #we want phone imei to be none if phone_imei is", "timeList: if abs((time - i[0]).total_seconds()) < 120 and i[1] not in used: used.append(i[1])", "i in imeiList: if abs((time - i[0]).total_seconds()) < 15 and i[1] not in", "time joined_df = pw_df.join(dw_df, col(\"outage_time\") == col(\"time\"), \"fullouter\") joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df =", "return count udfFilterTransition = udf(filterOutage, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df = pw_df.filter(\"outage_cluster_size", "base, return_count): count = 0 fft_cnt = 0 #we want phone imei to", "= pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out all transitions pw_df = pw_df.filter(\"transition != 0\") #now", "= 'unplugged' AND fft_cnt > -1 AND (fft_base = 50 OR fft_base =", "= joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now join the two datasets together so that we have", "udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df = joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove all of the phone records joined_df", "window size average the fft_cnt to see if there is a signal in", "joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove all of the phone records joined_df = joined_df.filter(\"phones_detecting >", "time and end_time for every outage pw_df = pw_df.filter(\"outage != 0\") #record the", "open('config.yaml') config = yaml.load(config) #connect to the database pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\":", "= udf(detectTransition, IntegerType()) w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag))", "that we have a #pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df = pw_df.withColumn(\"outage_events\",lit(1)) #pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\")", "OR type = 'plugged'\") #okay now we want the fft_cnt drop between plugged", "[] used.append(core_id) for i in timeList: if abs((time - i[0]).total_seconds()) < 120 and", "#now we need to join the data on time/outage time joined_df = pw_df.join(dw_df,", "AND fft_cnt > -1 AND (fft_base = 60 OR fft_base = '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show()", "pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we now have a list of all Powerwatch outages with an", "none if phone_imei is not None: return -1 used = [] for i", "0 #we want phone imei to be none if phone_imei is not None:", "#now join the two datasets together so that we have a #pw_df =", "pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df = pw_df.filter(\"outage_cluster = 1\") pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we now", "= joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time, phone_imei, imeiList, base, return_count): count = 0 fft_cnt =", "for each outage see how many unplug events occur dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\",", "OR product_id= 7009\") #now we need to created a window function that looks", "#plugged_60_df = dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND (fft_base = 60", "phone_imei, imeiList): count = 0 #we want phone imei to be none if", "joined_df.filter(\"phones_detecting > -1\") joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now join the two datasets together", "= udf(onlyOutages, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df = pw_df.filter(\"outage_cluster = 1\") pw_df", "edge of is powered and detects transitions #then we can filter out all", "== '60hz'): count += 1 fft_cnt += i[2] if(count == 0): return float(-1)", "\\ .config(conf=conf) \\ .master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI cluster size\") \\ .getOrCreate() config = open('config.yaml')", "if((time - lag_time).total_seconds() < 120): return 0 else: return 1 else: return 1", "dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df = dw_df.filter(\"type = 'unplugged' OR type = 'plugged'\") #okay", "in that metric window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def", "SparkConf import yaml import datetime import os from math import isnan conf =", "udf(calculateDuration, IntegerType()) pw_df = pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size = 150 w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df", "from pyspark.sql.types import FloatType, IntegerType, DateType, TimestampType from pyspark import SparkConf import yaml", "col, window, asc, desc, lead, lag, udf, hour, month, dayofmonth, collect_list, lit, year,", "before w = Window.orderBy(asc(\"outage_time\")) outage_time_lag = lag(\"outage_time\",1).over(w) def onlyOutages(time, lag_time): if(lag_time is not", "calculateDuration(startTime, endTime): delta = endTime-startTime seconds = delta.total_seconds() return int(seconds) udfcalculateDuration = udf(calculateDuration,", "need to collapse these individual outage events into actual outages #we can use", "joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df = joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df = joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove all", "value2 == True and value3 == True): return 1 else: return 0 udfCountTransition", "pw_df = pw_df.withColumn(\"restore_time\", time_lead) #now filter out everything that is not an outage.", "individual outage events into actual outages #we can use a similar method of", "== col(\"time\"), \"fullouter\") joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run a similar", "phone_imei, imeiList, base, return_count): count = 0 fft_cnt = 0 #we want phone", "#pw_df = pw_df.withColumn(\"outage_events\",lit(1)) #pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500)", "window, asc, desc, lead, lag, udf, hour, month, dayofmonth, collect_list, lit, year, coalesce,", "== 0 or millis == None or unplugMillis == None or isnan(millis) or", "onlyOutages(time, lag_time): if(lag_time is not None): if((time - lag_time).total_seconds() < 120): return 0", "udfFilterTransition = udf(filterOutage, FloatType()) joined_df = joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df = joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df", "pw_df # ##now filter out all single outages #pw_df = pw_df.filter(\"outage_cluster_size > 1\")", "if phone_imei is not None: return -1 used = [] for i in", "we have a #pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df = pw_df.withColumn(\"outage_events\",lit(1)) #pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df", "60): if abs((time - i[0]).total_seconds()) < 15 and i[2] is not None and", "for every outage pw_df = pw_df.filter(\"outage != 0\") #record the duration of the", "exact outage and restore times using millis def timeCorrect(time, millis, unplugMillis): if(unplugMillis ==", "-1 for i in imeiList: if(base == 50): if abs((time - i[0]).total_seconds()) <", "the outage def calculateDuration(startTime, endTime): delta = endTime-startTime seconds = delta.total_seconds() return int(seconds)", "count, float(fft_cnt)/float(count))) if(return_count): return float(count) else: return float(float(fft_cnt)/float(count)) udfFilterTransition = udf(filterOutage, FloatType()) joined_df", "\"0\") spark = SparkSession.builder \\ .config(conf=conf) \\ .master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI cluster size\") \\", "outage time #now we should take all DW unplug events and for each", "and i[1] not in used: used.append(i[1]) count += 1 if count > window_size:", "pw_df = pw_df.filter(\"outage_cluster_size > 1\") #now we need to collapse these individual outage", "#for each outage time we need to see how many DW unplug events", "== '50hz'): count += 1 fft_cnt += i[2] elif(base == 60): if abs((time", "joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df = joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df = joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df = joined_df.withColumn(\"60_fft_cnt\",", "= '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1", "i[3] == '50hz'): count += 1 fft_cnt += i[2] elif(base == 60): if", "return 1 else: return 0 udfCountTransition = udf(countOutage, IntegerType()) is_powered_lead = lead(\"is_powered\",1).over(w) is_powered_lag", "drop between plugged and unplugged for each phone imei #we will first try", "#read the data that we care about pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df = pw_df.filter(\"product_id", "that is not a transition def detectTransition(value1, value2): if(value1 == value2): return 0", "size average the fft_cnt to see if there is a signal in that", "outage for saidi reasons time_lead = lead(\"r_time\",1).over(w) pw_df = pw_df.withColumn(\"restore_time\", time_lead) #now filter", "#now we need to collapse these individual outage events into actual outages #we", "= joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df = joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df = joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove", "filter out everything that is not an outage. We should have a time", "lag, udf, hour, month, dayofmonth, collect_list, lit, year, coalesce, mean import pyspark.sql.functions as", "unplugged for each phone imei #we will first try per-plug differencing (although it", "remove all of the phone records joined_df = joined_df.filter(\"phones_detecting > -1\") joined_df =", "not in used: used.append(i[1]) count += 1 if count > window_size: return window_size", "0 else: return 1 else: return 1 udfFilterTransition = udf(onlyOutages, IntegerType()) pw_df =", "between plugged and unplugged for each phone imei #we will first try per-plug", "window window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time, phone_imei,", "joined_df.show(1000) #now join the two datasets together so that we have a #pw_df", "in imeiList: if abs((time - i[0]).total_seconds()) < 15 and i[1] not in used:", "#fft_lag = lag(\"fft_cnt\",1).over(w) dw_df = dw_df.filter(\"type = 'unplugged'\") #now we need to join", "pw_df = pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size = 150 w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w))", "return float(count) else: return float(float(fft_cnt)/float(count)) udfFilterTransition = udf(filterOutage, FloatType()) joined_df = joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False)))", "the duration of the outage def calculateDuration(startTime, endTime): delta = endTime-startTime seconds =", "udf(filterOutage, FloatType()) joined_df = joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df = joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df = joined_df.withColumn(\"avg_60_fft_cnt\",", "= dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND (fft_base = 50 OR", "udfCountTransition = udf(countOutage, IntegerType()) is_powered_lead = lead(\"is_powered\",1).over(w) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"outage\",", "is not None: return -1 used = [] for i in imeiList: if", "care about pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df = pw_df.filter(\"product_id = 7008 OR product_id= 7009\")", "dw_df.filter(\"type = 'unplugged' OR type = 'plugged'\") #okay now we want the fft_cnt", "udftimeCorrect = udf(timeCorrect, TimestampType()) pw_df = pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df = pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now", "#connect to the database pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read", "fft_base = '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df = dw_df.filter(\"type = 'unplugged'", "that we care about dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df = dw_df.filter(year(\"time\") == 2018) #get", "== False and value2 == True and value3 == True): return 1 else:", "imei #we will first try per-plug differencing (although it may be better to", "return 1 else: return 1 udfFilterTransition = udf(onlyOutages, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag))", "\\ .appName(\"SAIDI/SAIFI cluster size\") \\ .getOrCreate() config = open('config.yaml') config = yaml.load(config) #connect", "many unplug events occur dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read", "= lead(\"is_powered\",1).over(w) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag)) #now find", "math import isnan conf = SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\",", "return 0 udfCountTransition = udf(countOutage, IntegerType()) is_powered_lead = lead(\"is_powered\",1).over(w) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df", "AND (fft_base = 60 OR fft_base = '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) # #unplugged_50_df =", "60 OR fft_base = '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) # #unplugged_50_df = dw_df.filter(\"type = 'unplugged'", "import SparkConf import yaml import datetime import os from math import isnan conf", "joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run a similar metric as above #for each outage", "time we need to see how many DW unplug events occurred within some", "i[0]).total_seconds()) < 15 and i[1] not in used: used.append(i[1]) count += 1 if", "phone imei to be none if phone_imei is not None: return -1 for", "if abs((time - i[0]).total_seconds()) < 15 and i[1] not in used: used.append(i[1]) count", "per-plug differencing (although it may be better to take the averaged plug cnt", "is a signal in that metric window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df", "else: return 1 else: return 1 udfFilterTransition = udf(onlyOutages, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster\",", "see if there is a signal in that metric window_size = 100 w", "float(fft_cnt)/float(count))) if(return_count): return float(count) else: return float(float(fft_cnt)/float(count)) udfFilterTransition = udf(filterOutage, FloatType()) joined_df =", "1 if count > window_size: return window_size else: return count udfFilterTransition = udf(filterOutage,", "yaml import datetime import os from math import isnan conf = SparkConf() conf.set(\"spark.jars\",", "= udf(timeCorrect, TimestampType()) pw_df = pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df = pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote", "= SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\",", "> -1 AND (fft_base = 60 OR fft_base = '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df", "udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote the end time of the outage for saidi reasons time_lead", "delta = endTime-startTime seconds = delta.total_seconds() return int(seconds) udfcalculateDuration = udf(calculateDuration, IntegerType()) pw_df", "not a transition def detectTransition(value1, value2): if(value1 == value2): return 0 else: return", "# #unplugged_50_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND (fft_base =", "lagging edge of is powered and detects transitions #then we can filter out", "it may be better to take the averaged plug cnt for each phone)", "return 0 else: return 1 else: return 1 udfFilterTransition = udf(onlyOutages, IntegerType()) pw_df", "float(float(fft_cnt)/float(count)) udfFilterTransition = udf(filterOutage, FloatType()) joined_df = joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df = joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True)))", "all data that is not a transition def detectTransition(value1, value2): if(value1 == value2):", "'unplugged' OR type = 'plugged'\") #okay now we want the fft_cnt drop between", "similar method of windowing as before but only look at the row before", "dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df = dw_df.filter(\"type = 'unplugged' OR type = 'plugged'\") #okay now we", "= dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df = dw_df.filter(\"type = 'unplugged' OR type = 'plugged'\") #okay now", "plugged and unplugged for each phone imei #we will first try per-plug differencing", "= pw_df.join(dw_df, col(\"outage_time\") == col(\"time\"), \"fullouter\") joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now", "15 and i[2] is not None and (i[3] == '60' or i[3] ==", "count > window_size: return window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType()) pw_df", "joined_df = joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df = joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df = joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now", "joined_df = joined_df.filter(\"phones_detecting > -1\") joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now join the two", "abs((time - i[0]).total_seconds()) < 15 and i[1] not in used: used.append(i[1]) count +=", "None): if((time - lag_time).total_seconds() < 120): return 0 else: return 1 else: return", "be better to take the averaged plug cnt for each phone) #w =", "else: return 1 udfFilterTransition = udf(onlyOutages, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df =", "run a similar metric as above #for each outage time we need to", "count += 1 fft_cnt += i[2] if(count == 0): return float(-1) print(\"{},{},{}\".format(base, count,", "= joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df = joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df = joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df =", "False and value2 == True and value3 == True): return 1 else: return", "a window function that looks at the leading lagging edge of is powered", "50 OR fft_base = '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df = dw_df.filter(\"type = 'unplugged' AND", "> -1 AND (fft_base = 60 OR fft_base = '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) #", "we need to see how many DW unplug events occurred within some time", "windowing as before but only look at the row before w = Window.orderBy(asc(\"outage_time\"))", "return time - datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000) udftimeCorrect = udf(timeCorrect, TimestampType()) pw_df = pw_df.withColumn(\"outage_time\",", "have a time and end_time for every outage pw_df = pw_df.filter(\"outage != 0\")", "1\") pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we now have a list of all Powerwatch", "i[0]).total_seconds()) < 15 and i[2] is not None and (i[3] == '50' or", "use a similar method of windowing as before but only look at the", "fft_cnt as a baseline #plugged_50_df = dw_df.filter(\"type = 'plugged' AND fft_cnt > -1", "= 'plugged' AND fft_cnt > -1 AND (fft_base = 50 OR fft_base =", "#plugged_50_df = dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND (fft_base = 50", "detects transitions #then we can filter out all data that is not a", "better to take the averaged plug cnt for each phone) #w = Window.groupBy('phone_imei').orderBy(asc(\"time\"))", "seconds = delta.total_seconds() return int(seconds) udfcalculateDuration = udf(calculateDuration, IntegerType()) pw_df = pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\"))", "is not an outage. We should have a time and end_time for every", "cnt for each phone) #w = Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag = lag(\"fft_cnt\",1).over(w) dw_df = dw_df.filter(\"type", "= joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run a similar metric as above #for each outage time", "= pw_df.filter(\"outage_cluster_size > 1\") #pw_df = pw_df.select(\"month(time)\",\"sum(outage_duration)\",\"sum(outage_events)\",\"num_outages\") #pw_df = pw_df.groupBy(\"month(time)\").sum().orderBy(\"month(time)\") #pw_df = pw_df.show(200)", "#plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) # #unplugged_50_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND", "we want the fft_cnt drop between plugged and unplugged for each phone imei", "is_powered_lag)) #now find all the exact outage and restore times using millis def", "saidi reasons time_lead = lead(\"r_time\",1).over(w) pw_df = pw_df.withColumn(\"restore_time\", time_lead) #now filter out everything", "detectTransition(value1, value2): if(value1 == value2): return 0 else: return 1 udfDetectTransition = udf(detectTransition,", "= dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND (fft_base = 60 OR", "= joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove all of the phone records joined_df = joined_df.filter(\"phones_detecting", "in used: used.append(i[1]) count += 1 if count > window_size: return window_size else:", "at the leading lagging edge of is powered and detects transitions #then we", "= 60 OR fft_base = '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) # #unplugged_50_df = dw_df.filter(\"type =", "SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\")", "#unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df = dw_df.filter(\"type = 'unplugged' OR type =", "value3 == True): return 1 else: return 0 udfCountTransition = udf(countOutage, IntegerType()) is_powered_lead", "hour, month, dayofmonth, collect_list, lit, year, coalesce, mean import pyspark.sql.functions as F from", "\\ .master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI cluster size\") \\ .getOrCreate() config = open('config.yaml') config =", "same window size average the fft_cnt to see if there is a signal", "care about dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df = dw_df.filter(year(\"time\") == 2018) #get the avg", "0): return float(-1) print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count))) if(return_count): return float(count) else: return float(float(fft_cnt)/float(count)) udfFilterTransition", "pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size = 150 w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time,", "transition def detectTransition(value1, value2): if(value1 == value2): return 0 else: return 1 udfDetectTransition", "conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\") spark = SparkSession.builder \\ .config(conf=conf) \\ .master(\"local[4]\")", "and (i[3] == '60' or i[3] == '60hz'): count += 1 fft_cnt +=", "month, dayofmonth, collect_list, lit, year, coalesce, mean import pyspark.sql.functions as F from pyspark.sql.window", "time_lead) #now filter out everything that is not an outage. We should have", "= 'unplugged'\") #now we need to join the data on time/outage time joined_df", "= pw_df.filter(\"outage_cluster_size > 1\") #now we need to collapse these individual outage events", "take all DW unplug events and for each outage see how many unplug", "if(unplugMillis == 0 or millis == None or unplugMillis == None or isnan(millis)", "endTime-startTime seconds = delta.total_seconds() return int(seconds) udfcalculateDuration = udf(calculateDuration, IntegerType()) pw_df = pw_df.withColumn(\"outage_duration\",", "else: return 1 udfDetectTransition = udf(detectTransition, IntegerType()) w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag = lag(\"is_powered\",1).over(w)", "'50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND", "return_count): count = 0 fft_cnt = 0 #we want phone imei to be", "unplug events and for each outage see how many unplug events occur dw_df", "= [] used.append(core_id) for i in timeList: if abs((time - i[0]).total_seconds()) < 120", "#okay now we want the fft_cnt drop between plugged and unplugged for each", "def filterOutage(time, phone_imei, imeiList, base, return_count): count = 0 fft_cnt = 0 #we", "DW unplug events and for each outage see how many unplug events occur", ".appName(\"SAIDI/SAIFI cluster size\") \\ .getOrCreate() config = open('config.yaml') config = yaml.load(config) #connect to", "float(count) else: return float(float(fft_cnt)/float(count)) udfFilterTransition = udf(filterOutage, FloatType()) joined_df = joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df", "datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000) udftimeCorrect = udf(timeCorrect, TimestampType()) pw_df = pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df =", "\"pw_dedupe\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about pw_df", "col(\"time\"), \"fullouter\") joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run a similar metric", "window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time, phone_imei, imeiList,", "pw_df = pw_df.filter(\"outage_cluster = 1\") pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we now have a", "Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time, phone_imei, imeiList, base, return_count): count = 0", "is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out all transitions pw_df =", "we should take all DW unplug events and for each outage see how", "the averaged plug cnt for each phone) #w = Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag = lag(\"fft_cnt\",1).over(w)", "not None and (i[3] == '50' or i[3] == '50hz'): count += 1", "from pyspark.sql import SparkSession from pyspark.sql.functions import col, window, asc, desc, lead, lag,", "#pw_cp = pw_df # ##now filter out all single outages #pw_df = pw_df.filter(\"outage_cluster_size", "collect_list, lit, year, coalesce, mean import pyspark.sql.functions as F from pyspark.sql.window import Window", "udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df = pw_df.filter(\"outage_cluster_size > 1\") #now we need to collapse these individual", "-1 AND (fft_base = 60 OR fft_base = '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df =", "= Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time, core_id, timeList): count = 1 used", "lag(\"fft_cnt\",1).over(w) dw_df = dw_df.filter(\"type = 'unplugged'\") #now we need to join the data", "averaged plug cnt for each phone) #w = Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag = lag(\"fft_cnt\",1).over(w) dw_df", "mean import pyspark.sql.functions as F from pyspark.sql.window import Window from pyspark.sql.types import FloatType,", "return 0 else: return 1 udfDetectTransition = udf(detectTransition, IntegerType()) w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag", "udf(detectTransition, IntegerType()) w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter", "pw_df.withColumn(\"outage_events\",lit(1)) #pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp =", "(fft_base = 60 OR fft_base = '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) # #unplugged_50_df = dw_df.filter(\"type", "count > window_size: return window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType()) joined_df", "None and (i[3] == '50' or i[3] == '50hz'): count += 1 fft_cnt", "> 1\") #pw_df = pw_df.select(\"month(time)\",\"sum(outage_duration)\",\"sum(outage_events)\",\"num_outages\") #pw_df = pw_df.groupBy(\"month(time)\").sum().orderBy(\"month(time)\") #pw_df = pw_df.show(200) # #pw_cp.repartition(1).write.format(\"com.databricks.spark.csv\").option(\"header\",", "7009\") #now we need to created a window function that looks at the", "each outage (really restoration) def countOutage(value1, value2, value3): if(value1 == False and value2", "to be none if phone_imei is not None: return -1 used = []", "else: return count udfFilterTransition = udf(filterOutage, IntegerType()) joined_df = joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the", "#pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp = pw_df # ##now filter", "is not None and (i[3] == '50' or i[3] == '50hz'): count +=", "outage events into actual outages #we can use a similar method of windowing", "'plugged' AND fft_cnt > -1 AND (fft_base = 50 OR fft_base = '50hz')\")", "0 fft_cnt = 0 #we want phone imei to be none if phone_imei", "pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp = pw_df # ##now", "= pw_df # ##now filter out all single outages #pw_df = pw_df.filter(\"outage_cluster_size >", "#pw_df = pw_df.filter(\"outage_cluster_size > 1\") #pw_df = pw_df.select(\"month(time)\",\"sum(outage_duration)\",\"sum(outage_events)\",\"num_outages\") #pw_df = pw_df.groupBy(\"month(time)\").sum().orderBy(\"month(time)\") #pw_df =", "w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time, phone_imei, imeiList, base, return_count): count", "i[2] if(count == 0): return float(-1) print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count))) if(return_count): return float(count) else:", "time of the outage for saidi reasons time_lead = lead(\"r_time\",1).over(w) pw_df = pw_df.withColumn(\"restore_time\",", "> window_size: return window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType()) joined_df =", "True): return 1 else: return 0 udfCountTransition = udf(countOutage, IntegerType()) is_powered_lead = lead(\"is_powered\",1).over(w)", "udf(countOutage, IntegerType()) is_powered_lead = lead(\"is_powered\",1).over(w) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead,", "pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df = pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote the end time of the", "fft_base = '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count()) # #unplugged_50_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt", "udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove all of the phone records joined_df = joined_df.filter(\"phones_detecting > -1\")", "\"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\") spark = SparkSession.builder \\", "conf.set(\"spark.storage.memoryFraction\", \"0\") spark = SparkSession.builder \\ .config(conf=conf) \\ .master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI cluster size\")", "\"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df", "count each outage (really restoration) def countOutage(value1, value2, value3): if(value1 == False and", "outage and restore times using millis def timeCorrect(time, millis, unplugMillis): if(unplugMillis == 0", "actual outages #we can use a similar method of windowing as before but", "1 used = [] used.append(core_id) for i in timeList: if abs((time - i[0]).total_seconds())", "out all transitions pw_df = pw_df.filter(\"transition != 0\") #now count each outage (really", "python from pyspark.sql import SparkSession from pyspark.sql.functions import col, window, asc, desc, lead,", "#we will first try per-plug differencing (although it may be better to take", "a time and end_time for every outage pw_df = pw_df.filter(\"outage != 0\") #record", "to join the data on time/outage time joined_df = pw_df.join(dw_df, col(\"outage_time\") == col(\"time\"),", "#pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp = pw_df # ##now filter out all single", "AND fft_cnt > -1 AND (fft_base = 50 OR fft_base = '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show()", "each phone imei #we will first try per-plug differencing (although it may be", "1 udfFilterTransition = udf(onlyOutages, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df = pw_df.filter(\"outage_cluster =", "0 else: return 1 udfDetectTransition = udf(detectTransition, IntegerType()) w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag =", "= 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time, phone_imei, imeiList, base,", "'60hz'): count += 1 fft_cnt += i[2] if(count == 0): return float(-1) print(\"{},{},{}\".format(base,", "IntegerType()) is_powered_lead = lead(\"is_powered\",1).over(w) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag))", "we can filter out all data that is not a transition def detectTransition(value1,", "= pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we now have a list of all Powerwatch outages with", "= 50 OR fft_base = '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df = dw_df.filter(\"type = 'plugged'", "import SparkSession from pyspark.sql.functions import col, window, asc, desc, lead, lag, udf, hour,", "but only look at the row before w = Window.orderBy(asc(\"outage_time\")) outage_time_lag = lag(\"outage_time\",1).over(w)", "import col, window, asc, desc, lead, lag, udf, hour, month, dayofmonth, collect_list, lit,", "imeiList): count = 0 #we want phone imei to be none if phone_imei", "(although it may be better to take the averaged plug cnt for each", "(int(millis)-int(unplugMillis))*1000) udftimeCorrect = udf(timeCorrect, TimestampType()) pw_df = pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df = pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\"))", "we care about dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df = dw_df.filter(year(\"time\") == 2018) #get the", "list of all Powerwatch outages with an outage time #now we should take", "= dw_df.filter(\"type = 'unplugged'\") #now we need to join the data on time/outage", "as above #for each outage time we need to see how many DW", "== '50' or i[3] == '50hz'): count += 1 fft_cnt += i[2] elif(base", "to be none if phone_imei is not None: return -1 for i in", "filter out all data that is not a transition def detectTransition(value1, value2): if(value1", "DateType, TimestampType from pyspark import SparkConf import yaml import datetime import os from", "time else: return time - datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000) udftimeCorrect = udf(timeCorrect, TimestampType()) pw_df", "average the fft_cnt to see if there is a signal in that metric", "so that we have a #pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df = pw_df.withColumn(\"outage_events\",lit(1)) #pw_df =", "#unplugged_60_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND (fft_base = 60", "udf(onlyOutages, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df = pw_df.filter(\"outage_cluster = 1\") pw_df =", "'60' or i[3] == '60hz'): count += 1 fft_cnt += i[2] if(count ==", "udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df = joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df = joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove all of", "pw_df.filter(\"outage_cluster_size > 1\") #pw_df = pw_df.select(\"month(time)\",\"sum(outage_duration)\",\"sum(outage_events)\",\"num_outages\") #pw_df = pw_df.groupBy(\"month(time)\").sum().orderBy(\"month(time)\") #pw_df = pw_df.show(200) #", "pw_df.withColumn(\"restore_time\", time_lead) #now filter out everything that is not an outage. We should", "else: return time - datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000) udftimeCorrect = udf(timeCorrect, TimestampType()) pw_df =", "outage time we need to see how many DW unplug events occurred within", "= 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time, phone_imei, imeiList): count", "= pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df = pw_df.withColumn(\"outage_events\",lit(1)) #pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df =", "= '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df = dw_df.filter(\"type = 'plugged' AND fft_cnt > -1", "everything that is not an outage. We should have a time and end_time", "millis == None or unplugMillis == None or isnan(millis) or isnan(unplugMillis)): return time", "occur dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that", "count udfFilterTransition = udf(filterOutage, IntegerType()) joined_df = joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the same window", "IntegerType()) joined_df = joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the same window size average the fft_cnt", "> millis: return time else: return time - datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000) udftimeCorrect =", "pw_df = pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df = pw_df.filter(\"outage_cluster_size > 1\") #now we need to", "'plugged' AND fft_cnt > -1 AND (fft_base = 60 OR fft_base = '60hz')\")", "= 60 OR fft_base = '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df =", "100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time, phone_imei, imeiList, base, return_count):", "used = [] used.append(core_id) for i in timeList: if abs((time - i[0]).total_seconds()) <", "we care about pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df = pw_df.filter(\"product_id = 7008 OR product_id=", "similar metric as above #for each outage time we need to see how", "outage def calculateDuration(startTime, endTime): delta = endTime-startTime seconds = delta.total_seconds() return int(seconds) udfcalculateDuration", "IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df = pw_df.filter(\"outage_cluster = 1\") pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\")", "joined_df = joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time, phone_imei, imeiList, base, return_count): count = 0 fft_cnt", "'60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df = dw_df.filter(\"type = 'unplugged' OR type", "cluster size\") \\ .getOrCreate() config = open('config.yaml') config = yaml.load(config) #connect to the", "#unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND (fft_base", "IntegerType, DateType, TimestampType from pyspark import SparkConf import yaml import datetime import os", "os from math import isnan conf = SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\",", "- i[0]).total_seconds()) < 15 and i[2] is not None and (i[3] == '50'", "two datasets together so that we have a #pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df =", "= pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp = pw_df # ##now filter out", "out all data that is not a transition def detectTransition(value1, value2): if(value1 ==", "return time elif unplugMillis > millis: return time else: return time - datetime.timedelta(microseconds", "udf(filterOutage, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df = pw_df.filter(\"outage_cluster_size > 1\") #now we", "fft_cnt += i[2] elif(base == 60): if abs((time - i[0]).total_seconds()) < 15 and", "the data that we care about dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df = dw_df.filter(year(\"time\") ==", "will first try per-plug differencing (although it may be better to take the", "def onlyOutages(time, lag_time): if(lag_time is not None): if((time - lag_time).total_seconds() < 120): return", "how many unplug events occur dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"})", "'50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df = dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND", "of all Powerwatch outages with an outage time #now we should take all", "+= i[2] elif(base == 60): if abs((time - i[0]).total_seconds()) < 15 and i[2]", "#plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df = dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND (fft_base", "w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out all", "dw_df = dw_df.filter(year(\"time\") == 2018) #get the avg fft_cnt as a baseline #plugged_50_df", "the data that we care about pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df = pw_df.filter(\"product_id =", "None: return -1 for i in imeiList: if(base == 50): if abs((time -", "import pyspark.sql.functions as F from pyspark.sql.window import Window from pyspark.sql.types import FloatType, IntegerType,", "= dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND (fft_base = 60 OR", "spark = SparkSession.builder \\ .config(conf=conf) \\ .master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI cluster size\") \\ .getOrCreate()", "about dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df = dw_df.filter(year(\"time\") == 2018) #get the avg fft_cnt", "1\") #now we need to collapse these individual outage events into actual outages", "else: return count udfFilterTransition = udf(filterOutage, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df =", "= joined_df.filter(\"phones_detecting > -1\") joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now join the two datasets", "pw_df = pw_df.filter(\"product_id = 7008 OR product_id= 7009\") #now we need to created", "joined_df = joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df = joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove all of the", "= 7008 OR product_id= 7009\") #now we need to created a window function", "used.append(core_id) for i in timeList: if abs((time - i[0]).total_seconds()) < 120 and i[1]", "count += 1 fft_cnt += i[2] elif(base == 60): if abs((time - i[0]).total_seconds())", "return -1 for i in imeiList: if(base == 50): if abs((time - i[0]).total_seconds())", "single outages #pw_df = pw_df.filter(\"outage_cluster_size > 1\") #pw_df = pw_df.select(\"month(time)\",\"sum(outage_duration)\",\"sum(outage_events)\",\"num_outages\") #pw_df = pw_df.groupBy(\"month(time)\").sum().orderBy(\"month(time)\")", "to the database pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the", "unplug events occur dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the", "= 'unplugged' AND fft_cnt > -1 AND (fft_base = 60 OR fft_base =", "i[0]).total_seconds()) < 15 and i[2] is not None and (i[3] == '60' or", "should take all DW unplug events and for each outage see how many", "isnan(millis) or isnan(unplugMillis)): return time elif unplugMillis > millis: return time else: return", "1 fft_cnt += i[2] if(count == 0): return float(-1) print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count))) if(return_count):", "= pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp = pw_df #", "config = open('config.yaml') config = yaml.load(config) #connect to the database pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\",", "= udf(filterOutage, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df = pw_df.filter(\"outage_cluster_size > 1\") #now", "method of windowing as before but only look at the row before w", "w = Window.orderBy(asc(\"outage_time\")) outage_time_lag = lag(\"outage_time\",1).over(w) def onlyOutages(time, lag_time): if(lag_time is not None):", "used = [] for i in imeiList: if abs((time - i[0]).total_seconds()) < 15", "conf = SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\", \"15g\")", "-1 AND (fft_base = 50 OR fft_base = '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df =", "'unplugged'\") #now we need to join the data on time/outage time joined_df =", "== True and value3 == True): return 1 else: return 0 udfCountTransition =", "= delta.total_seconds() return int(seconds) udfcalculateDuration = udf(calculateDuration, IntegerType()) pw_df = pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size", "dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND (fft_base = 60 OR fft_base", "#okay we now have a list of all Powerwatch outages with an outage", "joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time, phone_imei, imeiList): count = 0 #we want phone imei to", "= 'plugged'\") #okay now we want the fft_cnt drop between plugged and unplugged", "join the two datasets together so that we have a #pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\")", "#we want phone imei to be none if phone_imei is not None: return", "properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about pw_df =", "= lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out all transitions pw_df = pw_df.filter(\"transition", "is not a transition def detectTransition(value1, value2): if(value1 == value2): return 0 else:", "udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag)) #now find all the exact outage and restore times using", "#print(unplugged_50_df.count()) #unplugged_60_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND (fft_base =", "is_powered_lead = lead(\"is_powered\",1).over(w) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag)) #now", "AND fft_cnt > -1 AND (fft_base = 60 OR fft_base = '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show()", "if(lag_time is not None): if((time - lag_time).total_seconds() < 120): return 0 else: return", "#print(plugged_50_df.count()) #plugged_60_df = dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND (fft_base =", "= Window.orderBy(asc(\"outage_time\")) outage_time_lag = lag(\"outage_time\",1).over(w) def onlyOutages(time, lag_time): if(lag_time is not None): if((time", "fft_cnt > -1 AND (fft_base = 60 OR fft_base = '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count())", "if(count == 0): return float(-1) print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count))) if(return_count): return float(count) else: return", "window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType()) joined_df = joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For", "-1 AND (fft_base = 50 OR fft_base = '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df =", "imei to be none if phone_imei is not None: return -1 used =", "data that we care about dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df = dw_df.filter(year(\"time\") == 2018)", "fft_base = '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt >", "FloatType()) joined_df = joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df = joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df = joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False)))", "# ##now filter out all single outages #pw_df = pw_df.filter(\"outage_cluster_size > 1\") #pw_df", "is powered and detects transitions #then we can filter out all data that", "as F from pyspark.sql.window import Window from pyspark.sql.types import FloatType, IntegerType, DateType, TimestampType", "return 1 udfFilterTransition = udf(onlyOutages, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df = pw_df.filter(\"outage_cluster", "countOutage(value1, value2, value3): if(value1 == False and value2 == True and value3 ==", "pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time, core_id, timeList): count = 1 used = []", "120 and i[1] not in used: used.append(i[1]) count += 1 if count >", "udfFilterTransition = udf(onlyOutages, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df = pw_df.filter(\"outage_cluster = 1\")", "pw_df.filter(\"outage_cluster = 1\") pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we now have a list of", "plug cnt for each phone) #w = Window.groupBy('phone_imei').orderBy(asc(\"time\")) #fft_lag = lag(\"fft_cnt\",1).over(w) dw_df =", "dw_df = dw_df.filter(\"type = 'unplugged'\") #now we need to join the data on", "w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time, phone_imei, imeiList): count = 0", "== 60): if abs((time - i[0]).total_seconds()) < 15 and i[2] is not None", "properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about dw_df =", "the fft_cnt to see if there is a signal in that metric window_size", "(really restoration) def countOutage(value1, value2, value3): if(value1 == False and value2 == True", "pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we", "the data on time/outage time joined_df = pw_df.join(dw_df, col(\"outage_time\") == col(\"time\"), \"fullouter\") joined_df", "AND (fft_base = 50 OR fft_base = '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df = dw_df.filter(\"type", "udfcalculateDuration = udf(calculateDuration, IntegerType()) pw_df = pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size = 150 w =", "a signal in that metric window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df =", "these individual outage events into actual outages #we can use a similar method", "if abs((time - i[0]).total_seconds()) < 120 and i[1] not in used: used.append(i[1]) count", "none if phone_imei is not None: return -1 for i in imeiList: if(base", "fft_cnt > -1 AND (fft_base = 60 OR fft_base = '60hz')\") #plugged_60_df.select(mean('fft_cnt')).show() #print(plugged_60_df.count())", "unplug events occurred within some time window window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size)", "#pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp = pw_df", "for i in imeiList: if(base == 50): if abs((time - i[0]).total_seconds()) < 15", "joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now join the two datasets together so that we have a", "lead, lag, udf, hour, month, dayofmonth, collect_list, lit, year, coalesce, mean import pyspark.sql.functions", "udfDetectTransition = udf(detectTransition, IntegerType()) w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"transition\",", "many DW unplug events occurred within some time window window_size = 100 w", "= pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time, core_id, timeList): count = 1 used = [] used.append(core_id)", "(i[3] == '60' or i[3] == '60hz'): count += 1 fft_cnt += i[2]", "avg fft_cnt as a baseline #plugged_50_df = dw_df.filter(\"type = 'plugged' AND fft_cnt >", "all transitions pw_df = pw_df.filter(\"transition != 0\") #now count each outage (really restoration)", "about pw_df = pw_df.select(pw_df['core_id'],pw_df['time'],pw_df['is_powered'],pw_df['product_id'],pw_df['millis'],pw_df['last_unplug_millis'],pw_df['last_plug_millis']) pw_df = pw_df.filter(\"product_id = 7008 OR product_id= 7009\") #now", "that looks at the leading lagging edge of is powered and detects transitions", "- i[0]).total_seconds()) < 15 and i[2] is not None and (i[3] == '60'", "joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the same window size average the fft_cnt to see if", "pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"]) #pw_df.show(500) #pw_cp = pw_df # ##now filter out all single outages #pw_df", "> 1\") #now we need to collapse these individual outage events into actual", "def timeCorrect(time, millis, unplugMillis): if(unplugMillis == 0 or millis == None or unplugMillis", "for saidi reasons time_lead = lead(\"r_time\",1).over(w) pw_df = pw_df.withColumn(\"restore_time\", time_lead) #now filter out", "or millis == None or unplugMillis == None or isnan(millis) or isnan(unplugMillis)): return", "to collapse these individual outage events into actual outages #we can use a", "elif(base == 60): if abs((time - i[0]).total_seconds()) < 15 and i[2] is not", "pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\")) pw_df = pw_df.filter(\"outage_cluster_size > 1\") #now we need to collapse these", "time elif unplugMillis > millis: return time else: return time - datetime.timedelta(microseconds =", "unplugMillis > millis: return time else: return time - datetime.timedelta(microseconds = (int(millis)-int(unplugMillis))*1000) udftimeCorrect", "pw_df.filter(\"product_id = 7008 OR product_id= 7009\") #now we need to created a window", "!= 0\") #record the duration of the outage def calculateDuration(startTime, endTime): delta =", "= spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care", "asc, desc, lead, lag, udf, hour, month, dayofmonth, collect_list, lit, year, coalesce, mean", "and value3 == True): return 1 else: return 0 udfCountTransition = udf(countOutage, IntegerType())", "60 OR fft_base = '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df = dw_df.filter(\"type", "0\") #record the duration of the outage def calculateDuration(startTime, endTime): delta = endTime-startTime", "#now we should take all DW unplug events and for each outage see", "data on time/outage time joined_df = pw_df.join(dw_df, col(\"outage_time\") == col(\"time\"), \"fullouter\") joined_df =", "window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time, phone_imei, imeiList):", "to see if there is a signal in that metric window_size = 100", "value2): return 0 else: return 1 udfDetectTransition = udf(detectTransition, IntegerType()) w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\"))", "occurred within some time window window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df =", "udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df = pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote the end time of the outage", "is_powered_lead, is_powered_lag)) #now find all the exact outage and restore times using millis", "True and value3 == True): return 1 else: return 0 udfCountTransition = udf(countOutage,", "if phone_imei is not None: return -1 for i in imeiList: if(base ==", "Window.orderBy(asc(\"outage_time\")) outage_time_lag = lag(\"outage_time\",1).over(w) def onlyOutages(time, lag_time): if(lag_time is not None): if((time -", "in imeiList: if(base == 50): if abs((time - i[0]).total_seconds()) < 15 and i[2]", "= pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag)) #now find all the exact outage and restore", "(fft_base = 50 OR fft_base = '50hz')\") #unplugged_50_df.select(mean('fft_cnt')).show() #print(unplugged_50_df.count()) #unplugged_60_df = dw_df.filter(\"type =", "Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time, phone_imei, imeiList): count = 0 #we want", "+= 1 fft_cnt += i[2] if(count == 0): return float(-1) print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count)))", "pyspark.sql.functions as F from pyspark.sql.window import Window from pyspark.sql.types import FloatType, IntegerType, DateType,", "2018) #get the avg fft_cnt as a baseline #plugged_50_df = dw_df.filter(\"type = 'plugged'", "= udf(countOutage, IntegerType()) is_powered_lead = lead(\"is_powered\",1).over(w) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\",", "abs((time - i[0]).total_seconds()) < 120 and i[1] not in used: used.append(i[1]) count +=", "15 and i[1] not in used: used.append(i[1]) count += 1 if count >", "database pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that", "pyspark.sql.types import FloatType, IntegerType, DateType, TimestampType from pyspark import SparkConf import yaml import", "+ \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\") spark = SparkSession.builder", "TimestampType()) pw_df = pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df = pw_df.withColumn(\"r_time\", udftimeCorrect(\"time\",\"millis\",\"last_plug_millis\")) #now denote the end", "#now denote the end time of the outage for saidi reasons time_lead =", "of windowing as before but only look at the row before w =", "+= 1 fft_cnt += i[2] elif(base == 60): if abs((time - i[0]).total_seconds()) <", "None: return -1 used = [] for i in imeiList: if abs((time -", "##now filter out all single outages #pw_df = pw_df.filter(\"outage_cluster_size > 1\") #pw_df =", "every outage pw_df = pw_df.filter(\"outage != 0\") #record the duration of the outage", "pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time, core_id, timeList): count = 1 used = [] used.append(core_id) for", "isnan conf = SparkConf() conf.set(\"spark.jars\", os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\",", "#we can use a similar method of windowing as before but only look", "int(seconds) udfcalculateDuration = udf(calculateDuration, IntegerType()) pw_df = pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size = 150 w", "-1\") joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now join the two datasets together so that", "= dw_df.filter(\"type = 'plugged' AND fft_cnt > -1 AND (fft_base = 50 OR", "- i[0]).total_seconds()) < 120 and i[1] not in used: used.append(i[1]) count += 1", "into actual outages #we can use a similar method of windowing as before", "we need to created a window function that looks at the leading lagging", "= open('config.yaml') config = yaml.load(config) #connect to the database pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\",", "7008 OR product_id= 7009\") #now we need to created a window function that", "core_id, timeList): count = 1 used = [] used.append(core_id) for i in timeList:", "#dw_df = dw_df.filter(\"type = 'unplugged' OR type = 'plugged'\") #okay now we want", "filterOutage(time, phone_imei, imeiList): count = 0 #we want phone imei to be none", "of the phone records joined_df = joined_df.filter(\"phones_detecting > -1\") joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000)", "and end_time for every outage pw_df = pw_df.filter(\"outage != 0\") #record the duration", "is not None and (i[3] == '60' or i[3] == '60hz'): count +=", "transitions pw_df = pw_df.filter(\"transition != 0\") #now count each outage (really restoration) def", "float(-1) print(\"{},{},{}\".format(base, count, float(fft_cnt)/float(count))) if(return_count): return float(count) else: return float(float(fft_cnt)/float(count)) udfFilterTransition = udf(filterOutage,", "i[1] not in used: used.append(i[1]) count += 1 if count > window_size: return", "all Powerwatch outages with an outage time #now we should take all DW", "i in timeList: if abs((time - i[0]).total_seconds()) < 120 and i[1] not in", "< 15 and i[2] is not None and (i[3] == '60' or i[3]", "= udf(filterOutage, IntegerType()) joined_df = joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the same window size average", "120): return 0 else: return 1 else: return 1 udfFilterTransition = udf(onlyOutages, IntegerType())", "fft_cnt to see if there is a signal in that metric window_size =", "for each phone imei #we will first try per-plug differencing (although it may", "#filter out all transitions pw_df = pw_df.filter(\"transition != 0\") #now count each outage", "data that is not a transition def detectTransition(value1, value2): if(value1 == value2): return", "the fft_cnt drop between plugged and unplugged for each phone imei #we will", "or i[3] == '60hz'): count += 1 fft_cnt += i[2] if(count == 0):", "= lag(\"fft_cnt\",1).over(w) dw_df = dw_df.filter(\"type = 'unplugged'\") #now we need to join the", "#unplugged_50_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND (fft_base = 50", "50 OR fft_base = '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df = dw_df.filter(\"type = 'plugged' AND", "pyspark.sql.functions import col, window, asc, desc, lead, lag, udf, hour, month, dayofmonth, collect_list,", "= joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time, phone_imei, imeiList): count = 0 #we want phone imei", "== value2): return 0 else: return 1 udfDetectTransition = udf(detectTransition, IntegerType()) w =", "dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND (fft_base = 60 OR fft_base", "how many DW unplug events occurred within some time window window_size = 100", "phone_imei is not None: return -1 for i in imeiList: if(base == 50):", "if(value1 == value2): return 0 else: return 1 udfDetectTransition = udf(detectTransition, IntegerType()) w", "'plugged'\") #okay now we want the fft_cnt drop between plugged and unplugged for", "on time/outage time joined_df = pw_df.join(dw_df, col(\"outage_time\") == col(\"time\"), \"fullouter\") joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\"))", "fft_cnt = 0 #we want phone imei to be none if phone_imei is", "duration of the outage def calculateDuration(startTime, endTime): delta = endTime-startTime seconds = delta.total_seconds()", "= 1 used = [] used.append(core_id) for i in timeList: if abs((time -", "0 udfCountTransition = udf(countOutage, IntegerType()) is_powered_lead = lead(\"is_powered\",1).over(w) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df =", "= Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time, phone_imei, imeiList): count = 0 #we", "config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base'])", "= (int(millis)-int(unplugMillis))*1000) udftimeCorrect = udf(timeCorrect, TimestampType()) pw_df = pw_df.withColumn(\"outage_time\", udftimeCorrect(\"time\",\"millis\",\"last_unplug_millis\")) pw_df = pw_df.withColumn(\"r_time\",", "= lag(\"outage_time\",1).over(w) def onlyOutages(time, lag_time): if(lag_time is not None): if((time - lag_time).total_seconds() <", "150 w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time, core_id, timeList): count =", "millis def timeCorrect(time, millis, unplugMillis): if(unplugMillis == 0 or millis == None or", "Powerwatch outages with an outage time #now we should take all DW unplug", "#now run a similar metric as above #for each outage time we need", "return count udfFilterTransition = udf(filterOutage, IntegerType()) joined_df = joined_df.withColumn(\"phones_detecting\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"imei_list\")) #For the same", "pw_df = pw_df.filter(\"transition != 0\") #now count each outage (really restoration) def countOutage(value1,", "count += 1 if count > window_size: return window_size else: return count udfFilterTransition", "dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df = dw_df.filter(year(\"time\") == 2018) #get the avg fft_cnt as a baseline", "spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about", "joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run a similar metric as above #for each outage time we", "joined_df.withColumn(\"fft_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\",\"fft_cnt\",\"fft_base\")).over(w)) def filterOutage(time, phone_imei, imeiList, base, return_count): count = 0 fft_cnt = 0", "the phone records joined_df = joined_df.filter(\"phones_detecting > -1\") joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now", "def filterOutage(time, core_id, timeList): count = 1 used = [] used.append(core_id) for i", "def filterOutage(time, phone_imei, imeiList): count = 0 #we want phone imei to be", "looks at the leading lagging edge of is powered and detects transitions #then", "dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df = dw_df.filter(year(\"time\") == 2018) #get the avg fft_cnt as", "or isnan(millis) or isnan(unplugMillis)): return time elif unplugMillis > millis: return time else:", "F from pyspark.sql.window import Window from pyspark.sql.types import FloatType, IntegerType, DateType, TimestampType from", "= Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out all transitions", "return window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType()) pw_df = pw_df.withColumn(\"outage_cluster_size\", udfFilterTransition(\"outage_time\",\"core_id\",\"outage_window_list\"))", "yaml.load(config) #connect to the database pw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"})", "reasons time_lead = lead(\"r_time\",1).over(w) pw_df = pw_df.withColumn(\"restore_time\", time_lead) #now filter out everything that", "datasets together so that we have a #pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df = pw_df.withColumn(\"outage_events\",lit(1))", "Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df = pw_df.withColumn(\"transition\", udfDetectTransition(\"is_powered\",is_powered_lag)) #filter out all transitions pw_df", "out all single outages #pw_df = pw_df.filter(\"outage_cluster_size > 1\") #pw_df = pw_df.select(\"month(time)\",\"sum(outage_duration)\",\"sum(outage_events)\",\"num_outages\") #pw_df", "is not None: return -1 for i in imeiList: if(base == 50): if", "= udf(filterOutage, FloatType()) joined_df = joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df = joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df =", "is not None): if((time - lag_time).total_seconds() < 120): return 0 else: return 1", "outage_time_lag = lag(\"outage_time\",1).over(w) def onlyOutages(time, lag_time): if(lag_time is not None): if((time - lag_time).total_seconds()", "want phone imei to be none if phone_imei is not None: return -1", "the same window size average the fft_cnt to see if there is a", "from pyspark.sql.functions import col, window, asc, desc, lead, lag, udf, hour, month, dayofmonth,", "a transition def detectTransition(value1, value2): if(value1 == value2): return 0 else: return 1", "#now we need to created a window function that looks at the leading", "return 1 udfDetectTransition = udf(detectTransition, IntegerType()) w = Window.partitionBy(\"core_id\").orderBy(asc(\"time\")) is_powered_lag = lag(\"is_powered\",1).over(w) pw_df", "IntegerType()) pw_df = pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size = 150 w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df =", "def countOutage(value1, value2, value3): if(value1 == False and value2 == True and value3", "timeList): count = 1 used = [] used.append(core_id) for i in timeList: if", "or isnan(unplugMillis)): return time elif unplugMillis > millis: return time else: return time", "time_lead = lead(\"r_time\",1).over(w) pw_df = pw_df.withColumn(\"restore_time\", time_lead) #now filter out everything that is", "fft_base = '50hz')\") #plugged_50_df.select(mean('fft_cnt')).show() #print(plugged_50_df.count()) #plugged_60_df = dw_df.filter(\"type = 'plugged' AND fft_cnt >", "join the data on time/outage time joined_df = pw_df.join(dw_df, col(\"outage_time\") == col(\"time\"), \"fullouter\")", "pw_df = pw_df.withColumn(\"outage\", udfCountTransition(\"is_powered\", is_powered_lead, is_powered_lag)) #now find all the exact outage and", "out everything that is not an outage. We should have a time and", "we need to collapse these individual outage events into actual outages #we can", "< 15 and i[2] is not None and (i[3] == '50' or i[3]", "from pyspark import SparkConf import yaml import datetime import os from math import", "and restore times using millis def timeCorrect(time, millis, unplugMillis): if(unplugMillis == 0 or", "import Window from pyspark.sql.types import FloatType, IntegerType, DateType, TimestampType from pyspark import SparkConf", "or i[3] == '50hz'): count += 1 fft_cnt += i[2] elif(base == 60):", "for i in imeiList: if abs((time - i[0]).total_seconds()) < 15 and i[1] not", "filterOutage(time, phone_imei, imeiList, base, return_count): count = 0 fft_cnt = 0 #we want", "joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df = joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove all of the phone records", "= lead(\"r_time\",1).over(w) pw_df = pw_df.withColumn(\"restore_time\", time_lead) #now filter out everything that is not", "window_size = 150 w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def filterOutage(time, core_id, timeList):", "joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now join the two datasets together so that we", "'unplugged' AND fft_cnt > -1 AND (fft_base = 50 OR fft_base = '50hz')\")", "imei to be none if phone_imei is not None: return -1 for i", "pw_df = pw_df.withColumn(\"outage_cluster\", udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df = pw_df.filter(\"outage_cluster = 1\") pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay", "udfFilterTransition(\"outage_time\",outage_time_lag)) pw_df = pw_df.filter(\"outage_cluster = 1\") pw_df = pw_df.select(\"outage_time\",\"outage_cluster_size\") #okay we now have", "100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def filterOutage(time, phone_imei, imeiList): count =", "joined_df = joined_df.withColumn(\"avg_50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(False))) joined_df = joined_df.withColumn(\"50_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(50),lit(True))) joined_df = joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df", "#now filter out everything that is not an outage. We should have a", "filter out all single outages #pw_df = pw_df.filter(\"outage_cluster_size > 1\") #pw_df = pw_df.select(\"month(time)\",\"sum(outage_duration)\",\"sum(outage_events)\",\"num_outages\")", "> window_size: return window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType()) pw_df =", "count = 1 used = [] used.append(core_id) for i in timeList: if abs((time", "there is a signal in that metric window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size)", "= pw_df.filter(\"transition != 0\") #now count each outage (really restoration) def countOutage(value1, value2,", "be none if phone_imei is not None: return -1 for i in imeiList:", "conf.set(\"spark.jars\", os.getenv(\"HOME\") + \"/.ivy2/jars/org.postgresql_postgresql-42.1.1.jar\") conf.set(\"spark.executor.extrajavaoptions\", \"-Xmx15000m\") conf.set(\"spark.executor.memory\", \"15g\") conf.set(\"spark.driver.memory\", \"15g\") conf.set(\"spark.storage.memoryFraction\", \"0\") spark", "of the outage for saidi reasons time_lead = lead(\"r_time\",1).over(w) pw_df = pw_df.withColumn(\"restore_time\", time_lead)", "= pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size = 150 w = Window.orderBy(asc(\"outage_time\")).rowsBetween(-1*window_size,window_size) pw_df = pw_df.withColumn(\"outage_window_list\",collect_list(F.struct(\"outage_time\",\"core_id\")).over(w)) def", "desc, lead, lag, udf, hour, month, dayofmonth, collect_list, lit, year, coalesce, mean import", "if count > window_size: return window_size else: return count udfFilterTransition = udf(filterOutage, IntegerType())", "used: used.append(i[1]) count += 1 if count > window_size: return window_size else: return", "we now have a list of all Powerwatch outages with an outage time", "transitions #then we can filter out all data that is not a transition", "with an outage time #now we should take all DW unplug events and", "< 15 and i[1] not in used: used.append(i[1]) count += 1 if count", "else: return 0 udfCountTransition = udf(countOutage, IntegerType()) is_powered_lead = lead(\"is_powered\",1).over(w) is_powered_lag = lag(\"is_powered\",1).over(w)", "some time window window_size = 100 w = Window.orderBy(asc(\"agg_time\"),).rowsBetween(-1*window_size,window_size) joined_df = joined_df.withColumn(\"imei_list\",collect_list(F.struct(\"agg_time\",\"phone_imei\")).over(w)) def", "all single outages #pw_df = pw_df.filter(\"outage_cluster_size > 1\") #pw_df = pw_df.select(\"month(time)\",\"sum(outage_duration)\",\"sum(outage_events)\",\"num_outages\") #pw_df =", "pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df = pw_df.withColumn(\"outage_events\",lit(1)) #pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\") #pw_df = pw_df.withColumn(\"num_outages\",pw_df[\"sum(outage_events)\"]/pw_df[\"outage_cluster_size\"])", "or unplugMillis == None or isnan(millis) or isnan(unplugMillis)): return time elif unplugMillis >", "and i[2] is not None and (i[3] == '60' or i[3] == '60hz'):", "outages #pw_df = pw_df.filter(\"outage_cluster_size > 1\") #pw_df = pw_df.select(\"month(time)\",\"sum(outage_duration)\",\"sum(outage_events)\",\"num_outages\") #pw_df = pw_df.groupBy(\"month(time)\").sum().orderBy(\"month(time)\") #pw_df", "before but only look at the row before w = Window.orderBy(asc(\"outage_time\")) outage_time_lag =", "spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"pw_dedupe\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about", "= dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df = dw_df.filter(year(\"time\") == 2018) #get the avg fft_cnt as a", "config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we care about dw_df = dw_df.select(dw_df['phone_imei'],dw_df['time'],dw_df['type'],dw_df['fft_cnt'],dw_df['fft_base']) dw_df =", "all of the phone records joined_df = joined_df.filter(\"phones_detecting > -1\") joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\")", "joined_df = pw_df.join(dw_df, col(\"outage_time\") == col(\"time\"), \"fullouter\") joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\")", "joined_df = joined_df.withColumn(\"agg_time\",coalesce(\"outage_time\",\"time\")) joined_df = joined_df.select(\"agg_time\",\"phone_imei\",\"outage_cluster_size\",\"fft_cnt\",\"fft_base\") #now run a similar metric as above", "= joined_df.withColumn(\"avg_60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(False))) joined_df = joined_df.withColumn(\"60_fft_cnt\", udfFilterTransition(\"agg_time\",\"phone_imei\",\"fft_list\",lit(60),lit(True))) #now remove all of the phone", "filterOutage(time, core_id, timeList): count = 1 used = [] used.append(core_id) for i in", "outage pw_df = pw_df.filter(\"outage != 0\") #record the duration of the outage def", "function that looks at the leading lagging edge of is powered and detects", "size\") \\ .getOrCreate() config = open('config.yaml') config = yaml.load(config) #connect to the database", "a #pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df = pw_df.withColumn(\"outage_events\",lit(1)) #pw_df = pw_df.groupBy(month(\"time\"),\"outage_cluster_size\").sum().orderBy(month(\"time\"),\"outage_cluster_size\") #pw_df = pw_df.select(\"month(time)\",\"outage_cluster_size\",\"sum(outage_duration)\",\"sum(outage_events)\")", "delta.total_seconds() return int(seconds) udfcalculateDuration = udf(calculateDuration, IntegerType()) pw_df = pw_df.withColumn(\"outage_duration\", udfcalculateDuration(\"outage_time\",\"restore_time\")) window_size =", "0 or millis == None or unplugMillis == None or isnan(millis) or isnan(unplugMillis)):", "#now find all the exact outage and restore times using millis def timeCorrect(time,", "(fft_base = 60 OR fft_base = '60hz')\") #unplugged_60_df.select(mean('fft_cnt')).show() #print(unplugged_60_df.count()) dw_df = dw_df.select(\"phone_imei\",\"time\",\"fft_cnt\",\"fft_base\") #dw_df", "SparkSession from pyspark.sql.functions import col, window, asc, desc, lead, lag, udf, hour, month,", "now we want the fft_cnt drop between plugged and unplugged for each phone", "outages with an outage time #now we should take all DW unplug events", "dw_df = spark.read.jdbc(\"jdbc:postgresql://timescale.lab11.eecs.umich.edu/powerwatch\", \"dumsorwatch\", properties={\"user\": config['user'], \"password\": config['password'],\"driver\":\"org.postgresql.Driver\"}) #read the data that we", "We should have a time and end_time for every outage pw_df = pw_df.filter(\"outage", "imeiList: if abs((time - i[0]).total_seconds()) < 15 and i[1] not in used: used.append(i[1])", "def detectTransition(value1, value2): if(value1 == value2): return 0 else: return 1 udfDetectTransition =", "an outage. We should have a time and end_time for every outage pw_df", "see how many DW unplug events occurred within some time window window_size =", "== 50): if abs((time - i[0]).total_seconds()) < 15 and i[2] is not None", "> -1\") joined_df = joined_df.select(\"agg_time\",\"outage_cluster_size\",\"phones_detecting\",\"avg_50_fft_cnt\",\"50_fft_cnt\",\"avg_60_fft_cnt\",\"60_fft_cnt\") joined_df.show(1000) #now join the two datasets together so", "isnan(unplugMillis)): return time elif unplugMillis > millis: return time else: return time -", "#get the avg fft_cnt as a baseline #plugged_50_df = dw_df.filter(\"type = 'plugged' AND", "< 120 and i[1] not in used: used.append(i[1]) count += 1 if count", "\\ .getOrCreate() config = open('config.yaml') config = yaml.load(config) #connect to the database pw_df", "and unplugged for each phone imei #we will first try per-plug differencing (although", "together so that we have a #pw_df = pw_df.select(\"time\",\"outage_duration\",\"outage_cluster_size\") #pw_df = pw_df.withColumn(\"outage_events\",lit(1)) #pw_df", "SparkSession.builder \\ .config(conf=conf) \\ .master(\"local[4]\") \\ .appName(\"SAIDI/SAIFI cluster size\") \\ .getOrCreate() config =", "#print(plugged_60_df.count()) # #unplugged_50_df = dw_df.filter(\"type = 'unplugged' AND fft_cnt > -1 AND (fft_base", "DW unplug events occurred within some time window window_size = 100 w =", "#then we can filter out all data that is not a transition def", "i[2] is not None and (i[3] == '50' or i[3] == '50hz'): count", "dw_df.filter(year(\"time\") == 2018) #get the avg fft_cnt as a baseline #plugged_50_df = dw_df.filter(\"type", "#pw_df.show(500) #pw_cp = pw_df # ##now filter out all single outages #pw_df =", "year, coalesce, mean import pyspark.sql.functions as F from pyspark.sql.window import Window from pyspark.sql.types", "= [] for i in imeiList: if abs((time - i[0]).total_seconds()) < 15 and", "None and (i[3] == '60' or i[3] == '60hz'): count += 1 fft_cnt" ]
[ "like: {scores[:10]}\") logger.info(f\"min score = {min_score}\") logger.info(f\"max score = {max_score}\") logger.info(f\"sum score =", "logger.info(f\"sum score = {sum_score}\") def test_save_load(self): print(\"-\" * 80) logger.info(\"test_save_load\\n\" + \"-\" *", "(\"multi\" if multi else \"uni\") + \".png\") test_ts = TimeSeries.from_pd(self.test_df) fig = self.model.plot_anomaly_plotly(", "metadata = self.dataset[0] self.train_df, self.test_df, self.test_labels = get_train_test_splits(df, metadata, 2000) if __name__ ==", "rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE", "time_series_prev=train_ts, plot_time_series_prev=True ) plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try: import kaleido fig.write_image(path, engine=\"kaleido\") except ImportError: logger.info(\"kaleido", "self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True ) plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try: import kaleido fig.write_image(path, engine=\"kaleido\") except", "ImportError: logger.info(\"plotly not installed, skipping test case\") class TestUnivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds()", "metadata: pd.DataFrame, n: int) -> (pd.DataFrame, pd.DataFrame, np.ndarray): train_df = df[metadata.trainval] test_df =", "test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n), test_df.head(n), test_labels[:n] class Mixin(ABC): def test_score(self): print(\"-\" *", "logger.info(f\"scores look like: {scores[:10]}\") logger.info(f\"min score = {min_score}\") logger.info(f\"max score = {max_score}\") logger.info(f\"sum", "score = {sum_score}\") def test_save_load(self): print(\"-\" * 80) logger.info(\"test_save_load\\n\" + \"-\" * 80", "TimeSeries.from_pd(self.test_df) score_ts = self.model.get_anomaly_score(test_ts) scores = score_ts.to_pd().values.flatten() min_score, max_score, sum_score = min(scores), max(scores),", "* 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi =", "threshold=AggregateAlarms(alm_threshold=1.5)) ) # Time series with anomalies in both train split and test", ":1] self.test_df = df.iloc[-len(df) // 2 :, :1] self.test_labels = df.iloc[-len(df) // 2", "scores = self.model.get_anomaly_score(test_ts) scores_np = scores.to_pd().values.flatten() loaded_model_scores = loaded_model.get_anomaly_score(test_ts) loaded_model_scores = loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np),", "test split df = pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp = pd.to_datetime(df.timestamp, unit=\"s\") df", "get_train_test_splits(df, metadata, 2000) if __name__ == \"__main__\": logging.basicConfig( format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\", stream=sys.stdout,", "Copyright (c) 2022 salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause #", "np import pandas as pd from merlion.models.defaults import DefaultDetector, DefaultDetectorConfig from merlion.plot import", "test_plot(self): try: import plotly print(\"-\" * 80) logger.info(\"test_plot\\n\" + \"-\" * 80 +", "LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause # from abc import ABC", "def run_init(self): set_random_seeds() self.model = DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) ) # Time series with", "class Mixin(ABC): def test_score(self): print(\"-\" * 80) logger.info(\"test_score\\n\" + \"-\" * 80 +", "anomalies in both train split and test split df = pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\",", "or https://opensource.org/licenses/BSD-3-Clause # from abc import ABC import logging import os from os.path", "not trying to save image\") except ImportError: logger.info(\"plotly not installed, skipping test case\")", "multi = train_ts.dim > 1 savedir = join(rootdir, \"tmp\", \"default\", \"anom\") os.makedirs(savedir, exist_ok=True)", "AggregateAlarms from merlion.utils import TimeSeries from ts_datasets.anomaly import * rootdir = dirname(dirname(dirname(abspath(__file__)))) logger", "plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try: import kaleido fig.write_image(path, engine=\"kaleido\") except ImportError: logger.info(\"kaleido not installed, not", "testing splits self.train_df = df.iloc[: -len(df) // 2, :1] self.test_df = df.iloc[-len(df) //", "alarms = self.model.post_rule(scores) loaded_model_alarms = loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def test_plot(self): try: import plotly", "test case\") class TestUnivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5))", "= train_ts.dim > 1 savedir = join(rootdir, \"tmp\", \"default\", \"anom\") os.makedirs(savedir, exist_ok=True) path", "2000) if __name__ == \"__main__\": logging.basicConfig( format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\", stream=sys.stdout, level=logging.INFO )", "in both train split and test split df = pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\"))", ":, :1] self.test_labels = df.iloc[-len(df) // 2 :, -1:] class TestMultivariate(unittest.TestCase, Mixin): def", "import sys import unittest import torch import random import numpy as np import", "unittest import torch import random import numpy as np import pandas as pd", "df.iloc[-len(df) // 2 :, -1:] class TestMultivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model =", "# Get training & testing splits self.train_df = df.iloc[: -len(df) // 2, :1]", "np.ndarray): train_df = df[metadata.trainval] test_df = df[~metadata.trainval] test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n), test_df.head(n),", "\"multi\" if multi else \"uni\") self.model.save(dirname=path) loaded_model = DefaultDetector.load(dirname=path) test_ts = TimeSeries.from_pd(self.test_df) scores", "2 :, :1] self.test_labels = df.iloc[-len(df) // 2 :, -1:] class TestMultivariate(unittest.TestCase, Mixin):", "self.model.train(train_ts) multi = train_ts.dim > 1 savedir = join(rootdir, \"tmp\", \"default\", \"anom\") os.makedirs(savedir,", "self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 savedir", "os.path import abspath, dirname, join import sys import unittest import torch import random", "score_ts.to_pd().values.flatten() min_score, max_score, sum_score = min(scores), max(scores), sum(scores) logger.info(f\"scores look like: {scores[:10]}\") logger.info(f\"min", "\"smap\")) df, metadata = self.dataset[0] self.train_df, self.test_df, self.test_labels = get_train_test_splits(df, metadata, 2000) if", "TimeSeries.from_pd(self.test_df) scores = self.model.get_anomaly_score(test_ts) scores_np = scores.to_pd().values.flatten() loaded_model_scores = loaded_model.get_anomaly_score(test_ts) loaded_model_scores = loaded_model_scores.to_pd().values.flatten()", "\"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp = pd.to_datetime(df.timestamp, unit=\"s\") df = df.set_index(\"timestamp\") # Get training &", "fig = self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True ) plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try: import kaleido fig.write_image(path,", "metadata, 2000) if __name__ == \"__main__\": logging.basicConfig( format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\", stream=sys.stdout, level=logging.INFO", "import ABC import logging import os from os.path import abspath, dirname, join import", "logger.info(\"kaleido not installed, not trying to save image\") except ImportError: logger.info(\"plotly not installed,", "abc import ABC import logging import os from os.path import abspath, dirname, join", "score = {min_score}\") logger.info(f\"max score = {max_score}\") logger.info(f\"sum score = {sum_score}\") def test_save_load(self):", "loaded_model_scores = loaded_model.get_anomaly_score(test_ts) loaded_model_scores = loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms = self.model.post_rule(scores) loaded_model_alarms =", "= pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp = pd.to_datetime(df.timestamp, unit=\"s\") df = df.set_index(\"timestamp\") #", "merlion.plot import plot_anoms_plotly from merlion.post_process.threshold import AggregateAlarms from merlion.utils import TimeSeries from ts_datasets.anomaly", "model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 path = join(rootdir,", "pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n), test_df.head(n), test_labels[:n] class Mixin(ABC): def test_score(self): print(\"-\" * 80) logger.info(\"test_score\\n\"", "80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts = TimeSeries.from_pd(self.test_df)", "salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license", "print(\"-\" * 80) logger.info(\"test_plot\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\")", "* 80) logger.info(\"test_plot\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts", "fig.write_image(path, engine=\"kaleido\") except ImportError: logger.info(\"kaleido not installed, not trying to save image\") except", "\"tmp\", \"default\", \"anom\", \"multi\" if multi else \"uni\") self.model.save(dirname=path) loaded_model = DefaultDetector.load(dirname=path) test_ts", "if multi else \"uni\") + \".png\") test_ts = TimeSeries.from_pd(self.test_df) fig = self.model.plot_anomaly_plotly( time_series=test_ts,", "n: int) -> (pd.DataFrame, pd.DataFrame, np.ndarray): train_df = df[metadata.trainval] test_df = df[~metadata.trainval] test_labels", "def test_plot(self): try: import plotly print(\"-\" * 80) logger.info(\"test_plot\\n\" + \"-\" * 80", "as pd from merlion.models.defaults import DefaultDetector, DefaultDetectorConfig from merlion.plot import plot_anoms_plotly from merlion.post_process.threshold", "from merlion.plot import plot_anoms_plotly from merlion.post_process.threshold import AggregateAlarms from merlion.utils import TimeSeries from", "logger.info(\"plotly not installed, skipping test case\") class TestUnivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model", "train_ts.dim > 1 path = join(rootdir, \"tmp\", \"default\", \"anom\", \"multi\" if multi else", "test_ts = TimeSeries.from_pd(self.test_df) fig = self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True ) plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try:", "TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts = TimeSeries.from_pd(self.test_df) score_ts = self.model.get_anomaly_score(test_ts) scores = score_ts.to_pd().values.flatten() min_score, max_score,", "run_init(self): set_random_seeds() self.model = DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) ) # Time series with anomalies", "\"anom\") os.makedirs(savedir, exist_ok=True) path = join(savedir, (\"multi\" if multi else \"uni\") + \".png\")", ":, -1:] class TestMultivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset =", "80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim", "case\") class TestUnivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) )", "test_df.head(n), test_labels[:n] class Mixin(ABC): def test_score(self): print(\"-\" * 80) logger.info(\"test_score\\n\" + \"-\" *", "= pd.to_datetime(df.timestamp, unit=\"s\") df = df.set_index(\"timestamp\") # Get training & testing splits self.train_df", "test_ts = TimeSeries.from_pd(self.test_df) score_ts = self.model.get_anomaly_score(test_ts) scores = score_ts.to_pd().values.flatten() min_score, max_score, sum_score =", "self.model.train(train_ts) multi = train_ts.dim > 1 path = join(rootdir, \"tmp\", \"default\", \"anom\", \"multi\"", "df.set_index(\"timestamp\") # Get training & testing splits self.train_df = df.iloc[: -len(df) // 2,", "import kaleido fig.write_image(path, engine=\"kaleido\") except ImportError: logger.info(\"kaleido not installed, not trying to save", "+ \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts)", "Time series with anomalies in both train split and test split df =", "print(\"-\" * 80) logger.info(\"test_save_load\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\")", "self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts = TimeSeries.from_pd(self.test_df) score_ts = self.model.get_anomaly_score(test_ts)", "loaded_model_scores = loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms = self.model.post_rule(scores) loaded_model_alarms = loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms))", "skipping test case\") class TestUnivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector( DefaultDetectorConfig(granularity=\"1h\",", "= df.iloc[: -len(df) // 2, :1] self.test_df = df.iloc[-len(df) // 2 :, :1]", "pd.to_datetime(df.timestamp, unit=\"s\") df = df.set_index(\"timestamp\") # Get training & testing splits self.train_df =", "# Copyright (c) 2022 salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause", "splits self.train_df = df.iloc[: -len(df) // 2, :1] self.test_df = df.iloc[-len(df) // 2", "= loaded_model.get_anomaly_score(test_ts) loaded_model_scores = loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms = self.model.post_rule(scores) loaded_model_alarms = loaded_model.post_rule(scores)", "torch import random import numpy as np import pandas as pd from merlion.models.defaults", "logging import os from os.path import abspath, dirname, join import sys import unittest", "not installed, not trying to save image\") except ImportError: logger.info(\"plotly not installed, skipping", "= TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 path = join(rootdir, \"tmp\", \"default\",", "TimeSeries.from_pd(self.test_df) fig = self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True ) plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try: import kaleido", "class TestUnivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) ) #", "-len(df) // 2, :1] self.test_df = df.iloc[-len(df) // 2 :, :1] self.test_labels =", "os from os.path import abspath, dirname, join import sys import unittest import torch", "BSD-3-Clause # For full license text, see the LICENSE file in the repo", "self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms = self.model.post_rule(scores) loaded_model_alarms = loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def test_plot(self): try:", "self.test_labels = get_train_test_splits(df, metadata, 2000) if __name__ == \"__main__\": logging.basicConfig( format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s:", "logger.info(\"test_plot\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df)", "+ \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim >", "max(scores), sum(scores) logger.info(f\"scores look like: {scores[:10]}\") logger.info(f\"min score = {min_score}\") logger.info(f\"max score =", "the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause # from abc import", "Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset = MSL(rootdir=join(rootdir, \"data\", \"smap\")) df,", "reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file", "join(rootdir, \"tmp\", \"default\", \"anom\", \"multi\" if multi else \"uni\") self.model.save(dirname=path) loaded_model = DefaultDetector.load(dirname=path)", "else \"uni\") + \".png\") test_ts = TimeSeries.from_pd(self.test_df) fig = self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True", "DefaultDetectorConfig from merlion.plot import plot_anoms_plotly from merlion.post_process.threshold import AggregateAlarms from merlion.utils import TimeSeries", "path = join(rootdir, \"tmp\", \"default\", \"anom\", \"multi\" if multi else \"uni\") self.model.save(dirname=path) loaded_model", "All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the", "self.model.train(train_ts) test_ts = TimeSeries.from_pd(self.test_df) score_ts = self.model.get_anomaly_score(test_ts) scores = score_ts.to_pd().values.flatten() min_score, max_score, sum_score", "\"uni\") self.model.save(dirname=path) loaded_model = DefaultDetector.load(dirname=path) test_ts = TimeSeries.from_pd(self.test_df) scores = self.model.get_anomaly_score(test_ts) scores_np =", "try: import kaleido fig.write_image(path, engine=\"kaleido\") except ImportError: logger.info(\"kaleido not installed, not trying to", "import pandas as pd from merlion.models.defaults import DefaultDetector, DefaultDetectorConfig from merlion.plot import plot_anoms_plotly", "= dirname(dirname(dirname(abspath(__file__)))) logger = logging.getLogger(__name__) def set_random_seeds(): torch.manual_seed(12345) random.seed(12345) np.random.seed(12345) def get_train_test_splits(df: pd.DataFrame,", "in the repo root or https://opensource.org/licenses/BSD-3-Clause # from abc import ABC import logging", "loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def test_plot(self): try: import plotly print(\"-\" * 80) logger.info(\"test_plot\\n\" +", "SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the", "import plot_anoms_plotly from merlion.post_process.threshold import AggregateAlarms from merlion.utils import TimeSeries from ts_datasets.anomaly import", "class TestMultivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset = MSL(rootdir=join(rootdir, \"data\",", "# For full license text, see the LICENSE file in the repo root", "engine=\"kaleido\") except ImportError: logger.info(\"kaleido not installed, not trying to save image\") except ImportError:", "numpy as np import pandas as pd from merlion.models.defaults import DefaultDetector, DefaultDetectorConfig from", "rootdir = dirname(dirname(dirname(abspath(__file__)))) logger = logging.getLogger(__name__) def set_random_seeds(): torch.manual_seed(12345) random.seed(12345) np.random.seed(12345) def get_train_test_splits(df:", "= logging.getLogger(__name__) def set_random_seeds(): torch.manual_seed(12345) random.seed(12345) np.random.seed(12345) def get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame, n:", "abspath, dirname, join import sys import unittest import torch import random import numpy", "\"anom\", \"multi\" if multi else \"uni\") self.model.save(dirname=path) loaded_model = DefaultDetector.load(dirname=path) test_ts = TimeSeries.from_pd(self.test_df)", "try: import plotly print(\"-\" * 80) logger.info(\"test_plot\\n\" + \"-\" * 80 + \"\\n\")", "os.makedirs(savedir, exist_ok=True) path = join(savedir, (\"multi\" if multi else \"uni\") + \".png\") test_ts", "= DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) ) # Time series with anomalies in both train", "> 1 path = join(rootdir, \"tmp\", \"default\", \"anom\", \"multi\" if multi else \"uni\")", "test_save_load(self): print(\"-\" * 80) logger.info(\"test_save_load\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training", "\"uni\") + \".png\") test_ts = TimeSeries.from_pd(self.test_df) fig = self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True )", "= MSL(rootdir=join(rootdir, \"data\", \"smap\")) df, metadata = self.dataset[0] self.train_df, self.test_df, self.test_labels = get_train_test_splits(df,", "DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) ) # Time series with anomalies in both train split", "df[~metadata.trainval] test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n), test_df.head(n), test_labels[:n] class Mixin(ABC): def test_score(self): print(\"-\"", "= loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms = self.model.post_rule(scores) loaded_model_alarms = loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def", "= join(rootdir, \"tmp\", \"default\", \"anom\") os.makedirs(savedir, exist_ok=True) path = join(savedir, (\"multi\" if multi", "image\") except ImportError: logger.info(\"plotly not installed, skipping test case\") class TestUnivariate(unittest.TestCase, Mixin): def", "test_labels[:n] class Mixin(ABC): def test_score(self): print(\"-\" * 80) logger.info(\"test_score\\n\" + \"-\" * 80", "{sum_score}\") def test_save_load(self): print(\"-\" * 80) logger.info(\"test_save_load\\n\" + \"-\" * 80 + \"\\n\")", "# from abc import ABC import logging import os from os.path import abspath,", "-> (pd.DataFrame, pd.DataFrame, np.ndarray): train_df = df[metadata.trainval] test_df = df[~metadata.trainval] test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly)", "80) logger.info(\"test_save_load\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts =", "self.model.post_rule(scores) loaded_model_alarms = loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def test_plot(self): try: import plotly print(\"-\" *", "DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset = MSL(rootdir=join(rootdir, \"data\", \"smap\")) df, metadata = self.dataset[0] self.train_df, self.test_df, self.test_labels", "test_ts = TimeSeries.from_pd(self.test_df) scores = self.model.get_anomaly_score(test_ts) scores_np = scores.to_pd().values.flatten() loaded_model_scores = loaded_model.get_anomaly_score(test_ts) loaded_model_scores", "ts_datasets.anomaly import * rootdir = dirname(dirname(dirname(abspath(__file__)))) logger = logging.getLogger(__name__) def set_random_seeds(): torch.manual_seed(12345) random.seed(12345)", "kaleido fig.write_image(path, engine=\"kaleido\") except ImportError: logger.info(\"kaleido not installed, not trying to save image\")", "self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def test_plot(self): try: import plotly print(\"-\" * 80) logger.info(\"test_plot\\n\" + \"-\"", "= self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True ) plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try: import kaleido fig.write_image(path, engine=\"kaleido\")", "scores.to_pd().values.flatten() loaded_model_scores = loaded_model.get_anomaly_score(test_ts) loaded_model_scores = loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms = self.model.post_rule(scores) loaded_model_alarms", "dirname, join import sys import unittest import torch import random import numpy as", "path = join(savedir, (\"multi\" if multi else \"uni\") + \".png\") test_ts = TimeSeries.from_pd(self.test_df)", "pd.DataFrame, n: int) -> (pd.DataFrame, pd.DataFrame, np.ndarray): train_df = df[metadata.trainval] test_df = df[~metadata.trainval]", "torch.manual_seed(12345) random.seed(12345) np.random.seed(12345) def get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame, n: int) -> (pd.DataFrame, pd.DataFrame,", "import random import numpy as np import pandas as pd from merlion.models.defaults import", "if multi else \"uni\") self.model.save(dirname=path) loaded_model = DefaultDetector.load(dirname=path) test_ts = TimeSeries.from_pd(self.test_df) scores =", "TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 savedir = join(rootdir, \"tmp\", \"default\", \"anom\")", "80) logger.info(\"test_score\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts =", "DefaultDetector, DefaultDetectorConfig from merlion.plot import plot_anoms_plotly from merlion.post_process.threshold import AggregateAlarms from merlion.utils import", "join(savedir, (\"multi\" if multi else \"uni\") + \".png\") test_ts = TimeSeries.from_pd(self.test_df) fig =", "df[metadata.trainval] test_df = df[~metadata.trainval] test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n), test_df.head(n), test_labels[:n] class Mixin(ABC):", "logger.info(f\"max score = {max_score}\") logger.info(f\"sum score = {sum_score}\") def test_save_load(self): print(\"-\" * 80)", "\"default\", \"anom\") os.makedirs(savedir, exist_ok=True) path = join(savedir, (\"multi\" if multi else \"uni\") +", "{min_score}\") logger.info(f\"max score = {max_score}\") logger.info(f\"sum score = {sum_score}\") def test_save_load(self): print(\"-\" *", "ImportError: logger.info(\"kaleido not installed, not trying to save image\") except ImportError: logger.info(\"plotly not", "list(loaded_model_alarms)) def test_plot(self): try: import plotly print(\"-\" * 80) logger.info(\"test_plot\\n\" + \"-\" *", "set_random_seeds(): torch.manual_seed(12345) random.seed(12345) np.random.seed(12345) def get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame, n: int) -> (pd.DataFrame,", "\"data\", \"smap\")) df, metadata = self.dataset[0] self.train_df, self.test_df, self.test_labels = get_train_test_splits(df, metadata, 2000)", "\"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts", ":1] self.test_labels = df.iloc[-len(df) // 2 :, -1:] class TestMultivariate(unittest.TestCase, Mixin): def run_init(self):", "look like: {scores[:10]}\") logger.info(f\"min score = {min_score}\") logger.info(f\"max score = {max_score}\") logger.info(f\"sum score", "self.test_df = df.iloc[-len(df) // 2 :, :1] self.test_labels = df.iloc[-len(df) // 2 :,", "\"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp = pd.to_datetime(df.timestamp, unit=\"s\") df = df.set_index(\"timestamp\") # Get training", "multi else \"uni\") + \".png\") test_ts = TimeSeries.from_pd(self.test_df) fig = self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts,", "and test split df = pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp = pd.to_datetime(df.timestamp, unit=\"s\")", "pd.DataFrame, metadata: pd.DataFrame, n: int) -> (pd.DataFrame, pd.DataFrame, np.ndarray): train_df = df[metadata.trainval] test_df", "test_score(self): print(\"-\" * 80) logger.info(\"test_score\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training", "// 2 :, -1:] class TestMultivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2)))", "TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 path = join(rootdir, \"tmp\", \"default\", \"anom\",", "df.iloc[: -len(df) // 2, :1] self.test_df = df.iloc[-len(df) // 2 :, :1] self.test_labels", "= DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset = MSL(rootdir=join(rootdir, \"data\", \"smap\")) df, metadata = self.dataset[0] self.train_df, self.test_df,", "self.model.save(dirname=path) loaded_model = DefaultDetector.load(dirname=path) test_ts = TimeSeries.from_pd(self.test_df) scores = self.model.get_anomaly_score(test_ts) scores_np = scores.to_pd().values.flatten()", "as np import pandas as pd from merlion.models.defaults import DefaultDetector, DefaultDetectorConfig from merlion.plot", "self.model = DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) ) # Time series with anomalies in both", "= df.set_index(\"timestamp\") # Get training & testing splits self.train_df = df.iloc[: -len(df) //", "ABC import logging import os from os.path import abspath, dirname, join import sys", "self.dataset = MSL(rootdir=join(rootdir, \"data\", \"smap\")) df, metadata = self.dataset[0] self.train_df, self.test_df, self.test_labels =", "= self.dataset[0] self.train_df, self.test_df, self.test_labels = get_train_test_splits(df, metadata, 2000) if __name__ == \"__main__\":", "dirname(dirname(dirname(abspath(__file__)))) logger = logging.getLogger(__name__) def set_random_seeds(): torch.manual_seed(12345) random.seed(12345) np.random.seed(12345) def get_train_test_splits(df: pd.DataFrame, metadata:", "sum_score = min(scores), max(scores), sum(scores) logger.info(f\"scores look like: {scores[:10]}\") logger.info(f\"min score = {min_score}\")", "80) logger.info(\"test_plot\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts =", "model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts = TimeSeries.from_pd(self.test_df) score_ts = self.model.get_anomaly_score(test_ts) scores =", "the repo root or https://opensource.org/licenses/BSD-3-Clause # from abc import ABC import logging import", "df = pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp = pd.to_datetime(df.timestamp, unit=\"s\") df = df.set_index(\"timestamp\")", "TimeSeries from ts_datasets.anomaly import * rootdir = dirname(dirname(dirname(abspath(__file__)))) logger = logging.getLogger(__name__) def set_random_seeds():", "df.iloc[-len(df) // 2 :, :1] self.test_labels = df.iloc[-len(df) // 2 :, -1:] class", "run_init(self): set_random_seeds() self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset = MSL(rootdir=join(rootdir, \"data\", \"smap\")) df, metadata =", "= min(scores), max(scores), sum(scores) logger.info(f\"scores look like: {scores[:10]}\") logger.info(f\"min score = {min_score}\") logger.info(f\"max", "time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True ) plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try: import kaleido fig.write_image(path, engine=\"kaleido\") except ImportError:", "train_df = df[metadata.trainval] test_df = df[~metadata.trainval] test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n), test_df.head(n), test_labels[:n]", "Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) ) # Time series", "train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts = TimeSeries.from_pd(self.test_df) score_ts = self.model.get_anomaly_score(test_ts) scores = score_ts.to_pd().values.flatten()", "Get training & testing splits self.train_df = df.iloc[: -len(df) // 2, :1] self.test_df", "except ImportError: logger.info(\"kaleido not installed, not trying to save image\") except ImportError: logger.info(\"plotly", "\"horizontal_spike_anomaly.csv\")) df.timestamp = pd.to_datetime(df.timestamp, unit=\"s\") df = df.set_index(\"timestamp\") # Get training & testing", "= DefaultDetector.load(dirname=path) test_ts = TimeSeries.from_pd(self.test_df) scores = self.model.get_anomaly_score(test_ts) scores_np = scores.to_pd().values.flatten() loaded_model_scores =", "import os from os.path import abspath, dirname, join import sys import unittest import", "\"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1", "from abc import ABC import logging import os from os.path import abspath, dirname,", "import logging import os from os.path import abspath, dirname, join import sys import", "installed, not trying to save image\") except ImportError: logger.info(\"plotly not installed, skipping test", "= get_train_test_splits(df, metadata, 2000) if __name__ == \"__main__\": logging.basicConfig( format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",", "For full license text, see the LICENSE file in the repo root or", "(c) 2022 salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For", "import plotly print(\"-\" * 80) logger.info(\"test_plot\\n\" + \"-\" * 80 + \"\\n\") self.run_init()", "-1:] class TestMultivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset = MSL(rootdir=join(rootdir,", "MSL(rootdir=join(rootdir, \"data\", \"smap\")) df, metadata = self.dataset[0] self.train_df, self.test_df, self.test_labels = get_train_test_splits(df, metadata,", "get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame, n: int) -> (pd.DataFrame, pd.DataFrame, np.ndarray): train_df = df[metadata.trainval]", "set_random_seeds() self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset = MSL(rootdir=join(rootdir, \"data\", \"smap\")) df, metadata = self.dataset[0]", "join import sys import unittest import torch import random import numpy as np", "exist_ok=True) path = join(savedir, (\"multi\" if multi else \"uni\") + \".png\") test_ts =", "except ImportError: logger.info(\"plotly not installed, skipping test case\") class TestUnivariate(unittest.TestCase, Mixin): def run_init(self):", "min(scores), max(scores), sum(scores) logger.info(f\"scores look like: {scores[:10]}\") logger.info(f\"min score = {min_score}\") logger.info(f\"max score", "= TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts = TimeSeries.from_pd(self.test_df) score_ts = self.model.get_anomaly_score(test_ts) scores = score_ts.to_pd().values.flatten() min_score,", "* 80) logger.info(\"test_save_load\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts", "* 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts =", "def set_random_seeds(): torch.manual_seed(12345) random.seed(12345) np.random.seed(12345) def get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame, n: int) ->", "split and test split df = pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp = pd.to_datetime(df.timestamp,", "= TimeSeries.from_pd(self.test_df) scores = self.model.get_anomaly_score(test_ts) scores_np = scores.to_pd().values.flatten() loaded_model_scores = loaded_model.get_anomaly_score(test_ts) loaded_model_scores =", "test_df = df[~metadata.trainval] test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n), test_df.head(n), test_labels[:n] class Mixin(ABC): def", "= loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def test_plot(self): try: import plotly print(\"-\" * 80) logger.info(\"test_plot\\n\"", "2 :, -1:] class TestMultivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset", "\"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi", "score_ts = self.model.get_anomaly_score(test_ts) scores = score_ts.to_pd().values.flatten() min_score, max_score, sum_score = min(scores), max(scores), sum(scores)", "pd.DataFrame, np.ndarray): train_df = df[metadata.trainval] test_df = df[~metadata.trainval] test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n),", "plotly print(\"-\" * 80) logger.info(\"test_plot\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training", "TestMultivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset = MSL(rootdir=join(rootdir, \"data\", \"smap\"))", "= {max_score}\") logger.info(f\"sum score = {sum_score}\") def test_save_load(self): print(\"-\" * 80) logger.info(\"test_save_load\\n\" +", "loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms = self.model.post_rule(scores) loaded_model_alarms = loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def test_plot(self):", "both train split and test split df = pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp", "sys import unittest import torch import random import numpy as np import pandas", "min_score, max_score, sum_score = min(scores), max(scores), sum(scores) logger.info(f\"scores look like: {scores[:10]}\") logger.info(f\"min score", "= self.model.get_anomaly_score(test_ts) scores_np = scores.to_pd().values.flatten() loaded_model_scores = loaded_model.get_anomaly_score(test_ts) loaded_model_scores = loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores))", "import abspath, dirname, join import sys import unittest import torch import random import", "merlion.utils import TimeSeries from ts_datasets.anomaly import * rootdir = dirname(dirname(dirname(abspath(__file__)))) logger = logging.getLogger(__name__)", "self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset = MSL(rootdir=join(rootdir, \"data\", \"smap\")) df, metadata = self.dataset[0] self.train_df,", "logger.info(f\"min score = {min_score}\") logger.info(f\"max score = {max_score}\") logger.info(f\"sum score = {sum_score}\") def", "multi else \"uni\") self.model.save(dirname=path) loaded_model = DefaultDetector.load(dirname=path) test_ts = TimeSeries.from_pd(self.test_df) scores = self.model.get_anomaly_score(test_ts)", "df, metadata = self.dataset[0] self.train_df, self.test_df, self.test_labels = get_train_test_splits(df, metadata, 2000) if __name__", "& testing splits self.train_df = df.iloc[: -len(df) // 2, :1] self.test_df = df.iloc[-len(df)", "import TimeSeries from ts_datasets.anomaly import * rootdir = dirname(dirname(dirname(abspath(__file__)))) logger = logging.getLogger(__name__) def", "Mixin(ABC): def test_score(self): print(\"-\" * 80) logger.info(\"test_score\\n\" + \"-\" * 80 + \"\\n\")", "import DefaultDetector, DefaultDetectorConfig from merlion.plot import plot_anoms_plotly from merlion.post_process.threshold import AggregateAlarms from merlion.utils", "else \"uni\") self.model.save(dirname=path) loaded_model = DefaultDetector.load(dirname=path) test_ts = TimeSeries.from_pd(self.test_df) scores = self.model.get_anomaly_score(test_ts) scores_np", "\".png\") test_ts = TimeSeries.from_pd(self.test_df) fig = self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True ) plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels))", "\"tmp\", \"default\", \"anom\") os.makedirs(savedir, exist_ok=True) path = join(savedir, (\"multi\" if multi else \"uni\")", "logger = logging.getLogger(__name__) def set_random_seeds(): torch.manual_seed(12345) random.seed(12345) np.random.seed(12345) def get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame,", "// 2 :, :1] self.test_labels = df.iloc[-len(df) // 2 :, -1:] class TestMultivariate(unittest.TestCase,", "len(loaded_model_scores)) alarms = self.model.post_rule(scores) loaded_model_alarms = loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def test_plot(self): try: import", "self.train_df = df.iloc[: -len(df) // 2, :1] self.test_df = df.iloc[-len(df) // 2 :,", "merlion.post_process.threshold import AggregateAlarms from merlion.utils import TimeSeries from ts_datasets.anomaly import * rootdir =", "plot_time_series_prev=True ) plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try: import kaleido fig.write_image(path, engine=\"kaleido\") except ImportError: logger.info(\"kaleido not", "repo root or https://opensource.org/licenses/BSD-3-Clause # from abc import ABC import logging import os", "if __name__ == \"__main__\": logging.basicConfig( format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\", stream=sys.stdout, level=logging.INFO ) unittest.main()", "save image\") except ImportError: logger.info(\"plotly not installed, skipping test case\") class TestUnivariate(unittest.TestCase, Mixin):", "savedir = join(rootdir, \"tmp\", \"default\", \"anom\") os.makedirs(savedir, exist_ok=True) path = join(savedir, (\"multi\" if", "= self.model.get_anomaly_score(test_ts) scores = score_ts.to_pd().values.flatten() min_score, max_score, sum_score = min(scores), max(scores), sum(scores) logger.info(f\"scores", "= df.iloc[-len(df) // 2 :, :1] self.test_labels = df.iloc[-len(df) // 2 :, -1:]", "logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 savedir =", "to save image\") except ImportError: logger.info(\"plotly not installed, skipping test case\") class TestUnivariate(unittest.TestCase,", "text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause # from", "scores = score_ts.to_pd().values.flatten() min_score, max_score, sum_score = min(scores), max(scores), sum(scores) logger.info(f\"scores look like:", "logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts = TimeSeries.from_pd(self.test_df) score_ts = self.model.get_anomaly_score(test_ts) scores", "return train_df.tail(n), test_df.head(n), test_labels[:n] class Mixin(ABC): def test_score(self): print(\"-\" * 80) logger.info(\"test_score\\n\" +", "+ \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts = TimeSeries.from_pd(self.test_df) score_ts", "set_random_seeds() self.model = DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) ) # Time series with anomalies in", "import numpy as np import pandas as pd from merlion.models.defaults import DefaultDetector, DefaultDetectorConfig", "pandas as pd from merlion.models.defaults import DefaultDetector, DefaultDetectorConfig from merlion.plot import plot_anoms_plotly from", "full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause", "= df[metadata.trainval] test_df = df[~metadata.trainval] test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n), test_df.head(n), test_labels[:n] class", "= join(rootdir, \"tmp\", \"default\", \"anom\", \"multi\" if multi else \"uni\") self.model.save(dirname=path) loaded_model =", "import torch import random import numpy as np import pandas as pd from", "import AggregateAlarms from merlion.utils import TimeSeries from ts_datasets.anomaly import * rootdir = dirname(dirname(dirname(abspath(__file__))))", "model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 savedir = join(rootdir,", "= scores.to_pd().values.flatten() loaded_model_scores = loaded_model.get_anomaly_score(test_ts) loaded_model_scores = loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms = self.model.post_rule(scores)", "trying to save image\") except ImportError: logger.info(\"plotly not installed, skipping test case\") class", "(pd.DataFrame, pd.DataFrame, np.ndarray): train_df = df[metadata.trainval] test_df = df[~metadata.trainval] test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly) return", "= join(savedir, (\"multi\" if multi else \"uni\") + \".png\") test_ts = TimeSeries.from_pd(self.test_df) fig", "# SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in", "= df.iloc[-len(df) // 2 :, -1:] class TestMultivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model", "> 1 savedir = join(rootdir, \"tmp\", \"default\", \"anom\") os.makedirs(savedir, exist_ok=True) path = join(savedir,", "multi = train_ts.dim > 1 path = join(rootdir, \"tmp\", \"default\", \"anom\", \"multi\" if", "* rootdir = dirname(dirname(dirname(abspath(__file__)))) logger = logging.getLogger(__name__) def set_random_seeds(): torch.manual_seed(12345) random.seed(12345) np.random.seed(12345) def", "training & testing splits self.train_df = df.iloc[: -len(df) // 2, :1] self.test_df =", "plot_anoms_plotly from merlion.post_process.threshold import AggregateAlarms from merlion.utils import TimeSeries from ts_datasets.anomaly import *", "int) -> (pd.DataFrame, pd.DataFrame, np.ndarray): train_df = df[metadata.trainval] test_df = df[~metadata.trainval] test_labels =", "def run_init(self): set_random_seeds() self.model = DefaultDetector(DefaultDetectorConfig(threshold=AggregateAlarms(alm_threshold=2))) self.dataset = MSL(rootdir=join(rootdir, \"data\", \"smap\")) df, metadata", "root or https://opensource.org/licenses/BSD-3-Clause # from abc import ABC import logging import os from", "pd from merlion.models.defaults import DefaultDetector, DefaultDetectorConfig from merlion.plot import plot_anoms_plotly from merlion.post_process.threshold import", "train_df.tail(n), test_df.head(n), test_labels[:n] class Mixin(ABC): def test_score(self): print(\"-\" * 80) logger.info(\"test_score\\n\" + \"-\"", "inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text,", "= TimeSeries.from_pd(self.test_df) fig = self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True ) plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try: import", "self.train_df, self.test_df, self.test_labels = get_train_test_splits(df, metadata, 2000) if __name__ == \"__main__\": logging.basicConfig( format=\"%(asctime)s", "from merlion.models.defaults import DefaultDetector, DefaultDetectorConfig from merlion.plot import plot_anoms_plotly from merlion.post_process.threshold import AggregateAlarms", "# Time series with anomalies in both train split and test split df", "= self.model.post_rule(scores) loaded_model_alarms = loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def test_plot(self): try: import plotly print(\"-\"", "logging.getLogger(__name__) def set_random_seeds(): torch.manual_seed(12345) random.seed(12345) np.random.seed(12345) def get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame, n: int)", "sum(scores) logger.info(f\"scores look like: {scores[:10]}\") logger.info(f\"min score = {min_score}\") logger.info(f\"max score = {max_score}\")", "train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 savedir = join(rootdir, \"tmp\",", "loaded_model.get_anomaly_score(test_ts) loaded_model_scores = loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms = self.model.post_rule(scores) loaded_model_alarms = loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms),", "* 80) logger.info(\"test_score\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts", "https://opensource.org/licenses/BSD-3-Clause # from abc import ABC import logging import os from os.path import", "2022 salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full", "{max_score}\") logger.info(f\"sum score = {sum_score}\") def test_save_load(self): print(\"-\" * 80) logger.info(\"test_save_load\\n\" + \"-\"", "scores_np = scores.to_pd().values.flatten() loaded_model_scores = loaded_model.get_anomaly_score(test_ts) loaded_model_scores = loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms =", "= {min_score}\") logger.info(f\"max score = {max_score}\") logger.info(f\"sum score = {sum_score}\") def test_save_load(self): print(\"-\"", "from merlion.utils import TimeSeries from ts_datasets.anomaly import * rootdir = dirname(dirname(dirname(abspath(__file__)))) logger =", "logger.info(\"test_score\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df)", "1 path = join(rootdir, \"tmp\", \"default\", \"anom\", \"multi\" if multi else \"uni\") self.model.save(dirname=path)", "= pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n), test_df.head(n), test_labels[:n] class Mixin(ABC): def test_score(self): print(\"-\" * 80)", "train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 path = join(rootdir, \"tmp\",", "logger.info(\"test_save_load\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df)", "self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 path", "self.test_df, self.test_labels = get_train_test_splits(df, metadata, 2000) if __name__ == \"__main__\": logging.basicConfig( format=\"%(asctime)s (%(module)s:%(lineno)d)", "TestUnivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector( DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) ) # Time", "series with anomalies in both train split and test split df = pd.read_csv(join(rootdir,", "merlion.models.defaults import DefaultDetector, DefaultDetectorConfig from merlion.plot import plot_anoms_plotly from merlion.post_process.threshold import AggregateAlarms from", "train split and test split df = pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp =", "self.model.get_anomaly_score(test_ts) scores_np = scores.to_pd().values.flatten() loaded_model_scores = loaded_model.get_anomaly_score(test_ts) loaded_model_scores = loaded_model_scores.to_pd().values.flatten() self.assertEqual(len(scores_np), len(loaded_model_scores)) alarms", "license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause #", "random import numpy as np import pandas as pd from merlion.models.defaults import DefaultDetector,", "score = {max_score}\") logger.info(f\"sum score = {sum_score}\") def test_save_load(self): print(\"-\" * 80) logger.info(\"test_save_load\\n\"", "def test_save_load(self): print(\"-\" * 80) logger.info(\"test_save_load\\n\" + \"-\" * 80 + \"\\n\") self.run_init()", "DefaultDetectorConfig(granularity=\"1h\", threshold=AggregateAlarms(alm_threshold=1.5)) ) # Time series with anomalies in both train split and", "loaded_model_alarms = loaded_model.post_rule(scores) self.assertSequenceEqual(list(alarms), list(loaded_model_alarms)) def test_plot(self): try: import plotly print(\"-\" * 80)", "installed, skipping test case\") class TestUnivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model = DefaultDetector(", "\"default\", \"anom\", \"multi\" if multi else \"uni\") self.model.save(dirname=path) loaded_model = DefaultDetector.load(dirname=path) test_ts =", "df = df.set_index(\"timestamp\") # Get training & testing splits self.train_df = df.iloc[: -len(df)", "from ts_datasets.anomaly import * rootdir = dirname(dirname(dirname(abspath(__file__)))) logger = logging.getLogger(__name__) def set_random_seeds(): torch.manual_seed(12345)", "np.random.seed(12345) def get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame, n: int) -> (pd.DataFrame, pd.DataFrame, np.ndarray): train_df", "1 savedir = join(rootdir, \"tmp\", \"default\", \"anom\") os.makedirs(savedir, exist_ok=True) path = join(savedir, (\"multi\"", "def get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame, n: int) -> (pd.DataFrame, pd.DataFrame, np.ndarray): train_df =", ") # Time series with anomalies in both train split and test split", "loaded_model = DefaultDetector.load(dirname=path) test_ts = TimeSeries.from_pd(self.test_df) scores = self.model.get_anomaly_score(test_ts) scores_np = scores.to_pd().values.flatten() loaded_model_scores", "self.model.get_anomaly_score(test_ts) scores = score_ts.to_pd().values.flatten() min_score, max_score, sum_score = min(scores), max(scores), sum(scores) logger.info(f\"scores look", "= train_ts.dim > 1 path = join(rootdir, \"tmp\", \"default\", \"anom\", \"multi\" if multi", "df.timestamp = pd.to_datetime(df.timestamp, unit=\"s\") df = df.set_index(\"timestamp\") # Get training & testing splits", "logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 path =", "file in the repo root or https://opensource.org/licenses/BSD-3-Clause # from abc import ABC import", "DefaultDetector.load(dirname=path) test_ts = TimeSeries.from_pd(self.test_df) scores = self.model.get_anomaly_score(test_ts) scores_np = scores.to_pd().values.flatten() loaded_model_scores = loaded_model.get_anomaly_score(test_ts)", "import unittest import torch import random import numpy as np import pandas as", "self.test_labels = df.iloc[-len(df) // 2 :, -1:] class TestMultivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds()", "unit=\"s\") df = df.set_index(\"timestamp\") # Get training & testing splits self.train_df = df.iloc[:", "= {sum_score}\") def test_save_load(self): print(\"-\" * 80) logger.info(\"test_save_load\\n\" + \"-\" * 80 +", "max_score, sum_score = min(scores), max(scores), sum(scores) logger.info(f\"scores look like: {scores[:10]}\") logger.info(f\"min score =", "= TimeSeries.from_pd(self.train_df) self.model.train(train_ts) multi = train_ts.dim > 1 savedir = join(rootdir, \"tmp\", \"default\",", "// 2, :1] self.test_df = df.iloc[-len(df) // 2 :, :1] self.test_labels = df.iloc[-len(df)", ") plot_anoms_plotly(fig, TimeSeries.from_pd(self.test_labels)) try: import kaleido fig.write_image(path, engine=\"kaleido\") except ImportError: logger.info(\"kaleido not installed,", "= score_ts.to_pd().values.flatten() min_score, max_score, sum_score = min(scores), max(scores), sum(scores) logger.info(f\"scores look like: {scores[:10]}\")", "see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause # from abc", "\"\\n\") self.run_init() logger.info(\"Training model...\\n\") train_ts = TimeSeries.from_pd(self.train_df) self.model.train(train_ts) test_ts = TimeSeries.from_pd(self.test_df) score_ts =", "{scores[:10]}\") logger.info(f\"min score = {min_score}\") logger.info(f\"max score = {max_score}\") logger.info(f\"sum score = {sum_score}\")", "from merlion.post_process.threshold import AggregateAlarms from merlion.utils import TimeSeries from ts_datasets.anomaly import * rootdir", "from os.path import abspath, dirname, join import sys import unittest import torch import", "with anomalies in both train split and test split df = pd.read_csv(join(rootdir, \"data\",", "= TimeSeries.from_pd(self.test_df) score_ts = self.model.get_anomaly_score(test_ts) scores = score_ts.to_pd().values.flatten() min_score, max_score, sum_score = min(scores),", "TimeSeries.from_pd(self.test_labels)) try: import kaleido fig.write_image(path, engine=\"kaleido\") except ImportError: logger.info(\"kaleido not installed, not trying", "train_ts.dim > 1 savedir = join(rootdir, \"tmp\", \"default\", \"anom\") os.makedirs(savedir, exist_ok=True) path =", "def test_score(self): print(\"-\" * 80) logger.info(\"test_score\\n\" + \"-\" * 80 + \"\\n\") self.run_init()", "# All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see", "random.seed(12345) np.random.seed(12345) def get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame, n: int) -> (pd.DataFrame, pd.DataFrame, np.ndarray):", "+ \".png\") test_ts = TimeSeries.from_pd(self.test_df) fig = self.model.plot_anomaly_plotly( time_series=test_ts, time_series_prev=train_ts, plot_time_series_prev=True ) plot_anoms_plotly(fig,", "self.dataset[0] self.train_df, self.test_df, self.test_labels = get_train_test_splits(df, metadata, 2000) if __name__ == \"__main__\": logging.basicConfig(", "not installed, skipping test case\") class TestUnivariate(unittest.TestCase, Mixin): def run_init(self): set_random_seeds() self.model =", "import * rootdir = dirname(dirname(dirname(abspath(__file__)))) logger = logging.getLogger(__name__) def set_random_seeds(): torch.manual_seed(12345) random.seed(12345) np.random.seed(12345)", "split df = pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp = pd.to_datetime(df.timestamp, unit=\"s\") df =", "# # Copyright (c) 2022 salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier:", "= df[~metadata.trainval] test_labels = pd.DataFrame(metadata[~metadata.trainval].anomaly) return train_df.tail(n), test_df.head(n), test_labels[:n] class Mixin(ABC): def test_score(self):", "2, :1] self.test_df = df.iloc[-len(df) // 2 :, :1] self.test_labels = df.iloc[-len(df) //", "join(rootdir, \"tmp\", \"default\", \"anom\") os.makedirs(savedir, exist_ok=True) path = join(savedir, (\"multi\" if multi else", "pd.read_csv(join(rootdir, \"data\", \"synthetic_anomaly\", \"horizontal_spike_anomaly.csv\")) df.timestamp = pd.to_datetime(df.timestamp, unit=\"s\") df = df.set_index(\"timestamp\") # Get", "print(\"-\" * 80) logger.info(\"test_score\\n\" + \"-\" * 80 + \"\\n\") self.run_init() logger.info(\"Training model...\\n\")" ]
[ "convolutional neural network architecture import torch from torch.autograd import Variable import torch.nn as", "2 for each of the 68 keypoint (x, y) pairs # As an", "nn.ReLU() self.pool = nn.MaxPool2d(2, 2) # 46 -> (32, 110, 110) self.drop1 =", "the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self):", "= 220 -> (32, 220, 220) self.act = nn.ReLU() self.pool = nn.MaxPool2d(2, 2)", "Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TODO: Define all the layers of this", "the keypoints ## it's suggested that you make this last layer output 136", "layers of this CNN, the only requirements are: ## 1. This network takes", "4)/1 + 1 = 43 -> (64, 107, 107) self.drop2 = nn.Dropout(p=0.2) #", "107, 107) self.drop2 = nn.Dropout(p=0.2) # after pooling -> (64, 53, 53) self.conv3", "nn.Dropout(p=0.2) self.dense2 = nn.Linear(1000,500) self.drop5 = nn.Dropout(p=0.2) self.dense3 = nn.Linear(500,136) def forward(self, x):", "this CNN, the only requirements are: ## 1. This network takes in a", "torch.nn as nn import torch.nn.functional as F # can use the below import", "3)/1 + 1 = 19 -> (128, 51, 51) self.drop3 = nn.Dropout(p=0.2) #", "## TODO: Define the feedforward behavior of this model ## x is the", "As an example, you've been given a convolutional layer, which you may (but", "import Variable import torch.nn as nn import torch.nn.functional as F # can use", "each of the 68 keypoint (x, y) pairs # As an example, you've", "this model ## x is the input image and, as an example, here", "# As an example, you've been given a convolutional layer, which you may", "= 43 -> (64, 107, 107) self.drop2 = nn.Dropout(p=0.2) # after pooling ->", "Variable import torch.nn as nn import torch.nn.functional as F # can use the", "This network takes in a square (same width and height), grayscale image as", "maps, 5x5 square convolution kernel # Image size = 224*224 -> self.conv1 =", "include a pool/conv step: x = self.drop1(self.pool(self.act(self.conv1(x)))) x = self.drop2(self.pool(self.act(self.conv2(x)))) x = self.drop3(self.pool(self.act(self.conv3(x))))", "the 68 keypoint (x, y) pairs # As an example, you've been given", "- 3)/1 + 1 = 19 -> (128, 51, 51) self.drop3 = nn.Dropout(p=0.2)", "image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel # Image", "# 128*25*25 = 80000 self.drop4 = nn.Dropout(p=0.2) self.dense2 = nn.Linear(1000,500) self.drop5 = nn.Dropout(p=0.2)", "# (110 - 4)/1 + 1 = 43 -> (64, 107, 107) self.drop2", "= 80000 self.drop4 = nn.Dropout(p=0.2) self.dense2 = nn.Linear(1000,500) self.drop5 = nn.Dropout(p=0.2) self.dense3 =", "you've been given a convolutional layer, which you may (but don't have to)", "= nn.MaxPool2d(2, 2) # 46 -> (32, 110, 110) self.drop1 = nn.Dropout(p=0.2) self.conv2", "initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def", "architecture import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional", "requirements are: ## 1. This network takes in a square (same width and", "def __init__(self): super(Net, self).__init__() ## TODO: Define all the layers of this CNN,", "choose to initialize the weights of your Net import torch.nn.init as I class", "image as input ## 2. It ends with a linear layer that represents", "as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TODO: Define all the", "layer that represents the keypoints ## it's suggested that you make this last", "+ 1 = 43 -> (64, 107, 107) self.drop2 = nn.Dropout(p=0.2) # after", "(32, 110, 110) self.drop1 = nn.Dropout(p=0.2) self.conv2 = nn.Conv2d(32, 64, 4) # (110", "(110 - 4)/1 + 1 = 43 -> (64, 107, 107) self.drop2 =", "1 = 19 -> (128, 51, 51) self.drop3 = nn.Dropout(p=0.2) # after pooling", "CNN, the only requirements are: ## 1. This network takes in a square", "x): ## TODO: Define the feedforward behavior of this model ## x is", "self.conv1 = nn.Conv2d(1, 32, 5) # (224 - 5)/1 + 1 = 220", "self.pool = nn.MaxPool2d(2, 2) # 46 -> (32, 110, 110) self.drop1 = nn.Dropout(p=0.2)", "values, 2 for each of the 68 keypoint (x, y) pairs # As", "nn.Dropout(p=0.2) # after pooling -> (64, 53, 53) self.conv3 = nn.Conv2d(64, 128, 3)", "2) # 46 -> (32, 110, 110) self.drop1 = nn.Dropout(p=0.2) self.conv2 = nn.Conv2d(32,", "self.drop2 = nn.Dropout(p=0.2) # after pooling -> (64, 53, 53) self.conv3 = nn.Conv2d(64,", "example, here you may choose to include a pool/conv step: x = self.drop1(self.pool(self.act(self.conv1(x))))", "of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__()", "nn.Conv2d(32, 64, 4) # (110 - 4)/1 + 1 = 43 -> (64,", "below import should you choose to initialize the weights of your Net import", "a pool/conv step: x = self.drop1(self.pool(self.act(self.conv1(x)))) x = self.drop2(self.pool(self.act(self.conv2(x)))) x = self.drop3(self.pool(self.act(self.conv3(x)))) x", "nn import torch.nn.functional as F # can use the below import should you", "19 -> (128, 51, 51) self.drop3 = nn.Dropout(p=0.2) # after pooling -> (128,", "square convolution kernel # Image size = 224*224 -> self.conv1 = nn.Conv2d(1, 32,", "= 19 -> (128, 51, 51) self.drop3 = nn.Dropout(p=0.2) # after pooling ->", "80000 self.drop4 = nn.Dropout(p=0.2) self.dense2 = nn.Linear(1000,500) self.drop5 = nn.Dropout(p=0.2) self.dense3 = nn.Linear(500,136)", "as nn import torch.nn.functional as F # can use the below import should", "to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module):", "input ## 2. It ends with a linear layer that represents the keypoints", "here you may choose to include a pool/conv step: x = self.drop1(self.pool(self.act(self.conv1(x)))) x", "can use the below import should you choose to initialize the weights of", "of this CNN, the only requirements are: ## 1. This network takes in", "= self.drop3(self.pool(self.act(self.conv3(x)))) x = x.view(x.size(0), -1) x = self.drop4(self.act(self.dense1(x))) x = self.drop5(self.act(self.dense2(x))) out", "step: x = self.drop1(self.pool(self.act(self.conv1(x)))) x = self.drop2(self.pool(self.act(self.conv2(x)))) x = self.drop3(self.pool(self.act(self.conv3(x)))) x = x.view(x.size(0),", "from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F #", "model ## x is the input image and, as an example, here you", "## it's suggested that you make this last layer output 136 values, 2", "# 46 -> (32, 110, 110) self.drop1 = nn.Dropout(p=0.2) self.conv2 = nn.Conv2d(32, 64,", "= nn.Dropout(p=0.2) self.dense2 = nn.Linear(1000,500) self.drop5 = nn.Dropout(p=0.2) self.dense3 = nn.Linear(500,136) def forward(self,", "you make this last layer output 136 values, 2 for each of the", "super(Net, self).__init__() ## TODO: Define all the layers of this CNN, the only", "Image size = 224*224 -> self.conv1 = nn.Conv2d(1, 32, 5) # (224 -", "107) self.drop2 = nn.Dropout(p=0.2) # after pooling -> (64, 53, 53) self.conv3 =", "-> (64, 53, 53) self.conv3 = nn.Conv2d(64, 128, 3) # (53 - 3)/1", "self.drop5 = nn.Dropout(p=0.2) self.dense3 = nn.Linear(500,136) def forward(self, x): ## TODO: Define the", "nn.Dropout(p=0.2) self.dense3 = nn.Linear(500,136) def forward(self, x): ## TODO: Define the feedforward behavior", "x.view(x.size(0), -1) x = self.drop4(self.act(self.dense1(x))) x = self.drop5(self.act(self.dense2(x))) out = self.dense3(x) return out", "that represents the keypoints ## it's suggested that you make this last layer", "25) self.dense1 = nn.Linear(80000,1000) # 128*25*25 = 80000 self.drop4 = nn.Dropout(p=0.2) self.dense2 =", "= nn.Conv2d(1, 32, 5) # (224 - 5)/1 + 1 = 220 ->", "forward(self, x): ## TODO: Define the feedforward behavior of this model ## x", "as F # can use the below import should you choose to initialize", "the input image and, as an example, here you may choose to include", "(53 - 3)/1 + 1 = 19 -> (128, 51, 51) self.drop3 =", "224*224 -> self.conv1 = nn.Conv2d(1, 32, 5) # (224 - 5)/1 + 1", "1 = 43 -> (64, 107, 107) self.drop2 = nn.Dropout(p=0.2) # after pooling", "keypoint (x, y) pairs # As an example, you've been given a convolutional", "(32, 220, 220) self.act = nn.ReLU() self.pool = nn.MaxPool2d(2, 2) # 46 ->", "a convolutional layer, which you may (but don't have to) change: # 1", "128*25*25 = 80000 self.drop4 = nn.Dropout(p=0.2) self.dense2 = nn.Linear(1000,500) self.drop5 = nn.Dropout(p=0.2) self.dense3", "5x5 square convolution kernel # Image size = 224*224 -> self.conv1 = nn.Conv2d(1,", "(224 - 5)/1 + 1 = 220 -> (32, 220, 220) self.act =", "# (53 - 3)/1 + 1 = 19 -> (128, 51, 51) self.drop3", "-> (128, 25, 25) self.dense1 = nn.Linear(80000,1000) # 128*25*25 = 80000 self.drop4 =", "+ 1 = 220 -> (32, 220, 220) self.act = nn.ReLU() self.pool =", "self.drop4 = nn.Dropout(p=0.2) self.dense2 = nn.Linear(1000,500) self.drop5 = nn.Dropout(p=0.2) self.dense3 = nn.Linear(500,136) def", "self.dense2 = nn.Linear(1000,500) self.drop5 = nn.Dropout(p=0.2) self.dense3 = nn.Linear(500,136) def forward(self, x): ##", "may choose to include a pool/conv step: x = self.drop1(self.pool(self.act(self.conv1(x)))) x = self.drop2(self.pool(self.act(self.conv2(x))))", "network takes in a square (same width and height), grayscale image as input", "(grayscale), 32 output channels/feature maps, 5x5 square convolution kernel # Image size =", "layer, which you may (but don't have to) change: # 1 input image", "= nn.Dropout(p=0.2) # after pooling -> (64, 53, 53) self.conv3 = nn.Conv2d(64, 128,", "def forward(self, x): ## TODO: Define the feedforward behavior of this model ##", "weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net,", "last layer output 136 values, 2 for each of the 68 keypoint (x,", "= nn.Linear(500,136) def forward(self, x): ## TODO: Define the feedforward behavior of this", "x = self.drop3(self.pool(self.act(self.conv3(x)))) x = x.view(x.size(0), -1) x = self.drop4(self.act(self.dense1(x))) x = self.drop5(self.act(self.dense2(x)))", "layer output 136 values, 2 for each of the 68 keypoint (x, y)", "grayscale image as input ## 2. It ends with a linear layer that", "been given a convolutional layer, which you may (but don't have to) change:", "## TODO: Define all the layers of this CNN, the only requirements are:", "53) self.conv3 = nn.Conv2d(64, 128, 3) # (53 - 3)/1 + 1 =", "self.dense3 = nn.Linear(500,136) def forward(self, x): ## TODO: Define the feedforward behavior of", "__init__(self): super(Net, self).__init__() ## TODO: Define all the layers of this CNN, the", "32 output channels/feature maps, 5x5 square convolution kernel # Image size = 224*224", "TODO: define the convolutional neural network architecture import torch from torch.autograd import Variable", "represents the keypoints ## it's suggested that you make this last layer output", "of this model ## x is the input image and, as an example,", "you may choose to include a pool/conv step: x = self.drop1(self.pool(self.act(self.conv1(x)))) x =", "takes in a square (same width and height), grayscale image as input ##", "TODO: Define all the layers of this CNN, the only requirements are: ##", "example, you've been given a convolutional layer, which you may (but don't have", "nn.MaxPool2d(2, 2) # 46 -> (32, 110, 110) self.drop1 = nn.Dropout(p=0.2) self.conv2 =", "(64, 107, 107) self.drop2 = nn.Dropout(p=0.2) # after pooling -> (64, 53, 53)", "the feedforward behavior of this model ## x is the input image and,", "and height), grayscale image as input ## 2. It ends with a linear", "an example, here you may choose to include a pool/conv step: x =", "output 136 values, 2 for each of the 68 keypoint (x, y) pairs", "= nn.Dropout(p=0.2) self.conv2 = nn.Conv2d(32, 64, 4) # (110 - 4)/1 + 1", "all the layers of this CNN, the only requirements are: ## 1. This", "pairs # As an example, you've been given a convolutional layer, which you", "the layers of this CNN, the only requirements are: ## 1. This network", "## 1. This network takes in a square (same width and height), grayscale", "220) self.act = nn.ReLU() self.pool = nn.MaxPool2d(2, 2) # 46 -> (32, 110,", "self.dense1 = nn.Linear(80000,1000) # 128*25*25 = 80000 self.drop4 = nn.Dropout(p=0.2) self.dense2 = nn.Linear(1000,500)", "TODO: Define the feedforward behavior of this model ## x is the input", "= nn.Linear(80000,1000) # 128*25*25 = 80000 self.drop4 = nn.Dropout(p=0.2) self.dense2 = nn.Linear(1000,500) self.drop5", "after pooling -> (64, 53, 53) self.conv3 = nn.Conv2d(64, 128, 3) # (53", "image and, as an example, here you may choose to include a pool/conv", "of the 68 keypoint (x, y) pairs # As an example, you've been", "input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel #", "class Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TODO: Define all the layers of", "linear layer that represents the keypoints ## it's suggested that you make this", "after pooling -> (128, 25, 25) self.dense1 = nn.Linear(80000,1000) # 128*25*25 = 80000", "= self.drop2(self.pool(self.act(self.conv2(x)))) x = self.drop3(self.pool(self.act(self.conv3(x)))) x = x.view(x.size(0), -1) x = self.drop4(self.act(self.dense1(x))) x", "import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as", "# can use the below import should you choose to initialize the weights", "you choose to initialize the weights of your Net import torch.nn.init as I", "(same width and height), grayscale image as input ## 2. It ends with", "5) # (224 - 5)/1 + 1 = 220 -> (32, 220, 220)", "nn.Dropout(p=0.2) self.conv2 = nn.Conv2d(32, 64, 4) # (110 - 4)/1 + 1 =", "choose to include a pool/conv step: x = self.drop1(self.pool(self.act(self.conv1(x)))) x = self.drop2(self.pool(self.act(self.conv2(x)))) x", "pooling -> (64, 53, 53) self.conv3 = nn.Conv2d(64, 128, 3) # (53 -", "64, 4) # (110 - 4)/1 + 1 = 43 -> (64, 107,", "the only requirements are: ## 1. This network takes in a square (same", "= nn.Dropout(p=0.2) # after pooling -> (128, 25, 25) self.dense1 = nn.Linear(80000,1000) #", "53, 53) self.conv3 = nn.Conv2d(64, 128, 3) # (53 - 3)/1 + 1", "change: # 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square", "- 5)/1 + 1 = 220 -> (32, 220, 220) self.act = nn.ReLU()", "4) # (110 - 4)/1 + 1 = 43 -> (64, 107, 107)", "43 -> (64, 107, 107) self.drop2 = nn.Dropout(p=0.2) # after pooling -> (64,", "feedforward behavior of this model ## x is the input image and, as", "which you may (but don't have to) change: # 1 input image channel", "-> (32, 110, 110) self.drop1 = nn.Dropout(p=0.2) self.conv2 = nn.Conv2d(32, 64, 4) #", "Define the feedforward behavior of this model ## x is the input image", "= self.drop1(self.pool(self.act(self.conv1(x)))) x = self.drop2(self.pool(self.act(self.conv2(x)))) x = self.drop3(self.pool(self.act(self.conv3(x)))) x = x.view(x.size(0), -1) x", "nn.Linear(80000,1000) # 128*25*25 = 80000 self.drop4 = nn.Dropout(p=0.2) self.dense2 = nn.Linear(1000,500) self.drop5 =", "torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TODO: Define all", "-> self.conv1 = nn.Conv2d(1, 32, 5) # (224 - 5)/1 + 1 =", "nn.Linear(1000,500) self.drop5 = nn.Dropout(p=0.2) self.dense3 = nn.Linear(500,136) def forward(self, x): ## TODO: Define", "Define all the layers of this CNN, the only requirements are: ## 1.", "1 = 220 -> (32, 220, 220) self.act = nn.ReLU() self.pool = nn.MaxPool2d(2,", "square (same width and height), grayscale image as input ## 2. It ends", "## TODO: define the convolutional neural network architecture import torch from torch.autograd import", "= nn.Conv2d(64, 128, 3) # (53 - 3)/1 + 1 = 19 ->", "y) pairs # As an example, you've been given a convolutional layer, which", "import torch.nn as nn import torch.nn.functional as F # can use the below", "110) self.drop1 = nn.Dropout(p=0.2) self.conv2 = nn.Conv2d(32, 64, 4) # (110 - 4)/1", "make this last layer output 136 values, 2 for each of the 68", "(128, 51, 51) self.drop3 = nn.Dropout(p=0.2) # after pooling -> (128, 25, 25)", "x = self.drop1(self.pool(self.act(self.conv1(x)))) x = self.drop2(self.pool(self.act(self.conv2(x)))) x = self.drop3(self.pool(self.act(self.conv3(x)))) x = x.view(x.size(0), -1)", "+ 1 = 19 -> (128, 51, 51) self.drop3 = nn.Dropout(p=0.2) # after", "your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() ##", "only requirements are: ## 1. This network takes in a square (same width", "torch.nn.functional as F # can use the below import should you choose to", "46 -> (32, 110, 110) self.drop1 = nn.Dropout(p=0.2) self.conv2 = nn.Conv2d(32, 64, 4)", "136 values, 2 for each of the 68 keypoint (x, y) pairs #", "(128, 25, 25) self.dense1 = nn.Linear(80000,1000) # 128*25*25 = 80000 self.drop4 = nn.Dropout(p=0.2)", "an example, you've been given a convolutional layer, which you may (but don't", "channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel # Image size", "5)/1 + 1 = 220 -> (32, 220, 220) self.act = nn.ReLU() self.pool", "25, 25) self.dense1 = nn.Linear(80000,1000) # 128*25*25 = 80000 self.drop4 = nn.Dropout(p=0.2) self.dense2", "may (but don't have to) change: # 1 input image channel (grayscale), 32", "= nn.Dropout(p=0.2) self.dense3 = nn.Linear(500,136) def forward(self, x): ## TODO: Define the feedforward", "pooling -> (128, 25, 25) self.dense1 = nn.Linear(80000,1000) # 128*25*25 = 80000 self.drop4", "network architecture import torch from torch.autograd import Variable import torch.nn as nn import", "torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F # can", "(but don't have to) change: # 1 input image channel (grayscale), 32 output", "self.act = nn.ReLU() self.pool = nn.MaxPool2d(2, 2) # 46 -> (32, 110, 110)", "you may (but don't have to) change: # 1 input image channel (grayscale),", "# Image size = 224*224 -> self.conv1 = nn.Conv2d(1, 32, 5) # (224", "nn.Dropout(p=0.2) # after pooling -> (128, 25, 25) self.dense1 = nn.Linear(80000,1000) # 128*25*25", "output channels/feature maps, 5x5 square convolution kernel # Image size = 224*224 ->", "## 2. It ends with a linear layer that represents the keypoints ##", "import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TODO: Define", "I class Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TODO: Define all the layers", "keypoints ## it's suggested that you make this last layer output 136 values,", "= nn.ReLU() self.pool = nn.MaxPool2d(2, 2) # 46 -> (32, 110, 110) self.drop1", "# after pooling -> (128, 25, 25) self.dense1 = nn.Linear(80000,1000) # 128*25*25 =", "self.drop3(self.pool(self.act(self.conv3(x)))) x = x.view(x.size(0), -1) x = self.drop4(self.act(self.dense1(x))) x = self.drop5(self.act(self.dense2(x))) out =", "torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F", "as input ## 2. It ends with a linear layer that represents the", "# after pooling -> (64, 53, 53) self.conv3 = nn.Conv2d(64, 128, 3) #", "for each of the 68 keypoint (x, y) pairs # As an example,", "Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TODO:", "pool/conv step: x = self.drop1(self.pool(self.act(self.conv1(x)))) x = self.drop2(self.pool(self.act(self.conv2(x)))) x = self.drop3(self.pool(self.act(self.conv3(x)))) x =", "self.conv2 = nn.Conv2d(32, 64, 4) # (110 - 4)/1 + 1 = 43", "## x is the input image and, as an example, here you may", "height), grayscale image as input ## 2. It ends with a linear layer", "convolution kernel # Image size = 224*224 -> self.conv1 = nn.Conv2d(1, 32, 5)", "as an example, here you may choose to include a pool/conv step: x", "x = self.drop2(self.pool(self.act(self.conv2(x)))) x = self.drop3(self.pool(self.act(self.conv3(x)))) x = x.view(x.size(0), -1) x = self.drop4(self.act(self.dense1(x)))", "it's suggested that you make this last layer output 136 values, 2 for", "1. This network takes in a square (same width and height), grayscale image", "= x.view(x.size(0), -1) x = self.drop4(self.act(self.dense1(x))) x = self.drop5(self.act(self.dense2(x))) out = self.dense3(x) return", "= nn.Conv2d(32, 64, 4) # (110 - 4)/1 + 1 = 43 ->", "-> (32, 220, 220) self.act = nn.ReLU() self.pool = nn.MaxPool2d(2, 2) # 46", "self).__init__() ## TODO: Define all the layers of this CNN, the only requirements", "x is the input image and, as an example, here you may choose", "size = 224*224 -> self.conv1 = nn.Conv2d(1, 32, 5) # (224 - 5)/1", "convolutional layer, which you may (but don't have to) change: # 1 input", "F # can use the below import should you choose to initialize the", "neural network architecture import torch from torch.autograd import Variable import torch.nn as nn", "= 224*224 -> self.conv1 = nn.Conv2d(1, 32, 5) # (224 - 5)/1 +", "self.drop1 = nn.Dropout(p=0.2) self.conv2 = nn.Conv2d(32, 64, 4) # (110 - 4)/1 +", "128, 3) # (53 - 3)/1 + 1 = 19 -> (128, 51,", "2. It ends with a linear layer that represents the keypoints ## it's", "to) change: # 1 input image channel (grayscale), 32 output channels/feature maps, 5x5", "# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution", "is the input image and, as an example, here you may choose to", "width and height), grayscale image as input ## 2. It ends with a", "don't have to) change: # 1 input image channel (grayscale), 32 output channels/feature", "with a linear layer that represents the keypoints ## it's suggested that you", "and, as an example, here you may choose to include a pool/conv step:", "the convolutional neural network architecture import torch from torch.autograd import Variable import torch.nn", "input image and, as an example, here you may choose to include a", "this last layer output 136 values, 2 for each of the 68 keypoint", "nn.Conv2d(64, 128, 3) # (53 - 3)/1 + 1 = 19 -> (128,", "in a square (same width and height), grayscale image as input ## 2.", "51) self.drop3 = nn.Dropout(p=0.2) # after pooling -> (128, 25, 25) self.dense1 =", "68 keypoint (x, y) pairs # As an example, you've been given a", "that you make this last layer output 136 values, 2 for each of", "nn.Conv2d(1, 32, 5) # (224 - 5)/1 + 1 = 220 -> (32,", "should you choose to initialize the weights of your Net import torch.nn.init as", "behavior of this model ## x is the input image and, as an", "32, 5) # (224 - 5)/1 + 1 = 220 -> (32, 220,", "-> (128, 51, 51) self.drop3 = nn.Dropout(p=0.2) # after pooling -> (128, 25,", "kernel # Image size = 224*224 -> self.conv1 = nn.Conv2d(1, 32, 5) #", "(64, 53, 53) self.conv3 = nn.Conv2d(64, 128, 3) # (53 - 3)/1 +", "self.drop1(self.pool(self.act(self.conv1(x)))) x = self.drop2(self.pool(self.act(self.conv2(x)))) x = self.drop3(self.pool(self.act(self.conv3(x)))) x = x.view(x.size(0), -1) x =", "It ends with a linear layer that represents the keypoints ## it's suggested", "220, 220) self.act = nn.ReLU() self.pool = nn.MaxPool2d(2, 2) # 46 -> (32,", "51, 51) self.drop3 = nn.Dropout(p=0.2) # after pooling -> (128, 25, 25) self.dense1", "have to) change: # 1 input image channel (grayscale), 32 output channels/feature maps,", "220 -> (32, 220, 220) self.act = nn.ReLU() self.pool = nn.MaxPool2d(2, 2) #", "a square (same width and height), grayscale image as input ## 2. It", "are: ## 1. This network takes in a square (same width and height),", "= nn.Linear(1000,500) self.drop5 = nn.Dropout(p=0.2) self.dense3 = nn.Linear(500,136) def forward(self, x): ## TODO:", "suggested that you make this last layer output 136 values, 2 for each", "define the convolutional neural network architecture import torch from torch.autograd import Variable import", "to include a pool/conv step: x = self.drop1(self.pool(self.act(self.conv1(x)))) x = self.drop2(self.pool(self.act(self.conv2(x)))) x =", "the below import should you choose to initialize the weights of your Net", "nn.Linear(500,136) def forward(self, x): ## TODO: Define the feedforward behavior of this model", "# (224 - 5)/1 + 1 = 220 -> (32, 220, 220) self.act", "given a convolutional layer, which you may (but don't have to) change: #", "channels/feature maps, 5x5 square convolution kernel # Image size = 224*224 -> self.conv1", "use the below import should you choose to initialize the weights of your", "x = x.view(x.size(0), -1) x = self.drop4(self.act(self.dense1(x))) x = self.drop5(self.act(self.dense2(x))) out = self.dense3(x)", "ends with a linear layer that represents the keypoints ## it's suggested that", "- 4)/1 + 1 = 43 -> (64, 107, 107) self.drop2 = nn.Dropout(p=0.2)", "a linear layer that represents the keypoints ## it's suggested that you make", "1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel", "3) # (53 - 3)/1 + 1 = 19 -> (128, 51, 51)", "(x, y) pairs # As an example, you've been given a convolutional layer,", "self.drop3 = nn.Dropout(p=0.2) # after pooling -> (128, 25, 25) self.dense1 = nn.Linear(80000,1000)", "-> (64, 107, 107) self.drop2 = nn.Dropout(p=0.2) # after pooling -> (64, 53,", "self.drop2(self.pool(self.act(self.conv2(x)))) x = self.drop3(self.pool(self.act(self.conv3(x)))) x = x.view(x.size(0), -1) x = self.drop4(self.act(self.dense1(x))) x =", "import torch.nn.functional as F # can use the below import should you choose", "110, 110) self.drop1 = nn.Dropout(p=0.2) self.conv2 = nn.Conv2d(32, 64, 4) # (110 -", "self.conv3 = nn.Conv2d(64, 128, 3) # (53 - 3)/1 + 1 = 19", "import should you choose to initialize the weights of your Net import torch.nn.init" ]
[ "post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this currently must be created already,", "# server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this currently must be created already, but", "SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this currently must be created already, but # '/'", "ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb') ftp.storbinary('STOR '+newFile.name, newFile) newFile.close() ftp.close() print \"it should be live", "for the newest post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this currently must", "PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb') ftp.storbinary('STOR '+newFile.name, newFile) newFile.close() ftp.close() print \"it should be", "newFile=open(newFile.name, 'rb') ftp.storbinary('STOR '+newFile.name, newFile) newFile.close() ftp.close() print \"it should be live at", "def getTime(): import time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime def htmlMaker(content, time): from string", "uploadPage(newFile): from ftplib import FTP ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb') ftp.storbinary('STOR '+newFile.name,", "content would go\") args=parser.parse_args() return args.c def getTime(): import time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return", "getTime(): import time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime def htmlMaker(content, time): from string import", "from ftplib import FTP ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb') ftp.storbinary('STOR '+newFile.name, newFile)", "time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime def htmlMaker(content, time): from string import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>')", "will create an HTML page and post it to my website #via python", "the main running process.\") parser.add_argument('--c',dest='c', help=\"This is where the content would go\") args=parser.parse_args()", "would go\") args=parser.parse_args() return args.c def getTime(): import time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime", "but # '/' should be acceptable as well. def getContent(): import argparse parser=argparse.ArgumentParser(description=\"Retrieves", "currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime def htmlMaker(content, time): from string import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time,", "newFile.close() ftp.close() print \"it should be live at \"+SERVER+'/'+SERVERDIRECTORY+'/'+newFile.name if __name__ == '__main__':", "currentTime def htmlMaker(content, time): from string import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html', 'w')", "it will accept is the text for the newest post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org'", "print \"it should be live at \"+SERVER+'/'+SERVERDIRECTORY+'/'+newFile.name if __name__ == '__main__': content=getContent() time=getTime()", "help=\"This is where the content would go\") args=parser.parse_args() return args.c def getTime(): import", "parser.add_argument('--c',dest='c', help=\"This is where the content would go\") args=parser.parse_args() return args.c def getTime():", "script that will create an HTML page and post it to my website", "argument it will accept is the text for the newest post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html", "my website #via python and html. The argument it will accept is the", "htmlMaker(content, time): from string import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate) htmlFile.close()", "args.c def getTime(): import time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime def htmlMaker(content, time): from", "ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb') ftp.storbinary('STOR '+newFile.name, newFile) newFile.close() ftp.close() print \"it should", "return currentTime def htmlMaker(content, time): from string import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html',", "be created already, but # '/' should be acceptable as well. def getContent():", "go\") args=parser.parse_args() return args.c def getTime(): import time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime def", "SERVERDIRECTORY='theDirectoryOnTheServer' #this currently must be created already, but # '/' should be acceptable", "content and returns it to the main running process.\") parser.add_argument('--c',dest='c', help=\"This is where", "text for the newest post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this currently", "<gh_stars>1-10 #intent: create a script that will create an HTML page and post", "string import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate) htmlFile.close() return htmlFile def", "html. The argument it will accept is the text for the newest post.", "ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb') ftp.storbinary('STOR '+newFile.name, newFile) newFile.close() ftp.close() print \"it", "newFile) newFile.close() ftp.close() print \"it should be live at \"+SERVER+'/'+SERVERDIRECTORY+'/'+newFile.name if __name__ ==", "create a script that will create an HTML page and post it to", "created already, but # '/' should be acceptable as well. def getContent(): import", "it to my website #via python and html. The argument it will accept", "def htmlMaker(content, time): from string import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate)", "USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this currently must be created already, but # '/' should", "htmlFile def uploadPage(newFile): from ftplib import FTP ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb')", "HTML page and post it to my website #via python and html. The", "import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate) htmlFile.close() return htmlFile def uploadPage(newFile):", "# '/' should be acceptable as well. def getContent(): import argparse parser=argparse.ArgumentParser(description=\"Retrieves the", "running process.\") parser.add_argument('--c',dest='c', help=\"This is where the content would go\") args=parser.parse_args() return args.c", "the content would go\") args=parser.parse_args() return args.c def getTime(): import time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec)", "import time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime def htmlMaker(content, time): from string import Template", "be live at \"+SERVER+'/'+SERVERDIRECTORY+'/'+newFile.name if __name__ == '__main__': content=getContent() time=getTime() newFile=htmlMaker(content, time) uploadPage(newFile)", "where the content would go\") args=parser.parse_args() return args.c def getTime(): import time currentTime=time.localtime()", "currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime def htmlMaker(content, time): from string import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content)", "should be acceptable as well. def getContent(): import argparse parser=argparse.ArgumentParser(description=\"Retrieves the content and", "is the text for the newest post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer'", "\"it should be live at \"+SERVER+'/'+SERVERDIRECTORY+'/'+newFile.name if __name__ == '__main__': content=getContent() time=getTime() newFile=htmlMaker(content,", "create an HTML page and post it to my website #via python and", "'rb') ftp.storbinary('STOR '+newFile.name, newFile) newFile.close() ftp.close() print \"it should be live at \"+SERVER+'/'+SERVERDIRECTORY+'/'+newFile.name", "accept is the text for the newest post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>'", "time): from string import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate) htmlFile.close() return", "htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate) htmlFile.close() return htmlFile def uploadPage(newFile): from ftplib", "and returns it to the main running process.\") parser.add_argument('--c',dest='c', help=\"This is where the", "ftplib import FTP ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb') ftp.storbinary('STOR '+newFile.name, newFile) newFile.close()", "an HTML page and post it to my website #via python and html.", "post it to my website #via python and html. The argument it will", "main running process.\") parser.add_argument('--c',dest='c', help=\"This is where the content would go\") args=parser.parse_args() return", "the newest post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this currently must be", "must be created already, but # '/' should be acceptable as well. def", "returns it to the main running process.\") parser.add_argument('--c',dest='c', help=\"This is where the content", "a script that will create an HTML page and post it to my", "to my website #via python and html. The argument it will accept is", "from string import Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate) htmlFile.close() return htmlFile", "should be live at \"+SERVER+'/'+SERVERDIRECTORY+'/'+newFile.name if __name__ == '__main__': content=getContent() time=getTime() newFile=htmlMaker(content, time)", "#intent: create a script that will create an HTML page and post it", "'+newFile.name, newFile) newFile.close() ftp.close() print \"it should be live at \"+SERVER+'/'+SERVERDIRECTORY+'/'+newFile.name if __name__", "and html. The argument it will accept is the text for the newest", "it to the main running process.\") parser.add_argument('--c',dest='c', help=\"This is where the content would", "import FTP ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb') ftp.storbinary('STOR '+newFile.name, newFile) newFile.close() ftp.close()", "ftp.storbinary('STOR '+newFile.name, newFile) newFile.close() ftp.close() print \"it should be live at \"+SERVER+'/'+SERVERDIRECTORY+'/'+newFile.name if", "newest post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this currently must be created", "parser=argparse.ArgumentParser(description=\"Retrieves the content and returns it to the main running process.\") parser.add_argument('--c',dest='c', help=\"This", "as well. def getContent(): import argparse parser=argparse.ArgumentParser(description=\"Retrieves the content and returns it to", "FTP ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb') ftp.storbinary('STOR '+newFile.name, newFile) newFile.close() ftp.close() print", "htmlFile.write(htmlTemplate) htmlFile.close() return htmlFile def uploadPage(newFile): from ftplib import FTP ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD)", "import argparse parser=argparse.ArgumentParser(description=\"Retrieves the content and returns it to the main running process.\")", "that will create an HTML page and post it to my website #via", "Template htmlTemplate=Template('<html>\\n<head>\\n<title>$thetime</title>\\n</head>\\n<body>\\n$thecontent\\n</body>\\n</html>') htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate) htmlFile.close() return htmlFile def uploadPage(newFile): from", "is where the content would go\") args=parser.parse_args() return args.c def getTime(): import time", "argparse parser=argparse.ArgumentParser(description=\"Retrieves the content and returns it to the main running process.\") parser.add_argument('--c',dest='c',", "return args.c def getTime(): import time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime def htmlMaker(content, time):", "the text for the newest post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this", "return htmlFile def uploadPage(newFile): from ftplib import FTP ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name,", "website #via python and html. The argument it will accept is the text", "will accept is the text for the newest post. # server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername'", "htmlFile.close() return htmlFile def uploadPage(newFile): from ftplib import FTP ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY)", "def uploadPage(newFile): from ftplib import FTP ftp=FTP(SERVER) ftp.login(USERNAME, PASSWORD) ftp.cwd(SERVERDIRECTORY) newFile=open(newFile.name, 'rb') ftp.storbinary('STOR", "'/' should be acceptable as well. def getContent(): import argparse parser=argparse.ArgumentParser(description=\"Retrieves the content", "PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this currently must be created already, but # '/' should be", "the content and returns it to the main running process.\") parser.add_argument('--c',dest='c', help=\"This is", "thecontent=content) htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate) htmlFile.close() return htmlFile def uploadPage(newFile): from ftplib import FTP", "def getContent(): import argparse parser=argparse.ArgumentParser(description=\"Retrieves the content and returns it to the main", "page and post it to my website #via python and html. The argument", "and post it to my website #via python and html. The argument it", "htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate) htmlFile.close() return htmlFile def uploadPage(newFile): from ftplib import FTP ftp=FTP(SERVER)", "#this currently must be created already, but # '/' should be acceptable as", "ftp.close() print \"it should be live at \"+SERVER+'/'+SERVERDIRECTORY+'/'+newFile.name if __name__ == '__main__': content=getContent()", "process.\") parser.add_argument('--c',dest='c', help=\"This is where the content would go\") args=parser.parse_args() return args.c def", "server.org/SERVERDIRECTORY/yyyyMonDayhhmmss.html SERVER='ftp.yourhost.org' USERNAME='yourFTPusername' PASSWORD='<PASSWORD>' SERVERDIRECTORY='theDirectoryOnTheServer' #this currently must be created already, but #", "well. def getContent(): import argparse parser=argparse.ArgumentParser(description=\"Retrieves the content and returns it to the", "'w') htmlFile.write(htmlTemplate) htmlFile.close() return htmlFile def uploadPage(newFile): from ftplib import FTP ftp=FTP(SERVER) ftp.login(USERNAME,", "be acceptable as well. def getContent(): import argparse parser=argparse.ArgumentParser(description=\"Retrieves the content and returns", "python and html. The argument it will accept is the text for the", "to the main running process.\") parser.add_argument('--c',dest='c', help=\"This is where the content would go\")", "getContent(): import argparse parser=argparse.ArgumentParser(description=\"Retrieves the content and returns it to the main running", "#via python and html. The argument it will accept is the text for", "args=parser.parse_args() return args.c def getTime(): import time currentTime=time.localtime() currentTime=str(currentTime.tm_year)+'_'+str(currentTime.tm_mon)+'_'+str(currentTime.tm_mday)+'_'+str(currentTime.tm_hour)+'_'+str(currentTime.tm_min)+'_'+str(currentTime.tm_sec) return currentTime def htmlMaker(content,", "currently must be created already, but # '/' should be acceptable as well.", "htmlTemplate=htmlTemplate.substitute(thetime=time, thecontent=content) htmlFile=file(time+'.html', 'w') htmlFile.write(htmlTemplate) htmlFile.close() return htmlFile def uploadPage(newFile): from ftplib import", "The argument it will accept is the text for the newest post. #", "already, but # '/' should be acceptable as well. def getContent(): import argparse", "acceptable as well. def getContent(): import argparse parser=argparse.ArgumentParser(description=\"Retrieves the content and returns it" ]
[ "np import paddlescience as psci import pytest import paddle from apibase import APIBase", "KIND, either express or implied. # See the License for the specific language", "num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet3(): \"\"\" xy shape (9, 4) \"\"\" xy_data =", "Unless required by applicable law or agreed to in writing, software # distributed", "xy_data = randtool(\"float\", 0, 10, (9, 2)) u = cal_with_np(xy_data, 2, 1, 2,", "return u class TestFCNet(APIBase): \"\"\" test flatten \"\"\" def hook(self): \"\"\" implement \"\"\"", "check grad self.static = False obj = TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def test_FCNet0(): \"\"\" default", "4)) u = cal_with_np(xy_data, 4, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=1, num_layers=2,", "numpy \"\"\" w = [] for i in range(num_layers): if i == 0:", "num_outs: 3 hidden_size: 20 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u", "i in range(num_layers): net.weights[i] = paddle.ones_like(net.weights[i]) res = net.nn_func(ins) return res def cal_with_np(ins,", "1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet4(): \"\"\" xy shape", "np.exp(-u)) u = np.matmul(u, w[-1]) return u class TestFCNet(APIBase): \"\"\" test flatten \"\"\"", "num_outs, num_layers, hidden_size, activation='tanh'): \"\"\" calculate with numpy \"\"\" w = [] for", "self.static = False obj = TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def test_FCNet0(): \"\"\" default \"\"\" xy_data", "10, (9, 2)) u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2,", "num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet4(): \"\"\" xy shape (9, 4) num_outs: 2", "u = ins for i in range(num_layers - 1): u = np.matmul(u, w[i])", "= cal_with_np(xy_data, 4, 3, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet", "\"\"\" calculate FCNet api \"\"\" net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size, dtype=dtype,", "this file except in compliance with the License. # You may obtain a", "cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'): \"\"\" calculate FCNet api \"\"\" net", "= True # enable check grad self.static = False obj = TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet", "== 'tanh': u = np.tanh(u) elif activation == 'sigmoid': u = 1 /", "obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet6(): \"\"\" xy shape (9,", "np.matmul(u, w[-1]) return u class TestFCNet(APIBase): \"\"\" test flatten \"\"\" def hook(self): \"\"\"", "ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet6(): \"\"\" xy shape (9, 4)", "@pytest.mark.api_network_FCNet def test_FCNet0(): \"\"\" default \"\"\" xy_data = np.array([[0.1, 0.5]]) u = cal_with_np(xy_data,", "activation='tanh'): \"\"\" calculate FCNet api \"\"\" net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size,", "psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size, dtype=dtype, activation=activation) for i in range(num_layers): net.weights[i] =", "4)) u = cal_with_np(xy_data, 4, 3, 2, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2,", "test flatten \"\"\" def hook(self): \"\"\" implement \"\"\" self.types = [np.float64] # self.debug", "3 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4,", "ANY KIND, either express or implied. # See the License for the specific", "FCNet api \"\"\" net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size, dtype=dtype, activation=activation) for", "ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet1(): \"\"\" xy shape (9, 2)", "\"\"\" xy_data = randtool(\"float\", 0, 10, (9, 2)) u = cal_with_np(xy_data, 2, 1,", "hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet3(): \"\"\" xy shape (9, 4) \"\"\" xy_data = randtool(\"float\",", "= randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 2, 2, 1)", "APIBase from apibase import randtool np.random.seed(22) paddle.seed(22) def cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size,", "\"\"\" xy shape (9, 4) num_outs: 3 \"\"\" xy_data = randtool(\"float\", 0, 1,", "test_FCNet1(): \"\"\" xy shape (9, 2) \"\"\" xy_data = randtool(\"float\", 0, 10, (9,", "= net.nn_func(ins) return res def cal_with_np(ins, num_ins, num_outs, num_layers, hidden_size, activation='tanh'): \"\"\" calculate", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "\"\"\" w = [] for i in range(num_layers): if i == 0: lsize", "= cal_with_np(xy_data, 3, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=3, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet", "- 1): u = np.matmul(u, w[i]) if activation == 'tanh': u = np.tanh(u)", "4, 2, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=2, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet5():", "num_outs: 3 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data,", "4) num_outs: 3 hidden_size: 20 num_layers: 5 \"\"\" xy_data = randtool(\"float\", 0, 1,", "= randtool(\"float\", 0, 1, (9, 3)) u = cal_with_np(xy_data, 3, 1, 2, 1)", "# enable check grad self.static = False obj = TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def test_FCNet0():", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "cal_with_np(xy_data, 3, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=3, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def", "np.matmul(u, w[i]) if activation == 'tanh': u = np.tanh(u) elif activation == 'sigmoid':", "hook(self): \"\"\" implement \"\"\" self.types = [np.float64] # self.debug = True # enable", "@pytest.mark.api_network_FCNet def test_FCNet1(): \"\"\" xy shape (9, 2) \"\"\" xy_data = randtool(\"float\", 0,", "1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet2(): \"\"\" xy shape", "activation=activation) for i in range(num_layers): net.weights[i] = paddle.ones_like(net.weights[i]) res = net.nn_func(ins) return res", "OF ANY KIND, either express or implied. # See the License for the", "'sigmoid': u = 1 / (1 + np.exp(-u)) u = np.matmul(u, w[-1]) return", "num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet7(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size:", "0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 2, 1) obj.run(res=u, ins=xy_data,", "4) num_outs: 3 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u =", "2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet6(): \"\"\" xy", "u = cal_with_np(xy_data, 4, 3, 5, 20, activation='sigmoid') obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5,", "pytest import paddle from apibase import APIBase from apibase import randtool np.random.seed(22) paddle.seed(22)", "dtype=dtype, activation=activation) for i in range(num_layers): net.weights[i] = paddle.ones_like(net.weights[i]) res = net.nn_func(ins) return", "2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet1():", "u = np.tanh(u) elif activation == 'sigmoid': u = 1 / (1 +", "= TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def test_FCNet0(): \"\"\" default \"\"\" xy_data = np.array([[0.1, 0.5]]) u", "1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 5, 20, activation='sigmoid') obj.run(res=u, ins=xy_data,", "hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet7(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20", "hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet2(): \"\"\" xy shape (9, 3) \"\"\" xy_data = randtool(\"float\",", "ins=xy_data, num_ins=4, num_outs=2, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet5(): \"\"\" xy shape (9, 4)", "activation='sigmoid' \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4,", "num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet1(): \"\"\" xy shape (9, 2) \"\"\"", "4, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet4():", "ins=xy_data, num_ins=4, num_outs=3, num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet8(): \"\"\" xy shape (9, 4)", "apibase import randtool np.random.seed(22) paddle.seed(22) def cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'):", "api \"\"\" net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size, dtype=dtype, activation=activation) for i", "hidden_size, dtype='float64', activation='tanh'): \"\"\" calculate FCNet api \"\"\" net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs,", "xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 5,", "(9, 4)) u = cal_with_np(xy_data, 4, 3, 5, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3,", "All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the", "def test_FCNet1(): \"\"\" xy shape (9, 2) \"\"\" xy_data = randtool(\"float\", 0, 10,", "test_FCNet7(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 num_layers: 5 \"\"\"", "4, 3, 5, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet8():", "res def cal_with_np(ins, num_ins, num_outs, num_layers, hidden_size, activation='tanh'): \"\"\" calculate with numpy \"\"\"", "\"\"\" default \"\"\" xy_data = np.array([[0.1, 0.5]]) u = cal_with_np(xy_data, 2, 1, 2,", "@pytest.mark.api_network_FCNet def test_FCNet4(): \"\"\" xy shape (9, 4) num_outs: 2 \"\"\" xy_data =", "num_ins=4, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet4(): \"\"\" xy shape (9, 4) num_outs:", "= num_ins rsize = hidden_size elif i == (num_layers - 1): lsize =", "shape (9, 2) \"\"\" xy_data = randtool(\"float\", 0, 10, (9, 2)) u =", "shape (9, 4) num_outs: 2 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4))", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "def test_FCNet5(): \"\"\" xy shape (9, 4) num_outs: 3 \"\"\" xy_data = randtool(\"float\",", "obj.run(res=u, ins=xy_data, num_ins=4, num_outs=2, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet5(): \"\"\" xy shape (9,", "20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet7(): \"\"\" xy shape", "language governing permissions and # limitations under the License. \"\"\" import numpy as", "xy shape (9, 2) \"\"\" xy_data = randtool(\"float\", 0, 10, (9, 2)) u", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "num_ins=num_ins, num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size, dtype=dtype, activation=activation) for i in range(num_layers): net.weights[i] = paddle.ones_like(net.weights[i])", "= randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 1, 2, 1)", "5 activation='sigmoid' \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data,", "dtype='float64', activation='tanh'): \"\"\" calculate FCNet api \"\"\" net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_layers=num_layers,", "paddlescience as psci import pytest import paddle from apibase import APIBase from apibase", "num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet4(): \"\"\" xy shape (9, 4) num_outs: 2 \"\"\"", "# self.debug = True # enable check grad self.static = False obj =", "def cal_with_np(ins, num_ins, num_outs, num_layers, hidden_size, activation='tanh'): \"\"\" calculate with numpy \"\"\" w", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def test_FCNet0(): \"\"\" default \"\"\" xy_data = np.array([[0.1, 0.5]]) u =", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "\"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 1,", "rsize = num_outs else: lsize = hidden_size rsize = hidden_size w.append(np.ones((lsize, rsize))) u", "xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 2, 2,", "2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet1(): \"\"\" xy", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "def test_FCNet7(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 num_layers: 5", "num_outs=3, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet6(): \"\"\" xy shape (9, 4) num_outs: 3", "def cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'): \"\"\" calculate FCNet api \"\"\"", "required by applicable law or agreed to in writing, software # distributed under", "paddle from apibase import APIBase from apibase import randtool np.random.seed(22) paddle.seed(22) def cal_FCNet(ins,", "applicable law or agreed to in writing, software # distributed under the License", "= np.array([[0.1, 0.5]]) u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2,", "specific language governing permissions and # limitations under the License. \"\"\" import numpy", "1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 2, 20) obj.run(res=u, ins=xy_data, num_ins=4,", "or agreed to in writing, software # distributed under the License is distributed", "4)) u = cal_with_np(xy_data, 4, 2, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=2, num_layers=2,", "num_outs=2, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet5(): \"\"\" xy shape (9, 4) num_outs: 3", "num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet3(): \"\"\" xy shape (9, 4) \"\"\" xy_data", "ins=xy_data, num_ins=3, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet3(): \"\"\" xy shape (9, 4)", "psci import pytest import paddle from apibase import APIBase from apibase import randtool", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "lsize = hidden_size rsize = num_outs else: lsize = hidden_size rsize = hidden_size", "num_layers, hidden_size, dtype='float64', activation='tanh'): \"\"\" calculate FCNet api \"\"\" net = psci.network.FCNet( num_ins=num_ins,", "(9, 2) \"\"\" xy_data = randtool(\"float\", 0, 10, (9, 2)) u = cal_with_np(xy_data,", "(9, 4)) u = cal_with_np(xy_data, 4, 2, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=2,", "num_ins rsize = hidden_size elif i == (num_layers - 1): lsize = hidden_size", "shape (9, 4) num_outs: 3 hidden_size: 20 num_layers: 5 \"\"\" xy_data = randtool(\"float\",", "(9, 4) num_outs: 3 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u", "num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size, dtype=dtype, activation=activation) for i in range(num_layers): net.weights[i] = paddle.ones_like(net.weights[i]) res", "\"\"\" net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size, dtype=dtype, activation=activation) for i in", "net.nn_func(ins) return res def cal_with_np(ins, num_ins, num_outs, num_layers, hidden_size, activation='tanh'): \"\"\" calculate with", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "num_outs else: lsize = hidden_size rsize = hidden_size w.append(np.ones((lsize, rsize))) u = ins", "\"\"\" xy_data = np.array([[0.1, 0.5]]) u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u,", "= cal_with_np(xy_data, 4, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet", "writing, software # distributed under the License is distributed on an \"AS IS\"", "as np import paddlescience as psci import pytest import paddle from apibase import", "if i == 0: lsize = num_ins rsize = hidden_size elif i ==", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "License. # You may obtain a copy of the License at # #", "20 num_layers: 5 activation='sigmoid' \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u", "import paddle from apibase import APIBase from apibase import randtool np.random.seed(22) paddle.seed(22) def", "rsize = hidden_size elif i == (num_layers - 1): lsize = hidden_size rsize", "ins for i in range(num_layers - 1): u = np.matmul(u, w[i]) if activation", "import pytest import paddle from apibase import APIBase from apibase import randtool np.random.seed(22)", "compliance with the License. # You may obtain a copy of the License", "i == 0: lsize = num_ins rsize = hidden_size elif i == (num_layers", "cal_with_np(xy_data, 4, 3, 5, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet def", "hidden_size: 20 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data,", "4, 3, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet6():", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "import APIBase from apibase import randtool np.random.seed(22) paddle.seed(22) def cal_FCNet(ins, num_ins, num_outs, num_layers,", "@pytest.mark.api_network_FCNet def test_FCNet8(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 num_layers:", "shape (9, 4) num_outs: 3 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4))", "calculate FCNet api \"\"\" net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size, dtype=dtype, activation=activation)", "1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet4(): \"\"\"", "num_outs=3, num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet8(): \"\"\" xy shape (9, 4) num_outs: 3", "lsize = hidden_size rsize = hidden_size w.append(np.ones((lsize, rsize))) u = ins for i", "(9, 3)) u = cal_with_np(xy_data, 3, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=3, num_outs=1,", "num_outs=3, num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet7(): \"\"\" xy shape (9, 4) num_outs: 3", "\"\"\" implement \"\"\" self.types = [np.float64] # self.debug = True # enable check", "\"\"\" xy shape (9, 3) \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 3))", "not use this file except in compliance with the License. # You may", "range(num_layers): if i == 0: lsize = num_ins rsize = hidden_size elif i", "4) num_outs: 3 hidden_size: 20 num_layers: 5 activation='sigmoid' \"\"\" xy_data = randtool(\"float\", 0,", "2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet2():", "3, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=3, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet3():", "ins=xy_data, num_ins=4, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet4(): \"\"\" xy shape (9, 4)", "License, Version 2.0 (the \"License\"); # you may not use this file except", "as psci import pytest import paddle from apibase import APIBase from apibase import", "cal_with_np(ins, num_ins, num_outs, num_layers, hidden_size, activation='tanh'): \"\"\" calculate with numpy \"\"\" w =", "num_layers=num_layers, hidden_size=hidden_size, dtype=dtype, activation=activation) for i in range(num_layers): net.weights[i] = paddle.ones_like(net.weights[i]) res =", "num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'): \"\"\" calculate FCNet api \"\"\" net = psci.network.FCNet(", "num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet6(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size:", "= np.tanh(u) elif activation == 'sigmoid': u = 1 / (1 + np.exp(-u))", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "\"\"\" xy shape (9, 2) \"\"\" xy_data = randtool(\"float\", 0, 10, (9, 2))", "= randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 2, 20)", "\"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 num_layers: 5 activation='sigmoid' \"\"\"", "num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet2(): \"\"\" xy shape (9, 3) \"\"\"", "num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet2(): \"\"\" xy shape (9, 3) \"\"\" xy_data", "num_outs: 2 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data,", "activation='tanh'): \"\"\" calculate with numpy \"\"\" w = [] for i in range(num_layers):", "xy shape (9, 4) num_outs: 3 hidden_size: 20 \"\"\" xy_data = randtool(\"float\", 0,", "/ (1 + np.exp(-u)) u = np.matmul(u, w[-1]) return u class TestFCNet(APIBase): \"\"\"", "@pytest.mark.api_network_FCNet def test_FCNet2(): \"\"\" xy shape (9, 3) \"\"\" xy_data = randtool(\"float\", 0,", "# you may not use this file except in compliance with the License.", "grad self.static = False obj = TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def test_FCNet0(): \"\"\" default \"\"\"", "@pytest.mark.api_network_FCNet def test_FCNet7(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 num_layers:", "0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 2, 20) obj.run(res=u, ins=xy_data,", "agreed to in writing, software # distributed under the License is distributed on", "cal_with_np(xy_data, 4, 2, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=2, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def", "rsize = hidden_size w.append(np.ones((lsize, rsize))) u = ins for i in range(num_layers -", "= randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 2, 1)", "randtool np.random.seed(22) paddle.seed(22) def cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'): \"\"\" calculate", "hidden_size=hidden_size, dtype=dtype, activation=activation) for i in range(num_layers): net.weights[i] = paddle.ones_like(net.weights[i]) res = net.nn_func(ins)", "= cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet", "num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet2(): \"\"\" xy shape (9, 3) \"\"\" xy_data =", "(the \"License\"); # you may not use this file except in compliance with", "num_ins=4, num_outs=3, num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet7(): \"\"\" xy shape (9, 4) num_outs:", "# Unless required by applicable law or agreed to in writing, software #", "by applicable law or agreed to in writing, software # distributed under the", "4) \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet5(): \"\"\" xy shape (9, 4) num_outs: 3 \"\"\"", "enable check grad self.static = False obj = TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def test_FCNet0(): \"\"\"", "u = cal_with_np(xy_data, 4, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=1, num_layers=2, hidden_size=1)", "= paddle.ones_like(net.weights[i]) res = net.nn_func(ins) return res def cal_with_np(ins, num_ins, num_outs, num_layers, hidden_size,", "True # enable check grad self.static = False obj = TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def", "num_ins=3, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet3(): \"\"\" xy shape (9, 4) \"\"\"", "randtool(\"float\", 0, 1, (9, 3)) u = cal_with_np(xy_data, 3, 1, 2, 1) obj.run(res=u,", "(9, 4)) u = cal_with_np(xy_data, 4, 3, 5, 20, activation='sigmoid') obj.run(res=u, ins=xy_data, num_ins=4,", "file except in compliance with the License. # You may obtain a copy", "\"\"\" calculate with numpy \"\"\" w = [] for i in range(num_layers): if", "obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet2(): \"\"\" xy shape (9,", "hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet6(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20", "0, 10, (9, 2)) u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data,", "w.append(np.ones((lsize, rsize))) u = ins for i in range(num_layers - 1): u =", "hidden_size, activation='tanh'): \"\"\" calculate with numpy \"\"\" w = [] for i in", "License for the specific language governing permissions and # limitations under the License.", "3)) u = cal_with_np(xy_data, 3, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=3, num_outs=1, num_layers=2,", "@pytest.mark.api_network_FCNet def test_FCNet6(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 \"\"\"", "0.5]]) u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2,", "num_outs: 3 hidden_size: 20 num_layers: 5 \"\"\" xy_data = randtool(\"float\", 0, 1, (9,", "num_ins=4, num_outs=3, num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet8(): \"\"\" xy shape (9, 4) num_outs:", "to in writing, software # distributed under the License is distributed on an", "i in range(num_layers): if i == 0: lsize = num_ins rsize = hidden_size", "implied. # See the License for the specific language governing permissions and #", "\"License\"); # you may not use this file except in compliance with the", "= [np.float64] # self.debug = True # enable check grad self.static = False", "Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "== 'sigmoid': u = 1 / (1 + np.exp(-u)) u = np.matmul(u, w[-1])", "\"\"\" def hook(self): \"\"\" implement \"\"\" self.types = [np.float64] # self.debug = True", "(9, 2)) u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1,", "test_FCNet8(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 num_layers: 5 activation='sigmoid'", "= psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size, dtype=dtype, activation=activation) for i in range(num_layers): net.weights[i]", "PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version", "hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet5(): \"\"\" xy shape (9, 4) num_outs: 3 \"\"\" xy_data", "in range(num_layers): if i == 0: lsize = num_ins rsize = hidden_size elif", "u = np.matmul(u, w[i]) if activation == 'tanh': u = np.tanh(u) elif activation", "or implied. # See the License for the specific language governing permissions and", "test_FCNet6(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 \"\"\" xy_data =", "u class TestFCNet(APIBase): \"\"\" test flatten \"\"\" def hook(self): \"\"\" implement \"\"\" self.types", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "u = np.matmul(u, w[-1]) return u class TestFCNet(APIBase): \"\"\" test flatten \"\"\" def", "(1 + np.exp(-u)) u = np.matmul(u, w[-1]) return u class TestFCNet(APIBase): \"\"\" test", "def test_FCNet0(): \"\"\" default \"\"\" xy_data = np.array([[0.1, 0.5]]) u = cal_with_np(xy_data, 2,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "(9, 4) \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data,", "= np.matmul(u, w[i]) if activation == 'tanh': u = np.tanh(u) elif activation ==", "(9, 4)) u = cal_with_np(xy_data, 4, 3, 2, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3,", "2)) u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2,", "w[i]) if activation == 'tanh': u = np.tanh(u) elif activation == 'sigmoid': u", "1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=3, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet3(): \"\"\"", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 1, 2,", "2 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4,", "== 0: lsize = num_ins rsize = hidden_size elif i == (num_layers -", "from apibase import randtool np.random.seed(22) paddle.seed(22) def cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size, dtype='float64',", "xy shape (9, 4) num_outs: 2 \"\"\" xy_data = randtool(\"float\", 0, 1, (9,", "2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet4(): \"\"\" xy", "xy shape (9, 4) num_outs: 3 hidden_size: 20 num_layers: 5 activation='sigmoid' \"\"\" xy_data", "5 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4,", "4)) u = cal_with_np(xy_data, 4, 3, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2,", "= ins for i in range(num_layers - 1): u = np.matmul(u, w[i]) if", "3 hidden_size: 20 num_layers: 5 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4))", "cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def", "u = cal_with_np(xy_data, 4, 2, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=2, num_layers=2, hidden_size=1)", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "you may not use this file except in compliance with the License. #", "shape (9, 3) \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 3)) u =", "\"\"\" xy shape (9, 4) \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4))", "0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 1, 2, 1) obj.run(res=u, ins=xy_data,", "(9, 4)) u = cal_with_np(xy_data, 4, 3, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3,", "test_FCNet4(): \"\"\" xy shape (9, 4) num_outs: 2 \"\"\" xy_data = randtool(\"float\", 0,", "= 1 / (1 + np.exp(-u)) u = np.matmul(u, w[-1]) return u class", "\"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3,", "num_ins=4, num_outs=2, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet5(): \"\"\" xy shape (9, 4) num_outs:", "lsize = num_ins rsize = hidden_size elif i == (num_layers - 1): lsize", "import paddlescience as psci import pytest import paddle from apibase import APIBase from", "rsize))) u = ins for i in range(num_layers - 1): u = np.matmul(u,", "obj.run(res=u, ins=xy_data, num_ins=3, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet3(): \"\"\" xy shape (9,", "3, 5, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet8(): \"\"\"", "num_layers: 5 activation='sigmoid' \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u =", "paddle.seed(22) def cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'): \"\"\" calculate FCNet api", "4) num_outs: 2 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u =", "randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 5, 20) obj.run(res=u,", "0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 5, 20) obj.run(res=u, ins=xy_data,", "use this file except in compliance with the License. # You may obtain", "Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the", "for the specific language governing permissions and # limitations under the License. \"\"\"", "hidden_size: 20 num_layers: 5 activation='sigmoid' \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4))", "num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet1(): \"\"\" xy shape (9, 2) \"\"\" xy_data =", "u = cal_with_np(xy_data, 3, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=3, num_outs=1, num_layers=2, hidden_size=1)", "0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 2, 2, 1) obj.run(res=u, ins=xy_data,", "20 num_layers: 5 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u =", "(9, 4) num_outs: 3 hidden_size: 20 \"\"\" xy_data = randtool(\"float\", 0, 1, (9,", "return res def cal_with_np(ins, num_ins, num_outs, num_layers, hidden_size, activation='tanh'): \"\"\" calculate with numpy", "def test_FCNet2(): \"\"\" xy shape (9, 3) \"\"\" xy_data = randtool(\"float\", 0, 1,", "implement \"\"\" self.types = [np.float64] # self.debug = True # enable check grad", "def test_FCNet3(): \"\"\" xy shape (9, 4) \"\"\" xy_data = randtool(\"float\", 0, 1,", "3 hidden_size: 20 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u =", "(9, 4) num_outs: 3 hidden_size: 20 num_layers: 5 \"\"\" xy_data = randtool(\"float\", 0,", "Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "if activation == 'tanh': u = np.tanh(u) elif activation == 'sigmoid': u =", "= cal_with_np(xy_data, 4, 3, 5, 20, activation='sigmoid') obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5, hidden_size=20)", "u = cal_with_np(xy_data, 4, 3, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=1)", "and # limitations under the License. \"\"\" import numpy as np import paddlescience", "'tanh': u = np.tanh(u) elif activation == 'sigmoid': u = 1 / (1", "u = cal_with_np(xy_data, 4, 3, 2, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=20)", "3, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet6(): \"\"\"", "2.0 (the \"License\"); # you may not use this file except in compliance", "1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet6(): \"\"\" xy shape", "0, 1, (9, 3)) u = cal_with_np(xy_data, 3, 1, 2, 1) obj.run(res=u, ins=xy_data,", "range(num_layers): net.weights[i] = paddle.ones_like(net.weights[i]) res = net.nn_func(ins) return res def cal_with_np(ins, num_ins, num_outs,", "hidden_size rsize = num_outs else: lsize = hidden_size rsize = hidden_size w.append(np.ones((lsize, rsize)))", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "default \"\"\" xy_data = np.array([[0.1, 0.5]]) u = cal_with_np(xy_data, 2, 1, 2, 1)", "== (num_layers - 1): lsize = hidden_size rsize = num_outs else: lsize =", "= cal_with_np(xy_data, 4, 2, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=2, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet", "paddle.ones_like(net.weights[i]) res = net.nn_func(ins) return res def cal_with_np(ins, num_ins, num_outs, num_layers, hidden_size, activation='tanh'):", "[] for i in range(num_layers): if i == 0: lsize = num_ins rsize", "xy_data = randtool(\"float\", 0, 1, (9, 3)) u = cal_with_np(xy_data, 3, 1, 2,", "u = cal_with_np(xy_data, 4, 3, 5, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5, hidden_size=20)", "# # Unless required by applicable law or agreed to in writing, software", "= cal_with_np(xy_data, 4, 3, 2, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet", "num_ins, num_outs, num_layers, hidden_size, activation='tanh'): \"\"\" calculate with numpy \"\"\" w = []", "express or implied. # See the License for the specific language governing permissions", "test_FCNet5(): \"\"\" xy shape (9, 4) num_outs: 3 \"\"\" xy_data = randtool(\"float\", 0,", "xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 2,", "cal_with_np(xy_data, 4, 3, 2, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet def", "1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 5, 20) obj.run(res=u, ins=xy_data, num_ins=4,", "(9, 4)) u = cal_with_np(xy_data, 4, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=1,", "def test_FCNet4(): \"\"\" xy shape (9, 4) num_outs: 2 \"\"\" xy_data = randtool(\"float\",", "xy_data = np.array([[0.1, 0.5]]) u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data,", "u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1)", "either express or implied. # See the License for the specific language governing", "4)) u = cal_with_np(xy_data, 4, 3, 5, 20, activation='sigmoid') obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3,", "hidden_size w.append(np.ones((lsize, rsize))) u = ins for i in range(num_layers - 1): u", "xy shape (9, 3) \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 3)) u", "self.types = [np.float64] # self.debug = True # enable check grad self.static =", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "(9, 4) num_outs: 2 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u", "self.debug = True # enable check grad self.static = False obj = TestFCNet(cal_FCNet)", "hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet1(): \"\"\" xy shape (9, 2) \"\"\" xy_data = randtool(\"float\",", "2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet2(): \"\"\" xy", "the License. # You may obtain a copy of the License at #", "shape (9, 4) num_outs: 3 hidden_size: 20 \"\"\" xy_data = randtool(\"float\", 0, 1,", "2) \"\"\" xy_data = randtool(\"float\", 0, 10, (9, 2)) u = cal_with_np(xy_data, 2,", "= randtool(\"float\", 0, 10, (9, 2)) u = cal_with_np(xy_data, 2, 1, 2, 1)", "False obj = TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def test_FCNet0(): \"\"\" default \"\"\" xy_data = np.array([[0.1,", "@pytest.mark.api_network_FCNet def test_FCNet3(): \"\"\" xy shape (9, 4) \"\"\" xy_data = randtool(\"float\", 0,", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=2, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet5(): \"\"\"", "= randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 5, 20,", "num_ins=4, num_outs=3, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet6(): \"\"\" xy shape (9, 4) num_outs:", "num_layers, hidden_size, activation='tanh'): \"\"\" calculate with numpy \"\"\" w = [] for i", "randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 2, 2, 1) obj.run(res=u,", "\"\"\" self.types = [np.float64] # self.debug = True # enable check grad self.static", "(c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache", "def test_FCNet6(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 \"\"\" xy_data", "net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_layers=num_layers, hidden_size=hidden_size, dtype=dtype, activation=activation) for i in range(num_layers):", "1) obj.run(res=u, ins=xy_data, num_ins=3, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet3(): \"\"\" xy shape", "1, (9, 3)) u = cal_with_np(xy_data, 3, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=3,", "[np.float64] # self.debug = True # enable check grad self.static = False obj", "obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet8(): \"\"\" xy shape (9,", "\"\"\" xy_data = randtool(\"float\", 0, 1, (9, 3)) u = cal_with_np(xy_data, 3, 1,", "with numpy \"\"\" w = [] for i in range(num_layers): if i ==", "activation == 'sigmoid': u = 1 / (1 + np.exp(-u)) u = np.matmul(u,", "test_FCNet0(): \"\"\" default \"\"\" xy_data = np.array([[0.1, 0.5]]) u = cal_with_np(xy_data, 2, 1,", "with the License. # You may obtain a copy of the License at", "xy shape (9, 4) num_outs: 3 \"\"\" xy_data = randtool(\"float\", 0, 1, (9,", "1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4,", "2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=2, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet5(): \"\"\" xy", "2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License,", "the specific language governing permissions and # limitations under the License. \"\"\" import", "(num_layers - 1): lsize = hidden_size rsize = num_outs else: lsize = hidden_size", "2, 1) obj.run(res=u, ins=xy_data, num_ins=3, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet3(): \"\"\" xy", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "permissions and # limitations under the License. \"\"\" import numpy as np import", "<reponame>levi131/PaddleScience<filename>tests/test_api/test_FCNet.py<gh_stars>0 \"\"\" # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # #", "License. \"\"\" import numpy as np import paddlescience as psci import pytest import", "1, (9, 4)) u = cal_with_np(xy_data, 4, 2, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4,", "obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet7(): \"\"\" xy shape (9,", "= randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 5, 20)", "= hidden_size rsize = num_outs else: lsize = hidden_size rsize = hidden_size w.append(np.ones((lsize,", "the License. \"\"\" import numpy as np import paddlescience as psci import pytest", "randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 2, 20) obj.run(res=u,", "hidden_size rsize = hidden_size w.append(np.ones((lsize, rsize))) u = ins for i in range(num_layers", "for i in range(num_layers): if i == 0: lsize = num_ins rsize =", "def hook(self): \"\"\" implement \"\"\" self.types = [np.float64] # self.debug = True #", "= hidden_size w.append(np.ones((lsize, rsize))) u = ins for i in range(num_layers - 1):", "w = [] for i in range(num_layers): if i == 0: lsize =", "3 hidden_size: 20 num_layers: 5 activation='sigmoid' \"\"\" xy_data = randtool(\"float\", 0, 1, (9,", "i in range(num_layers - 1): u = np.matmul(u, w[i]) if activation == 'tanh':", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "4)) u = cal_with_np(xy_data, 4, 3, 5, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5,", "ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet2(): \"\"\" xy shape (9, 3)", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "obj.run(res=u, ins=xy_data, num_ins=4, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet4(): \"\"\" xy shape (9,", "u = 1 / (1 + np.exp(-u)) u = np.matmul(u, w[-1]) return u", "# limitations under the License. \"\"\" import numpy as np import paddlescience as", "cal_with_np(xy_data, 4, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def", "from apibase import APIBase from apibase import randtool np.random.seed(22) paddle.seed(22) def cal_FCNet(ins, num_ins,", "randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 5, 20, activation='sigmoid')", "np.random.seed(22) paddle.seed(22) def cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'): \"\"\" calculate FCNet", "flatten \"\"\" def hook(self): \"\"\" implement \"\"\" self.types = [np.float64] # self.debug =", "Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "import numpy as np import paddlescience as psci import pytest import paddle from", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under", "4, 3, 2, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet7():", "= cal_with_np(xy_data, 4, 3, 5, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet", "calculate with numpy \"\"\" w = [] for i in range(num_layers): if i", "hidden_size: 20 num_layers: 5 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u", "See the License for the specific language governing permissions and # limitations under", "0: lsize = num_ins rsize = hidden_size elif i == (num_layers - 1):", "obj = TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def test_FCNet0(): \"\"\" default \"\"\" xy_data = np.array([[0.1, 0.5]])", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "net.weights[i] = paddle.ones_like(net.weights[i]) res = net.nn_func(ins) return res def cal_with_np(ins, num_ins, num_outs, num_layers,", "= [] for i in range(num_layers): if i == 0: lsize = num_ins", "randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 2, 1) obj.run(res=u,", "1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=2, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet5(): \"\"\" xy shape", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet8(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size:", "\"\"\" xy shape (9, 4) num_outs: 2 \"\"\" xy_data = randtool(\"float\", 0, 1,", "w[-1]) return u class TestFCNet(APIBase): \"\"\" test flatten \"\"\" def hook(self): \"\"\" implement", "elif activation == 'sigmoid': u = 1 / (1 + np.exp(-u)) u =", "- 1): lsize = hidden_size rsize = num_outs else: lsize = hidden_size rsize", "1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet1(): \"\"\" xy shape", "4) num_outs: 3 hidden_size: 20 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4))", "+ np.exp(-u)) u = np.matmul(u, w[-1]) return u class TestFCNet(APIBase): \"\"\" test flatten", "numpy as np import paddlescience as psci import pytest import paddle from apibase", "i == (num_layers - 1): lsize = hidden_size rsize = num_outs else: lsize", "hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet8(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20", "= hidden_size rsize = hidden_size w.append(np.ones((lsize, rsize))) u = ins for i in", "\"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 num_layers: 5 \"\"\" xy_data", "\"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 2,", "= hidden_size elif i == (num_layers - 1): lsize = hidden_size rsize =", "test_FCNet3(): \"\"\" xy shape (9, 4) \"\"\" xy_data = randtool(\"float\", 0, 1, (9,", "\"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 \"\"\" xy_data = randtool(\"float\",", "randtool(\"float\", 0, 10, (9, 2)) u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u,", "res = net.nn_func(ins) return res def cal_with_np(ins, num_ins, num_outs, num_layers, hidden_size, activation='tanh'): \"\"\"", "elif i == (num_layers - 1): lsize = hidden_size rsize = num_outs else:", "Version 2.0 (the \"License\"); # you may not use this file except in", "2, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet7(): \"\"\" xy", "xy shape (9, 4) \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u", "except in compliance with the License. # You may obtain a copy of", "np.array([[0.1, 0.5]]) u = cal_with_np(xy_data, 2, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1,", "num_ins, num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'): \"\"\" calculate FCNet api \"\"\" net =", "ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet7(): \"\"\" xy shape (9, 4)", "hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet4(): \"\"\" xy shape (9, 4) num_outs: 2 \"\"\" xy_data", "else: lsize = hidden_size rsize = hidden_size w.append(np.ones((lsize, rsize))) u = ins for", "3, 2, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet7(): \"\"\"", "randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 1, 2, 1) obj.run(res=u,", "1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet2(): \"\"\"", "limitations under the License. \"\"\" import numpy as np import paddlescience as psci", "def test_FCNet8(): \"\"\" xy shape (9, 4) num_outs: 3 hidden_size: 20 num_layers: 5", "(9, 4) num_outs: 3 hidden_size: 20 num_layers: 5 activation='sigmoid' \"\"\" xy_data = randtool(\"float\",", "\"\"\" import numpy as np import paddlescience as psci import pytest import paddle", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "num_outs: 3 hidden_size: 20 num_layers: 5 activation='sigmoid' \"\"\" xy_data = randtool(\"float\", 0, 1,", "xy shape (9, 4) num_outs: 3 hidden_size: 20 num_layers: 5 \"\"\" xy_data =", "import randtool np.random.seed(22) paddle.seed(22) def cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'): \"\"\"", "3) \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 3)) u = cal_with_np(xy_data, 3,", "governing permissions and # limitations under the License. \"\"\" import numpy as np", "hidden_size elif i == (num_layers - 1): lsize = hidden_size rsize = num_outs", "test_FCNet2(): \"\"\" xy shape (9, 3) \"\"\" xy_data = randtool(\"float\", 0, 1, (9,", "5, 20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet8(): \"\"\" xy", "@pytest.mark.api_network_FCNet def test_FCNet5(): \"\"\" xy shape (9, 4) num_outs: 3 \"\"\" xy_data =", "cal_with_np(xy_data, 4, 3, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def", "\"\"\" test flatten \"\"\" def hook(self): \"\"\" implement \"\"\" self.types = [np.float64] #", "in range(num_layers - 1): u = np.matmul(u, w[i]) if activation == 'tanh': u", "= num_outs else: lsize = hidden_size rsize = hidden_size w.append(np.ones((lsize, rsize))) u =", "shape (9, 4) num_outs: 3 hidden_size: 20 num_layers: 5 activation='sigmoid' \"\"\" xy_data =", "= np.matmul(u, w[-1]) return u class TestFCNet(APIBase): \"\"\" test flatten \"\"\" def hook(self):", "num_layers: 5 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data,", "\"\"\" # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed", "apibase import APIBase from apibase import randtool np.random.seed(22) paddle.seed(22) def cal_FCNet(ins, num_ins, num_outs,", "activation == 'tanh': u = np.tanh(u) elif activation == 'sigmoid': u = 1", "20 \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u = cal_with_np(xy_data, 4,", "for i in range(num_layers - 1): u = np.matmul(u, w[i]) if activation ==", "= False obj = TestFCNet(cal_FCNet) @pytest.mark.api_network_FCNet def test_FCNet0(): \"\"\" default \"\"\" xy_data =", "20) obj.run(res=u, ins=xy_data, num_ins=4, num_outs=3, num_layers=5, hidden_size=20) @pytest.mark.api_network_FCNet def test_FCNet8(): \"\"\" xy shape", "num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet1(): \"\"\" xy shape (9, 2) \"\"\" xy_data", "for i in range(num_layers): net.weights[i] = paddle.ones_like(net.weights[i]) res = net.nn_func(ins) return res def", "range(num_layers - 1): u = np.matmul(u, w[i]) if activation == 'tanh': u =", "(9, 3) \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 3)) u = cal_with_np(xy_data,", "1): u = np.matmul(u, w[i]) if activation == 'tanh': u = np.tanh(u) elif", "shape (9, 4) \"\"\" xy_data = randtool(\"float\", 0, 1, (9, 4)) u =", "in range(num_layers): net.weights[i] = paddle.ones_like(net.weights[i]) res = net.nn_func(ins) return res def cal_with_np(ins, num_ins,", "1): lsize = hidden_size rsize = num_outs else: lsize = hidden_size rsize =", "np.tanh(u) elif activation == 'sigmoid': u = 1 / (1 + np.exp(-u)) u", "1 / (1 + np.exp(-u)) u = np.matmul(u, w[-1]) return u class TestFCNet(APIBase):", "under the License. \"\"\" import numpy as np import paddlescience as psci import", "TestFCNet(APIBase): \"\"\" test flatten \"\"\" def hook(self): \"\"\" implement \"\"\" self.types = [np.float64]", "obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet1(): \"\"\" xy shape (9,", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "class TestFCNet(APIBase): \"\"\" test flatten \"\"\" def hook(self): \"\"\" implement \"\"\" self.types =", "1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=2, num_outs=1, num_layers=2, hidden_size=1) @pytest.mark.api_network_FCNet def test_FCNet1(): \"\"\"", "0, 1, (9, 4)) u = cal_with_np(xy_data, 4, 3, 5, 20, activation='sigmoid') obj.run(res=u,", "1, (9, 4)) u = cal_with_np(xy_data, 4, 1, 2, 1) obj.run(res=u, ins=xy_data, num_ins=4," ]
[ "\"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode, \"implied\": ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode, \"indirect_y\":", "IndirectYAddressingMode, \"relative\": RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode, } def build(addressing_mode): \"Build", "ClassVar from bitey.cpu.addressing_mode import ( AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode,", "ZeroPageYAddressingMode, } def build(addressing_mode): \"Build an AddressingMode instance from a string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)()", "ImmediateAddressingMode, \"implied\": ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode, \"relative\": RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode,", "ZeroPageYAddressingMode, ) @dataclass class AddressingModeFactory: addressing_mode_map: ClassVar[dict[str, AddressingMode]] = { \"absolute\": AbsoluteAddressingMode, \"absolute_indirect\":", "@dataclass class AddressingModeFactory: addressing_mode_map: ClassVar[dict[str, AddressingMode]] = { \"absolute\": AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\":", "addressing_mode_map: ClassVar[dict[str, AddressingMode]] = { \"absolute\": AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode,", "ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode, } def build(addressing_mode): \"Build an AddressingMode instance from", "\"immediate\": ImmediateAddressingMode, \"implied\": ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode, \"relative\": RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode, \"zeropage_x\":", "RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode, } def build(addressing_mode): \"Build an AddressingMode", "AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode, ) @dataclass class", "instance from a string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode): \"Given an addressing mode string,", "\"accumulator\": AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode, \"implied\": ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode, \"relative\": RelativeAddressingMode, \"zeropage\":", "\"zeropage_y\": ZeroPageYAddressingMode, } def build(addressing_mode): \"Build an AddressingMode instance from a string\" return", "from dataclasses import dataclass from typing import ClassVar from bitey.cpu.addressing_mode import ( AddressingMode,", "AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode): \"Given an addressing mode string, return the addressing mode class\"", "{ \"absolute\": AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode,", "an AddressingMode instance from a string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode): \"Given an addressing", "<reponame>jgerrish/bitey from dataclasses import dataclass from typing import ClassVar from bitey.cpu.addressing_mode import (", "} def build(addressing_mode): \"Build an AddressingMode instance from a string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)() def", "AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode, \"implied\": ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode,", "AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode, )", "AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode, \"implied\": ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode, \"relative\": RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode,", "AddressingModeFactory: addressing_mode_map: ClassVar[dict[str, AddressingMode]] = { \"absolute\": AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\":", "AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode, \"implied\": ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode,", "ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode, \"relative\": RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode,", "from typing import ClassVar from bitey.cpu.addressing_mode import ( AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode,", "\"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode, \"implied\": ImpliedAddressingMode, \"indirect_x\":", "\"relative\": RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode, } def build(addressing_mode): \"Build an", "import ( AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode,", "class AddressingModeFactory: addressing_mode_map: ClassVar[dict[str, AddressingMode]] = { \"absolute\": AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode,", "IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode, ) @dataclass class AddressingModeFactory: addressing_mode_map: ClassVar[dict[str, AddressingMode]] =", "def build(addressing_mode): \"Build an AddressingMode instance from a string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode):", "AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode, \"implied\": ImpliedAddressingMode,", "AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode, \"implied\": ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode, \"relative\": RelativeAddressingMode,", ") @dataclass class AddressingModeFactory: addressing_mode_map: ClassVar[dict[str, AddressingMode]] = { \"absolute\": AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode,", "get_mode_from_str(addressing_mode): \"Given an addressing mode string, return the addressing mode class\" m =", "import ClassVar from bitey.cpu.addressing_mode import ( AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode,", "ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode, ) @dataclass class AddressingModeFactory: addressing_mode_map: ClassVar[dict[str,", "typing import ClassVar from bitey.cpu.addressing_mode import ( AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode,", "AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode, ) @dataclass class AddressingModeFactory:", "\"zeropage\": ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode, } def build(addressing_mode): \"Build an AddressingMode instance", "RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode, ) @dataclass class AddressingModeFactory: addressing_mode_map: ClassVar[dict[str, AddressingMode]] = {", "ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode, } def build(addressing_mode): \"Build an AddressingMode instance from a string\"", "AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode,", "\"absolute_y\": AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode, \"implied\": ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode, \"relative\":", "def get_mode_from_str(addressing_mode): \"Given an addressing mode string, return the addressing mode class\" m", "\"implied\": ImpliedAddressingMode, \"indirect_x\": IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode, \"relative\": RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\":", "\"indirect_x\": IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode, \"relative\": RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode, }", "return AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode): \"Given an addressing mode string, return the addressing mode", "ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode, ) @dataclass class AddressingModeFactory: addressing_mode_map:", "bitey.cpu.addressing_mode import ( AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode,", "IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode, ) @dataclass class AddressingModeFactory: addressing_mode_map: ClassVar[dict[str, AddressingMode]]", "= { \"absolute\": AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode, \"immediate\":", "( AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode,", "\"Build an AddressingMode instance from a string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode): \"Given an", "from bitey.cpu.addressing_mode import ( AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode,", "ZeroPageXAddressingMode, ZeroPageYAddressingMode, ) @dataclass class AddressingModeFactory: addressing_mode_map: ClassVar[dict[str, AddressingMode]] = { \"absolute\": AbsoluteAddressingMode,", "dataclasses import dataclass from typing import ClassVar from bitey.cpu.addressing_mode import ( AddressingMode, AbsoluteAddressingMode,", "import dataclass from typing import ClassVar from bitey.cpu.addressing_mode import ( AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode,", "AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode, ) @dataclass", "dataclass from typing import ClassVar from bitey.cpu.addressing_mode import ( AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode,", "addressing mode string, return the addressing mode class\" m = AddressingModeFactory.addressing_mode_map[addressing_mode] return m", "\"Given an addressing mode string, return the addressing mode class\" m = AddressingModeFactory.addressing_mode_map[addressing_mode]", "ZeroPageAddressingMode, ZeroPageXAddressingMode, ZeroPageYAddressingMode, ) @dataclass class AddressingModeFactory: addressing_mode_map: ClassVar[dict[str, AddressingMode]] = { \"absolute\":", "build(addressing_mode): \"Build an AddressingMode instance from a string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode): \"Given", "an addressing mode string, return the addressing mode class\" m = AddressingModeFactory.addressing_mode_map[addressing_mode] return", "AddressingMode]] = { \"absolute\": AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode,", "from a string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode): \"Given an addressing mode string, return", "IndirectXAddressingMode, \"indirect_y\": IndirectYAddressingMode, \"relative\": RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode, } def", "\"indirect_y\": IndirectYAddressingMode, \"relative\": RelativeAddressingMode, \"zeropage\": ZeroPageAddressingMode, \"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode, } def build(addressing_mode):", "a string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode): \"Given an addressing mode string, return the", "\"zeropage_x\": ZeroPageXAddressingMode, \"zeropage_y\": ZeroPageYAddressingMode, } def build(addressing_mode): \"Build an AddressingMode instance from a", "\"absolute\": AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode, \"accumulator\": AccumulatorAddressingMode, \"immediate\": ImmediateAddressingMode, \"implied\":", "string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode): \"Given an addressing mode string, return the addressing", "ClassVar[dict[str, AddressingMode]] = { \"absolute\": AbsoluteAddressingMode, \"absolute_indirect\": AbsoluteIndirectAddressingMode, \"absolute_x\": AbsoluteXAddressingMode, \"absolute_y\": AbsoluteYAddressingMode, \"accumulator\":", "AddressingMode, AbsoluteAddressingMode, AbsoluteIndirectAddressingMode, AbsoluteXAddressingMode, AbsoluteYAddressingMode, AccumulatorAddressingMode, ImmediateAddressingMode, ImpliedAddressingMode, IndirectXAddressingMode, IndirectYAddressingMode, RelativeAddressingMode, ZeroPageAddressingMode, ZeroPageXAddressingMode,", "AddressingMode instance from a string\" return AddressingModeFactory.get_mode_from_str(addressing_mode)() def get_mode_from_str(addressing_mode): \"Given an addressing mode" ]
[ "* 1000 logging.verbose( 'Time to split into connected components subgraphs ' + 'and", "'start_time': start_time, 'end_time': end_time } scribbles.append(path_data) scribbles_data = {'scribbles': scribbles,} t = time.time()", "shape as `pred_masks`, one-hot vector for multi object nb_objects: Integer. Number of objects", "to generate the scribble. If not given, the worst frame given by the", "the sequence h, w = annotations.shape img_shape = np.asarray([w, h], dtype=np.float) pred, gt", "subgraphs ' + 'and remove the cycles: {:.3f} ms'.format(t), 2) t_start = time.time()", "from davisinteractive.evaluation.service import EvaluationService import time import numpy as np ROBOT_DEFAULT_PARAMETERS = {", "import batched_jaccard from davisinteractive.utils.operations import bezier_curve from davisinteractive.robot.interactive_robot import InteractiveScribblesRobot from davisinteractive.evaluation.service import", "davisinteractive.robot.interactive_robot import InteractiveScribblesRobot from davisinteractive.evaluation.service import EvaluationService import time import numpy as np", "gt_mask, nb_objects=None,): \"\"\" Interaction of the Scribble robot given a prediction. Given the", "logging.verbose( 'Time to compute the skeleton mask: {:.3f} ms'.format( skel_time * 1000), 2)", "in S] longest_paths = [P[idx] for idx in longest_paths_idx] t = (time.time() -", "object ID {} is empty. Skip object ID.'. format(obj_id)) continue # Generate scribbles", "end_time = time.time() logging.verbose( 'Generating the scribble for object id {} '.format(obj_id) +", "will return a scribble in the region that fails the most. # Arguments", "logging.info(('The robot took {:.3f} s to generate all the ' 'scribbles for {}", "Setting this value will speed up the computation. frame: Integer. Frame to generate", "max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): \"\"\" Robot constructor \"\"\" super(Interactrobot, self).__init__() if kernel_size >= 1.", "String. Name of the sequence to interact with. pred_masks: Numpy Array. Array with", "'Time to compute the skeleton mask: {:.3f} ms'.format( skel_time * 1000), 2) if", "obj_id), 2) start_time = time.time() error_mask = (gt == obj_id) & (pred !=", "skel_mask.sum() == 0: continue G, P = self._mask2graph(skel_mask) mask2graph_time = time.time() - start_time", "ground truth mask. If `None` the value will be infered from `y_true`. Setting", "davisinteractive import logging from davisinteractive.metrics import batched_jaccard from davisinteractive.utils.operations import bezier_curve from davisinteractive.robot.interactive_robot", "the value will be infered from `y_true`. Setting this value will speed up", "> 0) & (obj_ids < 255)] nb_objects = len(obj_ids) obj_ids = [i for", "to generate all the ' 'scribbles for {} objects.').format( t, nb_objects)) return scribbles_data", "ValueError('kernel_size must be a value between [0, 1).') self.kernel_size = kernel_size self.max_kernel_radius =", "(pred != obj_id) if error_mask.sum() == 0: logging.info( 'Error mask of object ID", "obj_ids = [i for i in range(nb_objects + 1)] # Infer height and", "i in range(nb_objects + 1)] # Infer height and width of the sequence", "Number of objects in the ground truth mask. If `None` the value will", "__init__(self, kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): \"\"\" Robot constructor \"\"\" super(Interactrobot, self).__init__() if kernel_size", "prediction, the robot will return a scribble in the region that fails the", "# Generate scribbles data file for p in scribbles_paths: p /= img_shape path_data", "vector for multi object gt_masks: Numpy Array. Array with the ground truth of", "Skip object ID.'. format(obj_id)) continue # Generate scribbles skel_mask = self._generate_scribble_mask(error_mask) skel_time =", "is None: obj_ids = np.unique(annotations) obj_ids = obj_ids[(obj_ids > 0) & (obj_ids <", "data type and shape as `pred_masks`, one-hot vector for multi object nb_objects: Integer.", "* 1000), 2) t_start = time.time() S = self._acyclics_subgraphs(G) t = (time.time() -", "'max_kernel_radius': 16, 'min_nb_nodes': 4, 'nb_points': 1000 } class Interactrobot(InteractiveScribblesRobot): def __init__(self, kernel_size=.2, max_kernel_radius=16,", "1000 } class Interactrobot(InteractiveScribblesRobot): def __init__(self, kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): \"\"\" Robot constructor", "this value will speed up the computation. frame: Integer. Frame to generate the", "time.time() error_mask = (gt == obj_id) & (pred != obj_id) if error_mask.sum() ==", "fails the most. # Arguments sequence: String. Name of the sequence to interact", "took {:.3f} s to generate all the ' 'scribbles for {} objects.').format( t,", "self.nb_points = nb_points def interact_singleimg(self, pred_mask, gt_mask, nb_objects=None,): \"\"\" Interaction of the Scribble", "object gt_masks: Numpy Array. Array with the ground truth of the sequence. It", "= nb_points def interact_singleimg(self, pred_mask, gt_mask, nb_objects=None,): \"\"\" Interaction of the Scribble robot", "G, P = self._mask2graph(skel_mask) mask2graph_time = time.time() - start_time - skel_time logging.verbose( 'Time", "t = (time.time() - t_start) * 1000 logging.verbose( 'Time to compute the bezier", "* 1000 logging.verbose( 'Time to compute the bezier curves: {:.3f} ms'.format(t), 2) end_time", "self.nb_points) for p in longest_paths ] t = (time.time() - t_start) * 1000", "{'scribbles': scribbles,} t = time.time() - robot_start logging.info(('The robot took {:.3f} s to", "!= obj_id) if error_mask.sum() == 0: logging.info( 'Error mask of object ID {}", "'min_nb_nodes': 4, 'nb_points': 1000 } class Interactrobot(InteractiveScribblesRobot): def __init__(self, kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000):", "sequence h, w = annotations.shape img_shape = np.asarray([w, h], dtype=np.float) pred, gt =", "time.time() scribbles_paths = [ bezier_curve(p, self.nb_points) for p in longest_paths ] t =", "a scribble in the region that fails the most. # Arguments sequence: String.", "& (pred != obj_id) if error_mask.sum() == 0: logging.info( 'Error mask of object", "# Infer height and width of the sequence h, w = annotations.shape img_shape", "= (time.time() - t_start) * 1000 logging.verbose( 'Time to compute the bezier curves:", "w = annotations.shape img_shape = np.asarray([w, h], dtype=np.float) pred, gt = predictions, annotations", "empty. Skip object ID.'. format(obj_id)) continue # Generate scribbles skel_mask = self._generate_scribble_mask(error_mask) skel_time", "will speed up the computation. frame: Integer. Frame to generate the scribble. If", "frame: Integer. Frame to generate the scribble. If not given, the worst frame", "dtype=np.int) annotations = np.asarray(gt_mask, dtype=np.int) if nb_objects is None: obj_ids = np.unique(annotations) obj_ids", "constructor \"\"\" super(Interactrobot, self).__init__() if kernel_size >= 1. or kernel_size < 0: raise", "= np.unique(annotations) obj_ids = obj_ids[(obj_ids > 0) & (obj_ids < 255)] nb_objects =", "trees: {:.3f} ms'. format(t), 2) t_start = time.time() scribbles_paths = [ bezier_curve(p, self.nb_points)", "(time.time() - t_start) * 1000 logging.verbose( 'Time to split into connected components subgraphs", "bezier curves: {:.3f} ms'.format(t), 2) end_time = time.time() logging.verbose( 'Generating the scribble for", "'{:.3f} ms'.format(mask2graph_time * 1000), 2) t_start = time.time() S = self._acyclics_subgraphs(G) t =", "same data type and shape as `pred_masks`, one-hot vector for multi object nb_objects:", "W), one-hot vector for multi object gt_masks: Numpy Array. Array with the ground", "given a prediction. Given the sequence and a mask prediction, the robot will", "np.asarray(pred_mask, dtype=np.int) annotations = np.asarray(gt_mask, dtype=np.int) if nb_objects is None: obj_ids = np.unique(annotations)", "time.time() - robot_start logging.info(('The robot took {:.3f} s to generate all the '", "h, w = annotations.shape img_shape = np.asarray([w, h], dtype=np.float) pred, gt = predictions,", "mask into a graph: ' + '{:.3f} ms'.format(mask2graph_time * 1000), 2) t_start =", "import numpy as np ROBOT_DEFAULT_PARAMETERS = { 'kernel_size': .2, 'max_kernel_radius': 16, 'min_nb_nodes': 4,", "interact_singleimg(self, pred_mask, gt_mask, nb_objects=None,): \"\"\" Interaction of the Scribble robot given a prediction.", "* 1000), 2) if skel_mask.sum() == 0: continue G, P = self._mask2graph(skel_mask) mask2graph_time", "sequence and a mask prediction, the robot will return a scribble in the", "the region that fails the most. # Arguments sequence: String. Name of the", "mask2graph_time = time.time() - start_time - skel_time logging.verbose( 'Time to transform the skeleton", "= (time.time() - t_start) * 1000 logging.verbose( 'Time to compute the longest path", "`None` the value will be infered from `y_true`. Setting this value will speed", "= self._mask2graph(skel_mask) mask2graph_time = time.time() - start_time - skel_time logging.verbose( 'Time to transform", "< 255)] nb_objects = len(obj_ids) obj_ids = [i for i in range(nb_objects +", "obj_id) if error_mask.sum() == 0: logging.info( 'Error mask of object ID {} is", "transform the skeleton mask into a graph: ' + '{:.3f} ms'.format(mask2graph_time * 1000),", "split into connected components subgraphs ' + 'and remove the cycles: {:.3f} ms'.format(t),", "pred_masks: Numpy Array. Array with the prediction masks. It must be an integer", "computation. frame: Integer. Frame to generate the scribble. If not given, the worst", "[0, 1).') self.kernel_size = kernel_size self.max_kernel_radius = max_kernel_radius self.min_nb_nodes = min_nb_nodes self.nb_points =", "] t = (time.time() - t_start) * 1000 logging.verbose( 'Time to compute the", "ms'. format(t), 2) t_start = time.time() scribbles_paths = [ bezier_curve(p, self.nb_points) for p", "an integer array with shape (H x W), one-hot vector for multi object", "gt = predictions, annotations scribbles = [] for obj_id in obj_ids: logging.verbose( 'Creating", "self._acyclics_subgraphs(G) t = (time.time() - t_start) * 1000 logging.verbose( 'Time to split into", "time.time() longest_paths_idx = [self._longest_path_in_tree(s) for s in S] longest_paths = [P[idx] for idx", "mask at object_id={}'.format( obj_id), 2) start_time = time.time() error_mask = (gt == obj_id)", "= time.time() logging.verbose( 'Generating the scribble for object id {} '.format(obj_id) + 'took", "{:.3f} ms'. format(t), 2) t_start = time.time() scribbles_paths = [ bezier_curve(p, self.nb_points) for", "be a value between [0, 1).') self.kernel_size = kernel_size self.max_kernel_radius = max_kernel_radius self.min_nb_nodes", "Interaction of the Scribble robot given a prediction. Given the sequence and a", "integer array with shape (H x W), one-hot vector for multi object gt_masks:", "0: logging.info( 'Error mask of object ID {} is empty. Skip object ID.'.", "numpy as np ROBOT_DEFAULT_PARAMETERS = { 'kernel_size': .2, 'max_kernel_radius': 16, 'min_nb_nodes': 4, 'nb_points':", "import InteractiveScribblesRobot from davisinteractive.evaluation.service import EvaluationService import time import numpy as np ROBOT_DEFAULT_PARAMETERS", "\"\"\" Robot constructor \"\"\" super(Interactrobot, self).__init__() if kernel_size >= 1. or kernel_size <", "def interact_singleimg(self, pred_mask, gt_mask, nb_objects=None,): \"\"\" Interaction of the Scribble robot given a", "is empty. Skip object ID.'. format(obj_id)) continue # Generate scribbles skel_mask = self._generate_scribble_mask(error_mask)", "= obj_ids[(obj_ids > 0) & (obj_ids < 255)] nb_objects = len(obj_ids) obj_ids =", "object nb_objects: Integer. Number of objects in the ground truth mask. If `None`", "if error_mask.sum() == 0: logging.info( 'Error mask of object ID {} is empty.", "for p in scribbles_paths: p /= img_shape path_data = { 'path': p.tolist(), 'object_id':", "'and remove the cycles: {:.3f} ms'.format(t), 2) t_start = time.time() longest_paths_idx = [self._longest_path_in_tree(s)", "robot_start = time.time() predictions = np.asarray(pred_mask, dtype=np.int) annotations = np.asarray(gt_mask, dtype=np.int) if nb_objects", "the sequence and a mask prediction, the robot will return a scribble in", "sequence: String. Name of the sequence to interact with. pred_masks: Numpy Array. Array", "from davisinteractive.metrics import batched_jaccard from davisinteractive.utils.operations import bezier_curve from davisinteractive.robot.interactive_robot import InteractiveScribblesRobot from", "start_time - skel_time logging.verbose( 'Time to transform the skeleton mask into a graph:", "[self._longest_path_in_tree(s) for s in S] longest_paths = [P[idx] for idx in longest_paths_idx] t", "= [i for i in range(nb_objects + 1)] # Infer height and width", "skeleton mask: {:.3f} ms'.format( skel_time * 1000), 2) if skel_mask.sum() == 0: continue", "ID.'. format(obj_id)) continue # Generate scribbles skel_mask = self._generate_scribble_mask(error_mask) skel_time = time.time() -", "scribbles = [] for obj_id in obj_ids: logging.verbose( 'Creating scribbles from error mask", "format(obj_id)) continue # Generate scribbles skel_mask = self._generate_scribble_mask(error_mask) skel_time = time.time() - start_time", "have the same data type and shape as `pred_masks`, one-hot vector for multi", "scribble for object id {} '.format(obj_id) + 'took {:.3f} ms'.format((end_time - start_time) *", "the worst frame given by the jaccard will be used. # Returns dict:", "dtype=np.float) pred, gt = predictions, annotations scribbles = [] for obj_id in obj_ids:", "of objects in the ground truth mask. If `None` the value will be", "speed up the computation. frame: Integer. Frame to generate the scribble. If not", "path on the trees: {:.3f} ms'. format(t), 2) t_start = time.time() scribbles_paths =", "multi object gt_masks: Numpy Array. Array with the ground truth of the sequence.", "= max_kernel_radius self.min_nb_nodes = min_nb_nodes self.nb_points = nb_points def interact_singleimg(self, pred_mask, gt_mask, nb_objects=None,):", "as np ROBOT_DEFAULT_PARAMETERS = { 'kernel_size': .2, 'max_kernel_radius': 16, 'min_nb_nodes': 4, 'nb_points': 1000", "mask: {:.3f} ms'.format( skel_time * 1000), 2) if skel_mask.sum() == 0: continue G,", "int(obj_id), 'start_time': start_time, 'end_time': end_time } scribbles.append(path_data) scribbles_data = {'scribbles': scribbles,} t =", "scribbles_data = {'scribbles': scribbles,} t = time.time() - robot_start logging.info(('The robot took {:.3f}", "= time.time() - robot_start logging.info(('The robot took {:.3f} s to generate all the", "absolute_import, division from davisinteractive import logging from davisinteractive.metrics import batched_jaccard from davisinteractive.utils.operations import", "< 0: raise ValueError('kernel_size must be a value between [0, 1).') self.kernel_size =", "will be used. # Returns dict: Return a scribble (default representation). \"\"\" robot_start", "`y_true`. Setting this value will speed up the computation. frame: Integer. Frame to", "to split into connected components subgraphs ' + 'and remove the cycles: {:.3f}", "in longest_paths ] t = (time.time() - t_start) * 1000 logging.verbose( 'Time to", "= time.time() predictions = np.asarray(pred_mask, dtype=np.int) annotations = np.asarray(gt_mask, dtype=np.int) if nb_objects is", "- robot_start logging.info(('The robot took {:.3f} s to generate all the ' 'scribbles", "= [self._longest_path_in_tree(s) for s in S] longest_paths = [P[idx] for idx in longest_paths_idx]", "t_start) * 1000 logging.verbose( 'Time to compute the bezier curves: {:.3f} ms'.format(t), 2)", "logging.verbose( 'Time to split into connected components subgraphs ' + 'and remove the", "in the ground truth mask. If `None` the value will be infered from", "It must have the same data type and shape as `pred_masks`, one-hot vector", "(time.time() - t_start) * 1000 logging.verbose( 'Time to compute the longest path on", "between [0, 1).') self.kernel_size = kernel_size self.max_kernel_radius = max_kernel_radius self.min_nb_nodes = min_nb_nodes self.nb_points", "of the sequence to interact with. pred_masks: Numpy Array. Array with the prediction", "error_mask.sum() == 0: logging.info( 'Error mask of object ID {} is empty. Skip", "object ID.'. format(obj_id)) continue # Generate scribbles skel_mask = self._generate_scribble_mask(error_mask) skel_time = time.time()", "obj_ids: logging.verbose( 'Creating scribbles from error mask at object_id={}'.format( obj_id), 2) start_time =", "== obj_id) & (pred != obj_id) if error_mask.sum() == 0: logging.info( 'Error mask", "batched_jaccard from davisinteractive.utils.operations import bezier_curve from davisinteractive.robot.interactive_robot import InteractiveScribblesRobot from davisinteractive.evaluation.service import EvaluationService", "of the sequence. It must have the same data type and shape as", "t_start) * 1000 logging.verbose( 'Time to compute the longest path on the trees:", "2) # Generate scribbles data file for p in scribbles_paths: p /= img_shape", "2) t_start = time.time() longest_paths_idx = [self._longest_path_in_tree(s) for s in S] longest_paths =", "be infered from `y_true`. Setting this value will speed up the computation. frame:", "truth of the sequence. It must have the same data type and shape", "{ 'kernel_size': .2, 'max_kernel_radius': 16, 'min_nb_nodes': 4, 'nb_points': 1000 } class Interactrobot(InteractiveScribblesRobot): def", "p in scribbles_paths: p /= img_shape path_data = { 'path': p.tolist(), 'object_id': int(obj_id),", "time.time() logging.verbose( 'Generating the scribble for object id {} '.format(obj_id) + 'took {:.3f}", "logging.verbose( 'Time to compute the longest path on the trees: {:.3f} ms'. format(t),", "file for p in scribbles_paths: p /= img_shape path_data = { 'path': p.tolist(),", "skel_time logging.verbose( 'Time to transform the skeleton mask into a graph: ' +", "+ '{:.3f} ms'.format(mask2graph_time * 1000), 2) t_start = time.time() S = self._acyclics_subgraphs(G) t", "'Time to transform the skeleton mask into a graph: ' + '{:.3f} ms'.format(mask2graph_time", "'Time to compute the longest path on the trees: {:.3f} ms'. format(t), 2)", "np.asarray([w, h], dtype=np.float) pred, gt = predictions, annotations scribbles = [] for obj_id", "from `y_true`. Setting this value will speed up the computation. frame: Integer. Frame", "most. # Arguments sequence: String. Name of the sequence to interact with. pred_masks:", "id {} '.format(obj_id) + 'took {:.3f} ms'.format((end_time - start_time) * 1000), 2) #", "'took {:.3f} ms'.format((end_time - start_time) * 1000), 2) # Generate scribbles data file", "obj_ids = np.unique(annotations) obj_ids = obj_ids[(obj_ids > 0) & (obj_ids < 255)] nb_objects", "bezier_curve(p, self.nb_points) for p in longest_paths ] t = (time.time() - t_start) *", "min_nb_nodes=4, nb_points=1000): \"\"\" Robot constructor \"\"\" super(Interactrobot, self).__init__() if kernel_size >= 1. or", "ms'.format((end_time - start_time) * 1000), 2) # Generate scribbles data file for p", "path_data = { 'path': p.tolist(), 'object_id': int(obj_id), 'start_time': start_time, 'end_time': end_time } scribbles.append(path_data)", "gt_masks: Numpy Array. Array with the ground truth of the sequence. It must", "not given, the worst frame given by the jaccard will be used. #", "'end_time': end_time } scribbles.append(path_data) scribbles_data = {'scribbles': scribbles,} t = time.time() - robot_start", "into connected components subgraphs ' + 'and remove the cycles: {:.3f} ms'.format(t), 2)", "2) t_start = time.time() scribbles_paths = [ bezier_curve(p, self.nb_points) for p in longest_paths", "continue # Generate scribbles skel_mask = self._generate_scribble_mask(error_mask) skel_time = time.time() - start_time logging.verbose(", "Integer. Number of objects in the ground truth mask. If `None` the value", "(default representation). \"\"\" robot_start = time.time() predictions = np.asarray(pred_mask, dtype=np.int) annotations = np.asarray(gt_mask,", "graph: ' + '{:.3f} ms'.format(mask2graph_time * 1000), 2) t_start = time.time() S =", "= (gt == obj_id) & (pred != obj_id) if error_mask.sum() == 0: logging.info(", "`pred_masks`, one-hot vector for multi object nb_objects: Integer. Number of objects in the", "= np.asarray([w, h], dtype=np.float) pred, gt = predictions, annotations scribbles = [] for", "'Generating the scribble for object id {} '.format(obj_id) + 'took {:.3f} ms'.format((end_time -", "import bezier_curve from davisinteractive.robot.interactive_robot import InteractiveScribblesRobot from davisinteractive.evaluation.service import EvaluationService import time import", "Given the sequence and a mask prediction, the robot will return a scribble", "self).__init__() if kernel_size >= 1. or kernel_size < 0: raise ValueError('kernel_size must be", "ms'.format(t), 2) end_time = time.time() logging.verbose( 'Generating the scribble for object id {}", "scribbles_paths = [ bezier_curve(p, self.nb_points) for p in longest_paths ] t = (time.time()", "type and shape as `pred_masks`, one-hot vector for multi object nb_objects: Integer. Number", "import logging from davisinteractive.metrics import batched_jaccard from davisinteractive.utils.operations import bezier_curve from davisinteractive.robot.interactive_robot import", "sequence to interact with. pred_masks: Numpy Array. Array with the prediction masks. It", "= { 'path': p.tolist(), 'object_id': int(obj_id), 'start_time': start_time, 'end_time': end_time } scribbles.append(path_data) scribbles_data", "Numpy Array. Array with the prediction masks. It must be an integer array", "from davisinteractive import logging from davisinteractive.metrics import batched_jaccard from davisinteractive.utils.operations import bezier_curve from", "used. # Returns dict: Return a scribble (default representation). \"\"\" robot_start = time.time()", "longest_paths_idx = [self._longest_path_in_tree(s) for s in S] longest_paths = [P[idx] for idx in", "time.time() - start_time - skel_time logging.verbose( 'Time to transform the skeleton mask into", "given by the jaccard will be used. # Returns dict: Return a scribble", "= time.time() longest_paths_idx = [self._longest_path_in_tree(s) for s in S] longest_paths = [P[idx] for", "the computation. frame: Integer. Frame to generate the scribble. If not given, the", "import time import numpy as np ROBOT_DEFAULT_PARAMETERS = { 'kernel_size': .2, 'max_kernel_radius': 16,", "{} '.format(obj_id) + 'took {:.3f} ms'.format((end_time - start_time) * 1000), 2) # Generate", "Array with the ground truth of the sequence. It must have the same", "self._mask2graph(skel_mask) mask2graph_time = time.time() - start_time - skel_time logging.verbose( 'Time to transform the", "1000), 2) if skel_mask.sum() == 0: continue G, P = self._mask2graph(skel_mask) mask2graph_time =", "the sequence to interact with. pred_masks: Numpy Array. Array with the prediction masks.", "dict: Return a scribble (default representation). \"\"\" robot_start = time.time() predictions = np.asarray(pred_mask,", "S] longest_paths = [P[idx] for idx in longest_paths_idx] t = (time.time() - t_start)", "logging.verbose( 'Generating the scribble for object id {} '.format(obj_id) + 'took {:.3f} ms'.format((end_time", "the ground truth of the sequence. It must have the same data type", "'path': p.tolist(), 'object_id': int(obj_id), 'start_time': start_time, 'end_time': end_time } scribbles.append(path_data) scribbles_data = {'scribbles':", "logging.info( 'Error mask of object ID {} is empty. Skip object ID.'. format(obj_id))", "{:.3f} ms'.format( skel_time * 1000), 2) if skel_mask.sum() == 0: continue G, P", "ROBOT_DEFAULT_PARAMETERS = { 'kernel_size': .2, 'max_kernel_radius': 16, 'min_nb_nodes': 4, 'nb_points': 1000 } class", "given, the worst frame given by the jaccard will be used. # Returns", "np.asarray(gt_mask, dtype=np.int) if nb_objects is None: obj_ids = np.unique(annotations) obj_ids = obj_ids[(obj_ids >", "- skel_time logging.verbose( 'Time to transform the skeleton mask into a graph: '", "value will be infered from `y_true`. Setting this value will speed up the", "\"\"\" super(Interactrobot, self).__init__() if kernel_size >= 1. or kernel_size < 0: raise ValueError('kernel_size", "self.min_nb_nodes = min_nb_nodes self.nb_points = nb_points def interact_singleimg(self, pred_mask, gt_mask, nb_objects=None,): \"\"\" Interaction", "data file for p in scribbles_paths: p /= img_shape path_data = { 'path':", "Name of the sequence to interact with. pred_masks: Numpy Array. Array with the", "worst frame given by the jaccard will be used. # Returns dict: Return", "* 1000 logging.verbose( 'Time to compute the longest path on the trees: {:.3f}", "the prediction masks. It must be an integer array with shape (H x", "max_kernel_radius self.min_nb_nodes = min_nb_nodes self.nb_points = nb_points def interact_singleimg(self, pred_mask, gt_mask, nb_objects=None,): \"\"\"", "{ 'path': p.tolist(), 'object_id': int(obj_id), 'start_time': start_time, 'end_time': end_time } scribbles.append(path_data) scribbles_data =", "obj_id) & (pred != obj_id) if error_mask.sum() == 0: logging.info( 'Error mask of", "obj_ids[(obj_ids > 0) & (obj_ids < 255)] nb_objects = len(obj_ids) obj_ids = [i", ".2, 'max_kernel_radius': 16, 'min_nb_nodes': 4, 'nb_points': 1000 } class Interactrobot(InteractiveScribblesRobot): def __init__(self, kernel_size=.2,", "0: raise ValueError('kernel_size must be a value between [0, 1).') self.kernel_size = kernel_size", "annotations = np.asarray(gt_mask, dtype=np.int) if nb_objects is None: obj_ids = np.unique(annotations) obj_ids =", "object id {} '.format(obj_id) + 'took {:.3f} ms'.format((end_time - start_time) * 1000), 2)", "robot will return a scribble in the region that fails the most. #", "= kernel_size self.max_kernel_radius = max_kernel_radius self.min_nb_nodes = min_nb_nodes self.nb_points = nb_points def interact_singleimg(self,", "{} is empty. Skip object ID.'. format(obj_id)) continue # Generate scribbles skel_mask =", "= [ bezier_curve(p, self.nb_points) for p in longest_paths ] t = (time.time() -", "must be a value between [0, 1).') self.kernel_size = kernel_size self.max_kernel_radius = max_kernel_radius", "must be an integer array with shape (H x W), one-hot vector for", "logging.verbose( 'Time to transform the skeleton mask into a graph: ' + '{:.3f}", "{:.3f} s to generate all the ' 'scribbles for {} objects.').format( t, nb_objects))", "predictions, annotations scribbles = [] for obj_id in obj_ids: logging.verbose( 'Creating scribbles from", "= np.asarray(gt_mask, dtype=np.int) if nb_objects is None: obj_ids = np.unique(annotations) obj_ids = obj_ids[(obj_ids", "2) t_start = time.time() S = self._acyclics_subgraphs(G) t = (time.time() - t_start) *", "scribble in the region that fails the most. # Arguments sequence: String. Name", "start_time = time.time() error_mask = (gt == obj_id) & (pred != obj_id) if", "skeleton mask into a graph: ' + '{:.3f} ms'.format(mask2graph_time * 1000), 2) t_start", "generate the scribble. If not given, the worst frame given by the jaccard", "if nb_objects is None: obj_ids = np.unique(annotations) obj_ids = obj_ids[(obj_ids > 0) &", "t_start) * 1000 logging.verbose( 'Time to split into connected components subgraphs ' +", "ms'.format(mask2graph_time * 1000), 2) t_start = time.time() S = self._acyclics_subgraphs(G) t = (time.time()", "a mask prediction, the robot will return a scribble in the region that", "a graph: ' + '{:.3f} ms'.format(mask2graph_time * 1000), 2) t_start = time.time() S", "to compute the longest path on the trees: {:.3f} ms'. format(t), 2) t_start", "mask prediction, the robot will return a scribble in the region that fails", "compute the longest path on the trees: {:.3f} ms'. format(t), 2) t_start =", "in range(nb_objects + 1)] # Infer height and width of the sequence h,", "for idx in longest_paths_idx] t = (time.time() - t_start) * 1000 logging.verbose( 'Time", "2) start_time = time.time() error_mask = (gt == obj_id) & (pred != obj_id)", "# Generate scribbles skel_mask = self._generate_scribble_mask(error_mask) skel_time = time.time() - start_time logging.verbose( 'Time", "value between [0, 1).') self.kernel_size = kernel_size self.max_kernel_radius = max_kernel_radius self.min_nb_nodes = min_nb_nodes", "2) if skel_mask.sum() == 0: continue G, P = self._mask2graph(skel_mask) mask2graph_time = time.time()", "scribbles data file for p in scribbles_paths: p /= img_shape path_data = {", "frame given by the jaccard will be used. # Returns dict: Return a", "the same data type and shape as `pred_masks`, one-hot vector for multi object", "0: continue G, P = self._mask2graph(skel_mask) mask2graph_time = time.time() - start_time - skel_time", "\"\"\" robot_start = time.time() predictions = np.asarray(pred_mask, dtype=np.int) annotations = np.asarray(gt_mask, dtype=np.int) if", "np ROBOT_DEFAULT_PARAMETERS = { 'kernel_size': .2, 'max_kernel_radius': 16, 'min_nb_nodes': 4, 'nb_points': 1000 }", "to interact with. pred_masks: Numpy Array. Array with the prediction masks. It must", "remove the cycles: {:.3f} ms'.format(t), 2) t_start = time.time() longest_paths_idx = [self._longest_path_in_tree(s) for", "nb_objects: Integer. Number of objects in the ground truth mask. If `None` the", "nb_objects = len(obj_ids) obj_ids = [i for i in range(nb_objects + 1)] #", "or kernel_size < 0: raise ValueError('kernel_size must be a value between [0, 1).')", "Numpy Array. Array with the ground truth of the sequence. It must have", "of the sequence h, w = annotations.shape img_shape = np.asarray([w, h], dtype=np.float) pred,", "a prediction. Given the sequence and a mask prediction, the robot will return", "be used. # Returns dict: Return a scribble (default representation). \"\"\" robot_start =", "= (time.time() - t_start) * 1000 logging.verbose( 'Time to split into connected components", "/= img_shape path_data = { 'path': p.tolist(), 'object_id': int(obj_id), 'start_time': start_time, 'end_time': end_time", "width of the sequence h, w = annotations.shape img_shape = np.asarray([w, h], dtype=np.float)", "one-hot vector for multi object gt_masks: Numpy Array. Array with the ground truth", "return a scribble in the region that fails the most. # Arguments sequence:", "- t_start) * 1000 logging.verbose( 'Time to compute the longest path on the", "Array with the prediction masks. It must be an integer array with shape", "p /= img_shape path_data = { 'path': p.tolist(), 'object_id': int(obj_id), 'start_time': start_time, 'end_time':", "Array. Array with the ground truth of the sequence. It must have the", "If `None` the value will be infered from `y_true`. Setting this value will", "kernel_size >= 1. or kernel_size < 0: raise ValueError('kernel_size must be a value", "kernel_size < 0: raise ValueError('kernel_size must be a value between [0, 1).') self.kernel_size", "pred, gt = predictions, annotations scribbles = [] for obj_id in obj_ids: logging.verbose(", "scribbles skel_mask = self._generate_scribble_mask(error_mask) skel_time = time.time() - start_time logging.verbose( 'Time to compute", "255)] nb_objects = len(obj_ids) obj_ids = [i for i in range(nb_objects + 1)]", "vector for multi object nb_objects: Integer. Number of objects in the ground truth", "'Creating scribbles from error mask at object_id={}'.format( obj_id), 2) start_time = time.time() error_mask", "for multi object gt_masks: Numpy Array. Array with the ground truth of the", "predictions = np.asarray(pred_mask, dtype=np.int) annotations = np.asarray(gt_mask, dtype=np.int) if nb_objects is None: obj_ids", "= time.time() - start_time - skel_time logging.verbose( 'Time to transform the skeleton mask", "with. pred_masks: Numpy Array. Array with the prediction masks. It must be an", "in longest_paths_idx] t = (time.time() - t_start) * 1000 logging.verbose( 'Time to compute", "[ bezier_curve(p, self.nb_points) for p in longest_paths ] t = (time.time() - t_start)", "davisinteractive.evaluation.service import EvaluationService import time import numpy as np ROBOT_DEFAULT_PARAMETERS = { 'kernel_size':", "Interactrobot(InteractiveScribblesRobot): def __init__(self, kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): \"\"\" Robot constructor \"\"\" super(Interactrobot, self).__init__()", "to transform the skeleton mask into a graph: ' + '{:.3f} ms'.format(mask2graph_time *", "that fails the most. # Arguments sequence: String. Name of the sequence to", "' + 'and remove the cycles: {:.3f} ms'.format(t), 2) t_start = time.time() longest_paths_idx", "Infer height and width of the sequence h, w = annotations.shape img_shape =", "annotations scribbles = [] for obj_id in obj_ids: logging.verbose( 'Creating scribbles from error", "time.time() - start_time logging.verbose( 'Time to compute the skeleton mask: {:.3f} ms'.format( skel_time", "[] for obj_id in obj_ids: logging.verbose( 'Creating scribbles from error mask at object_id={}'.format(", "'kernel_size': .2, 'max_kernel_radius': 16, 'min_nb_nodes': 4, 'nb_points': 1000 } class Interactrobot(InteractiveScribblesRobot): def __init__(self,", "objects in the ground truth mask. If `None` the value will be infered", "sequence. It must have the same data type and shape as `pred_masks`, one-hot", "skel_mask = self._generate_scribble_mask(error_mask) skel_time = time.time() - start_time logging.verbose( 'Time to compute the", "division from davisinteractive import logging from davisinteractive.metrics import batched_jaccard from davisinteractive.utils.operations import bezier_curve", "object_id={}'.format( obj_id), 2) start_time = time.time() error_mask = (gt == obj_id) & (pred", "logging from davisinteractive.metrics import batched_jaccard from davisinteractive.utils.operations import bezier_curve from davisinteractive.robot.interactive_robot import InteractiveScribblesRobot", "= {'scribbles': scribbles,} t = time.time() - robot_start logging.info(('The robot took {:.3f} s", "the bezier curves: {:.3f} ms'.format(t), 2) end_time = time.time() logging.verbose( 'Generating the scribble", "super(Interactrobot, self).__init__() if kernel_size >= 1. or kernel_size < 0: raise ValueError('kernel_size must", "== 0: continue G, P = self._mask2graph(skel_mask) mask2graph_time = time.time() - start_time -", "from __future__ import absolute_import, division from davisinteractive import logging from davisinteractive.metrics import batched_jaccard", "logging.verbose( 'Time to compute the bezier curves: {:.3f} ms'.format(t), 2) end_time = time.time()", "prediction masks. It must be an integer array with shape (H x W),", "1)] # Infer height and width of the sequence h, w = annotations.shape", "robot_start logging.info(('The robot took {:.3f} s to generate all the ' 'scribbles for", "the trees: {:.3f} ms'. format(t), 2) t_start = time.time() scribbles_paths = [ bezier_curve(p,", "(obj_ids < 255)] nb_objects = len(obj_ids) obj_ids = [i for i in range(nb_objects", "as `pred_masks`, one-hot vector for multi object nb_objects: Integer. Number of objects in", "and shape as `pred_masks`, one-hot vector for multi object nb_objects: Integer. Number of", "longest_paths = [P[idx] for idx in longest_paths_idx] t = (time.time() - t_start) *", "nb_objects is None: obj_ids = np.unique(annotations) obj_ids = obj_ids[(obj_ids > 0) & (obj_ids", "will be infered from `y_true`. Setting this value will speed up the computation.", "value will speed up the computation. frame: Integer. Frame to generate the scribble.", "error_mask = (gt == obj_id) & (pred != obj_id) if error_mask.sum() == 0:", "= [] for obj_id in obj_ids: logging.verbose( 'Creating scribbles from error mask at", "robot took {:.3f} s to generate all the ' 'scribbles for {} objects.').format(", "if kernel_size >= 1. or kernel_size < 0: raise ValueError('kernel_size must be a", "and width of the sequence h, w = annotations.shape img_shape = np.asarray([w, h],", "+ 'and remove the cycles: {:.3f} ms'.format(t), 2) t_start = time.time() longest_paths_idx =", "logging.verbose( 'Creating scribbles from error mask at object_id={}'.format( obj_id), 2) start_time = time.time()", "skel_time = time.time() - start_time logging.verbose( 'Time to compute the skeleton mask: {:.3f}", "t = (time.time() - t_start) * 1000 logging.verbose( 'Time to split into connected", "scribbles,} t = time.time() - robot_start logging.info(('The robot took {:.3f} s to generate", "the scribble. If not given, the worst frame given by the jaccard will", "scribbles from error mask at object_id={}'.format( obj_id), 2) start_time = time.time() error_mask =", "s to generate all the ' 'scribbles for {} objects.').format( t, nb_objects)) return", "truth mask. If `None` the value will be infered from `y_true`. Setting this", "for multi object nb_objects: Integer. Number of objects in the ground truth mask.", "= annotations.shape img_shape = np.asarray([w, h], dtype=np.float) pred, gt = predictions, annotations scribbles", "16, 'min_nb_nodes': 4, 'nb_points': 1000 } class Interactrobot(InteractiveScribblesRobot): def __init__(self, kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4,", "+ 'took {:.3f} ms'.format((end_time - start_time) * 1000), 2) # Generate scribbles data", ">= 1. or kernel_size < 0: raise ValueError('kernel_size must be a value between", "from davisinteractive.robot.interactive_robot import InteractiveScribblesRobot from davisinteractive.evaluation.service import EvaluationService import time import numpy as", "(gt == obj_id) & (pred != obj_id) if error_mask.sum() == 0: logging.info( 'Error", "(time.time() - t_start) * 1000 logging.verbose( 'Time to compute the bezier curves: {:.3f}", "Returns dict: Return a scribble (default representation). \"\"\" robot_start = time.time() predictions =", "bezier_curve from davisinteractive.robot.interactive_robot import InteractiveScribblesRobot from davisinteractive.evaluation.service import EvaluationService import time import numpy", "Return a scribble (default representation). \"\"\" robot_start = time.time() predictions = np.asarray(pred_mask, dtype=np.int)", "for i in range(nb_objects + 1)] # Infer height and width of the", "[i for i in range(nb_objects + 1)] # Infer height and width of", "the Scribble robot given a prediction. Given the sequence and a mask prediction,", "= time.time() - start_time logging.verbose( 'Time to compute the skeleton mask: {:.3f} ms'.format(", "{:.3f} ms'.format(t), 2) t_start = time.time() longest_paths_idx = [self._longest_path_in_tree(s) for s in S]", "for s in S] longest_paths = [P[idx] for idx in longest_paths_idx] t =", "the cycles: {:.3f} ms'.format(t), 2) t_start = time.time() longest_paths_idx = [self._longest_path_in_tree(s) for s", "if skel_mask.sum() == 0: continue G, P = self._mask2graph(skel_mask) mask2graph_time = time.time() -", "(H x W), one-hot vector for multi object gt_masks: Numpy Array. Array with", "= np.asarray(pred_mask, dtype=np.int) annotations = np.asarray(gt_mask, dtype=np.int) if nb_objects is None: obj_ids =", "'Time to compute the bezier curves: {:.3f} ms'.format(t), 2) end_time = time.time() logging.verbose(", "dtype=np.int) if nb_objects is None: obj_ids = np.unique(annotations) obj_ids = obj_ids[(obj_ids > 0)", "t = (time.time() - t_start) * 1000 logging.verbose( 'Time to compute the longest", "1000 logging.verbose( 'Time to compute the bezier curves: {:.3f} ms'.format(t), 2) end_time =", "InteractiveScribblesRobot from davisinteractive.evaluation.service import EvaluationService import time import numpy as np ROBOT_DEFAULT_PARAMETERS =", "skel_time * 1000), 2) if skel_mask.sum() == 0: continue G, P = self._mask2graph(skel_mask)", "one-hot vector for multi object nb_objects: Integer. Number of objects in the ground", "from davisinteractive.utils.operations import bezier_curve from davisinteractive.robot.interactive_robot import InteractiveScribblesRobot from davisinteractive.evaluation.service import EvaluationService import", "Robot constructor \"\"\" super(Interactrobot, self).__init__() if kernel_size >= 1. or kernel_size < 0:", "of object ID {} is empty. Skip object ID.'. format(obj_id)) continue # Generate", "p.tolist(), 'object_id': int(obj_id), 'start_time': start_time, 'end_time': end_time } scribbles.append(path_data) scribbles_data = {'scribbles': scribbles,}", "for object id {} '.format(obj_id) + 'took {:.3f} ms'.format((end_time - start_time) * 1000),", "the scribble for object id {} '.format(obj_id) + 'took {:.3f} ms'.format((end_time - start_time)", "scribbles_paths: p /= img_shape path_data = { 'path': p.tolist(), 'object_id': int(obj_id), 'start_time': start_time,", "class Interactrobot(InteractiveScribblesRobot): def __init__(self, kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): \"\"\" Robot constructor \"\"\" super(Interactrobot,", "= time.time() scribbles_paths = [ bezier_curve(p, self.nb_points) for p in longest_paths ] t", "4, 'nb_points': 1000 } class Interactrobot(InteractiveScribblesRobot): def __init__(self, kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): \"\"\"", "raise ValueError('kernel_size must be a value between [0, 1).') self.kernel_size = kernel_size self.max_kernel_radius", "shape (H x W), one-hot vector for multi object gt_masks: Numpy Array. Array", "- start_time) * 1000), 2) # Generate scribbles data file for p in", "t = time.time() - robot_start logging.info(('The robot took {:.3f} s to generate all", "format(t), 2) t_start = time.time() scribbles_paths = [ bezier_curve(p, self.nb_points) for p in", "__future__ import absolute_import, division from davisinteractive import logging from davisinteractive.metrics import batched_jaccard from", "multi object nb_objects: Integer. Number of objects in the ground truth mask. If", "nb_points=1000): \"\"\" Robot constructor \"\"\" super(Interactrobot, self).__init__() if kernel_size >= 1. or kernel_size", "kernel_size self.max_kernel_radius = max_kernel_radius self.min_nb_nodes = min_nb_nodes self.nb_points = nb_points def interact_singleimg(self, pred_mask,", "img_shape = np.asarray([w, h], dtype=np.float) pred, gt = predictions, annotations scribbles = []", "== 0: logging.info( 'Error mask of object ID {} is empty. Skip object", "= min_nb_nodes self.nb_points = nb_points def interact_singleimg(self, pred_mask, gt_mask, nb_objects=None,): \"\"\" Interaction of", "on the trees: {:.3f} ms'. format(t), 2) t_start = time.time() scribbles_paths = [", "start_time) * 1000), 2) # Generate scribbles data file for p in scribbles_paths:", "jaccard will be used. # Returns dict: Return a scribble (default representation). \"\"\"", "# Arguments sequence: String. Name of the sequence to interact with. pred_masks: Numpy", "'Error mask of object ID {} is empty. Skip object ID.'. format(obj_id)) continue", "up the computation. frame: Integer. Frame to generate the scribble. If not given,", "scribble (default representation). \"\"\" robot_start = time.time() predictions = np.asarray(pred_mask, dtype=np.int) annotations =", "mask of object ID {} is empty. Skip object ID.'. format(obj_id)) continue #", "\"\"\" Interaction of the Scribble robot given a prediction. Given the sequence and", "Generate scribbles data file for p in scribbles_paths: p /= img_shape path_data =", "for p in longest_paths ] t = (time.time() - t_start) * 1000 logging.verbose(", "to compute the skeleton mask: {:.3f} ms'.format( skel_time * 1000), 2) if skel_mask.sum()", "- t_start) * 1000 logging.verbose( 'Time to compute the bezier curves: {:.3f} ms'.format(t),", "by the jaccard will be used. # Returns dict: Return a scribble (default", "array with shape (H x W), one-hot vector for multi object gt_masks: Numpy", "error mask at object_id={}'.format( obj_id), 2) start_time = time.time() error_mask = (gt ==", "cycles: {:.3f} ms'.format(t), 2) t_start = time.time() longest_paths_idx = [self._longest_path_in_tree(s) for s in", "masks. It must be an integer array with shape (H x W), one-hot", "0) & (obj_ids < 255)] nb_objects = len(obj_ids) obj_ids = [i for i", "def __init__(self, kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): \"\"\" Robot constructor \"\"\" super(Interactrobot, self).__init__() if", "Generate scribbles skel_mask = self._generate_scribble_mask(error_mask) skel_time = time.time() - start_time logging.verbose( 'Time to", "with the ground truth of the sequence. It must have the same data", "'object_id': int(obj_id), 'start_time': start_time, 'end_time': end_time } scribbles.append(path_data) scribbles_data = {'scribbles': scribbles,} t", "a scribble (default representation). \"\"\" robot_start = time.time() predictions = np.asarray(pred_mask, dtype=np.int) annotations", "It must be an integer array with shape (H x W), one-hot vector", "and a mask prediction, the robot will return a scribble in the region", "region that fails the most. # Arguments sequence: String. Name of the sequence", "1000 logging.verbose( 'Time to compute the longest path on the trees: {:.3f} ms'.", "Scribble robot given a prediction. Given the sequence and a mask prediction, the", "If not given, the worst frame given by the jaccard will be used.", "range(nb_objects + 1)] # Infer height and width of the sequence h, w", "components subgraphs ' + 'and remove the cycles: {:.3f} ms'.format(t), 2) t_start =", "with the prediction masks. It must be an integer array with shape (H", "must have the same data type and shape as `pred_masks`, one-hot vector for", "time import numpy as np ROBOT_DEFAULT_PARAMETERS = { 'kernel_size': .2, 'max_kernel_radius': 16, 'min_nb_nodes':", "= time.time() S = self._acyclics_subgraphs(G) t = (time.time() - t_start) * 1000 logging.verbose(", "1000 logging.verbose( 'Time to split into connected components subgraphs ' + 'and remove", "the most. # Arguments sequence: String. Name of the sequence to interact with.", "the skeleton mask: {:.3f} ms'.format( skel_time * 1000), 2) if skel_mask.sum() == 0:", "curves: {:.3f} ms'.format(t), 2) end_time = time.time() logging.verbose( 'Generating the scribble for object", "{:.3f} ms'.format((end_time - start_time) * 1000), 2) # Generate scribbles data file for", "'nb_points': 1000 } class Interactrobot(InteractiveScribblesRobot): def __init__(self, kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): \"\"\" Robot", "the longest path on the trees: {:.3f} ms'. format(t), 2) t_start = time.time()", "davisinteractive.metrics import batched_jaccard from davisinteractive.utils.operations import bezier_curve from davisinteractive.robot.interactive_robot import InteractiveScribblesRobot from davisinteractive.evaluation.service", "- t_start) * 1000 logging.verbose( 'Time to split into connected components subgraphs '", "scribble. If not given, the worst frame given by the jaccard will be", "len(obj_ids) obj_ids = [i for i in range(nb_objects + 1)] # Infer height", "height and width of the sequence h, w = annotations.shape img_shape = np.asarray([w,", "annotations.shape img_shape = np.asarray([w, h], dtype=np.float) pred, gt = predictions, annotations scribbles =", "= time.time() error_mask = (gt == obj_id) & (pred != obj_id) if error_mask.sum()", "longest_paths ] t = (time.time() - t_start) * 1000 logging.verbose( 'Time to compute", "kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): \"\"\" Robot constructor \"\"\" super(Interactrobot, self).__init__() if kernel_size >=", "None: obj_ids = np.unique(annotations) obj_ids = obj_ids[(obj_ids > 0) & (obj_ids < 255)]", "1000), 2) # Generate scribbles data file for p in scribbles_paths: p /=", "from error mask at object_id={}'.format( obj_id), 2) start_time = time.time() error_mask = (gt", "time.time() S = self._acyclics_subgraphs(G) t = (time.time() - t_start) * 1000 logging.verbose( 'Time", "in obj_ids: logging.verbose( 'Creating scribbles from error mask at object_id={}'.format( obj_id), 2) start_time", "start_time logging.verbose( 'Time to compute the skeleton mask: {:.3f} ms'.format( skel_time * 1000),", "1. or kernel_size < 0: raise ValueError('kernel_size must be a value between [0,", "in the region that fails the most. # Arguments sequence: String. Name of", "img_shape path_data = { 'path': p.tolist(), 'object_id': int(obj_id), 'start_time': start_time, 'end_time': end_time }", "import EvaluationService import time import numpy as np ROBOT_DEFAULT_PARAMETERS = { 'kernel_size': .2,", "robot given a prediction. Given the sequence and a mask prediction, the robot", "time.time() predictions = np.asarray(pred_mask, dtype=np.int) annotations = np.asarray(gt_mask, dtype=np.int) if nb_objects is None:", "a value between [0, 1).') self.kernel_size = kernel_size self.max_kernel_radius = max_kernel_radius self.min_nb_nodes =", "& (obj_ids < 255)] nb_objects = len(obj_ids) obj_ids = [i for i in", "prediction. Given the sequence and a mask prediction, the robot will return a", "of the Scribble robot given a prediction. Given the sequence and a mask", "obj_ids = obj_ids[(obj_ids > 0) & (obj_ids < 255)] nb_objects = len(obj_ids) obj_ids", "min_nb_nodes self.nb_points = nb_points def interact_singleimg(self, pred_mask, gt_mask, nb_objects=None,): \"\"\" Interaction of the", "= len(obj_ids) obj_ids = [i for i in range(nb_objects + 1)] # Infer", "t_start = time.time() longest_paths_idx = [self._longest_path_in_tree(s) for s in S] longest_paths = [P[idx]", "longest_paths_idx] t = (time.time() - t_start) * 1000 logging.verbose( 'Time to compute the", "start_time, 'end_time': end_time } scribbles.append(path_data) scribbles_data = {'scribbles': scribbles,} t = time.time() -", "- start_time logging.verbose( 'Time to compute the skeleton mask: {:.3f} ms'.format( skel_time *", "in scribbles_paths: p /= img_shape path_data = { 'path': p.tolist(), 'object_id': int(obj_id), 'start_time':", "1000), 2) t_start = time.time() S = self._acyclics_subgraphs(G) t = (time.time() - t_start)", "np.unique(annotations) obj_ids = obj_ids[(obj_ids > 0) & (obj_ids < 255)] nb_objects = len(obj_ids)", "<reponame>yuk6heo/GIS-RAmap from __future__ import absolute_import, division from davisinteractive import logging from davisinteractive.metrics import", "t_start = time.time() S = self._acyclics_subgraphs(G) t = (time.time() - t_start) * 1000", "s in S] longest_paths = [P[idx] for idx in longest_paths_idx] t = (time.time()", "representation). \"\"\" robot_start = time.time() predictions = np.asarray(pred_mask, dtype=np.int) annotations = np.asarray(gt_mask, dtype=np.int)", "continue G, P = self._mask2graph(skel_mask) mask2graph_time = time.time() - start_time - skel_time logging.verbose(", "idx in longest_paths_idx] t = (time.time() - t_start) * 1000 logging.verbose( 'Time to", "nb_points def interact_singleimg(self, pred_mask, gt_mask, nb_objects=None,): \"\"\" Interaction of the Scribble robot given", "- start_time - skel_time logging.verbose( 'Time to transform the skeleton mask into a", "the ground truth mask. If `None` the value will be infered from `y_true`.", "the sequence. It must have the same data type and shape as `pred_masks`,", "+ 1)] # Infer height and width of the sequence h, w =", "ms'.format( skel_time * 1000), 2) if skel_mask.sum() == 0: continue G, P =", "be an integer array with shape (H x W), one-hot vector for multi", "infered from `y_true`. Setting this value will speed up the computation. frame: Integer.", "with shape (H x W), one-hot vector for multi object gt_masks: Numpy Array.", "Integer. Frame to generate the scribble. If not given, the worst frame given", "[P[idx] for idx in longest_paths_idx] t = (time.time() - t_start) * 1000 logging.verbose(", "EvaluationService import time import numpy as np ROBOT_DEFAULT_PARAMETERS = { 'kernel_size': .2, 'max_kernel_radius':", "p in longest_paths ] t = (time.time() - t_start) * 1000 logging.verbose( 'Time", "longest path on the trees: {:.3f} ms'. format(t), 2) t_start = time.time() scribbles_paths", "2) end_time = time.time() logging.verbose( 'Generating the scribble for object id {} '.format(obj_id)", "self.kernel_size = kernel_size self.max_kernel_radius = max_kernel_radius self.min_nb_nodes = min_nb_nodes self.nb_points = nb_points def", "the jaccard will be used. # Returns dict: Return a scribble (default representation).", "} scribbles.append(path_data) scribbles_data = {'scribbles': scribbles,} t = time.time() - robot_start logging.info(('The robot", "t_start = time.time() scribbles_paths = [ bezier_curve(p, self.nb_points) for p in longest_paths ]", "= { 'kernel_size': .2, 'max_kernel_radius': 16, 'min_nb_nodes': 4, 'nb_points': 1000 } class Interactrobot(InteractiveScribblesRobot):", "pred_mask, gt_mask, nb_objects=None,): \"\"\" Interaction of the Scribble robot given a prediction. Given", "nb_objects=None,): \"\"\" Interaction of the Scribble robot given a prediction. Given the sequence", "at object_id={}'.format( obj_id), 2) start_time = time.time() error_mask = (gt == obj_id) &", "to compute the bezier curves: {:.3f} ms'.format(t), 2) end_time = time.time() logging.verbose( 'Generating", "= self._acyclics_subgraphs(G) t = (time.time() - t_start) * 1000 logging.verbose( 'Time to split", "end_time } scribbles.append(path_data) scribbles_data = {'scribbles': scribbles,} t = time.time() - robot_start logging.info(('The", "{:.3f} ms'.format(t), 2) end_time = time.time() logging.verbose( 'Generating the scribble for object id", "import absolute_import, division from davisinteractive import logging from davisinteractive.metrics import batched_jaccard from davisinteractive.utils.operations", "* 1000), 2) # Generate scribbles data file for p in scribbles_paths: p", "} class Interactrobot(InteractiveScribblesRobot): def __init__(self, kernel_size=.2, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): \"\"\" Robot constructor \"\"\"", "'Time to split into connected components subgraphs ' + 'and remove the cycles:", "interact with. pred_masks: Numpy Array. Array with the prediction masks. It must be", "= predictions, annotations scribbles = [] for obj_id in obj_ids: logging.verbose( 'Creating scribbles", "self.max_kernel_radius = max_kernel_radius self.min_nb_nodes = min_nb_nodes self.nb_points = nb_points def interact_singleimg(self, pred_mask, gt_mask,", "S = self._acyclics_subgraphs(G) t = (time.time() - t_start) * 1000 logging.verbose( 'Time to", "ground truth of the sequence. It must have the same data type and", "connected components subgraphs ' + 'and remove the cycles: {:.3f} ms'.format(t), 2) t_start", "compute the bezier curves: {:.3f} ms'.format(t), 2) end_time = time.time() logging.verbose( 'Generating the", "' + '{:.3f} ms'.format(mask2graph_time * 1000), 2) t_start = time.time() S = self._acyclics_subgraphs(G)", "x W), one-hot vector for multi object gt_masks: Numpy Array. Array with the", "P = self._mask2graph(skel_mask) mask2graph_time = time.time() - start_time - skel_time logging.verbose( 'Time to", "self._generate_scribble_mask(error_mask) skel_time = time.time() - start_time logging.verbose( 'Time to compute the skeleton mask:", "the robot will return a scribble in the region that fails the most.", "h], dtype=np.float) pred, gt = predictions, annotations scribbles = [] for obj_id in", "for obj_id in obj_ids: logging.verbose( 'Creating scribbles from error mask at object_id={}'.format( obj_id),", "= self._generate_scribble_mask(error_mask) skel_time = time.time() - start_time logging.verbose( 'Time to compute the skeleton", "Array. Array with the prediction masks. It must be an integer array with", "davisinteractive.utils.operations import bezier_curve from davisinteractive.robot.interactive_robot import InteractiveScribblesRobot from davisinteractive.evaluation.service import EvaluationService import time", "# Returns dict: Return a scribble (default representation). \"\"\" robot_start = time.time() predictions", "ID {} is empty. Skip object ID.'. format(obj_id)) continue # Generate scribbles skel_mask", "1).') self.kernel_size = kernel_size self.max_kernel_radius = max_kernel_radius self.min_nb_nodes = min_nb_nodes self.nb_points = nb_points", "ms'.format(t), 2) t_start = time.time() longest_paths_idx = [self._longest_path_in_tree(s) for s in S] longest_paths", "Frame to generate the scribble. If not given, the worst frame given by", "'.format(obj_id) + 'took {:.3f} ms'.format((end_time - start_time) * 1000), 2) # Generate scribbles", "Arguments sequence: String. Name of the sequence to interact with. pred_masks: Numpy Array.", "into a graph: ' + '{:.3f} ms'.format(mask2graph_time * 1000), 2) t_start = time.time()", "the skeleton mask into a graph: ' + '{:.3f} ms'.format(mask2graph_time * 1000), 2)", "compute the skeleton mask: {:.3f} ms'.format( skel_time * 1000), 2) if skel_mask.sum() ==", "mask. If `None` the value will be infered from `y_true`. Setting this value", "scribbles.append(path_data) scribbles_data = {'scribbles': scribbles,} t = time.time() - robot_start logging.info(('The robot took", "obj_id in obj_ids: logging.verbose( 'Creating scribbles from error mask at object_id={}'.format( obj_id), 2)", "= [P[idx] for idx in longest_paths_idx] t = (time.time() - t_start) * 1000" ]
[ "VH_ROOT_KEY from pyramid.interfaces import ITraverser from zope import interface from zope.component import queryMultiAdapter", "__future__ import division from __future__ import print_function from __future__ import absolute_import from pyramid", "cover return {'context': ob, 'view_name': segment[2:], 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx +", "but safely: if the handlers themselves raise a location error, turn that into", "import VH_ROOT_KEY from pyramid.interfaces import ITraverser from zope import interface from zope.component import", "or '/' subpath = matchdict.get('subpath', ()) if not is_nonstr_iter(subpath): # pragma: no cover", "from __future__ import absolute_import from pyramid import traversal from pyramid.compat import is_nonstr_iter from", "vpath_tuple: # JAM: Fire traversal events, mainly so sites get installed. See #", "1:], 'traversed': vpath_tuple[:vroot_idx + i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root}", "installed component registry # instead of the request registry (which # is the", "the request registry (which # is the global component registry if # pyramid", "called here. If they can't take # two arguments, then we bail. Sucks.", "pyramid.interfaces import VH_ROOT_KEY from pyramid.interfaces import ITraverser from zope import interface from zope.component", "two by making the pyramid request implement the right thing. \"\"\" def __init__(self,", "resource(_zresource): \"\"\" Handles resource lookup in a way compatible with :mod:`zope.browserresource`. This package", "= self.root ob = vroot = root if vpath == '/': # invariant:", "means they get called here. If they can't take # two arguments, then", "a type of KeyError. The DefaultTraversable turns # plain KeyError and TypeErrors into", "implement the right thing. \"\"\" def __init__(self, context, request): request = IBrowserRequest(request) if", "the superclass implementation is entirely monolithic # and we so we cannot reuse", "decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple = split_path_info(vroot_path) # both will (must) be unicode or asciistr vpath", "return {'context': ob, 'view_name': empty, 'subpath': subpath, 'traversed': vpath_tuple, 'virtual_root': vroot, 'virtual_root_path': vroot_tuple,", "from pyramid.interfaces import ITraverser from zope import interface from zope.component import queryMultiAdapter from", "# which means they get called here. If they can't take # two", "= split_path_info(subpath) else: # pragma: no cover # this request did not match", "case, we let traversing handle it, because it needs a named adapter #", "import is_nonstr_iter from pyramid.compat import decode_path_info from pyramid.exceptions import URLDecodeError from pyramid.httpexceptions import", "vpath_tuple = () else: i = 0 view_selector = self.VIEW_SELECTOR # A list", "pattern, plus the support of namespace lookups (:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`). As this object", "from pyramid. environ = request.environ if request.matchdict is not None: matchdict = request.matchdict", "a setup or programmer error logger.debug(\"LocationError from traverse subscribers\", exc_info=True) raise HTTPNotFound(\"Traversal failed\")", "act of # traversing has changed the site manager; # zope.site.site.threadSiteSubscriber will #", ":meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" # JAM: Unfortunately, the superclass implementation is entirely monolithic # and", "IDefaultBrowserLayer from zope.traversing.namespace import resource as _zresource lineage = traversal.lineage find_interface = traversal.find_interface", "# (In the namespace case, we let traversing handle it, because it needs", "route subpath = () try: # empty if mounted under a path in", "as it would in # plain zope traversal. (XXX: Why not?) if segment.startswith(view_selector):", "are. See our # configure.zcml for what is. # JAM: Damn stupid implementation", "for example path = decode_path_info(environ['PATH_INFO'] or '/') except KeyError: path = '/' except", "from pyramid import traversal from pyramid.compat import is_nonstr_iter from pyramid.compat import decode_path_info from", "a traversable /except/ when a namespace is found. # therefore, we explicitly query", "find a traversable /except/ when a namespace is found. # therefore, we explicitly", "which means they get called here. If they can't take # two arguments,", "__future__ import print_function from __future__ import absolute_import from pyramid import traversal from pyramid.compat", "it fires :obj:`~.IBeforeTraverseEvent` events. If you either load the configuration from :mod:`zope.app.publication` or", "would install security proxies along the way. We probably don't need to #", "() vpath = path vroot_idx = -1 root = self.root ob = vroot", "a {traverse}) # routing has already decoded these elements, so we just #", "when a namespace is found. # therefore, we explicitly query for the multi", "is not a *subpath stararg (just a {subpath}) # routing has already decoded", "the :mod:`zope.traversing.api` machinery instead of (only) dictionary lookups. This provides is with the", "As this object traverses, it fires :obj:`~.IBeforeTraverseEvent` events. If you either load the", "Because handlers are deliberately doing this, we stop traversal and abort rather than", "it. Be sure not to fire multiple times # for this (E.g., the", "case the act of # traversing has changed the site manager; # zope.site.site.threadSiteSubscriber", "will # do this for each BeforeTraverseEvent # that's fired (though that's not", "resource lookup in a way compatible with :mod:`zope.browserresource`. This package registers resources as", "coding: utf-8 -*- \"\"\" Support for resource tree traversal. \"\"\" from __future__ import", "if the handlers themselves raise a location error, turn that into a HTTP", "# configure.zcml for what is. # JAM: Damn stupid implementation of traversePathElement ignores", "as multi-adapters. # None of the default namespaces are. See our # configure.zcml", "i += 1 # JAM: Also fire before traversal for the actual context", "root} class resource(_zresource): \"\"\" Handles resource lookup in a way compatible with :mod:`zope.browserresource`.", "# need to join them path = '/'.join(path) or '/' subpath = matchdict.get('subpath',", "try: # empty if mounted under a path in mod_wsgi, for example path", "tuple vpath_tuple = () else: i = 0 view_selector = self.VIEW_SELECTOR # A", "\"\"\" A :class:`pyramid.interfaces.ITraverser` based on pyramid's default traverser, but modified to use the", "= vpath_tuple[i + 1:] next_ob = ztraversing.traversePathElement(ob, segment, remaining_path, traversable=traversable, request=request) if remaining_path", "a location error, turn that into a HTTP 404 exception. Because handlers are", "from zope.traversing import api as ztraversing from zope.traversing.interfaces import ITraversable from zope.traversing.interfaces import", "if not is_nonstr_iter(subpath): # pragma: no cover # this is not a *subpath", "None if segment and segment[0] not in '+@' \\ and not ITraversable.providedBy(ob): try:", "zope.site.site.threadSiteSubscriber will # do this for each BeforeTraverseEvent # that's fired (though that's", "= matchdict.get('traverse', '/') or '/' if is_nonstr_iter(path): # this is a *traverse stararg", "import interface from zope.component import queryMultiAdapter from zope.event import notify from zope.location.interfaces import", "request=request) if remaining_path != vpath_tuple[i + 1:]: # Is this if check necessary?", "actually traverse into it. Be sure not to fire multiple times # for", "queryMultiAdapter from zope.event import notify from zope.location.interfaces import LocationError from zope.traversing import api", "zope.location.interfaces import LocationError from zope.traversing import api as ztraversing from zope.traversing.interfaces import ITraversable", "that's not # registered by default). traversable = queryMultiAdapter((ob, request), ITraversable) except TypeError:", "from traverse subscribers\", exc_info=True) raise HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A :class:`pyramid.interfaces.ITraverser`", "find a view and context, etc. This is limiting, but safe. \"\"\" try:", "segment in vpath_tuple: # JAM: Fire traversal events, mainly so sites get installed.", "absolute_import from pyramid import traversal from pyramid.compat import is_nonstr_iter from pyramid.compat import decode_path_info", "ob = vroot = root if vpath == '/': # invariant: vpath must", "string, so we just need # to split it subpath = split_path_info(subpath) else:", "if segment.startswith(view_selector): # pragma: no cover return {'context': ob, 'view_name': segment[2:], 'subpath': vpath_tuple[i", "a HTTP 404 exception. Because handlers are deliberately doing this, we stop traversal", "vroot = root if vpath == '/': # invariant: vpath must not be", "a BeforeTraverseEvent, but safely: if the handlers themselves raise a location error, turn", "lookup in a way compatible with :mod:`zope.browserresource`. This package registers resources as named", "let traversing handle it, because it needs a named adapter # after parsing)", "'root': root} try: # JAM: This is where we differ. instead of using", "*subpath stararg (just a {subpath}) # routing has already decoded this string, so", "DefaultTraversable turns # plain KeyError and TypeErrors into LocationError. return {'context': ob, 'view_name':", "multiple times # for this (E.g., the root). This logic is complicated by", "support of namespace lookups (:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`). As this object traverses, it fires", "request implement the right thing. \"\"\" def __init__(self, context, request): request = IBrowserRequest(request)", "using and the code is lifted directly from pyramid. environ = request.environ if", "each BeforeTraverseEvent # that's fired (though that's not # registered by default). traversable", "Unfortunately, the superclass implementation is entirely monolithic # and we so we cannot", "JAM: Fire traversal events, mainly so sites get installed. See # zope.publisher.base. _notify_before_traverse_event(ob,", "of # traversing has changed the site manager; # zope.site.site.threadSiteSubscriber will # do", "traversal. (XXX: Why not?) if segment.startswith(view_selector): # pragma: no cover return {'context': ob,", "'/' subpath = matchdict.get('subpath', ()) if not is_nonstr_iter(subpath): # pragma: no cover #", "flexibility of the :obj:`zope.traversing.interfaces.ITraversable` adapter pattern, plus the support of namespace lookups (:func:`zope.traversing.namespace.nsParse`", "to traversal_path if we know it's going # to return the empty tuple", "zope.traversing.interfaces import BeforeTraverseEvent from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.traversing.namespace", "# HTTP_X_VHM_ROOT vroot_path = decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple = split_path_info(vroot_path) # both will (must) be", "assign vpath_tuple[i + 1:] = remaining_path except LocationError: # LocationError is a type", "be made the current site. \"\"\" def __init__(self, root): traversal.ResourceTreeTraverser.__init__(self, root) def __call__(self,", "we use the traversing machinery. # The zope app would use IPublishTraverser, which", "is_nonstr_iter(subpath): # pragma: no cover # this is not a *subpath stararg (just", "dictionary lookups. This provides is with the flexibility of the :obj:`zope.traversing.interfaces.ITraversable` adapter pattern,", "traversal and abort rather than try to return an information dictionary and find", "= vroot_path + path vroot_idx = len(vroot_tuple) - 1 else: vroot_tuple = ()", "__future__ import absolute_import from pyramid import traversal from pyramid.compat import is_nonstr_iter from pyramid.compat", "is where we differ. instead of using __getitem__, # we use the traversing", "the request here, we require all traversers # (including the namespace traversers) to", "registered as multi-adapters. # None of the default namespaces are. See our #", "this for each BeforeTraverseEvent # that's fired (though that's not # registered by", "404 exception. Because handlers are deliberately doing this, we stop traversal and abort", "no cover return {'context': ob, 'view_name': segment[2:], 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx", "next_ob = ztraversing.traversePathElement(ob, segment, remaining_path, traversable=traversable, request=request) if remaining_path != vpath_tuple[i + 1:]:", "{'context': ob, 'view_name': empty, 'subpath': subpath, 'traversed': vpath_tuple, 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root':", "'view_name': segment[2:], 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i + 1], 'virtual_root':", "_notify_before_traverse_event(ob, request) # JAM: Notice that checking for '@@' is special cased, and", "= traversal.lineage find_interface = traversal.find_interface empty = traversal.empty split_path_info = traversal.split_path_info logger =", "to subscribe to this event, then any Zope site managers found along the", "1:] = remaining_path except LocationError: # LocationError is a type of KeyError. The", "# zope.publisher.base. _notify_before_traverse_event(ob, request) # JAM: Notice that checking for '@@' is special", "def _notify_before_traverse_event(ob, request): \"\"\" Notifies a BeforeTraverseEvent, but safely: if the handlers themselves", "This is where we differ. instead of using __getitem__, # we use the", "import ITraversable from zope.traversing.interfaces import BeforeTraverseEvent from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import", "adapter ourself in the non-namespace case # (In the namespace case, we let", "not ITraversable.providedBy(ob): try: # Use the installed component registry # instead of the", "if remaining_path != vpath_tuple[i + 1:]: # Is this if check necessary? It", "pragma: no cover # HTTP_X_VHM_ROOT vroot_path = decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple = split_path_info(vroot_path) # both", "already decoded these elements, so we just # need to join them path", "1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} if i == vroot_idx: # pragma:", "vroot, 'virtual_root_path': vroot_tuple, 'root': root} try: # JAM: This is where we differ.", "we just # need to join them path = '/'.join(path) or '/' subpath", "matchdict = request.matchdict path = matchdict.get('traverse', '/') or '/' if is_nonstr_iter(path): # this", "thing. \"\"\" def __init__(self, context, request): request = IBrowserRequest(request) if not IDefaultBrowserLayer.providedBy(request): interface.alsoProvides(request,", "1 # JAM: Also fire before traversal for the actual context item, since", "# prevent a call to traversal_path if we know it's going # to", "are # original. # JAM: Note the abundance of no covers. These are", "bail. Sucks. pass remaining_path = vpath_tuple[i + 1:] next_ob = ztraversing.traversePathElement(ob, segment, remaining_path,", "-*- \"\"\" Support for resource tree traversal. \"\"\" from __future__ import division from", "using __getitem__, # we use the traversing machinery. # The zope app would", "making the pyramid request implement the right thing. \"\"\" def __init__(self, context, request):", "of it. Instead, # we copy-and-paste it. Unless otherwise noted, comments below are", "next_ob i += 1 # JAM: Also fire before traversal for the actual", "is not None: matchdict = request.matchdict path = matchdict.get('traverse', '/') or '/' if", "{traverse}) # routing has already decoded these elements, so we just # need", "raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason) if VH_ROOT_KEY in environ: # pragma: no", "# JAM: Fire traversal events, mainly so sites get installed. See # zope.publisher.base.", "pragma: no cover return {'context': ob, 'view_name': segment[2:], 'subpath': vpath_tuple[i + 1:], 'traversed':", "= decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple = split_path_info(vroot_path) # both will (must) be unicode or asciistr", "mounted under a path in mod_wsgi, for example path = decode_path_info(environ['PATH_INFO'] or '/')", "ob = next_ob i += 1 # JAM: Also fire before traversal for", "so we just # need to join them path = '/'.join(path) or '/'", "the current site. \"\"\" def __init__(self, root): traversal.ResourceTreeTraverser.__init__(self, root) def __call__(self, request): #", "be empty # prevent a call to traversal_path if we know it's going", "import ITraverser from zope import interface from zope.component import queryMultiAdapter from zope.event import", "registry # instead of the request registry (which # is the global component", "1:]: # Is this if check necessary? It would be faster to #", "then we bail. Sucks. pass remaining_path = vpath_tuple[i + 1:] next_ob = ztraversing.traversePathElement(ob,", "empty tuple vpath_tuple = () else: i = 0 view_selector = self.VIEW_SELECTOR #", "next_ob ob = next_ob i += 1 # JAM: Also fire before traversal", "from zope.traversing.namespace import resource as _zresource lineage = traversal.lineage find_interface = traversal.find_interface empty", "\"\"\" def __init__(self, context, request): request = IBrowserRequest(request) if not IDefaultBrowserLayer.providedBy(request): interface.alsoProvides(request, IDefaultBrowserLayer)", "if request.matchdict is not None: matchdict = request.matchdict path = matchdict.get('traverse', '/') or", "from zope.traversing.interfaces import ITraversable from zope.traversing.interfaces import BeforeTraverseEvent from zope.publisher.interfaces.browser import IBrowserRequest from", "import resource as _zresource lineage = traversal.lineage find_interface = traversal.find_interface empty = traversal.empty", "stop traversal and abort rather than try to return an information dictionary and", "Support for resource tree traversal. \"\"\" from __future__ import division from __future__ import", "# plain KeyError and TypeErrors into LocationError. return {'context': ob, 'view_name': segment, 'subpath':", "install security proxies along the way. We probably don't need to # do", "this (E.g., the root). This logic is complicated by the # multi-returns above.", "safely: if the handlers themselves raise a location error, turn that into a", "'/') or '/' if is_nonstr_iter(path): # this is a *traverse stararg (not a", "= '/'.join(path) or '/' subpath = matchdict.get('subpath', ()) if not is_nonstr_iter(subpath): # pragma:", "implementation of traversePathElement ignores # the request argument to find a traversable /except/", "standalone registry) in case the act of # traversing has changed the site", "pragma: no cover vroot = next_ob ob = next_ob i += 1 #", ":mod:`zope.app.publication` or manually enable the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to subscribe to this event, then", "view_selector = self.VIEW_SELECTOR # A list so that remaining_path can be modified vpath_tuple", "!= vpath_tuple[i + 1:]: # Is this if check necessary? It would be", "location error, turn that into a HTTP 404 exception. Because handlers are deliberately", "= traversal.empty split_path_info = traversal.split_path_info logger = __import__('logging').getLogger(__name__) __all__ = [ 'ZopeResourceTreeTraverser', 'resource',", "of the :obj:`zope.traversing.interfaces.ITraversable` adapter pattern, plus the support of namespace lookups (:func:`zope.traversing.namespace.nsParse` and", "ITraversable from zope.traversing.interfaces import BeforeTraverseEvent from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer", "= -1 root = self.root ob = vroot = root if vpath ==", "except KeyError: path = '/' except UnicodeDecodeError as e: raise URLDecodeError(e.encoding, e.object, e.start,", "invariant: vpath must not be empty # prevent a call to traversal_path if", "it, because it needs a named adapter # after parsing) traversable = None", "These are for features we are # not currently using and the code", "We probably don't need to # do that? TODO: # NOTE: By passing", "as _zresource lineage = traversal.lineage find_interface = traversal.find_interface empty = traversal.empty split_path_info =", "from pyramid.exceptions import URLDecodeError from pyramid.httpexceptions import HTTPNotFound from pyramid.interfaces import VH_ROOT_KEY from", "# pragma: no cover # HTTP_X_VHM_ROOT vroot_path = decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple = split_path_info(vroot_path) #", "get called here. If they can't take # two arguments, then we bail.", "LocationError. return {'context': ob, 'view_name': segment, 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx +", "normal namespace lookup as it would in # plain zope traversal. (XXX: Why", "# this is not a *subpath stararg (just a {subpath}) # routing has", "if is_nonstr_iter(path): # this is a *traverse stararg (not a {traverse}) # routing", "import notify from zope.location.interfaces import LocationError from zope.traversing import api as ztraversing from", "traversable /except/ when a namespace is found. # therefore, we explicitly query for", "from __future__ import print_function from __future__ import absolute_import from pyramid import traversal from", "before traversal for the actual context item, since we # won't actually traverse", ":obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to subscribe to this event, then any Zope site managers found", "from zope.event import notify from zope.location.interfaces import LocationError from zope.traversing import api as", "require all traversers # (including the namespace traversers) to be registered as multi-adapters.", "# JAM: Also fire before traversal for the actual context item, since we", "import absolute_import from pyramid import traversal from pyramid.compat import is_nonstr_iter from pyramid.compat import", "# this request did not match a route subpath = () try: #", "return an information dictionary and find a view and context, etc. This is", "e.start, e.end, e.reason) if VH_ROOT_KEY in environ: # pragma: no cover # HTTP_X_VHM_ROOT", "'ZopeResourceTreeTraverser', 'resource', ] def _notify_before_traverse_event(ob, request): \"\"\" Notifies a BeforeTraverseEvent, but safely: if", "traversal. \"\"\" from __future__ import division from __future__ import print_function from __future__ import", "we know it's going # to return the empty tuple vpath_tuple = ()", "so we cannot reuse any part of it. Instead, # we copy-and-paste it.", "to find a traversable /except/ when a namespace is found. # therefore, we", "cover # HTTP_X_VHM_ROOT vroot_path = decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple = split_path_info(vroot_path) # both will (must)", "LocationError from zope.traversing import api as ztraversing from zope.traversing.interfaces import ITraversable from zope.traversing.interfaces", "vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple,", "'traversed': vpath_tuple[:vroot_idx + i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} try:", "the actual context item, since we # won't actually traverse into it. Be", "None: matchdict = request.matchdict path = matchdict.get('traverse', '/') or '/' if is_nonstr_iter(path): #", "going # to return the empty tuple vpath_tuple = () else: i =", "- 1 else: vroot_tuple = () vpath = path vroot_idx = -1 root", "Note the abundance of no covers. These are for features we are #", "(though that's not # registered by default). traversable = queryMultiAdapter((ob, request), ITraversable) except", "TypeErrors into LocationError. return {'context': ob, 'view_name': segment, 'subpath': vpath_tuple[i + 1:], 'traversed':", "If you either load the configuration from :mod:`zope.app.publication` or manually enable the :obj:`zope.site.site.threadSiteSubscriber", "# pragma: no cover # this request did not match a route subpath", "# standalone registry) in case the act of # traversing has changed the", "'virtual_root_path': vroot_tuple, 'root': root} try: # JAM: This is where we differ. instead", "+ i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} if i ==", "the namespace case, we let traversing handle it, because it needs a named", "See # zope.publisher.base. _notify_before_traverse_event(ob, request) # JAM: Notice that checking for '@@' is", "import decode_path_info from pyramid.exceptions import URLDecodeError from pyramid.httpexceptions import HTTPNotFound from pyramid.interfaces import", "Sucks. pass remaining_path = vpath_tuple[i + 1:] next_ob = ztraversing.traversePathElement(ob, segment, remaining_path, traversable=traversable,", "in '+@' \\ and not ITraversable.providedBy(ob): try: # Use the installed component registry", "fires :obj:`~.IBeforeTraverseEvent` events. If you either load the configuration from :mod:`zope.app.publication` or manually", "Zope site managers found along the way will be made the current site.", "in vpath_tuple: # JAM: Fire traversal events, mainly so sites get installed. See", "of traversePathElement ignores # the request argument to find a traversable /except/ when", "e.reason) if VH_ROOT_KEY in environ: # pragma: no cover # HTTP_X_VHM_ROOT vroot_path =", "vroot, 'virtual_root_path': vroot_tuple, 'root': root} class resource(_zresource): \"\"\" Handles resource lookup in a", "under a path in mod_wsgi, for example path = decode_path_info(environ['PATH_INFO'] or '/') except", "Notice that checking for '@@' is special cased, and # doesn't go through", "path = decode_path_info(environ['PATH_INFO'] or '/') except KeyError: path = '/' except UnicodeDecodeError as", "they get called here. If they can't take # two arguments, then we", "This logic is complicated by the # multi-returns above. _notify_before_traverse_event(ob, request) return {'context':", "= matchdict.get('subpath', ()) if not is_nonstr_iter(subpath): # pragma: no cover # this is", "api as ztraversing from zope.traversing.interfaces import ITraversable from zope.traversing.interfaces import BeforeTraverseEvent from zope.publisher.interfaces.browser", "no cover # this is not a *subpath stararg (just a {subpath}) #", "the namespace traversers) to be registered as multi-adapters. # None of the default", "ob, 'view_name': segment[2:], 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i + 1],", "that remaining_path can be modified vpath_tuple = list(split_path_info(vpath)) for segment in vpath_tuple: #", "a *subpath stararg (just a {subpath}) # routing has already decoded this string,", "the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to subscribe to this event, then any Zope site managers", "traversable = None if segment and segment[0] not in '+@' \\ and not", "load the configuration from :mod:`zope.app.publication` or manually enable the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to subscribe", "app would use IPublishTraverser, which # would install security proxies along the way.", "pyramid's default traverser, but modified to use the :mod:`zope.traversing.api` machinery instead of (only)", "if mounted under a path in mod_wsgi, for example path = decode_path_info(environ['PATH_INFO'] or", "explicitly query for the multi adapter ourself in the non-namespace case # (In", "path vroot_idx = -1 root = self.root ob = vroot = root if", "fire before traversal for the actual context item, since we # won't actually", "vroot_idx = len(vroot_tuple) - 1 else: vroot_tuple = () vpath = path vroot_idx", "this if check necessary? It would be faster to # always assign vpath_tuple[i", "is found. # therefore, we explicitly query for the multi adapter ourself in", "traversing handle it, because it needs a named adapter # after parsing) traversable", "If they can't take # two arguments, then we bail. Sucks. pass remaining_path", "so we just need # to split it subpath = split_path_info(subpath) else: #", "vroot_path + path vroot_idx = len(vroot_tuple) - 1 else: vroot_tuple = () vpath", "checking for '@@' is special cased, and # doesn't go through the normal", "asciistr vpath = vroot_path + path vroot_idx = len(vroot_tuple) - 1 else: vroot_tuple", "along the way. We probably don't need to # do that? TODO: #", "ourself in the non-namespace case # (In the namespace case, we let traversing", "+ 1:]: # Is this if check necessary? It would be faster to", "'traversed': vpath_tuple, 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} class resource(_zresource): \"\"\" Handles resource", "Some things are registered for \"*\" (DefaultTraversable) # which means they get called", "Instead, # we copy-and-paste it. Unless otherwise noted, comments below are # original.", "would in # plain zope traversal. (XXX: Why not?) if segment.startswith(view_selector): # pragma:", "are registered for \"*\" (DefaultTraversable) # which means they get called here. If", "+ 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} if i == vroot_idx: #", "path in mod_wsgi, for example path = decode_path_info(environ['PATH_INFO'] or '/') except KeyError: path", "# The zope app would use IPublishTraverser, which # would install security proxies", "for the actual context item, since we # won't actually traverse into it.", "way, or a # standalone registry) in case the act of # traversing", "or '/') except KeyError: path = '/' except UnicodeDecodeError as e: raise URLDecodeError(e.encoding,", "traversal.split_path_info logger = __import__('logging').getLogger(__name__) __all__ = [ 'ZopeResourceTreeTraverser', 'resource', ] def _notify_before_traverse_event(ob, request):", "= next_ob i += 1 # JAM: Also fire before traversal for the", "= () vpath = path vroot_idx = -1 root = self.root ob =", "namespaces are. See our # configure.zcml for what is. # JAM: Damn stupid", "machinery. # The zope app would use IPublishTraverser, which # would install security", "would be faster to # always assign vpath_tuple[i + 1:] = remaining_path except", "matchdict.get('traverse', '/') or '/' if is_nonstr_iter(path): # this is a *traverse stararg (not", "@interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A :class:`pyramid.interfaces.ITraverser` based on pyramid's default traverser, but modified", "proxies along the way. We probably don't need to # do that? TODO:", "# do that? TODO: # NOTE: By passing the request here, we require", "is with the flexibility of the :obj:`zope.traversing.interfaces.ITraversable` adapter pattern, plus the support of", "traversing machinery. # The zope app would use IPublishTraverser, which # would install", "__call__(self, request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" # JAM: Unfortunately, the superclass", "def __call__(self, request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" # JAM: Unfortunately, the", "pyramid.compat import is_nonstr_iter from pyramid.compat import decode_path_info from pyramid.exceptions import URLDecodeError from pyramid.httpexceptions", "= ztraversing.traversePathElement(ob, segment, remaining_path, traversable=traversable, request=request) if remaining_path != vpath_tuple[i + 1:]: #", "zope.traversing.interfaces import ITraversable from zope.traversing.interfaces import BeforeTraverseEvent from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser", "of the request registry (which # is the global component registry if #", "code is lifted directly from pyramid. environ = request.environ if request.matchdict is not", "found. # therefore, we explicitly query for the multi adapter ourself in the", "segment and segment[0] not in '+@' \\ and not ITraversable.providedBy(ob): try: # Use", ":func:`zope.traversing.namespace.namespaceLookup`). As this object traverses, it fires :obj:`~.IBeforeTraverseEvent` events. If you either load", "this object traverses, it fires :obj:`~.IBeforeTraverseEvent` events. If you either load the configuration", "the way. We probably don't need to # do that? TODO: # NOTE:", "# (including the namespace traversers) to be registered as multi-adapters. # None of", "# pragma: no cover # this is not a *subpath stararg (just a", "ITraversable.providedBy(ob): try: # Use the installed component registry # instead of the request", "+ i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} try: # JAM:", "vpath_tuple[:vroot_idx + i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} if i", "# registered by default). traversable = queryMultiAdapter((ob, request), ITraversable) except TypeError: # Some", "events, mainly so sites get installed. See # zope.publisher.base. _notify_before_traverse_event(ob, request) # JAM:", "tree traversal. \"\"\" from __future__ import division from __future__ import print_function from __future__", "it needs a named adapter # after parsing) traversable = None if segment", "the configuration from :mod:`zope.app.publication` or manually enable the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to subscribe to", "cannot reuse any part of it. Instead, # we copy-and-paste it. Unless otherwise", "except TypeError: # Some things are registered for \"*\" (DefaultTraversable) # which means", "here. If they can't take # two arguments, then we bail. Sucks. pass", "subpath = () try: # empty if mounted under a path in mod_wsgi,", "# pyramid was configured that way, or a # standalone registry) in case", "i = 0 view_selector = self.VIEW_SELECTOR # A list so that remaining_path can", "lifted directly from pyramid. environ = request.environ if request.matchdict is not None: matchdict", "by the # multi-returns above. _notify_before_traverse_event(ob, request) return {'context': ob, 'view_name': empty, 'subpath':", "\"\"\" from __future__ import division from __future__ import print_function from __future__ import absolute_import", "IPublishTraverser, which # would install security proxies along the way. We probably don't", "object traverses, it fires :obj:`~.IBeforeTraverseEvent` events. If you either load the configuration from", "the two by making the pyramid request implement the right thing. \"\"\" def", "the site manager; # zope.site.site.threadSiteSubscriber will # do this for each BeforeTraverseEvent #", "error, turn that into a HTTP 404 exception. Because handlers are deliberately doing", "package registers resources as named adapters from :class:`.IDefaultBrowserLayer` to Interface. We connect the", "# doesn't go through the normal namespace lookup as it would in #", "for '@@' is special cased, and # doesn't go through the normal namespace", "from zope.traversing.interfaces import BeforeTraverseEvent from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from", "ignores # the request argument to find a traversable /except/ when a namespace", "as named adapters from :class:`.IDefaultBrowserLayer` to Interface. We connect the two by making", "traversable = queryMultiAdapter((ob, request), ITraversable) except TypeError: # Some things are registered for", "site manager; # zope.site.site.threadSiteSubscriber will # do this for each BeforeTraverseEvent # that's", "things are registered for \"*\" (DefaultTraversable) # which means they get called here.", "URLDecodeError from pyramid.httpexceptions import HTTPNotFound from pyramid.interfaces import VH_ROOT_KEY from pyramid.interfaces import ITraverser", "the code is lifted directly from pyramid. environ = request.environ if request.matchdict is", "len(vroot_tuple) - 1 else: vroot_tuple = () vpath = path vroot_idx = -1", "vroot_tuple = () vpath = path vroot_idx = -1 root = self.root ob", "from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.traversing.namespace import resource as", "Notifies a BeforeTraverseEvent, but safely: if the handlers themselves raise a location error,", "segment, remaining_path, traversable=traversable, request=request) if remaining_path != vpath_tuple[i + 1:]: # Is this", "if we know it's going # to return the empty tuple vpath_tuple =", "\"\"\" # JAM: Unfortunately, the superclass implementation is entirely monolithic # and we", "a path in mod_wsgi, for example path = decode_path_info(environ['PATH_INFO'] or '/') except KeyError:", "by making the pyramid request implement the right thing. \"\"\" def __init__(self, context,", "# Use the installed component registry # instead of the request registry (which", "that checking for '@@' is special cased, and # doesn't go through the", "and :func:`zope.traversing.namespace.namespaceLookup`). As this object traverses, it fires :obj:`~.IBeforeTraverseEvent` events. If you either", "managers found along the way will be made the current site. \"\"\" def", "call to traversal_path if we know it's going # to return the empty", "to Interface. We connect the two by making the pyramid request implement the", "for \"*\" (DefaultTraversable) # which means they get called here. If they can't", "abort rather than try to return an information dictionary and find a view", "'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} try: # JAM: This is where we", "default namespaces are. See our # configure.zcml for what is. # JAM: Damn", "and the code is lifted directly from pyramid. environ = request.environ if request.matchdict", "not is_nonstr_iter(subpath): # pragma: no cover # this is not a *subpath stararg", "1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} try: # JAM: This is where", "since we # won't actually traverse into it. Be sure not to fire", "__all__ = [ 'ZopeResourceTreeTraverser', 'resource', ] def _notify_before_traverse_event(ob, request): \"\"\" Notifies a BeforeTraverseEvent,", "way will be made the current site. \"\"\" def __init__(self, root): traversal.ResourceTreeTraverser.__init__(self, root)", "= '/' except UnicodeDecodeError as e: raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason) if", "split_path_info(vroot_path) # both will (must) be unicode or asciistr vpath = vroot_path +", "= path vroot_idx = -1 root = self.root ob = vroot = root", "# Some things are registered for \"*\" (DefaultTraversable) # which means they get", "example path = decode_path_info(environ['PATH_INFO'] or '/') except KeyError: path = '/' except UnicodeDecodeError", "of namespace lookups (:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`). As this object traverses, it fires :obj:`~.IBeforeTraverseEvent`", "e.end, e.reason) if VH_ROOT_KEY in environ: # pragma: no cover # HTTP_X_VHM_ROOT vroot_path", "remaining_path, traversable=traversable, request=request) if remaining_path != vpath_tuple[i + 1:]: # Is this if", "# for this (E.g., the root). This logic is complicated by the #", "stupid implementation of traversePathElement ignores # the request argument to find a traversable", "HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A :class:`pyramid.interfaces.ITraverser` based on pyramid's default traverser,", "pyramid.interfaces import ITraverser from zope import interface from zope.component import queryMultiAdapter from zope.event", "match a route subpath = () try: # empty if mounted under a", "the multi adapter ourself in the non-namespace case # (In the namespace case,", "decode_path_info(environ['PATH_INFO'] or '/') except KeyError: path = '/' except UnicodeDecodeError as e: raise", "plus the support of namespace lookups (:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`). As this object traverses,", "implementation is entirely monolithic # and we so we cannot reuse any part", "# None of the default namespaces are. See our # configure.zcml for what", "# -*- coding: utf-8 -*- \"\"\" Support for resource tree traversal. \"\"\" from", "# traversing has changed the site manager; # zope.site.site.threadSiteSubscriber will # do this", "turn that into a HTTP 404 exception. Because handlers are deliberately doing this,", "i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} if i == vroot_idx:", "lookups. This provides is with the flexibility of the :obj:`zope.traversing.interfaces.ITraversable` adapter pattern, plus", "= request.matchdict path = matchdict.get('traverse', '/') or '/' if is_nonstr_iter(path): # this is", "multi adapter ourself in the non-namespace case # (In the namespace case, we", "= traversal.split_path_info logger = __import__('logging').getLogger(__name__) __all__ = [ 'ZopeResourceTreeTraverser', 'resource', ] def _notify_before_traverse_event(ob,", "(must) be unicode or asciistr vpath = vroot_path + path vroot_idx = len(vroot_tuple)", "e.object, e.start, e.end, e.reason) if VH_ROOT_KEY in environ: # pragma: no cover #", "logger = __import__('logging').getLogger(__name__) __all__ = [ 'ZopeResourceTreeTraverser', 'resource', ] def _notify_before_traverse_event(ob, request): \"\"\"", "See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" # JAM: Unfortunately, the superclass implementation is entirely monolithic #", "segment[2:], 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i + 1], 'virtual_root': vroot,", "'subpath': subpath, 'traversed': vpath_tuple, 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} class resource(_zresource): \"\"\"", "\"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" # JAM: Unfortunately, the superclass implementation is entirely monolithic", "zope traversal. (XXX: Why not?) if segment.startswith(view_selector): # pragma: no cover return {'context':", "current site. \"\"\" def __init__(self, root): traversal.ResourceTreeTraverser.__init__(self, root) def __call__(self, request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements", "not?) if segment.startswith(view_selector): # pragma: no cover return {'context': ob, 'view_name': segment[2:], 'subpath':", ":class:`pyramid.interfaces.ITraverser` based on pyramid's default traverser, but modified to use the :mod:`zope.traversing.api` machinery", "vroot = next_ob ob = next_ob i += 1 # JAM: Also fire", "try to return an information dictionary and find a view and context, etc.", "into it. Be sure not to fire multiple times # for this (E.g.,", "#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" Support for resource tree traversal.", "an information dictionary and find a view and context, etc. This is limiting,", "this is often a setup or programmer error logger.debug(\"LocationError from traverse subscribers\", exc_info=True)", "unicode or asciistr vpath = vroot_path + path vroot_idx = len(vroot_tuple) - 1", "named adapter # after parsing) traversable = None if segment and segment[0] not", "abundance of no covers. These are for features we are # not currently", "connect the two by making the pyramid request implement the right thing. \"\"\"", "import api as ztraversing from zope.traversing.interfaces import ITraversable from zope.traversing.interfaces import BeforeTraverseEvent from", "except UnicodeDecodeError as e: raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason) if VH_ROOT_KEY in", "are for features we are # not currently using and the code is", "HTTPNotFound from pyramid.interfaces import VH_ROOT_KEY from pyramid.interfaces import ITraverser from zope import interface", "to this event, then any Zope site managers found along the way will", "the abundance of no covers. These are for features we are # not", "after parsing) traversable = None if segment and segment[0] not in '+@' \\", "lookup as it would in # plain zope traversal. (XXX: Why not?) if", "if VH_ROOT_KEY in environ: # pragma: no cover # HTTP_X_VHM_ROOT vroot_path = decode_path_info(environ[VH_ROOT_KEY])", "not # registered by default). traversable = queryMultiAdapter((ob, request), ITraversable) except TypeError: #", "and segment[0] not in '+@' \\ and not ITraversable.providedBy(ob): try: # Use the", "import traversal from pyramid.compat import is_nonstr_iter from pyramid.compat import decode_path_info from pyramid.exceptions import", "exception. Because handlers are deliberately doing this, we stop traversal and abort rather", "= None if segment and segment[0] not in '+@' \\ and not ITraversable.providedBy(ob):", "traversal.empty split_path_info = traversal.split_path_info logger = __import__('logging').getLogger(__name__) __all__ = [ 'ZopeResourceTreeTraverser', 'resource', ]", "+ path vroot_idx = len(vroot_tuple) - 1 else: vroot_tuple = () vpath =", "made the current site. \"\"\" def __init__(self, root): traversal.ResourceTreeTraverser.__init__(self, root) def __call__(self, request):", "We connect the two by making the pyramid request implement the right thing.", "'/') except KeyError: path = '/' except UnicodeDecodeError as e: raise URLDecodeError(e.encoding, e.object,", "will be made the current site. \"\"\" def __init__(self, root): traversal.ResourceTreeTraverser.__init__(self, root) def", "traversing has changed the site manager; # zope.site.site.threadSiteSubscriber will # do this for", "pass remaining_path = vpath_tuple[i + 1:] next_ob = ztraversing.traversePathElement(ob, segment, remaining_path, traversable=traversable, request=request)", "list so that remaining_path can be modified vpath_tuple = list(split_path_info(vpath)) for segment in", "don't need to # do that? TODO: # NOTE: By passing the request", "'view_name': segment, 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i + 1], 'virtual_root':", "import queryMultiAdapter from zope.event import notify from zope.location.interfaces import LocationError from zope.traversing import", "traversal.lineage find_interface = traversal.find_interface empty = traversal.empty split_path_info = traversal.split_path_info logger = __import__('logging').getLogger(__name__)", "reuse any part of it. Instead, # we copy-and-paste it. Unless otherwise noted,", "monolithic # and we so we cannot reuse any part of it. Instead,", "use the traversing machinery. # The zope app would use IPublishTraverser, which #", "that into a HTTP 404 exception. Because handlers are deliberately doing this, we", "sure not to fire multiple times # for this (E.g., the root). This", "== vroot_idx: # pragma: no cover vroot = next_ob ob = next_ob i", "split_path_info = traversal.split_path_info logger = __import__('logging').getLogger(__name__) __all__ = [ 'ZopeResourceTreeTraverser', 'resource', ] def", "vpath_tuple = list(split_path_info(vpath)) for segment in vpath_tuple: # JAM: Fire traversal events, mainly", "(E.g., the root). This logic is complicated by the # multi-returns above. _notify_before_traverse_event(ob,", "request) return {'context': ob, 'view_name': empty, 'subpath': subpath, 'traversed': vpath_tuple, 'virtual_root': vroot, 'virtual_root_path':", "way. We probably don't need to # do that? TODO: # NOTE: By", "JAM: Also fire before traversal for the actual context item, since we #", "traversePathElement ignores # the request argument to find a traversable /except/ when a", "'traversed': vpath_tuple[:vroot_idx + i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} if", "Is this if check necessary? It would be faster to # always assign", "safe. \"\"\" try: notify(BeforeTraverseEvent(ob, request)) except LocationError: # this is often a setup", "vroot_idx: # pragma: no cover vroot = next_ob ob = next_ob i +=", "pyramid import traversal from pyramid.compat import is_nonstr_iter from pyramid.compat import decode_path_info from pyramid.exceptions", "notify(BeforeTraverseEvent(ob, request)) except LocationError: # this is often a setup or programmer error", "print_function from __future__ import absolute_import from pyramid import traversal from pyramid.compat import is_nonstr_iter", "else: i = 0 view_selector = self.VIEW_SELECTOR # A list so that remaining_path", "BeforeTraverseEvent, but safely: if the handlers themselves raise a location error, turn that", "parsing) traversable = None if segment and segment[0] not in '+@' \\ and", "component registry # instead of the request registry (which # is the global", "path = '/'.join(path) or '/' subpath = matchdict.get('subpath', ()) if not is_nonstr_iter(subpath): #", "-1 root = self.root ob = vroot = root if vpath == '/':", "changed the site manager; # zope.site.site.threadSiteSubscriber will # do this for each BeforeTraverseEvent", "is a *traverse stararg (not a {traverse}) # routing has already decoded these", "it would in # plain zope traversal. (XXX: Why not?) if segment.startswith(view_selector): #", "need # to split it subpath = split_path_info(subpath) else: # pragma: no cover", "be modified vpath_tuple = list(split_path_info(vpath)) for segment in vpath_tuple: # JAM: Fire traversal", "not currently using and the code is lifted directly from pyramid. environ =", "registry if # pyramid was configured that way, or a # standalone registry)", "exc_info=True) raise HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A :class:`pyramid.interfaces.ITraverser` based on pyramid's", "'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} if i == vroot_idx: # pragma: no", "from __future__ import division from __future__ import print_function from __future__ import absolute_import from", "to use the :mod:`zope.traversing.api` machinery instead of (only) dictionary lookups. This provides is", "passing the request here, we require all traversers # (including the namespace traversers)", "remaining_path != vpath_tuple[i + 1:]: # Is this if check necessary? It would", ":obj:`zope.traversing.interfaces.ITraversable` adapter pattern, plus the support of namespace lookups (:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`). As", "path = '/' except UnicodeDecodeError as e: raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason)", "# to split it subpath = split_path_info(subpath) else: # pragma: no cover #", "sites get installed. See # zope.publisher.base. _notify_before_traverse_event(ob, request) # JAM: Notice that checking", "just need # to split it subpath = split_path_info(subpath) else: # pragma: no", "installed. See # zope.publisher.base. _notify_before_traverse_event(ob, request) # JAM: Notice that checking for '@@'", "cased, and # doesn't go through the normal namespace lookup as it would", "__getitem__, # we use the traversing machinery. # The zope app would use", "above. _notify_before_traverse_event(ob, request) return {'context': ob, 'view_name': empty, 'subpath': subpath, 'traversed': vpath_tuple, 'virtual_root':", "we explicitly query for the multi adapter ourself in the non-namespace case #", "zope import interface from zope.component import queryMultiAdapter from zope.event import notify from zope.location.interfaces", "ITraverser from zope import interface from zope.component import queryMultiAdapter from zope.event import notify", "this, we stop traversal and abort rather than try to return an information", "Unless otherwise noted, comments below are # original. # JAM: Note the abundance", "special cased, and # doesn't go through the normal namespace lookup as it", "= traversal.find_interface empty = traversal.empty split_path_info = traversal.split_path_info logger = __import__('logging').getLogger(__name__) __all__ =", "zope.publisher.base. _notify_before_traverse_event(ob, request) # JAM: Notice that checking for '@@' is special cased,", "*traverse stararg (not a {traverse}) # routing has already decoded these elements, so", "(XXX: Why not?) if segment.startswith(view_selector): # pragma: no cover return {'context': ob, 'view_name':", "# that's fired (though that's not # registered by default). traversable = queryMultiAdapter((ob,", "multi-returns above. _notify_before_traverse_event(ob, request) return {'context': ob, 'view_name': empty, 'subpath': subpath, 'traversed': vpath_tuple,", "()) if not is_nonstr_iter(subpath): # pragma: no cover # this is not a", "a # standalone registry) in case the act of # traversing has changed", "traversers # (including the namespace traversers) to be registered as multi-adapters. # None", "probably don't need to # do that? TODO: # NOTE: By passing the", "Interface. We connect the two by making the pyramid request implement the right", "not None: matchdict = request.matchdict path = matchdict.get('traverse', '/') or '/' if is_nonstr_iter(path):", "mod_wsgi, for example path = decode_path_info(environ['PATH_INFO'] or '/') except KeyError: path = '/'", "manually enable the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to subscribe to this event, then any Zope", "(:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`). As this object traverses, it fires :obj:`~.IBeforeTraverseEvent` events. If you", "+ 1:] next_ob = ztraversing.traversePathElement(ob, segment, remaining_path, traversable=traversable, request=request) if remaining_path != vpath_tuple[i", "arguments, then we bail. Sucks. pass remaining_path = vpath_tuple[i + 1:] next_ob =", "request) # JAM: Notice that checking for '@@' is special cased, and #", "Why not?) if segment.startswith(view_selector): # pragma: no cover return {'context': ob, 'view_name': segment[2:],", "KeyError. The DefaultTraversable turns # plain KeyError and TypeErrors into LocationError. return {'context':", "join them path = '/'.join(path) or '/' subpath = matchdict.get('subpath', ()) if not", "'virtual_root_path': vroot_tuple, 'root': root} if i == vroot_idx: # pragma: no cover vroot", ":mod:`zope.traversing.api` machinery instead of (only) dictionary lookups. This provides is with the flexibility", "these elements, so we just # need to join them path = '/'.join(path)", "from zope import interface from zope.component import queryMultiAdapter from zope.event import notify from", "root): traversal.ResourceTreeTraverser.__init__(self, root) def __call__(self, request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" #", "would use IPublishTraverser, which # would install security proxies along the way. We", "# do this for each BeforeTraverseEvent # that's fired (though that's not #", "into a HTTP 404 exception. Because handlers are deliberately doing this, we stop", "is limiting, but safe. \"\"\" try: notify(BeforeTraverseEvent(ob, request)) except LocationError: # this is", "raise HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A :class:`pyramid.interfaces.ITraverser` based on pyramid's default", "pragma: no cover # this request did not match a route subpath =", "logic is complicated by the # multi-returns above. _notify_before_traverse_event(ob, request) return {'context': ob,", "subpath = split_path_info(subpath) else: # pragma: no cover # this request did not", "of using __getitem__, # we use the traversing machinery. # The zope app", "is often a setup or programmer error logger.debug(\"LocationError from traverse subscribers\", exc_info=True) raise", "component registry if # pyramid was configured that way, or a # standalone", "needs a named adapter # after parsing) traversable = None if segment and", "= [ 'ZopeResourceTreeTraverser', 'resource', ] def _notify_before_traverse_event(ob, request): \"\"\" Notifies a BeforeTraverseEvent, but", "a route subpath = () try: # empty if mounted under a path", "environ: # pragma: no cover # HTTP_X_VHM_ROOT vroot_path = decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple = split_path_info(vroot_path)", "the # multi-returns above. _notify_before_traverse_event(ob, request) return {'context': ob, 'view_name': empty, 'subpath': subpath,", "'@@' is special cased, and # doesn't go through the normal namespace lookup", "pyramid request implement the right thing. \"\"\" def __init__(self, context, request): request =", "context, request): request = IBrowserRequest(request) if not IDefaultBrowserLayer.providedBy(request): interface.alsoProvides(request, IDefaultBrowserLayer) # We lie", "# zope.site.site.threadSiteSubscriber will # do this for each BeforeTraverseEvent # that's fired (though", "# JAM: Notice that checking for '@@' is special cased, and # doesn't", "traversal.ResourceTreeTraverser.__init__(self, root) def __call__(self, request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" # JAM:", "named adapters from :class:`.IDefaultBrowserLayer` to Interface. We connect the two by making the", "but modified to use the :mod:`zope.traversing.api` machinery instead of (only) dictionary lookups. This", "segment.startswith(view_selector): # pragma: no cover return {'context': ob, 'view_name': segment[2:], 'subpath': vpath_tuple[i +", "of no covers. These are for features we are # not currently using", "] def _notify_before_traverse_event(ob, request): \"\"\" Notifies a BeforeTraverseEvent, but safely: if the handlers", "routing has already decoded this string, so we just need # to split", "ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A :class:`pyramid.interfaces.ITraverser` based on pyramid's default traverser, but modified to use", "in # plain zope traversal. (XXX: Why not?) if segment.startswith(view_selector): # pragma: no", "except LocationError: # LocationError is a type of KeyError. The DefaultTraversable turns #", "This package registers resources as named adapters from :class:`.IDefaultBrowserLayer` to Interface. We connect", "\"\"\" def __init__(self, root): traversal.ResourceTreeTraverser.__init__(self, root) def __call__(self, request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See", "we bail. Sucks. pass remaining_path = vpath_tuple[i + 1:] next_ob = ztraversing.traversePathElement(ob, segment,", "the root). This logic is complicated by the # multi-returns above. _notify_before_traverse_event(ob, request)", "we just need # to split it subpath = split_path_info(subpath) else: # pragma:", "cover vroot = next_ob ob = next_ob i += 1 # JAM: Also", "we so we cannot reuse any part of it. Instead, # we copy-and-paste", "handlers themselves raise a location error, turn that into a HTTP 404 exception.", "from pyramid.httpexceptions import HTTPNotFound from pyramid.interfaces import VH_ROOT_KEY from pyramid.interfaces import ITraverser from", "necessary? It would be faster to # always assign vpath_tuple[i + 1:] =", "already decoded this string, so we just need # to split it subpath", "routing has already decoded these elements, so we just # need to join", "= root if vpath == '/': # invariant: vpath must not be empty", "registry (which # is the global component registry if # pyramid was configured", "zope.component import queryMultiAdapter from zope.event import notify from zope.location.interfaces import LocationError from zope.traversing", "not to fire multiple times # for this (E.g., the root). This logic", "the flexibility of the :obj:`zope.traversing.interfaces.ITraversable` adapter pattern, plus the support of namespace lookups", "covers. These are for features we are # not currently using and the", "The zope app would use IPublishTraverser, which # would install security proxies along", "features we are # not currently using and the code is lifted directly", "from zope.component import queryMultiAdapter from zope.event import notify from zope.location.interfaces import LocationError from", "pyramid. environ = request.environ if request.matchdict is not None: matchdict = request.matchdict path", "in the non-namespace case # (In the namespace case, we let traversing handle", "subscribers\", exc_info=True) raise HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A :class:`pyramid.interfaces.ITraverser` based on", "either load the configuration from :mod:`zope.app.publication` or manually enable the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to", "for features we are # not currently using and the code is lifted", "site managers found along the way will be made the current site. \"\"\"", "view and context, etc. This is limiting, but safe. \"\"\" try: notify(BeforeTraverseEvent(ob, request))", "them path = '/'.join(path) or '/' subpath = matchdict.get('subpath', ()) if not is_nonstr_iter(subpath):", "vroot_idx = -1 root = self.root ob = vroot = root if vpath", "lookups (:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`). As this object traverses, it fires :obj:`~.IBeforeTraverseEvent` events. If", "configuration from :mod:`zope.app.publication` or manually enable the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to subscribe to this", "This provides is with the flexibility of the :obj:`zope.traversing.interfaces.ITraversable` adapter pattern, plus the", "stararg (not a {traverse}) # routing has already decoded these elements, so we", "if vpath == '/': # invariant: vpath must not be empty # prevent", "i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} try: # JAM: This", "namespace is found. # therefore, we explicitly query for the multi adapter ourself", "(DefaultTraversable) # which means they get called here. If they can't take #", "limiting, but safe. \"\"\" try: notify(BeforeTraverseEvent(ob, request)) except LocationError: # this is often", "from zope.location.interfaces import LocationError from zope.traversing import api as ztraversing from zope.traversing.interfaces import", "a way compatible with :mod:`zope.browserresource`. This package registers resources as named adapters from", "noted, comments below are # original. # JAM: Note the abundance of no", "this is not a *subpath stararg (just a {subpath}) # routing has already", "a call to traversal_path if we know it's going # to return the", "this event, then any Zope site managers found along the way will be", "else: vroot_tuple = () vpath = path vroot_idx = -1 root = self.root", "registry) in case the act of # traversing has changed the site manager;", "# instead of the request registry (which # is the global component registry", "# two arguments, then we bail. Sucks. pass remaining_path = vpath_tuple[i + 1:]", "segment, 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i + 1], 'virtual_root': vroot,", "so sites get installed. See # zope.publisher.base. _notify_before_traverse_event(ob, request) # JAM: Notice that", "from :mod:`zope.app.publication` or manually enable the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to subscribe to this event,", "traverse subscribers\", exc_info=True) raise HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A :class:`pyramid.interfaces.ITraverser` based", "# JAM: Note the abundance of no covers. These are for features we", "registered by default). traversable = queryMultiAdapter((ob, request), ITraversable) except TypeError: # Some things", "\"\"\" Support for resource tree traversal. \"\"\" from __future__ import division from __future__", "ztraversing.traversePathElement(ob, segment, remaining_path, traversable=traversable, request=request) if remaining_path != vpath_tuple[i + 1:]: # Is", "A list so that remaining_path can be modified vpath_tuple = list(split_path_info(vpath)) for segment", "# JAM: Damn stupid implementation of traversePathElement ignores # the request argument to", "request here, we require all traversers # (including the namespace traversers) to be", "empty if mounted under a path in mod_wsgi, for example path = decode_path_info(environ['PATH_INFO']", "to # do that? TODO: # NOTE: By passing the request here, we", "__init__(self, root): traversal.ResourceTreeTraverser.__init__(self, root) def __call__(self, request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\"", "# JAM: Unfortunately, the superclass implementation is entirely monolithic # and we so", "= split_path_info(vroot_path) # both will (must) be unicode or asciistr vpath = vroot_path", "See our # configure.zcml for what is. # JAM: Damn stupid implementation of", "has already decoded this string, so we just need # to split it", "'virtual_root_path': vroot_tuple, 'root': root} class resource(_zresource): \"\"\" Handles resource lookup in a way", "our # configure.zcml for what is. # JAM: Damn stupid implementation of traversePathElement", "\"\"\" Notifies a BeforeTraverseEvent, but safely: if the handlers themselves raise a location", "request): \"\"\" Notifies a BeforeTraverseEvent, but safely: if the handlers themselves raise a", "we stop traversal and abort rather than try to return an information dictionary", "root) def __call__(self, request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" # JAM: Unfortunately,", "# pragma: no cover return {'context': ob, 'view_name': segment[2:], 'subpath': vpath_tuple[i + 1:],", "pyramid.compat import decode_path_info from pyramid.exceptions import URLDecodeError from pyramid.httpexceptions import HTTPNotFound from pyramid.interfaces", "import URLDecodeError from pyramid.httpexceptions import HTTPNotFound from pyramid.interfaces import VH_ROOT_KEY from pyramid.interfaces import", "try: # JAM: This is where we differ. instead of using __getitem__, #", "Use the installed component registry # instead of the request registry (which #", "know it's going # to return the empty tuple vpath_tuple = () else:", "list(split_path_info(vpath)) for segment in vpath_tuple: # JAM: Fire traversal events, mainly so sites", "for segment in vpath_tuple: # JAM: Fire traversal events, mainly so sites get", "'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} class resource(_zresource): \"\"\" Handles resource lookup in", "environ = request.environ if request.matchdict is not None: matchdict = request.matchdict path =", "both will (must) be unicode or asciistr vpath = vroot_path + path vroot_idx", "None of the default namespaces are. See our # configure.zcml for what is.", "turns # plain KeyError and TypeErrors into LocationError. return {'context': ob, 'view_name': segment,", "import LocationError from zope.traversing import api as ztraversing from zope.traversing.interfaces import ITraversable from", "# original. # JAM: Note the abundance of no covers. These are for", "themselves raise a location error, turn that into a HTTP 404 exception. Because", "then any Zope site managers found along the way will be made the", "in case the act of # traversing has changed the site manager; #", "information dictionary and find a view and context, etc. This is limiting, but", "faster to # always assign vpath_tuple[i + 1:] = remaining_path except LocationError: #", "here, we require all traversers # (including the namespace traversers) to be registered", "i == vroot_idx: # pragma: no cover vroot = next_ob ob = next_ob", "BeforeTraverseEvent from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.traversing.namespace import resource", "if i == vroot_idx: # pragma: no cover vroot = next_ob ob =", "the normal namespace lookup as it would in # plain zope traversal. (XXX:", "URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason) if VH_ROOT_KEY in environ: # pragma: no cover", "subscribe to this event, then any Zope site managers found along the way", "error logger.debug(\"LocationError from traverse subscribers\", exc_info=True) raise HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\"", "copy-and-paste it. Unless otherwise noted, comments below are # original. # JAM: Note", "0 view_selector = self.VIEW_SELECTOR # A list so that remaining_path can be modified", "pyramid.httpexceptions import HTTPNotFound from pyramid.interfaces import VH_ROOT_KEY from pyramid.interfaces import ITraverser from zope", "it. Unless otherwise noted, comments below are # original. # JAM: Note the", "UnicodeDecodeError as e: raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason) if VH_ROOT_KEY in environ:", "import BeforeTraverseEvent from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.traversing.namespace import", "resources as named adapters from :class:`.IDefaultBrowserLayer` to Interface. We connect the two by", "is_nonstr_iter from pyramid.compat import decode_path_info from pyramid.exceptions import URLDecodeError from pyramid.httpexceptions import HTTPNotFound", "'view_name': empty, 'subpath': subpath, 'traversed': vpath_tuple, 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} class", "because it needs a named adapter # after parsing) traversable = None if", "'/'.join(path) or '/' subpath = matchdict.get('subpath', ()) if not is_nonstr_iter(subpath): # pragma: no", "the way will be made the current site. \"\"\" def __init__(self, root): traversal.ResourceTreeTraverser.__init__(self,", "failed\") @interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A :class:`pyramid.interfaces.ITraverser` based on pyramid's default traverser, but", "etc. This is limiting, but safe. \"\"\" try: notify(BeforeTraverseEvent(ob, request)) except LocationError: #", "return {'context': ob, 'view_name': segment, 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i", "to be registered as multi-adapters. # None of the default namespaces are. See", "queryMultiAdapter((ob, request), ITraversable) except TypeError: # Some things are registered for \"*\" (DefaultTraversable)", "directly from pyramid. environ = request.environ if request.matchdict is not None: matchdict =", "class resource(_zresource): \"\"\" Handles resource lookup in a way compatible with :mod:`zope.browserresource`. This", "division from __future__ import print_function from __future__ import absolute_import from pyramid import traversal", "else: # pragma: no cover # this request did not match a route", "site. \"\"\" def __init__(self, root): traversal.ResourceTreeTraverser.__init__(self, root) def __call__(self, request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\"", "vroot_tuple = split_path_info(vroot_path) # both will (must) be unicode or asciistr vpath =", "self.VIEW_SELECTOR # A list so that remaining_path can be modified vpath_tuple = list(split_path_info(vpath))", "for this (E.g., the root). This logic is complicated by the # multi-returns", "= IBrowserRequest(request) if not IDefaultBrowserLayer.providedBy(request): interface.alsoProvides(request, IDefaultBrowserLayer) # We lie super(resource, self).__init__(context, request)", "traversal events, mainly so sites get installed. See # zope.publisher.base. _notify_before_traverse_event(ob, request) #", "all traversers # (including the namespace traversers) to be registered as multi-adapters. #", "traversal for the actual context item, since we # won't actually traverse into", "= () else: i = 0 view_selector = self.VIEW_SELECTOR # A list so", "# LocationError is a type of KeyError. The DefaultTraversable turns # plain KeyError", "# the request argument to find a traversable /except/ when a namespace is", "ztraversing from zope.traversing.interfaces import ITraversable from zope.traversing.interfaces import BeforeTraverseEvent from zope.publisher.interfaces.browser import IBrowserRequest", "has already decoded these elements, so we just # need to join them", "JAM: Damn stupid implementation of traversePathElement ignores # the request argument to find", "and TypeErrors into LocationError. return {'context': ob, 'view_name': segment, 'subpath': vpath_tuple[i + 1:],", "'/' if is_nonstr_iter(path): # this is a *traverse stararg (not a {traverse}) #", "(including the namespace traversers) to be registered as multi-adapters. # None of the", "adapters from :class:`.IDefaultBrowserLayer` to Interface. We connect the two by making the pyramid", "dictionary and find a view and context, etc. This is limiting, but safe.", "'/' except UnicodeDecodeError as e: raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason) if VH_ROOT_KEY", "vpath = path vroot_idx = -1 root = self.root ob = vroot =", "return the empty tuple vpath_tuple = () else: i = 0 view_selector =", "# JAM: This is where we differ. instead of using __getitem__, # we", "just # need to join them path = '/'.join(path) or '/' subpath =", "modified to use the :mod:`zope.traversing.api` machinery instead of (only) dictionary lookups. This provides", "ob, 'view_name': segment, 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i + 1],", "the traversing machinery. # The zope app would use IPublishTraverser, which # would", "\"\"\" Handles resource lookup in a way compatible with :mod:`zope.browserresource`. This package registers", "query for the multi adapter ourself in the non-namespace case # (In the", "traversers) to be registered as multi-adapters. # None of the default namespaces are.", "traverser, but modified to use the :mod:`zope.traversing.api` machinery instead of (only) dictionary lookups.", "event, then any Zope site managers found along the way will be made", "will (must) be unicode or asciistr vpath = vroot_path + path vroot_idx =", "we let traversing handle it, because it needs a named adapter # after", "\\ and not ITraversable.providedBy(ob): try: # Use the installed component registry # instead", "LocationError: # LocationError is a type of KeyError. The DefaultTraversable turns # plain", "_notify_before_traverse_event(ob, request) return {'context': ob, 'view_name': empty, 'subpath': subpath, 'traversed': vpath_tuple, 'virtual_root': vroot,", "vroot_tuple, 'root': root} class resource(_zresource): \"\"\" Handles resource lookup in a way compatible", ":obj:`~.IBeforeTraverseEvent` events. If you either load the configuration from :mod:`zope.app.publication` or manually enable", "(only) dictionary lookups. This provides is with the flexibility of the :obj:`zope.traversing.interfaces.ITraversable` adapter", "mainly so sites get installed. See # zope.publisher.base. _notify_before_traverse_event(ob, request) # JAM: Notice", "any part of it. Instead, # we copy-and-paste it. Unless otherwise noted, comments", "a named adapter # after parsing) traversable = None if segment and segment[0]", "adapter pattern, plus the support of namespace lookups (:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`). As this", "resource as _zresource lineage = traversal.lineage find_interface = traversal.find_interface empty = traversal.empty split_path_info", "subpath = matchdict.get('subpath', ()) if not is_nonstr_iter(subpath): # pragma: no cover # this", "logger.debug(\"LocationError from traverse subscribers\", exc_info=True) raise HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A", "in mod_wsgi, for example path = decode_path_info(environ['PATH_INFO'] or '/') except KeyError: path =", "e: raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason) if VH_ROOT_KEY in environ: # pragma:", "'root': root} class resource(_zresource): \"\"\" Handles resource lookup in a way compatible with", "= self.VIEW_SELECTOR # A list so that remaining_path can be modified vpath_tuple =", "ITraversable) except TypeError: # Some things are registered for \"*\" (DefaultTraversable) # which", "enable the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to subscribe to this event, then any Zope site", "Damn stupid implementation of traversePathElement ignores # the request argument to find a", "we cannot reuse any part of it. Instead, # we copy-and-paste it. Unless", "vroot_tuple, 'root': root} if i == vroot_idx: # pragma: no cover vroot =", "# to return the empty tuple vpath_tuple = () else: i = 0", "do that? TODO: # NOTE: By passing the request here, we require all", "+ 1:] = remaining_path except LocationError: # LocationError is a type of KeyError.", "setup or programmer error logger.debug(\"LocationError from traverse subscribers\", exc_info=True) raise HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser)", "def __init__(self, root): traversal.ResourceTreeTraverser.__init__(self, root) def __call__(self, request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`.", "{'context': ob, 'view_name': segment, 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i +", "namespace traversers) to be registered as multi-adapters. # None of the default namespaces", "= remaining_path except LocationError: # LocationError is a type of KeyError. The DefaultTraversable", "request = IBrowserRequest(request) if not IDefaultBrowserLayer.providedBy(request): interface.alsoProvides(request, IDefaultBrowserLayer) # We lie super(resource, self).__init__(context,", "# after parsing) traversable = None if segment and segment[0] not in '+@'", "VH_ROOT_KEY in environ: # pragma: no cover # HTTP_X_VHM_ROOT vroot_path = decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple", "request.matchdict path = matchdict.get('traverse', '/') or '/' if is_nonstr_iter(path): # this is a", "doesn't go through the normal namespace lookup as it would in # plain", "split_path_info(subpath) else: # pragma: no cover # this request did not match a", "the non-namespace case # (In the namespace case, we let traversing handle it,", "# invariant: vpath must not be empty # prevent a call to traversal_path", "vroot_path = decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple = split_path_info(vroot_path) # both will (must) be unicode or", "the default namespaces are. See our # configure.zcml for what is. # JAM:", "superclass implementation is entirely monolithic # and we so we cannot reuse any", "configure.zcml for what is. # JAM: Damn stupid implementation of traversePathElement ignores #", "a namespace is found. # therefore, we explicitly query for the multi adapter", "otherwise noted, comments below are # original. # JAM: Note the abundance of", "this is a *traverse stararg (not a {traverse}) # routing has already decoded", "if check necessary? It would be faster to # always assign vpath_tuple[i +", "zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.traversing.namespace import resource as _zresource lineage = traversal.lineage find_interface", "provides is with the flexibility of the :obj:`zope.traversing.interfaces.ITraversable` adapter pattern, plus the support", "LocationError is a type of KeyError. The DefaultTraversable turns # plain KeyError and", "# plain zope traversal. (XXX: Why not?) if segment.startswith(view_selector): # pragma: no cover", "'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i + 1], 'virtual_root': vroot, 'virtual_root_path':", "[ 'ZopeResourceTreeTraverser', 'resource', ] def _notify_before_traverse_event(ob, request): \"\"\" Notifies a BeforeTraverseEvent, but safely:", "to return the empty tuple vpath_tuple = () else: i = 0 view_selector", "Be sure not to fire multiple times # for this (E.g., the root).", "the pyramid request implement the right thing. \"\"\" def __init__(self, context, request): request", "was configured that way, or a # standalone registry) in case the act", "pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" # JAM: Unfortunately, the superclass implementation is entirely", "is entirely monolithic # and we so we cannot reuse any part of", "or '/' if is_nonstr_iter(path): # this is a *traverse stararg (not a {traverse})", "decoded these elements, so we just # need to join them path =", "import division from __future__ import print_function from __future__ import absolute_import from pyramid import", "registered for \"*\" (DefaultTraversable) # which means they get called here. If they", "go through the normal namespace lookup as it would in # plain zope", "no cover vroot = next_ob ob = next_ob i += 1 # JAM:", "based on pyramid's default traverser, but modified to use the :mod:`zope.traversing.api` machinery instead", "the installed component registry # instead of the request registry (which # is", "zope.traversing.namespace import resource as _zresource lineage = traversal.lineage find_interface = traversal.find_interface empty =", "is the global component registry if # pyramid was configured that way, or", "remaining_path can be modified vpath_tuple = list(split_path_info(vpath)) for segment in vpath_tuple: # JAM:", "instead of using __getitem__, # we use the traversing machinery. # The zope", "is a type of KeyError. The DefaultTraversable turns # plain KeyError and TypeErrors", "that way, or a # standalone registry) in case the act of #", "_zresource lineage = traversal.lineage find_interface = traversal.find_interface empty = traversal.empty split_path_info = traversal.split_path_info", "events. If you either load the configuration from :mod:`zope.app.publication` or manually enable the", "path vroot_idx = len(vroot_tuple) - 1 else: vroot_tuple = () vpath = path", "they can't take # two arguments, then we bail. Sucks. pass remaining_path =", "<zope.site.site>` to subscribe to this event, then any Zope site managers found along", "TODO: # NOTE: By passing the request here, we require all traversers #", "of the default namespaces are. See our # configure.zcml for what is. #", "KeyError and TypeErrors into LocationError. return {'context': ob, 'view_name': segment, 'subpath': vpath_tuple[i +", "decode_path_info from pyramid.exceptions import URLDecodeError from pyramid.httpexceptions import HTTPNotFound from pyramid.interfaces import VH_ROOT_KEY", "from pyramid.interfaces import VH_ROOT_KEY from pyramid.interfaces import ITraverser from zope import interface from", "and abort rather than try to return an information dictionary and find a", "if segment and segment[0] not in '+@' \\ and not ITraversable.providedBy(ob): try: #", "below are # original. # JAM: Note the abundance of no covers. These", "vpath = vroot_path + path vroot_idx = len(vroot_tuple) - 1 else: vroot_tuple =", "# we use the traversing machinery. # The zope app would use IPublishTraverser,", "to join them path = '/'.join(path) or '/' subpath = matchdict.get('subpath', ()) if", "ob, 'view_name': empty, 'subpath': subpath, 'traversed': vpath_tuple, 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root}", "context, etc. This is limiting, but safe. \"\"\" try: notify(BeforeTraverseEvent(ob, request)) except LocationError:", "for what is. # JAM: Damn stupid implementation of traversePathElement ignores # the", "+ 1:], 'traversed': vpath_tuple[:vroot_idx + i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root':", "has changed the site manager; # zope.site.site.threadSiteSubscriber will # do this for each", "root). This logic is complicated by the # multi-returns above. _notify_before_traverse_event(ob, request) return", "request)) except LocationError: # this is often a setup or programmer error logger.debug(\"LocationError", "found along the way will be made the current site. \"\"\" def __init__(self,", "a *traverse stararg (not a {traverse}) # routing has already decoded these elements,", "which # would install security proxies along the way. We probably don't need", "'+@' \\ and not ITraversable.providedBy(ob): try: # Use the installed component registry #", "elements, so we just # need to join them path = '/'.join(path) or", "be faster to # always assign vpath_tuple[i + 1:] = remaining_path except LocationError:", "= len(vroot_tuple) - 1 else: vroot_tuple = () vpath = path vroot_idx =", "import print_function from __future__ import absolute_import from pyramid import traversal from pyramid.compat import", "# pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" # JAM: Unfortunately, the superclass implementation is", "namespace lookups (:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`). As this object traverses, it fires :obj:`~.IBeforeTraverseEvent` events.", "# this is a *traverse stararg (not a {traverse}) # routing has already", "this request did not match a route subpath = () try: # empty", "-*- coding: utf-8 -*- \"\"\" Support for resource tree traversal. \"\"\" from __future__", "import IDefaultBrowserLayer from zope.traversing.namespace import resource as _zresource lineage = traversal.lineage find_interface =", "non-namespace case # (In the namespace case, we let traversing handle it, because", "the global component registry if # pyramid was configured that way, or a", "JAM: This is where we differ. instead of using __getitem__, # we use", "+= 1 # JAM: Also fire before traversal for the actual context item,", "configured that way, or a # standalone registry) in case the act of", "you either load the configuration from :mod:`zope.app.publication` or manually enable the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>`", "as e: raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason) if VH_ROOT_KEY in environ: #", "are # not currently using and the code is lifted directly from pyramid.", "{'context': ob, 'view_name': segment[2:], 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i +", "from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.traversing.namespace import resource as _zresource lineage = traversal.lineage", "It would be faster to # always assign vpath_tuple[i + 1:] = remaining_path", "() try: # empty if mounted under a path in mod_wsgi, for example", "part of it. Instead, # we copy-and-paste it. Unless otherwise noted, comments below", "path = matchdict.get('traverse', '/') or '/' if is_nonstr_iter(path): # this is a *traverse", "with :mod:`zope.browserresource`. This package registers resources as named adapters from :class:`.IDefaultBrowserLayer` to Interface.", "traversable=traversable, request=request) if remaining_path != vpath_tuple[i + 1:]: # Is this if check", "request.matchdict is not None: matchdict = request.matchdict path = matchdict.get('traverse', '/') or '/'", "differ. instead of using __getitem__, # we use the traversing machinery. # The", "context item, since we # won't actually traverse into it. Be sure not", "and we so we cannot reuse any part of it. Instead, # we", "item, since we # won't actually traverse into it. Be sure not to", "is special cased, and # doesn't go through the normal namespace lookup as", "global component registry if # pyramid was configured that way, or a #", "remaining_path = vpath_tuple[i + 1:] next_ob = ztraversing.traversePathElement(ob, segment, remaining_path, traversable=traversable, request=request) if", "instead of the request registry (which # is the global component registry if", "fire multiple times # for this (E.g., the root). This logic is complicated", "this string, so we just need # to split it subpath = split_path_info(subpath)", "the handlers themselves raise a location error, turn that into a HTTP 404", "is_nonstr_iter(path): # this is a *traverse stararg (not a {traverse}) # routing has", "not match a route subpath = () try: # empty if mounted under", "currently using and the code is lifted directly from pyramid. environ = request.environ", "where we differ. instead of using __getitem__, # we use the traversing machinery.", "request registry (which # is the global component registry if # pyramid was", "traversal_path if we know it's going # to return the empty tuple vpath_tuple", "compatible with :mod:`zope.browserresource`. This package registers resources as named adapters from :class:`.IDefaultBrowserLayer` to", "times # for this (E.g., the root). This logic is complicated by the", "# would install security proxies along the way. We probably don't need to", "manager; # zope.site.site.threadSiteSubscriber will # do this for each BeforeTraverseEvent # that's fired", "Handles resource lookup in a way compatible with :mod:`zope.browserresource`. This package registers resources", "1 else: vroot_tuple = () vpath = path vroot_idx = -1 root =", "can't take # two arguments, then we bail. Sucks. pass remaining_path = vpath_tuple[i", "by default). traversable = queryMultiAdapter((ob, request), ITraversable) except TypeError: # Some things are", "# routing has already decoded these elements, so we just # need to", "must not be empty # prevent a call to traversal_path if we know", "default). traversable = queryMultiAdapter((ob, request), ITraversable) except TypeError: # Some things are registered", "to return an information dictionary and find a view and context, etc. This", "and not ITraversable.providedBy(ob): try: # Use the installed component registry # instead of", "registers resources as named adapters from :class:`.IDefaultBrowserLayer` to Interface. We connect the two", "the right thing. \"\"\" def __init__(self, context, request): request = IBrowserRequest(request) if not", "programmer error logger.debug(\"LocationError from traverse subscribers\", exc_info=True) raise HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser) class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser):", "HTTP_X_VHM_ROOT vroot_path = decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple = split_path_info(vroot_path) # both will (must) be unicode", "A :class:`pyramid.interfaces.ITraverser` based on pyramid's default traverser, but modified to use the :mod:`zope.traversing.api`", "with the flexibility of the :obj:`zope.traversing.interfaces.ITraversable` adapter pattern, plus the support of namespace", "it subpath = split_path_info(subpath) else: # pragma: no cover # this request did", "root if vpath == '/': # invariant: vpath must not be empty #", "in a way compatible with :mod:`zope.browserresource`. This package registers resources as named adapters", "= list(split_path_info(vpath)) for segment in vpath_tuple: # JAM: Fire traversal events, mainly so", "multi-adapters. # None of the default namespaces are. See our # configure.zcml for", "modified vpath_tuple = list(split_path_info(vpath)) for segment in vpath_tuple: # JAM: Fire traversal events,", "get installed. See # zope.publisher.base. _notify_before_traverse_event(ob, request) # JAM: Notice that checking for", "JAM: Notice that checking for '@@' is special cased, and # doesn't go", "to fire multiple times # for this (E.g., the root). This logic is", "try: # Use the installed component registry # instead of the request registry", "or a # standalone registry) in case the act of # traversing has", "the :obj:`zope.traversing.interfaces.ITraversable` adapter pattern, plus the support of namespace lookups (:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`).", "(which # is the global component registry if # pyramid was configured that", "for resource tree traversal. \"\"\" from __future__ import division from __future__ import print_function", "empty # prevent a call to traversal_path if we know it's going #", "than try to return an information dictionary and find a view and context,", "take # two arguments, then we bail. Sucks. pass remaining_path = vpath_tuple[i +", "zope.event import notify from zope.location.interfaces import LocationError from zope.traversing import api as ztraversing", "traverse into it. Be sure not to fire multiple times # for this", "check necessary? It would be faster to # always assign vpath_tuple[i + 1:]", "not be empty # prevent a call to traversal_path if we know it's", ":class:`.IDefaultBrowserLayer` to Interface. We connect the two by making the pyramid request implement", "two arguments, then we bail. Sucks. pass remaining_path = vpath_tuple[i + 1:] next_ob", "plain KeyError and TypeErrors into LocationError. return {'context': ob, 'view_name': segment, 'subpath': vpath_tuple[i", "= next_ob ob = next_ob i += 1 # JAM: Also fire before", "is. # JAM: Damn stupid implementation of traversePathElement ignores # the request argument", "resource tree traversal. \"\"\" from __future__ import division from __future__ import print_function from", "NOTE: By passing the request here, we require all traversers # (including the", "# both will (must) be unicode or asciistr vpath = vroot_path + path", "empty = traversal.empty split_path_info = traversal.split_path_info logger = __import__('logging').getLogger(__name__) __all__ = [ 'ZopeResourceTreeTraverser',", "deliberately doing this, we stop traversal and abort rather than try to return", "= 0 view_selector = self.VIEW_SELECTOR # A list so that remaining_path can be", "traversal.find_interface empty = traversal.empty split_path_info = traversal.split_path_info logger = __import__('logging').getLogger(__name__) __all__ = [", "lineage = traversal.lineage find_interface = traversal.find_interface empty = traversal.empty split_path_info = traversal.split_path_info logger", "a {subpath}) # routing has already decoded this string, so we just need", "/except/ when a namespace is found. # therefore, we explicitly query for the", "we # won't actually traverse into it. Be sure not to fire multiple", "or asciistr vpath = vroot_path + path vroot_idx = len(vroot_tuple) - 1 else:", "vpath_tuple[i + 1:] = remaining_path except LocationError: # LocationError is a type of", "need to # do that? TODO: # NOTE: By passing the request here,", "= queryMultiAdapter((ob, request), ITraversable) except TypeError: # Some things are registered for \"*\"", "raise a location error, turn that into a HTTP 404 exception. Because handlers", "zope app would use IPublishTraverser, which # would install security proxies along the", "pyramid.exceptions import URLDecodeError from pyramid.httpexceptions import HTTPNotFound from pyramid.interfaces import VH_ROOT_KEY from pyramid.interfaces", "= request.environ if request.matchdict is not None: matchdict = request.matchdict path = matchdict.get('traverse',", "be unicode or asciistr vpath = vroot_path + path vroot_idx = len(vroot_tuple) -", "won't actually traverse into it. Be sure not to fire multiple times #", "the request argument to find a traversable /except/ when a namespace is found.", "HTTP 404 exception. Because handlers are deliberately doing this, we stop traversal and", "security proxies along the way. We probably don't need to # do that?", "self.root ob = vroot = root if vpath == '/': # invariant: vpath", "# and we so we cannot reuse any part of it. Instead, #", "\"\"\" try: notify(BeforeTraverseEvent(ob, request)) except LocationError: # this is often a setup or", "empty, 'subpath': subpath, 'traversed': vpath_tuple, 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} class resource(_zresource):", "case # (In the namespace case, we let traversing handle it, because it", "vpath_tuple[:vroot_idx + i + 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} try: #", "machinery instead of (only) dictionary lookups. This provides is with the flexibility of", "for each BeforeTraverseEvent # that's fired (though that's not # registered by default).", "from pyramid.compat import decode_path_info from pyramid.exceptions import URLDecodeError from pyramid.httpexceptions import HTTPNotFound from", "LocationError: # this is often a setup or programmer error logger.debug(\"LocationError from traverse", "no cover # HTTP_X_VHM_ROOT vroot_path = decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple = split_path_info(vroot_path) # both will", "IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.traversing.namespace import resource as _zresource lineage =", "or manually enable the :obj:`zope.site.site.threadSiteSubscriber <zope.site.site>` to subscribe to this event, then any", "# Is this if check necessary? It would be faster to # always", "it. Instead, # we copy-and-paste it. Unless otherwise noted, comments below are #", "\"*\" (DefaultTraversable) # which means they get called here. If they can't take", "# this is often a setup or programmer error logger.debug(\"LocationError from traverse subscribers\",", "# NOTE: By passing the request here, we require all traversers # (including", "KeyError: path = '/' except UnicodeDecodeError as e: raise URLDecodeError(e.encoding, e.object, e.start, e.end,", "that? TODO: # NOTE: By passing the request here, we require all traversers", "# won't actually traverse into it. Be sure not to fire multiple times", "what is. # JAM: Damn stupid implementation of traversePathElement ignores # the request", "vroot_tuple, 'root': root} try: # JAM: This is where we differ. instead of", "into LocationError. return {'context': ob, 'view_name': segment, 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx", "rather than try to return an information dictionary and find a view and", "for the multi adapter ourself in the non-namespace case # (In the namespace", "matchdict.get('subpath', ()) if not is_nonstr_iter(subpath): # pragma: no cover # this is not", "cover # this request did not match a route subpath = () try:", "as ztraversing from zope.traversing.interfaces import ITraversable from zope.traversing.interfaces import BeforeTraverseEvent from zope.publisher.interfaces.browser import", "request): # pylint:disable=too-many-locals,too-many-branches,too-many-statements \"\"\" See :meth:`pyramid.interfaces.ITraversar.__call__`. \"\"\" # JAM: Unfortunately, the superclass implementation", "__import__('logging').getLogger(__name__) __all__ = [ 'ZopeResourceTreeTraverser', 'resource', ] def _notify_before_traverse_event(ob, request): \"\"\" Notifies a", "or programmer error logger.debug(\"LocationError from traverse subscribers\", exc_info=True) raise HTTPNotFound(\"Traversal failed\") @interface.implementer(ITraverser) class", "= () try: # empty if mounted under a path in mod_wsgi, for", "import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.traversing.namespace import resource as _zresource lineage", "namespace lookup as it would in # plain zope traversal. (XXX: Why not?)", "we differ. instead of using __getitem__, # we use the traversing machinery. #", "not in '+@' \\ and not ITraversable.providedBy(ob): try: # Use the installed component", "pyramid was configured that way, or a # standalone registry) in case the", "right thing. \"\"\" def __init__(self, context, request): request = IBrowserRequest(request) if not IDefaultBrowserLayer.providedBy(request):", "# empty if mounted under a path in mod_wsgi, for example path =", "did not match a route subpath = () try: # empty if mounted", "The DefaultTraversable turns # plain KeyError and TypeErrors into LocationError. return {'context': ob,", "# A list so that remaining_path can be modified vpath_tuple = list(split_path_info(vpath)) for", "stararg (just a {subpath}) # routing has already decoded this string, so we", "that's fired (though that's not # registered by default). traversable = queryMultiAdapter((ob, request),", "not a *subpath stararg (just a {subpath}) # routing has already decoded this", "any Zope site managers found along the way will be made the current", "we are # not currently using and the code is lifted directly from", "subpath, 'traversed': vpath_tuple, 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} class resource(_zresource): \"\"\" Handles", "traversal from pyramid.compat import is_nonstr_iter from pyramid.compat import decode_path_info from pyramid.exceptions import URLDecodeError", "we copy-and-paste it. Unless otherwise noted, comments below are # original. # JAM:", "# always assign vpath_tuple[i + 1:] = remaining_path except LocationError: # LocationError is", "always assign vpath_tuple[i + 1:] = remaining_path except LocationError: # LocationError is a", "plain zope traversal. (XXX: Why not?) if segment.startswith(view_selector): # pragma: no cover return", "often a setup or programmer error logger.debug(\"LocationError from traverse subscribers\", exc_info=True) raise HTTPNotFound(\"Traversal", "# not currently using and the code is lifted directly from pyramid. environ", "traverses, it fires :obj:`~.IBeforeTraverseEvent` events. If you either load the configuration from :mod:`zope.app.publication`", "utf-8 -*- \"\"\" Support for resource tree traversal. \"\"\" from __future__ import division", "from pyramid.compat import is_nonstr_iter from pyramid.compat import decode_path_info from pyramid.exceptions import URLDecodeError from", "be registered as multi-adapters. # None of the default namespaces are. See our", "vroot, 'virtual_root_path': vroot_tuple, 'root': root} if i == vroot_idx: # pragma: no cover", "original. # JAM: Note the abundance of no covers. These are for features", "fired (though that's not # registered by default). traversable = queryMultiAdapter((ob, request), ITraversable)", "if # pyramid was configured that way, or a # standalone registry) in", "return {'context': ob, 'view_name': segment[2:], 'subpath': vpath_tuple[i + 1:], 'traversed': vpath_tuple[:vroot_idx + i", "interface from zope.component import queryMultiAdapter from zope.event import notify from zope.location.interfaces import LocationError", "'/': # invariant: vpath must not be empty # prevent a call to", "are deliberately doing this, we stop traversal and abort rather than try to", "and find a view and context, etc. This is limiting, but safe. \"\"\"", "handlers are deliberately doing this, we stop traversal and abort rather than try", "# pragma: no cover vroot = next_ob ob = next_ob i += 1", "notify from zope.location.interfaces import LocationError from zope.traversing import api as ztraversing from zope.traversing.interfaces", "from :class:`.IDefaultBrowserLayer` to Interface. We connect the two by making the pyramid request", "python # -*- coding: utf-8 -*- \"\"\" Support for resource tree traversal. \"\"\"", "request.environ if request.matchdict is not None: matchdict = request.matchdict path = matchdict.get('traverse', '/')", "root} try: # JAM: This is where we differ. instead of using __getitem__,", "do this for each BeforeTraverseEvent # that's fired (though that's not # registered", "therefore, we explicitly query for the multi adapter ourself in the non-namespace case", "= __import__('logging').getLogger(__name__) __all__ = [ 'ZopeResourceTreeTraverser', 'resource', ] def _notify_before_traverse_event(ob, request): \"\"\" Notifies", "{subpath}) # routing has already decoded this string, so we just need #", "import HTTPNotFound from pyramid.interfaces import VH_ROOT_KEY from pyramid.interfaces import ITraverser from zope import", "root} if i == vroot_idx: # pragma: no cover vroot = next_ob ob", "request argument to find a traversable /except/ when a namespace is found. #", "and # doesn't go through the normal namespace lookup as it would in", "# routing has already decoded this string, so we just need # to", "it's going # to return the empty tuple vpath_tuple = () else: i", "can be modified vpath_tuple = list(split_path_info(vpath)) for segment in vpath_tuple: # JAM: Fire", "and context, etc. This is limiting, but safe. \"\"\" try: notify(BeforeTraverseEvent(ob, request)) except", "use IPublishTraverser, which # would install security proxies along the way. We probably", "zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.traversing.namespace import resource as _zresource", "a view and context, etc. This is limiting, but safe. \"\"\" try: notify(BeforeTraverseEvent(ob,", "namespace case, we let traversing handle it, because it needs a named adapter", "# is the global component registry if # pyramid was configured that way,", "of KeyError. The DefaultTraversable turns # plain KeyError and TypeErrors into LocationError. return", "split it subpath = split_path_info(subpath) else: # pragma: no cover # this request", "way compatible with :mod:`zope.browserresource`. This package registers resources as named adapters from :class:`.IDefaultBrowserLayer`", "BeforeTraverseEvent # that's fired (though that's not # registered by default). traversable =", "vpath_tuple[i + 1:] next_ob = ztraversing.traversePathElement(ob, segment, remaining_path, traversable=traversable, request=request) if remaining_path !=", "doing this, we stop traversal and abort rather than try to return an", "class ZopeResourceTreeTraverser(traversal.ResourceTreeTraverser): \"\"\" A :class:`pyramid.interfaces.ITraverser` based on pyramid's default traverser, but modified to", "root = self.root ob = vroot = root if vpath == '/': #", "prevent a call to traversal_path if we know it's going # to return", "() else: i = 0 view_selector = self.VIEW_SELECTOR # A list so that", "# therefore, we explicitly query for the multi adapter ourself in the non-namespace", "1:] next_ob = ztraversing.traversePathElement(ob, segment, remaining_path, traversable=traversable, request=request) if remaining_path != vpath_tuple[i +", "the empty tuple vpath_tuple = () else: i = 0 view_selector = self.VIEW_SELECTOR", "try: notify(BeforeTraverseEvent(ob, request)) except LocationError: # this is often a setup or programmer", "= decode_path_info(environ['PATH_INFO'] or '/') except KeyError: path = '/' except UnicodeDecodeError as e:", "vpath must not be empty # prevent a call to traversal_path if we", "no cover # this request did not match a route subpath = ()", "in environ: # pragma: no cover # HTTP_X_VHM_ROOT vroot_path = decode_path_info(environ[VH_ROOT_KEY]) vroot_tuple =", "type of KeyError. The DefaultTraversable turns # plain KeyError and TypeErrors into LocationError.", "actual context item, since we # won't actually traverse into it. Be sure", "no covers. These are for features we are # not currently using and", "vpath == '/': # invariant: vpath must not be empty # prevent a", "'root': root} if i == vroot_idx: # pragma: no cover vroot = next_ob", "complicated by the # multi-returns above. _notify_before_traverse_event(ob, request) return {'context': ob, 'view_name': empty,", "so that remaining_path can be modified vpath_tuple = list(split_path_info(vpath)) for segment in vpath_tuple:", "is complicated by the # multi-returns above. _notify_before_traverse_event(ob, request) return {'context': ob, 'view_name':", "adapter # after parsing) traversable = None if segment and segment[0] not in", "TypeError: # Some things are registered for \"*\" (DefaultTraversable) # which means they", "Also fire before traversal for the actual context item, since we # won't", "request did not match a route subpath = () try: # empty if", "== '/': # invariant: vpath must not be empty # prevent a call", "argument to find a traversable /except/ when a namespace is found. # therefore,", "use the :mod:`zope.traversing.api` machinery instead of (only) dictionary lookups. This provides is with", "'resource', ] def _notify_before_traverse_event(ob, request): \"\"\" Notifies a BeforeTraverseEvent, but safely: if the", "This is limiting, but safe. \"\"\" try: notify(BeforeTraverseEvent(ob, request)) except LocationError: # this", "of (only) dictionary lookups. This provides is with the flexibility of the :obj:`zope.traversing.interfaces.ITraversable`", "entirely monolithic # and we so we cannot reuse any part of it.", "need to join them path = '/'.join(path) or '/' subpath = matchdict.get('subpath', ())", "pragma: no cover # this is not a *subpath stararg (just a {subpath})", "decoded this string, so we just need # to split it subpath =", "(In the namespace case, we let traversing handle it, because it needs a", "we require all traversers # (including the namespace traversers) to be registered as", "handle it, because it needs a named adapter # after parsing) traversable =", "vpath_tuple[i + 1:]: # Is this if check necessary? It would be faster", "to # always assign vpath_tuple[i + 1:] = remaining_path except LocationError: # LocationError", "remaining_path except LocationError: # LocationError is a type of KeyError. The DefaultTraversable turns", "request): request = IBrowserRequest(request) if not IDefaultBrowserLayer.providedBy(request): interface.alsoProvides(request, IDefaultBrowserLayer) # We lie super(resource,", "segment[0] not in '+@' \\ and not ITraversable.providedBy(ob): try: # Use the installed", "the support of namespace lookups (:func:`zope.traversing.namespace.nsParse` and :func:`zope.traversing.namespace.namespaceLookup`). As this object traverses, it", "+ 1], 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} try: # JAM: This is", "__init__(self, context, request): request = IBrowserRequest(request) if not IDefaultBrowserLayer.providedBy(request): interface.alsoProvides(request, IDefaultBrowserLayer) # We", "instead of (only) dictionary lookups. This provides is with the flexibility of the", "through the normal namespace lookup as it would in # plain zope traversal.", "Fire traversal events, mainly so sites get installed. See # zope.publisher.base. _notify_before_traverse_event(ob, request)", "to split it subpath = split_path_info(subpath) else: # pragma: no cover # this", "= vroot = root if vpath == '/': # invariant: vpath must not", "JAM: Unfortunately, the superclass implementation is entirely monolithic # and we so we", "vpath_tuple, 'virtual_root': vroot, 'virtual_root_path': vroot_tuple, 'root': root} class resource(_zresource): \"\"\" Handles resource lookup", "_notify_before_traverse_event(ob, request): \"\"\" Notifies a BeforeTraverseEvent, but safely: if the handlers themselves raise", "cover # this is not a *subpath stararg (just a {subpath}) # routing", "# we copy-and-paste it. Unless otherwise noted, comments below are # original. #", "# multi-returns above. _notify_before_traverse_event(ob, request) return {'context': ob, 'view_name': empty, 'subpath': subpath, 'traversed':", "default traverser, but modified to use the :mod:`zope.traversing.api` machinery instead of (only) dictionary", "except LocationError: # this is often a setup or programmer error logger.debug(\"LocationError from", "JAM: Note the abundance of no covers. These are for features we are", "along the way will be made the current site. \"\"\" def __init__(self, root):", "but safe. \"\"\" try: notify(BeforeTraverseEvent(ob, request)) except LocationError: # this is often a", "comments below are # original. # JAM: Note the abundance of no covers.", "(not a {traverse}) # routing has already decoded these elements, so we just", "the act of # traversing has changed the site manager; # zope.site.site.threadSiteSubscriber will", "request), ITraversable) except TypeError: # Some things are registered for \"*\" (DefaultTraversable) #", ":mod:`zope.browserresource`. This package registers resources as named adapters from :class:`.IDefaultBrowserLayer` to Interface. We", "def __init__(self, context, request): request = IBrowserRequest(request) if not IDefaultBrowserLayer.providedBy(request): interface.alsoProvides(request, IDefaultBrowserLayer) #", "on pyramid's default traverser, but modified to use the :mod:`zope.traversing.api` machinery instead of", "is lifted directly from pyramid. environ = request.environ if request.matchdict is not None:", "find_interface = traversal.find_interface empty = traversal.empty split_path_info = traversal.split_path_info logger = __import__('logging').getLogger(__name__) __all__", "(just a {subpath}) # routing has already decoded this string, so we just", "zope.traversing import api as ztraversing from zope.traversing.interfaces import ITraversable from zope.traversing.interfaces import BeforeTraverseEvent", "By passing the request here, we require all traversers # (including the namespace" ]
[ "指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。", "譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。", "**ジャンル** > 楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA = f\"\"\" {DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca [曲数] [レベル(:high/low)]", "# その他 MAX_MUSICS = setting[\"misc\"][\"max_musics\"] CMDPREF = setting[\"misc\"][\"command_prefix\"] APP_VERSION = \"3.0\" CHANNEL_NAME =", "> アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** > 楽曲のノーツ数を指定します。 > 半角数字で入力してください。 **BPM** > 楽曲のBPMを指定します。 >", "アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。 【コマンド例】", "> アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。", "[アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` `{CMDPREF}search [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` {HIGHLOW} 【パラメータ】", "(`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。", "setting[\"logging\"][\"loglevel_stdio\"] loglevel_file = setting[\"logging\"][\"loglevel_file\"] log_filename = setting[\"logging\"][\"log_filename\"] # その他 MAX_MUSICS = setting[\"misc\"][\"max_musics\"] CMDPREF", "【コマンド文字列】 `{CMDPREF}random [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` `{CMDPREF}search [レベル(:high/low)] [ジャンル] [アーティスト]", "`{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 >", "LUNATICおよびボーナストラックには対応していません。 \"\"\" # 書きかけ HELPMES_MAIMAI = f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai [曲数] [レベル(:high/low)]", "楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとINFERNOの両方から検索します。 > レベルが指定されたときのみ機能します。 【注意点】 - ジャンルは1つのみ指定可能です。 【不具合】 - 『オリジナル』を指定すると『TANO\\\\*C(オリジナル)』も同時に検索されてしまいます。", "`{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki - 13 - - - -", "bot v{APP_VERSION}**\" HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM = f\"\"\" {DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random [曲数]", "{DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル]", "} # URL URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA", "json.load(s) else: setting = { \"token\": { \"discord\": env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"] }, \"logging\":", "**maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル] [アーティスト]", "int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"] } } # URL URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\"", "`{CMDPREF}random_wacca [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}swacca`でも可)", "setting = { \"token\": { \"discord\": env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"] }, \"logging\": { \"logging\":", "setting[\"logging\"][\"logging\"] loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"] loglevel_file = setting[\"logging\"][\"loglevel_file\"] log_filename = setting[\"logging\"][\"log_filename\"] # その他 MAX_MUSICS", "= setting[\"misc\"][\"command_prefix\"] APP_VERSION = \"3.0\" CHANNEL_NAME = \"選曲bot\" # ヘルプメッセージ DECLARATION_NAME = f\"**CHUNITHM", "`{CMDPREF}search [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。", "> 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** >", "全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random - 13 - - - - exp`:", "DISCORD_TOKEN = setting[\"token\"][\"discord\"] # API関係 API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"]) # logger関係 tz = setting[\"misc\"][\"timezone\"]", "Random Selector bot v{APP_VERSION}**\" HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM = f\"\"\" {DECLARATION_NAME} 【コマンド文字列】", "`{CMDPREF}search none 東方Project none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search - - - - 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。", "CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"] DISCORD_TOKEN = setting[\"token\"][\"discord\"] # API関係 API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"]) # logger関係", "env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"] }, \"misc\": { \"channel_id\": int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"], \"api_lifetime\":", "[曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW}", "[アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数**", "f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)]", "env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"] }, \"misc\": { \"channel_id\": int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\":", "半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。", "> 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`:", "[レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。", "\"\"\" HELPMES_WACCA = f\"\"\" {DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]`", "as env from distutils.util import strtobool if os.path.isfile(\"setting.json\"): with open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\") as", "[難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 >", "**BPM** > 楽曲のBPMを指定します。 > 半角数字で入力してください。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 >", "`{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 >", "**ジャンル** > 楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度**", "- - - - 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - WORLD'S ENDには対応していません。 -", "`{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random - 13 - - - -", "s: setting = json.load(s) else: setting = { \"token\": { \"discord\": env[\"discord_token\"], \"chunirec\":", "楽曲のノーツ数を指定します。 > 半角数字で入力してください。 **BPM** > 楽曲のBPMを指定します。 > 半角数字で入力してください。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。", "= \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS =", "[アーティスト] [難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数**", "\"token\": { \"discord\": env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"] }, \"logging\": { \"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"],", "= setting[\"misc\"][\"timezone\"] is_logging = setting[\"logging\"][\"logging\"] loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"] loglevel_file = setting[\"logging\"][\"loglevel_file\"] log_filename =", "> 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random -", "半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** >", "【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** >", "トークン CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"] DISCORD_TOKEN = setting[\"token\"][\"discord\"] # API関係 API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"]) #", "setting[\"misc\"][\"command_prefix\"] APP_VERSION = \"3.0\" CHANNEL_NAME = \"選曲bot\" # ヘルプメッセージ DECLARATION_NAME = f\"**CHUNITHM Random", "= setting[\"token\"][\"discord\"] # API関係 API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"]) # logger関係 tz = setting[\"misc\"][\"timezone\"] is_logging", "> それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。", "env[\"chunirec_token\"] }, \"logging\": { \"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"] },", "> 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA = f\"\"\" {DECLARATION_NAME} **WACCA選曲機能**", "- exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none 東方Project none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search - - -", "**アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 >", "\"\"\" HELPMES_ONGEKI = f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]`", "[アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数**", "= \"https://reiwa.f5.si/phigros_all.json\" # トークン CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"] DISCORD_TOKEN = setting[\"token\"][\"discord\"] # API関係 API_LIFETIME", "`{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI = f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki [曲数] [レベル(:high/low)] [ジャンル] [アーティスト]", "exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。 \"\"\" #", "[難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 >", "- - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。", "> 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 >", "os.path.isfile(\"setting.json\"): with open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\") as s: setting = json.load(s) else: setting =", "[ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` `{CMDPREF}search [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` {HIGHLOW}", "`{CMDPREF}random 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random - 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。", "- exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。 \"\"\"", "> 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。", "- - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 -", "none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search - - - - 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。", "【注意点】 - ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。 \"\"\" # 書きかけ HELPMES_MAIMAI = f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能**", "WACCA: `{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI = f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki [曲数] [レベル(:high/low)] [ジャンル]", "**難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとINFERNOの両方から検索します。 > レベルが指定されたときのみ機能します。 【注意点】 - ジャンルは1つのみ指定可能です。 【不具合】", "none 東方Project none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search - - - - 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】", "[曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW}", "\"loglevel_file\": env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"] }, \"misc\": { \"channel_id\": int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]),", "> 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 >", "- 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - WORLD'S ENDには対応していません。 - 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 -", "HELPMES_WACCA = f\"\"\" {DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可)", "[ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。", "ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。 \"\"\" # 書きかけ HELPMES_MAIMAI = f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai", "[ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` `{CMDPREF}search [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。", "14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。 \"\"\" # 書きかけ HELPMES_MAIMAI =", "= setting[\"logging\"][\"log_filename\"] # その他 MAX_MUSICS = setting[\"misc\"][\"max_musics\"] CMDPREF = setting[\"misc\"][\"command_prefix\"] APP_VERSION = \"3.0\"", "**WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル] [アーティスト]", "(`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。", "[BPM(:high/low)] [難易度]` {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 >", "[ジャンル] [アーティスト] [難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 >", "譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。", "\"channel_id\": int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"] } } #", "> 楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** >", "[アーティスト] [難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。", "半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。", "= \"選曲bot\" # ヘルプメッセージ DECLARATION_NAME = f\"**CHUNITHM Random Selector bot v{APP_VERSION}**\" HIGHLOW =", "is_logging = setting[\"logging\"][\"logging\"] loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"] loglevel_file = setting[\"logging\"][\"loglevel_file\"] log_filename = setting[\"logging\"][\"log_filename\"] #", "> 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 >", "- - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none 東方Project none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search -", "**オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル] [アーティスト]", "[難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** >", "= json.load(s) else: setting = { \"token\": { \"discord\": env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"] },", "\"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"] } } # URL URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\"", "『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。", "`{CMDPREF}random [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` `{CMDPREF}search [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)]", "URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\" #", "= \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\" # トークン CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"] DISCORD_TOKEN = setting[\"token\"][\"discord\"]", "- WORLD'S ENDには対応していません。 - 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 - オンゲキ: `{CMDPREF}help_ongeki` - WACCA: `{CMDPREF}help_wacca` \"\"\"", "[レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。", "【コマンド文字列】 `{CMDPREF}random_wacca [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]`", "> 楽曲のBPMを指定します。 > 半角数字で入力してください。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。", "- - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none 東方Project none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search", "}, \"logging\": { \"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"] }, \"misc\":", "楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 >", "[難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 >", "os import environ as env from distutils.util import strtobool if os.path.isfile(\"setting.json\"): with open(\"setting.json\",", "f\"\"\" {DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)]", "setting[\"misc\"][\"max_musics\"] CMDPREF = setting[\"misc\"][\"command_prefix\"] APP_VERSION = \"3.0\" CHANNEL_NAME = \"選曲bot\" # ヘルプメッセージ DECLARATION_NAME", "setting[\"logging\"][\"loglevel_file\"] log_filename = setting[\"logging\"][\"log_filename\"] # その他 MAX_MUSICS = setting[\"misc\"][\"max_musics\"] CMDPREF = setting[\"misc\"][\"command_prefix\"] APP_VERSION", "**難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random", "『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** > 楽曲のノーツ数を指定します。 > 半角数字で入力してください。", "- 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 - オンゲキ: `{CMDPREF}help_ongeki` - WACCA: `{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI = f\"\"\"", "楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。", "= setting[\"token\"][\"chunirec\"] DISCORD_TOKEN = setting[\"token\"][\"discord\"] # API関係 API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"]) # logger関係 tz", "- - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。", "Selector bot v{APP_VERSION}**\" HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM = f\"\"\" {DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random", "[アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。", "**レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト**", "> 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 >", "\"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\" # トークン CHUNIREC_TOKEN", "`{CMDPREF}random_ongeki 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki - 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。", "{ \"token\": { \"discord\": env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"] }, \"logging\": { \"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\":", "13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki - 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14", "> 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 \"\"\"", "= f\"\"\" {DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` `{CMDPREF}search", "URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA", "**アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** > 楽曲のノーツ数を指定します。 > 半角数字で入力してください。 **BPM**", "import strtobool if os.path.isfile(\"setting.json\"): with open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\") as s: setting = json.load(s)", "= setting[\"logging\"][\"loglevel_stdio\"] loglevel_file = setting[\"logging\"][\"loglevel_file\"] log_filename = setting[\"logging\"][\"log_filename\"] # その他 MAX_MUSICS = setting[\"misc\"][\"max_musics\"]", "[レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` `{CMDPREF}search [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]`", "\"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\"", "13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 -", "from os import environ as env from distutils.util import strtobool if os.path.isfile(\"setting.json\"): with", "書きかけ HELPMES_MAIMAI = f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]`", "APP_VERSION = \"3.0\" CHANNEL_NAME = \"選曲bot\" # ヘルプメッセージ DECLARATION_NAME = f\"**CHUNITHM Random Selector", "[レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 >", "= \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\" # トークン", "HELPMES_MAIMAI = f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rmai`でも可)", "- - 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - WORLD'S ENDには対応していません。 - 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。", "`:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM = f\"\"\" {DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)]", "[レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。", "- ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。 \"\"\" # 書きかけ HELPMES_MAIMAI = f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】", "> 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト**", "> 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとINFERNOの両方から検索します。", "> 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 >", "楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5 13+:up`:", "(`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。", "as s: setting = json.load(s) else: setting = { \"token\": { \"discord\": env[\"discord_token\"],", "{ \"channel_id\": int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"] } }", "= f\"**CHUNITHM Random Selector bot v{APP_VERSION}**\" HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM = f\"\"\"", "{ \"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"] }, \"misc\": { \"channel_id\":", "それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** > 楽曲が属するジャンルを指定します。", "楽曲のBPMを指定します。 > 半角数字で入力してください。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】", "それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル**", "> 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとINFERNOの両方から検索します。 > レベルが指定されたときのみ機能します。 【注意点】 -", "DECLARATION_NAME = f\"**CHUNITHM Random Selector bot v{APP_VERSION}**\" HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM =", "**アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。 >", "(`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。", "[ジャンル] [アーティスト] [難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 >", "- 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none 東方Project none 1000:low`:", "URL URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\"", "\"timezone\": env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"] } } # URL URL_chunirec", "【コマンド文字列】 `{CMDPREF}random_maimai [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]`", "[曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW}", "= f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai", "setting[\"misc\"][\"timezone\"] is_logging = setting[\"logging\"][\"logging\"] loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"] loglevel_file = setting[\"logging\"][\"loglevel_file\"] log_filename = setting[\"logging\"][\"log_filename\"]", "表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル**", "setting[\"logging\"][\"log_filename\"] # その他 MAX_MUSICS = setting[\"misc\"][\"max_musics\"] CMDPREF = setting[\"misc\"][\"command_prefix\"] APP_VERSION = \"3.0\" CHANNEL_NAME", "\"3.0\" CHANNEL_NAME = \"選曲bot\" # ヘルプメッセージ DECLARATION_NAME = f\"**CHUNITHM Random Selector bot v{APP_VERSION}**\"", "strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"] }, \"misc\": { \"channel_id\": int(env[\"channel_id\"]), \"timezone\":", "`{CMDPREF}help_ongeki` - WACCA: `{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI = f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki [曲数]", "> 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。", "東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。 \"\"\" # 書きかけ HELPMES_MAIMAI = f\"\"\"", "楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。", "[ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。", "import json import os from os import environ as env from distutils.util import", "f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)]", "> 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 >", "URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\" # トークン CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"] DISCORD_TOKEN =", "int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"] } } # URL", "\"max_musics\": int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"] } } # URL URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI =", "【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki - 13 - - -", "> 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** > 楽曲のノーツ数を指定します。 >", "URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\" # トークン CHUNIREC_TOKEN =", "> 半角数字で入力してください。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`:", "\"https://reiwa.f5.si/phigros_all.json\" # トークン CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"] DISCORD_TOKEN = setting[\"token\"][\"discord\"] # API関係 API_LIFETIME =", "東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search - - - - 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - WORLD'S", "13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none 東方Project none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。", "[アーティスト] [難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。", "> 楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA = f\"\"\" {DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca [曲数] [レベル(:high/low)] [ジャンル]", "- ジャンルは1つのみ指定可能です。 - WORLD'S ENDには対応していません。 - 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 - オンゲキ: `{CMDPREF}help_ongeki` - WACCA:", "\"chunirec\": env[\"chunirec_token\"] }, \"logging\": { \"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"]", "[ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。", "> 楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** >", "URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\" # トークン CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"] DISCORD_TOKEN = setting[\"token\"][\"discord\"] # API関係", "[アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 >", "指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki", "HELPMES_CHUNITHM = f\"\"\" {DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]`", "『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。", "(`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。", "【注意点】 - ジャンルは1つのみ指定可能です。 - WORLD'S ENDには対応していません。 - 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 - オンゲキ: `{CMDPREF}help_ongeki` -", "import os from os import environ as env from distutils.util import strtobool if", "> 楽曲のノーツ数を指定します。 > 半角数字で入力してください。 **BPM** > 楽曲のBPMを指定します。 > 半角数字で入力してください。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 >", "CMDPREF = setting[\"misc\"][\"command_prefix\"] APP_VERSION = \"3.0\" CHANNEL_NAME = \"選曲bot\" # ヘルプメッセージ DECLARATION_NAME =", "指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random - 13", "\"log_filename\": env[\"log_filename\"] }, \"misc\": { \"channel_id\": int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]),", "半角数字で入力してください。 **BPM** > 楽曲のBPMを指定します。 > 半角数字で入力してください。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。", "CHANNEL_NAME = \"選曲bot\" # ヘルプメッセージ DECLARATION_NAME = f\"**CHUNITHM Random Selector bot v{APP_VERSION}**\" HIGHLOW", "[ジャンル] [アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 >", "\"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"] }, \"misc\": { \"channel_id\": int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"],", "int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"] } } # URL URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI", "log_filename = setting[\"logging\"][\"log_filename\"] # その他 MAX_MUSICS = setting[\"misc\"][\"max_musics\"] CMDPREF = setting[\"misc\"][\"command_prefix\"] APP_VERSION =", "`{CMDPREF}random_ongeki - 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。", "(`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。", "= \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\" # トークン CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"]", "if os.path.isfile(\"setting.json\"): with open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\") as s: setting = json.load(s) else: setting", "[レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】", "env from distutils.util import strtobool if os.path.isfile(\"setting.json\"): with open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\") as s:", "その他 MAX_MUSICS = setting[\"misc\"][\"max_musics\"] CMDPREF = setting[\"misc\"][\"command_prefix\"] APP_VERSION = \"3.0\" CHANNEL_NAME = \"選曲bot\"", "exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none 東方Project none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search - - - -", "指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。", "> レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki - 13 -", "> 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。", "\"misc\": { \"channel_id\": int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"] }", "13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random - 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none", "> 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。", "オンゲキ: `{CMDPREF}help_ongeki` - WACCA: `{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI = f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki", "{ \"discord\": env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"] }, \"logging\": { \"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\":", "API関係 API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"]) # logger関係 tz = setting[\"misc\"][\"timezone\"] is_logging = setting[\"logging\"][\"logging\"] loglevel_stdio", "= f\"\"\" {DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca", "# ヘルプメッセージ DECLARATION_NAME = f\"**CHUNITHM Random Selector bot v{APP_VERSION}**\" HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\"", "[難易度]` `{CMDPREF}search [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** >", "\"r\", encoding=\"UTF-8_sig\") as s: setting = json.load(s) else: setting = { \"token\": {", "**レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA =", "\"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\" # トークン CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"] DISCORD_TOKEN = setting[\"token\"][\"discord\"] #", "- - - 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - WORLD'S ENDには対応していません。 - 一部の値が未登録になっている場合があります。", "表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 >", "int(setting[\"misc\"][\"api_lifetime\"]) # logger関係 tz = setting[\"misc\"][\"timezone\"] is_logging = setting[\"logging\"][\"logging\"] loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"] loglevel_file", "半角数字で入力してください。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。", "open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\") as s: setting = json.load(s) else: setting = { \"token\":", "> 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** > 楽曲のノーツ数を指定します。 > 半角数字で入力してください。 **BPM** >", "『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。", "\"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\"", "> 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5", "> 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 >", "> 指定する場合、『exp』もしくは『inf』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとINFERNOの両方から検索します。 > レベルが指定されたときのみ機能します。 【注意点】 - ジャンルは1つのみ指定可能です。 【不具合】 - 『オリジナル』を指定すると『TANO\\\\*C(オリジナル)』も同時に検索されてしまいます。 \"\"\"", "楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5 13+:up`:", "レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。 \"\"\" # 書きかけ", "{HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル**", "楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA = f\"\"\" {DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca [曲数] [レベル(:high/low)] [ジャンル] [アーティスト]", "f\"\"\" {DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` `{CMDPREF}search [レベル(:high/low)]", "> アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとINFERNOの両方から検索します。 > レベルが指定されたときのみ機能します。", "env[\"command_prefix\"] } } # URL URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI =", "else: setting = { \"token\": { \"discord\": env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"] }, \"logging\": {", "= setting[\"logging\"][\"logging\"] loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"] loglevel_file = setting[\"logging\"][\"loglevel_file\"] log_filename = setting[\"logging\"][\"log_filename\"] # その他", "= f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki", "\"選曲bot\" # ヘルプメッセージ DECLARATION_NAME = f\"**CHUNITHM Random Selector bot v{APP_VERSION}**\" HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。", "[レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rwacca`でも可) `{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】", "strtobool if os.path.isfile(\"setting.json\"): with open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\") as s: setting = json.load(s) else:", "tz = setting[\"misc\"][\"timezone\"] is_logging = setting[\"logging\"][\"logging\"] loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"] loglevel_file = setting[\"logging\"][\"loglevel_file\"] log_filename", "レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none 東方Project none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search - - - - 300:high`:", "from distutils.util import strtobool if os.path.isfile(\"setting.json\"): with open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\") as s: setting", "json import os from os import environ as env from distutils.util import strtobool", "**ノーツ数** > 楽曲のノーツ数を指定します。 > 半角数字で入力してください。 **BPM** > 楽曲のBPMを指定します。 > 半角数字で入力してください。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。", "[難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** >", "指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。", "**曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 >", "loglevel_file = setting[\"logging\"][\"loglevel_file\"] log_filename = setting[\"logging\"][\"log_filename\"] # その他 MAX_MUSICS = setting[\"misc\"][\"max_musics\"] CMDPREF =", "f\"**CHUNITHM Random Selector bot v{APP_VERSION}**\" HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM = f\"\"\" {DECLARATION_NAME}", "指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki - 13", "MAX_MUSICS = setting[\"misc\"][\"max_musics\"] CMDPREF = setting[\"misc\"][\"command_prefix\"] APP_VERSION = \"3.0\" CHANNEL_NAME = \"選曲bot\" #", "`{CMDPREF}random_ongeki [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可)", "レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random - 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none 東方Project", "**難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki", "**レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。", "> それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** >", "5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random - 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search", "env[\"log_filename\"] }, \"misc\": { \"channel_id\": int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]), \"command_prefix\":", "- - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none 東方Project none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search - -", "setting[\"token\"][\"chunirec\"] DISCORD_TOKEN = setting[\"token\"][\"discord\"] # API関係 API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"]) # logger関係 tz =", "import environ as env from distutils.util import strtobool if os.path.isfile(\"setting.json\"): with open(\"setting.json\", \"r\",", "[ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。", "API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"]) # logger関係 tz = setting[\"misc\"][\"timezone\"] is_logging = setting[\"logging\"][\"logging\"] loglevel_stdio =", "v{APP_VERSION}**\" HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM = f\"\"\" {DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random [曲数] [レベル(:high/low)]", "> レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random - 13 -", "# 書きかけ HELPMES_MAIMAI = f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai [曲数] [レベル(:high/low)] [ジャンル] [アーティスト]", "大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。", "他、以下の楽曲の検索機能があります。 - オンゲキ: `{CMDPREF}help_ongeki` - WACCA: `{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI = f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能**", "> 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki -", "東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。 \"\"\" # 書きかけ HELPMES_MAIMAI = f\"\"\" {DECLARATION_NAME}", "楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** > 楽曲のノーツ数を指定します。", "[難易度]` {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。", "【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random - 13 - - -", "> 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA = f\"\"\"", "> 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 >", "- 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】", "【コマンド文字列】 `{CMDPREF}random_ongeki [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]`", "} } # URL URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\"", "**レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト**", "= \"3.0\" CHANNEL_NAME = \"選曲bot\" # ヘルプメッセージ DECLARATION_NAME = f\"**CHUNITHM Random Selector bot", "[曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` `{CMDPREF}search [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)]", "f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM = f\"\"\" {DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)]", "> 半角数字で入力してください。 **BPM** > 楽曲のBPMを指定します。 > 半角数字で入力してください。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 >", "loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"] loglevel_file = setting[\"logging\"][\"loglevel_file\"] log_filename = setting[\"logging\"][\"log_filename\"] # その他 MAX_MUSICS =", "指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random", "# トークン CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"] DISCORD_TOKEN = setting[\"token\"][\"discord\"] # API関係 API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"])", "> 楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** >", "楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとINFERNOの両方から検索します。 >", "> 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** > 楽曲が属するジャンルを指定します。 >", "[ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。", "\"logging\": { \"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"] }, \"misc\": {", "楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式、もしくは『12.6』『13.7』のような譜面定数形式で入力してください。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。", "{DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` `{CMDPREF}search [レベル(:high/low)] [ジャンル]", "= f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM = f\"\"\" {DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random [曲数] [レベル(:high/low)] [ジャンル] [アーティスト]", "- オンゲキ: `{CMDPREF}help_ongeki` - WACCA: `{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI = f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】", "全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - WORLD'S ENDには対応していません。 - 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 - オンゲキ: `{CMDPREF}help_ongeki`", "楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。", "URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS", "# logger関係 tz = setting[\"misc\"][\"timezone\"] is_logging = setting[\"logging\"][\"logging\"] loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"] loglevel_file =", "distutils.util import strtobool if os.path.isfile(\"setting.json\"): with open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\") as s: setting =", "5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki - 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki", "`{CMDPREF}search_ongeki 14 東方Project`: 東方Projectの楽曲の中からレベル14の曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - LUNATICおよびボーナストラックには対応していません。 \"\"\" # 書きかけ HELPMES_MAIMAI", "HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM = f\"\"\" {DECLARATION_NAME} 【コマンド文字列】 `{CMDPREF}random [曲数] [レベル(:high/low)] [ジャンル]", "{DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル]", "{DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル]", "environ as env from distutils.util import strtobool if os.path.isfile(\"setting.json\"): with open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\")", "ジャンルは1つのみ指定可能です。 - WORLD'S ENDには対応していません。 - 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 - オンゲキ: `{CMDPREF}help_ongeki` - WACCA: `{CMDPREF}help_wacca`", "『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。", "- WACCA: `{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI = f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki [曲数] [レベル(:high/low)]", "半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA", "= \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA = \"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA =", "= setting[\"logging\"][\"loglevel_file\"] log_filename = setting[\"logging\"][\"log_filename\"] # その他 MAX_MUSICS = setting[\"misc\"][\"max_musics\"] CMDPREF = setting[\"misc\"][\"command_prefix\"]", "アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** > 楽曲のノーツ数を指定します。 > 半角数字で入力してください。 **BPM** > 楽曲のBPMを指定します。 > 半角数字で入力してください。", "レベルが指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random_ongeki`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki - 13 - -", "setting = json.load(s) else: setting = { \"token\": { \"discord\": env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"]", "> 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとMASTERの両方から検索します。 > レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5", "> 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 >", "}, \"misc\": { \"channel_id\": int(env[\"channel_id\"]), \"timezone\": env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"]", "[レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可) `{CMDPREF}search_ongeki [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}sgeki`でも可) {HIGHLOW} 【パラメータ】", "\"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"], \"log_filename\": env[\"log_filename\"] }, \"misc\": { \"channel_id\": int(env[\"channel_id\"]),", "**ジャンル** > 楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度**", "**ジャンル** > 楽曲が属するジャンルを指定します。 > 『ORIGINAL』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『イロドリミドリ』『ゲキマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数**", "logger関係 tz = setting[\"misc\"][\"timezone\"] is_logging = setting[\"logging\"][\"logging\"] loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"] loglevel_file = setting[\"logging\"][\"loglevel_file\"]", "東方Project none 1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search - - - - 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 -", "with open(\"setting.json\", \"r\", encoding=\"UTF-8_sig\") as s: setting = json.load(s) else: setting = {", "大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとINFERNOの両方から検索します。 > レベルが指定されたときのみ機能します。 【注意点】 - ジャンルは1つのみ指定可能です。", "encoding=\"UTF-8_sig\") as s: setting = json.load(s) else: setting = { \"token\": { \"discord\":", "全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random_ongeki 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki - 13 - - - - exp`:", "`{CMDPREF}search_wacca [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}swacca`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** > 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 >", "譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA = f\"\"\" {DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca [曲数]", "os from os import environ as env from distutils.util import strtobool if os.path.isfile(\"setting.json\"):", "# URL URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI = \"https://maimai.sega.jp/data/DXsongs.json\" URL_WACCA =", "= int(setting[\"misc\"][\"api_lifetime\"]) # logger関係 tz = setting[\"misc\"][\"timezone\"] is_logging = setting[\"logging\"][\"logging\"] loglevel_stdio = setting[\"logging\"][\"loglevel_stdio\"]", "大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** > 楽曲のノーツ数を指定します。 > 半角数字で入力してください。 **BPM** > 楽曲のBPMを指定します。 > 半角数字で入力してください。 **難易度** >", "レベルもしくはノーツ数が指定されたときのみ機能します。 【コマンド例】 `{CMDPREF}random`: 全楽曲の中からランダムに3曲選びます。 `{CMDPREF}random 5 13+:up`: レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random - 13 - -", "『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはMASTERのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『mas』と指定してください。", "楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** > 楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。", "楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA = f\"\"\" {DECLARATION_NAME}", "[BPM(:high/low)] [難易度]` `{CMDPREF}search [レベル(:high/low)] [ジャンル] [アーティスト] [ノーツ数(:high/low)] [BPM(:high/low)] [難易度]` {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数**", "\"\"\" # 書きかけ HELPMES_MAIMAI = f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai [曲数] [レベル(:high/low)] [ジャンル]", "> 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『オンゲキ』『POPS&ANIME』『niconico』『東方Project』『VARIETY』『チュウマイ』から1つ選んで入力してください。 **アーティスト** >", "楽曲のアーティスト名を指定します。 > アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** > 楽曲のノーツ数を指定します。 > 半角数字で入力してください。 **BPM** > 楽曲のBPMを指定します。", "`{CMDPREF}random_maimai [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}smai`でも可)", "[難易度]` (`{CMDPREF}rmai`でも可) `{CMDPREF}search_maimai [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}smai`でも可) {HIGHLOW} 【パラメータ】 指定しないパラメータは、`-`もしくは`none`と入力してください。 **曲数** >", "\"command_prefix\": env[\"command_prefix\"] } } # URL URL_chunirec = \"https://reiwa.f5.si/chunirec_all.json\" URL_ONGEKI = \"https://ongeki.sega.jp/assets/json/music/music.json\" URL_MAIMAI", "『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA = f\"\"\" {DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】", "> 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとINFERNOの両方から検索します。 > レベルが指定されたときのみ機能します。 【注意点】 - ジャンルは1つのみ指定可能です。 【不具合】 -", "ENDには対応していません。 - 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 - オンゲキ: `{CMDPREF}help_ongeki` - WACCA: `{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI =", "= { \"token\": { \"discord\": env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"] }, \"logging\": { \"logging\": strtobool(env[\"logging\"]),", "> 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **ノーツ数** > 楽曲のノーツ数を指定します。 > 半角数字で入力してください。 **BPM** > 楽曲のBPMを指定します。 > 半角数字で入力してください。 **難易度**", "\"discord\": env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"] }, \"logging\": { \"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"],", "> 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。 > 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 > 『アニメ/POP』『ボカロ』『東方アレンジ』『2.5次元』『バラエティ』『オリジナル』『TANO\\\\*C』『TANO\\\\*C(オリジナル)』から1つ選んで入力してください。 **アーティスト** >", "`{CMDPREF}search - - - - 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - WORLD'S ENDには対応していません。", "300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 - WORLD'S ENDには対応していません。 - 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 - オンゲキ:", "レベル13+以上の楽曲の中からランダムに5曲選びます。 `{CMDPREF}random_ongeki - 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search_ongeki 14 東方Project`:", "アーティスト名を入力してください。 > 大文字・小文字および全角・半角を考慮しない部分一致で検索されます。 **難易度** > 楽曲の難易度を指定します。EXPERTのみもしくはINFERNOのみの検索をする場合に使用します。 > 指定する場合、『exp』もしくは『inf』と指定してください。 > 指定されないか、不正な値を指定した場合は自動的にEXPERTとINFERNOの両方から検索します。 > レベルが指定されたときのみ機能します。 【注意点】", "env[\"discord_token\"], \"chunirec\": env[\"chunirec_token\"] }, \"logging\": { \"logging\": strtobool(env[\"logging\"]), \"loglevel_stdio\": env[\"loglevel_stdio\"], \"loglevel_file\": env[\"loglevel_file\"], \"log_filename\":", "`{CMDPREF}random - 13 - - - - exp`: レベル13のEXPERTの楽曲をランダムに3曲選びます。 `{CMDPREF}search none 東方Project none", "HELPMES_ONGEKI = f\"\"\" {DECLARATION_NAME} **オンゲキ選曲機能** 【コマンド文字列】 `{CMDPREF}random_ongeki [曲数] [レベル(:high/low)] [ジャンル] [アーティスト] [難易度]` (`{CMDPREF}rgeki`でも可)", "1000:low`: 東方Projectの楽曲の中からノーツ数が1000以下の楽曲を検索します。 `{CMDPREF}search - - - - 300:high`: 全楽曲の中からBPM300以上の楽曲を検索します。 【注意点】 - ジャンルは1つのみ指定可能です。 -", "> 譜面定数は使えません。 **ジャンル** > 楽曲が属するジャンルを指定します。 \"\"\" HELPMES_WACCA = f\"\"\" {DECLARATION_NAME} **WACCA選曲機能** 【コマンド文字列】 `{CMDPREF}random_wacca", "\"https://reiwa.f5.si/wacca_all.json\" URL_ARCAEA = \"https://reiwa.f5.si/arcaea_all.json\" URL_PHIGROS = \"https://reiwa.f5.si/phigros_all.json\" # トークン CHUNIREC_TOKEN = setting[\"token\"][\"chunirec\"] DISCORD_TOKEN", "= setting[\"misc\"][\"max_musics\"] CMDPREF = setting[\"misc\"][\"command_prefix\"] APP_VERSION = \"3.0\" CHANNEL_NAME = \"選曲bot\" # ヘルプメッセージ", "> 表示する曲数を指定します。最大{MAX_MUSICS}曲まで表示できます。 > それ以上の数字を入力した場合、ランダム選曲コマンドにおいては{MAX_MUSICS}曲として扱われ、検索コマンドではエラー扱いになります。 > 指定されなかった場合、3曲として扱われます。 > 半角数字で入力してください。 **レベル** > 楽曲のレベルを指定します。 > 『10』『13+』のようなレベル表記形式で入力してください。", "WORLD'S ENDには対応していません。 - 一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 - オンゲキ: `{CMDPREF}help_ongeki` - WACCA: `{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI", "setting[\"token\"][\"discord\"] # API関係 API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"]) # logger関係 tz = setting[\"misc\"][\"timezone\"] is_logging =", "一部の値が未登録になっている場合があります。 他、以下の楽曲の検索機能があります。 - オンゲキ: `{CMDPREF}help_ongeki` - WACCA: `{CMDPREF}help_wacca` \"\"\" HELPMES_ONGEKI = f\"\"\" {DECLARATION_NAME}", "env[\"timezone\"], \"api_lifetime\": int(env[\"api_lifetime\"]), \"max_musics\": int(env[\"max_musics\"]), \"command_prefix\": env[\"command_prefix\"] } } # URL URL_chunirec =", "# API関係 API_LIFETIME = int(setting[\"misc\"][\"api_lifetime\"]) # logger関係 tz = setting[\"misc\"][\"timezone\"] is_logging = setting[\"logging\"][\"logging\"]", "ヘルプメッセージ DECLARATION_NAME = f\"**CHUNITHM Random Selector bot v{APP_VERSION}**\" HIGHLOW = f\"\"\"※`(:high/low)`がついているパラメータは、後ろに『:high』もしくは『:low』を付け足すことで『以上』『以下』を表すことができます。 `:up/:down`や`:big/:small`でも可能です。\"\"\" HELPMES_CHUNITHM", "- LUNATICおよびボーナストラックには対応していません。 \"\"\" # 書きかけ HELPMES_MAIMAI = f\"\"\" {DECLARATION_NAME} **maimaiでらっくす選曲機能** 【コマンド文字列】 `{CMDPREF}random_maimai [曲数]" ]
[ "likelihood_x (str, optional): input data likelihood type. Defaults to 'gaussian'. likelihood_y (str, optional):", "tensor with the log variances (batch_size, latent_dim) samples (int, optional): number of samples.", "import * from src.models.hmc import * # ============= HMCVAE ============= # class HMCVAE(BaseVAE):", "(float, optional): Learning rate for the decoder (p(x|z1)). Defaults to 1e-3. lr_predictor (float,", "self.HMC = HMC(dim=latent_dim, L=L, T=T, chains=chains, chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False self.L = L self.T", "observed_target) hmc (bool): sample posterior using HMC (True). Defaults to True samples (int):", "z=z, theta=theta_x).sum(-1) rec_y = self.predictor.logp(yt, observed_y, z=zx).sum(-1) kls = self.encoder.regularizer(mu_z, logvar_z, observed) elbo", "loss_2, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('HMC_objective', -loss_1, on_step=False, on_epoch=True, prog_bar=True, logger=True) self.step_idx +=", "true posterior z, _ = self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples) return z # ============= Modified", "z # ============= Modified PL functions ============= # def configure_optimizers(self): opt_vae = torch.optim.Adam(list(self.decoder.parameters())", "kls.sum(0).unsqueeze(-1) elbo = elbo[elbo!=0].mean() rec_x = rec_x[rec_x!=0].mean() rec_y = rec_y[rec_y!=0].mean() kl_mean = torch.zeros(len(kls)).to(self.device)", "https://arxiv.org/abs/2202.04599 \"\"\" def __init__(self, dataset: str, dim_x: int, dim_y: int, latent_dim = 10,", "opt_hmc.step() if self.sksd and self.step_idx % self.update_s_each == 0: self.HMC.log_inflation.requires_grad = True deactivate(self.encoder)", "1, data_path='../data/', split_idx=0, L=5, T=10, chains=1, chains_sksd=30, sksd=1, pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3,", "opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step() # Optimize theta_x, theta_y and phi (decoders and HMC) activate(self.decoder)", "= self.normalize_y(y) yon = yn * observed_y y_tilde = torch.cat([yon, observed_y], axis=1) xy", "kl in enumerate(kls): self.log('kl_{:d}'.format(l), kl, on_step=False, on_epoch=True, prog_bar=False, logger=True) else: self.hmc=True loss_3, loss_1,", "on_epoch=True, prog_bar=True, logger=True) if logging: self.log('-rec_x', -rec_x, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('-rec_y', -rec_y,", "logvar_z = self.encoder(xy) z = self.sample_z(mu_z, logvar_z, samples=samples, hmc=False) theta_x = self.decoder(z) x_hat", "self.log('-rec_x', -rec_x, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('-rec_y', -rec_y, on_step=False, on_epoch=True, prog_bar=False, logger=True) for", "(torch.Tensor): tensor with the log variances (batch_size, latent_dim) samples (int, optional): number of", "% self.update_s_each == 0: self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False", "Defaults to 0.1. imbalanced_y (bool, optional): True for compensating imbalanced classification. Defaults to", "torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale = torch.optim.Adam([self.HMC.log_inflation], lr=self.lr_scale) return [opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc, opt_scale]", "elbo[elbo!=0].mean() rec_x = rec_x[rec_x!=0].mean() rec_y = rec_y[rec_y!=0].mean() kl_mean = torch.zeros(len(kls)).to(self.device) for l, kl", "= chains_sksd self.sksd = sksd self.pre_steps = pre_steps self.lr_pre = lr_pre self.lr_encoder =", "observed_x], axis=1) y = y.view(-1, self.dim_y) observed_y = observed_y.view(-1, self.dim_y) # Normalize the", "lr=self.lr_decoder, weight_decay=0.01) opt_predictor = torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01) opt_encoder = torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01) opt_hmc", "returns: loss_VI, loss_HMC, loss_SKSD, rec_x, rec_y, kl \"\"\" if hmc==True: # Activate only", "data_path='../data/', split_idx=0, L=5, T=10, chains=1, chains_sksd=30, sksd=1, pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3,", "\"\"\" if hmc==True: # Activate only encoder activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False", "training stage. Defaults to 1e-3. lr_encoder (float, optional): Learning rate for the encoder", "logvar: torch.Tensor, samples=1, hmc=True) -> torch.Tensor: \"\"\" Draw latent samples from a given", "steps. Defaults to 5. T (int, optional): length of the HMC chains. Defaults", "batch_idx (int): batch index from the training set logging (bool): log metrics into", "hmc (bool): sample posterior using HMC (True). Defaults to True samples (int): number", "opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step() # Optimize theta_x, theta_y and phi (decoders and", "Args: batch (tuple): contains (data, observed_data, target, observed_target) hmc (bool): sample posterior using", "x, observed_x, y, observed_y = batch x = x.view(-1, self.dim_x) # Normalize the", "def sample_z(self, mu: torch.Tensor, logvar: torch.Tensor, samples=1, hmc=True) -> torch.Tensor: \"\"\" Draw latent", "a given approx posterior parameterized by mu and logvar Args: mu (torch.Tensor): tensor", "samples=samples, hmc=False) theta_x = self.decoder(z) x_hat = self.build_x_hat(xn, observed_x, theta_x) zx = torch.cat([z,x_hat],dim=-1)", "following https://arxiv.org/abs/2202.04599 - For the first pre_steps, optimize parameters by maximizing the ELBO", "learning reate for all the parameters during the VI training stage. Defaults to", "T (int, optional): length of the HMC chains. Defaults to 10. chains (int,", "hmc samples or Gaussian samples from the proposal. Defaults to True. Returns: torch.Tensor:", "prog_bar=False, logger=True) for l, kl in enumerate(kls): self.log('kl_{:d}'.format(l), kl, on_step=False, on_epoch=True, prog_bar=False, logger=True)", "self.lr_predictor = lr_predictor self.lr_hmc = lr_hmc self.lr_scale = lr_scale self.update_s_each = update_s_each self.hmc=True", "optional): Learning rate for the HMC hyperparameters (matrix of step sizes). Defaults to", "chains. Defaults to 10. chains (int, optional): number of parallel HMC chains. Defaults", "returns elbo, logp and sksd # Activate decoder, predictor and hmc activate(self.decoder) activate(self.predictor)", "rate for the predictor. Defaults to 1e-3. lr_hmc (float, optional): Learning rate for", "data) mu_z, logvar_z = self.encoder(xy) z = self.sample_z(mu_z, logvar_z, samples=samples, hmc=False) theta_x =", "arch='base', dim_h=256, likelihood_x = 'gaussian', likelihood_y = 'gaussian', variance=0.1, imbalanced_y = False, categories_y", "a Hamiltonian VAE (HMC-VAE) as described in https://arxiv.org/abs/2202.04599 \"\"\" def __init__(self, dataset: str,", "-> tuple: \"\"\" Forward data through the model. For the pretraining stage, use", "self.sksd==1: # Deactivate everything except scale self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad", "kl_mean else: # returns elbo, logp and sksd # Activate decoder, predictor and", "lr_scale = 1e-2, update_s_each=10 ): \"\"\" HMCVAE Initialization Args: dataset (str): name of", "(bool): log metrics into Tensorboard (True). Default True \"\"\" (opt_vae, opt_decoder, opt_predictor, opt_encoder,", "rec_y, kls = self.forward(batch, hmc=False, samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step() self.log('ELBO', -loss_3, on_step=False, on_epoch=True,", "ELBO. Defaults to 1. data_path (str, optional): path to load/save the data. Defaults", "keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0) # Define the HMC objective self.HMC.logp = self.logp_func(xo, observed_x, yon,", "to load/save the data. Defaults to '../data/'. split_idx (int, optional): idx of the", "128. lr (float, optional): learning rate for the parameter optimization. Defaults to 1e-3.", "loss_2 = self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else: loss_2 = None return loss_3, loss_1, loss_2 def", "# Reparametrization z = reparameterize(mu, torch.exp(logvar)) else: # sample from the true posterior", "optimize parameters by maximizing the ELBO - For the rest, optimize encoder using", "Args: mu (torch.Tensor): tensor with the means (batch_size, latent_dim) logvar (torch.Tensor): tensor with", "steps (before using HMC). Defaults to 18e3. lr_pre (float, optional): learning reate for", "hmc==False: # returns elbo return loss_3, rec_x, rec_y, kl_mean else: # returns elbo,", "batch, contains (data, observed_data, target, observed_target) \"\"\" batch = [b.to(self.device) for b in", "compensating imbalanced classification. Defaults to False. categories_y (int, optional): number of categories when", "...) dim_x (int): input data dimension dim_y (int): target data dimension latent_dim (int,", "latent_dim = latent_dim, arch=arch, dim_h=dim_h, likelihood_x = likelihood_x, likelihood_y = likelihood_y, variance=variance, imbalanced_y=imbalanced_y,", "+ # All rights reserved. This file is part of the HH-VAEM, and", "yon = yn * observed_y y_tilde = torch.cat([yon, observed_y], axis=1) xy = torch.cat([x_tilde,", "lr=1e-3, samples_MC = 1, data_path='../data/', split_idx=0, L=5, T=10, chains=1, chains_sksd=30, sksd=1, pre_steps=2e3, lr_pre=1e-3,", "logging: self.log('SKSD', loss_2, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('HMC_objective', -loss_1, on_step=False, on_epoch=True, prog_bar=True, logger=True)", "(for not using kl if no observed data) mu_z, logvar_z = self.encoder(xy) z", "for computing the ELBO. Defaults to 1. data_path (str, optional): path to load/save", "self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples) return z # ============= Modified PL functions ============= # def", "encoder parameters. Defaults to 1e-3. lr_decoder (float, optional): Learning rate for the decoder", "opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale) opt_scale.step() scale = torch.exp(self.HMC.log_inflation) self.log('scale', scale, on_step=False, on_epoch=True,", "from the training set logging (bool): log metrics into Tensorboard (True). Default True", "factor. Defaults to 10. \"\"\" super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y, latent_dim = latent_dim, arch=arch,", "# returns elbo return loss_3, rec_x, rec_y, kl_mean else: # returns elbo, logp", "optional): draw hmc samples or Gaussian samples from the proposal. Defaults to True.", "in enumerate(kls): self.log('kl_{:d}'.format(l), kl, on_step=False, on_epoch=True, prog_bar=False, logger=True) else: self.hmc=True loss_3, loss_1, loss_2", "opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step() # Optimize theta_x, theta_y and phi (decoders and HMC)", "Encoder again for not sharing gradients mu_z, logvar_z = self.encoder(xy) zT = self.sample_z(mu_z,", "log metrics into Tensorboard (True). Default True \"\"\" (opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc,", "##### Optimization # Optimize psi (encoder) activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad", "learning rate for the parameter optimization. Defaults to 1e-3. samples_MC (int, optional): number", "logger=True) self.log('-rec_y', -rec_y, on_step=False, on_epoch=True, prog_bar=False, logger=True) for l, kl in enumerate(kls): self.log('kl_{:d}'.format(l),", "loss_3 = -elbo if hmc==False: # returns elbo return loss_3, rec_x, rec_y, kl_mean", "def configure_optimizers(self): opt_vae = torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters()) + list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01) opt_decoder =", "number of standard VI training steps (before using HMC). Defaults to 18e3. lr_pre", "training_step(self, batch: tuple, batch_idx: int, logging: bool=True): \"\"\" Perform a traning step following", "using HMC (True). Defaults to True samples (int): number of MC samples for", "self.hmc=True self.save_hyperparameters('L', 'T', 'chains', 'sksd', 'pre_steps', 'lr_pre', 'lr_encoder', 'lr_decoder', 'lr_predictor', 'lr_hmc', 'lr_scale', 'update_s_each')", "xy = torch.cat([x_tilde, y_tilde], axis=1) observed = torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0) # Define", "q(eps|zy) using the SKSD regularizer (1) or not (0). Defaults to 1. pre_steps", "= False # Encoder again for not sharing gradients mu_z, logvar_z = self.encoder(xy)", "factor for q(eps|zy) using the SKSD regularizer (1) or not (0). Defaults to", "opt_scale) = self.optimizers(use_pl_optimizer=True) if self.step_idx < self.pre_steps: self.hmc=False loss_3, rec_x, rec_y, kls =", "batch (tuple): contains (data, observed_data, target, observed_target) hmc (bool): sample posterior using HMC", "stage. Defaults to 1e-3. lr_encoder (float, optional): Learning rate for the encoder parameters.", "(tuple): contains (data, observed_data, target, observed_target) Returns: tuple: preprocessed batch, contains (data, observed_data,", "(xt=x if no preprocessing) # observed is observed_x OR observed_y (for not using", "rec_y, kl If hmc=True, returns: loss_VI, loss_HMC, loss_SKSD, rec_x, rec_y, kl \"\"\" if", "target is categorical. Defaults to 1. prediction_metric (str, optional): name of the prediction", "stage, use the ELBO. For the rest, use HMC Args: batch (tuple): contains", "= self.logp_func(xo, observed_x, yon, observed_y) return xn, yn, xy, observed def sample_z(self, mu:", "if no preprocessing) # observed is observed_x OR observed_y (for not using kl", "prog_bar=True, logger=True) self.step_idx += 1 def preprocess_batch(self, batch: tuple): \"\"\" Preprocessing operations for", "'sksd', 'pre_steps', 'lr_pre', 'lr_encoder', 'lr_decoder', 'lr_predictor', 'lr_hmc', 'lr_scale', 'update_s_each') self.step_idx=0 # training step", "factor Defaults to 1e-2. update_s_each (int, optional): Interval of steps for optimizing the", "# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright (c) 2022 by <NAME>, UC3M. + # All rights", "# sample from the true posterior z, _ = self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples) return", "draw hmc samples or Gaussian samples from the proposal. Defaults to True. Returns:", "optional): name of the prediction metric for validation ('rmse', 'accuracy'). Defaults to 'rmse'.", "return loss_3, loss_1, loss_2 def training_step(self, batch: tuple, batch_idx: int, logging: bool=True): \"\"\"", "hmc (bool, optional): draw hmc samples or Gaussian samples from the proposal. Defaults", "split. Defaults to 0. L (int, optional): number of Leapfrog steps. Defaults to", "Preprocessing operations for the batch (overrides the base class function) for defining the", "when the target is categorical. Defaults to 1. prediction_metric (str, optional): name of", "the proposal. Defaults to True. Returns: torch.Tensor: latent samples \"\"\" if hmc==False or", "scale self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False loss_2 = self.HMC.evaluate_sksd(mu_z,", "using HMC). Defaults to 18e3. lr_pre (float, optional): learning reate for all the", "= self.normalize_x(x) xt, yt, xy, observed = self.preprocess_batch(batch) # xt is the preprocessed", "Leapfrog steps. Defaults to 5. T (int, optional): length of the HMC chains.", "opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step() # Optimize theta_x, theta_y and phi (decoders", "y) Args: batch (tuple): contains (data, observed_data, target, observed_target) Returns: tuple: preprocessed batch,", "data through the model. For the pretraining stage, use the ELBO. For the", "self.HMC.log_eps.requires_grad = False loss_2 = self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else: loss_2 = None return loss_3,", "on_step=False, on_epoch=True, prog_bar=False, logger=True) for l, kl in enumerate(kls): self.log('kl_{:d}'.format(l), kl, on_step=False, on_epoch=True,", "rec_y = self.predictor.logp(yt, observed_y, z=zx).sum(-1) kls = self.encoder.regularizer(mu_z, logvar_z, observed) elbo = rec_x", "Optimize theta_x, theta_y and phi (decoders and HMC) activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True", "if self.step_idx < self.pre_steps: self.hmc=False loss_3, rec_x, rec_y, kls = self.forward(batch, hmc=False, samples=self.samples_MC)", "the SKSD. Defaults to 30. sksd (int, optional): learn a scale factor for", "opt_decoder = torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01) opt_predictor = torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01) opt_encoder = torch.optim.Adam(list(self.encoder.parameters()),", "from a given approx posterior parameterized by mu and logvar Args: mu (torch.Tensor):", "============= Modified PL functions ============= # def configure_optimizers(self): opt_vae = torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters())", "rest using HMC objective and SKSD Args: batch (tuple): contains (data, observed_data, target,", "10. chains (int, optional): number of parallel HMC chains. Defaults to 1. chains_sksd", "HMCVAE Initialization Args: dataset (str): name of the dataset (boston, mnist, ...) dim_x", "self.sksd and self.step_idx % self.update_s_each == 0: self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor)", "opt_vae.step() self.log('ELBO', -loss_3, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('-rec_x', -rec_x, on_step=False, on_epoch=True,", "self.update_s_each == 0: self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False opt_encoder.zero_grad()", "* observed_x x_tilde = torch.cat([xo, observed_x], axis=1) y = y.view(-1, self.dim_y) observed_y =", "(_type_, optional): Learning rate for the scale (inflation) factor Defaults to 1e-2. update_s_each", "likelihood_y, variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size, lr=lr, samples_MC = samples_MC, data_path=data_path, split_idx=split_idx) self.HMC", "x_hat = self.build_x_hat(xn, observed_x, theta_x) zx = torch.cat([z,x_hat],dim=-1) rec_x = self.decoder.logp(xt, observed_x, z=z,", "self.hmc=False loss_3, rec_x, rec_y, kls = self.forward(batch, hmc=False, samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step() self.log('ELBO',", "sample from the true posterior z, _ = self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples) return z", "= torch.cat([z,x_hat],dim=-1) rec_x = self.decoder.logp(xt, observed_x, z=z, theta=theta_x).sum(-1) rec_y = self.predictor.logp(yt, observed_y, z=zx).sum(-1)", "(int, optional): dimension of the latent space. Defaults to 10. arch (str, optional):", "For the pretraining stage, use the ELBO. For the rest, use HMC Args:", "torch.exp(logvar_z)) else: loss_2 = None return loss_3, loss_1, loss_2 def training_step(self, batch: tuple,", "of Leapfrog steps. Defaults to 5. T (int, optional): length of the HMC", "(str, optional): name of the prediction metric for validation ('rmse', 'accuracy'). Defaults to", "= pre_steps self.lr_pre = lr_pre self.lr_encoder = lr_encoder self.lr_decoder = lr_decoder self.lr_predictor =", "the HMC hyperparameters (matrix of step sizes). Defaults to 1e-3. lr_scale (_type_, optional):", "def __init__(self, dataset: str, dim_x: int, dim_y: int, latent_dim = 10, arch='base', dim_h=256,", "bool=True): \"\"\" Perform a traning step following https://arxiv.org/abs/2202.04599 - For the first pre_steps,", "that should have + # been included as part of this package. +", "= rec_y[rec_y!=0].mean() kl_mean = torch.zeros(len(kls)).to(self.device) for l, kl in enumerate(kls): kl_mean[l]= kl[kl!=0].mean() loss_3", "the HH-VAEM, and is released under + # the \"MIT License Agreement\". Please", "(int, optional): idx of the training split. Defaults to 0. L (int, optional):", "of step sizes). Defaults to 1e-3. lr_scale (_type_, optional): Learning rate for the", "[opt_decoder, opt_predictor, opt_hmc]) opt_decoder.step() opt_predictor.step() opt_hmc.step() if self.sksd and self.step_idx % self.update_s_each ==", "of the architecture for encoder/decoder from the 'archs' file. Defaults to 'base'. dim_h", "opt_scale.step() scale = torch.exp(self.HMC.log_inflation) self.log('scale', scale, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('SKSD',", "samples=samples) loss_1 = -self.HMC.logp(zT) loss_1 = loss_1[loss_1!=0].mean() if self.sksd==1: # Deactivate everything except", "Copyright (c) 2022 by <NAME>, UC3M. + # All rights reserved. This file", "dim_y (int): target data dimension latent_dim (int, optional): dimension of the latent space.", "self.HMC.log_eps.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale) opt_scale.step() scale =", "self.dim_x) # Normalize the data xn = self.normalize_x(x) xo = xn * observed_x", "(str, optional): name of the architecture for encoder/decoder from the 'archs' file. Defaults", "to 10. \"\"\" super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y, latent_dim = latent_dim, arch=arch, dim_h=dim_h, likelihood_x", "dim_y=dim_y, latent_dim = latent_dim, arch=arch, dim_h=dim_h, likelihood_x = likelihood_x, likelihood_y = likelihood_y, variance=variance,", "torch.Tensor, samples=1, hmc=True) -> torch.Tensor: \"\"\" Draw latent samples from a given approx", "lr_hmc (float, optional): Learning rate for the HMC hyperparameters (matrix of step sizes).", "(tuple): contains (data, observed_data, target, observed_target) hmc (bool): sample posterior using HMC (True).", "# All rights reserved. This file is part of the HH-VAEM, and is", "using the SKSD regularizer (1) or not (0). Defaults to 1. pre_steps (float,", "logp and sksd # Activate decoder, predictor and hmc activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad =", "= torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01) opt_predictor = torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01) opt_encoder = torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder,", "All rights reserved. This file is part of the HH-VAEM, and is released", "sample posterior using HMC (True). Defaults to True samples (int): number of MC", "= L self.T = T self.chains = chains self.chains_sksd = chains_sksd self.sksd =", "lr_predictor=1e-3, lr_hmc=1e-3, lr_scale = 1e-2, update_s_each=10 ): \"\"\" HMCVAE Initialization Args: dataset (str):", "'T', 'chains', 'sksd', 'pre_steps', 'lr_pre', 'lr_encoder', 'lr_decoder', 'lr_predictor', 'lr_hmc', 'lr_scale', 'update_s_each') self.step_idx=0 #", "30. sksd (int, optional): learn a scale factor for q(eps|zy) using the SKSD", "optional): True for compensating imbalanced classification. Defaults to False. categories_y (int, optional): number", "observed) elbo = rec_x + rec_y - kls.sum(0).unsqueeze(-1) elbo = elbo[elbo!=0].mean() rec_x =", "# ============= Modified PL functions ============= # def configure_optimizers(self): opt_vae = torch.optim.Adam(list(self.decoder.parameters()) +", "is observed_x OR observed_y (for not using kl if no observed data) mu_z,", "self.HMC.log_inflation.requires_grad = False # Encoder again for not sharing gradients mu_z, logvar_z =", "# observed is observed_x OR observed_y (for not using kl if no observed", "input data dimension dim_y (int): target data dimension latent_dim (int, optional): dimension of", "for the scale (inflation) factor Defaults to 1e-2. update_s_each (int, optional): Interval of", "samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step() self.log('ELBO', -loss_3, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('-rec_x',", "True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False # Encoder again for not sharing gradients mu_z,", "dim_y: int, latent_dim = 10, arch='base', dim_h=256, likelihood_x = 'gaussian', likelihood_y = 'gaussian',", "for the batch (overrides the base class function) for defining the HMC objective", "samples=1, hmc=True) -> torch.Tensor: \"\"\" Draw latent samples from a given approx posterior", "mu.repeat(samples, 1, 1).transpose(0, 1) logvar = logvar.repeat(samples, 1, 1).transpose(0, 1) # Reparametrization z", "xy, observed = self.preprocess_batch(batch) # xt is the preprocessed input (xt=x if no", "kl If hmc=True, returns: loss_VI, loss_HMC, loss_SKSD, rec_x, rec_y, kl \"\"\" if hmc==True:", "-loss_1, on_step=False, on_epoch=True, prog_bar=True, logger=True) self.step_idx += 1 def preprocess_batch(self, batch: tuple): \"\"\"", "not using kl if no observed data) mu_z, logvar_z = self.encoder(xy) z =", "the hidden vectors. Defaults to 256. likelihood_x (str, optional): input data likelihood type.", "split_idx (int, optional): idx of the training split. Defaults to 0. L (int,", "using ELBO, and the rest using HMC objective and SKSD Args: batch (tuple):", "lr=lr, samples_MC = samples_MC, data_path=data_path, split_idx=split_idx) self.HMC = HMC(dim=latent_dim, L=L, T=T, chains=chains, chains_sksd=chains_sksd,", "axis=1) xy = torch.cat([x_tilde, y_tilde], axis=1) observed = torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0) #", "samples (int, optional): number of samples. Defaults to 1. hmc (bool, optional): draw", "src.models.hmc import * # ============= HMCVAE ============= # class HMCVAE(BaseVAE): \"\"\" Implements a", "predictor and hmc activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False #", "# Activate decoder, predictor and hmc activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad", "is categorical. Defaults to 1. prediction_metric (str, optional): name of the prediction metric", "1 def preprocess_batch(self, batch: tuple): \"\"\" Preprocessing operations for the batch (overrides the", "HMC) activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad()", "self.log('HMC_objective', -loss_1, on_step=False, on_epoch=True, prog_bar=True, logger=True) self.step_idx += 1 def preprocess_batch(self, batch: tuple):", "z = reparameterize(mu, torch.exp(logvar)) else: # sample from the true posterior z, _", "self.HMC.logp = self.logp_func(xo, observed_x, yon, observed_y) return xn, yn, xy, observed def sample_z(self,", "self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False loss_2 = self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z))", "posterior parameterized by mu and logvar Args: mu (torch.Tensor): tensor with the means", "self.lr_pre = lr_pre self.lr_encoder = lr_encoder self.lr_decoder = lr_decoder self.lr_predictor = lr_predictor self.lr_hmc", "for encoder/decoder from the 'archs' file. Defaults to 'base'. dim_h (int, optional): dimension", "Hamiltonian VAE (HMC-VAE) as described in https://arxiv.org/abs/2202.04599 \"\"\" def __init__(self, dataset: str, dim_x:", "= yn * observed_y y_tilde = torch.cat([yon, observed_y], axis=1) xy = torch.cat([x_tilde, y_tilde],", "steps for optimizing the scale factor. Defaults to 10. \"\"\" super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x,", "dimension dim_y (int): target data dimension latent_dim (int, optional): dimension of the latent", "means (batch_size, latent_dim) logvar (torch.Tensor): tensor with the log variances (batch_size, latent_dim) samples", "1e-2. update_s_each (int, optional): Interval of steps for optimizing the scale factor. Defaults", "the dataset (boston, mnist, ...) dim_x (int): input data dimension dim_y (int): target", "if logging: self.log('-rec_x', -rec_x, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('-rec_y', -rec_y, on_step=False, on_epoch=True, prog_bar=False,", "<reponame>ipeis/HH-VAEM # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright (c) 2022 by <NAME>, UC3M. + # All", "the predictor. Defaults to 1e-3. lr_hmc (float, optional): Learning rate for the HMC", "latent space. Defaults to 10. arch (str, optional): name of the architecture for", "OR observed_y (for not using kl if no observed data) mu_z, logvar_z =", "\"MIT License Agreement\". Please see the LICENSE file that should have + #", "T self.chains = chains self.chains_sksd = chains_sksd self.sksd = sksd self.pre_steps = pre_steps", "the LICENSE file that should have + # been included as part of", "during the VI training stage. Defaults to 1e-3. lr_encoder (float, optional): Learning rate", "functions ============= # def configure_optimizers(self): opt_vae = torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters()) + list(self.encoder.parameters()), lr=self.lr_pre,", "(str, optional): input data likelihood type. Defaults to 'gaussian'. likelihood_y (str, optional): target", "of parallel HMC chains. Defaults to 1. chains_sksd (int, optional): number of parallel", "HMC(dim=latent_dim, L=L, T=T, chains=chains, chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False self.L = L self.T = T", "batch: tuple, hmc=True, samples=1) -> tuple: \"\"\" Forward data through the model. For", "= self.normalize_x(x) xo = xn * observed_x x_tilde = torch.cat([xo, observed_x], axis=1) y", "of steps for optimizing the scale factor. Defaults to 10. \"\"\" super(HMCVAE, self).__init__(dataset=dataset,", "optional): number of Leapfrog steps. Defaults to 5. T (int, optional): length of", "x = x.view(-1, self.dim_x) # Normalize the data xn = self.normalize_x(x) xo =", "observed_data, target, observed_target) Returns: tuple: preprocessed batch, contains (data, observed_data, target, observed_target) \"\"\"", "if hmc==False or self.validation and self.global_step < self.pre_steps: # Repeat samples_MC times for", "keepdim=True)>0) # Define the HMC objective self.HMC.logp = self.logp_func(xo, observed_x, yon, observed_y) return", "z = self.sample_z(mu_z, logvar_z, samples=samples, hmc=False) theta_x = self.decoder(z) x_hat = self.build_x_hat(xn, observed_x,", "* observed_y y_tilde = torch.cat([yon, observed_y], axis=1) xy = torch.cat([x_tilde, y_tilde], axis=1) observed", "= torch.cat([yon, observed_y], axis=1) xy = torch.cat([x_tilde, y_tilde], axis=1) observed = torch.logical_or(observed_x.sum(-1, keepdim=True)>0,", "= self.predictor.logp(yt, observed_y, z=zx).sum(-1) kls = self.encoder.regularizer(mu_z, logvar_z, observed) elbo = rec_x +", "loss_1 = loss_1[loss_1!=0].mean() if self.sksd==1: # Deactivate everything except scale self.HMC.log_inflation.requires_grad = True", "file is part of the HH-VAEM, and is released under + # the", "else: # sample from the true posterior z, _ = self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples)", "(True). Defaults to True samples (int): number of MC samples for computing the", "ELBO Returns: If hmc=False, returns: loss_VI, rec_x, rec_y, kl If hmc=True, returns: loss_VI,", "chains_sksd self.sksd = sksd self.pre_steps = pre_steps self.lr_pre = lr_pre self.lr_encoder = lr_encoder", "theta_y and phi (decoders and HMC) activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad", "5. T (int, optional): length of the HMC chains. Defaults to 10. chains", "self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step() # Optimize theta_x,", "the latent space. Defaults to 10. arch (str, optional): name of the architecture", "of the HMC chains. Defaults to 10. chains (int, optional): number of parallel", "and phi (decoders and HMC) activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad =", "z=zx).sum(-1) kls = self.encoder.regularizer(mu_z, logvar_z, observed) elbo = rec_x + rec_y - kls.sum(0).unsqueeze(-1)", "arch (str, optional): name of the architecture for encoder/decoder from the 'archs' file.", "optional): Learning rate for the decoder (p(x|z1)). Defaults to 1e-3. lr_predictor (float, optional):", "update_s_each self.hmc=True self.save_hyperparameters('L', 'T', 'chains', 'sksd', 'pre_steps', 'lr_pre', 'lr_encoder', 'lr_decoder', 'lr_predictor', 'lr_hmc', 'lr_scale',", "or Gaussian samples from the proposal. Defaults to True. Returns: torch.Tensor: latent samples", "# the \"MIT License Agreement\". Please see the LICENSE file that should have", "for the decoder (p(x|z1)). Defaults to 1e-3. lr_predictor (float, optional): Learning rate for", "the base class function) for defining the HMC objective p(epsilon)(x, y) Args: batch", "1. pre_steps (float, optional): number of standard VI training steps (before using HMC).", "batch_size (int, optional): batch size. Defaults to 128. lr (float, optional): learning rate", "lr_scale self.update_s_each = update_s_each self.hmc=True self.save_hyperparameters('L', 'T', 'chains', 'sksd', 'pre_steps', 'lr_pre', 'lr_encoder', 'lr_decoder',", "self.decoder(z) x_hat = self.build_x_hat(xn, observed_x, theta_x) zx = torch.cat([z,x_hat],dim=-1) rec_x = self.decoder.logp(xt, observed_x,", "= logvar.repeat(samples, 1, 1).transpose(0, 1) # Reparametrization z = reparameterize(mu, torch.exp(logvar)) else: #", "kl if no observed data) mu_z, logvar_z = self.encoder(xy) z = self.sample_z(mu_z, logvar_z,", "likelihood_x = likelihood_x, likelihood_y = likelihood_y, variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size, lr=lr, samples_MC", "= self.optimizers(use_pl_optimizer=True) if self.step_idx < self.pre_steps: self.hmc=False loss_3, rec_x, rec_y, kls = self.forward(batch,", "= xn * observed_x x_tilde = torch.cat([xo, observed_x], axis=1) y = y.view(-1, self.dim_y)", "defining the HMC objective p(epsilon)(x, y) Args: batch (tuple): contains (data, observed_data, target,", "rec_x, rec_y, kl_mean else: # returns elbo, logp and sksd # Activate decoder,", "= x.view(-1, self.dim_x) # Normalize the data xn = self.normalize_x(x) xo = xn", "Initialization Args: dataset (str): name of the dataset (boston, mnist, ...) dim_x (int):", "self.build_x_hat(xn, observed_x, theta_x) zx = torch.cat([z,x_hat],dim=-1) rec_x = self.decoder.logp(xt, observed_x, z=z, theta=theta_x).sum(-1) rec_y", "(HMC-VAE) as described in https://arxiv.org/abs/2202.04599 \"\"\" def __init__(self, dataset: str, dim_x: int, dim_y:", "a traning step following https://arxiv.org/abs/2202.04599 - For the first pre_steps, optimize parameters by", "# ============= Modified base functions ============= # def forward(self, batch: tuple, hmc=True, samples=1)", "self.hmc=True loss_3, loss_1, loss_2 = self.forward(batch, samples=self.chains) ##### Optimization # Optimize psi (encoder)", "'lr_encoder', 'lr_decoder', 'lr_predictor', 'lr_hmc', 'lr_scale', 'update_s_each') self.step_idx=0 # training step index # =============", "= sksd self.pre_steps = pre_steps self.lr_pre = lr_pre self.lr_encoder = lr_encoder self.lr_decoder =", "under + # the \"MIT License Agreement\". Please see the LICENSE file that", "hmc==False or self.validation and self.global_step < self.pre_steps: # Repeat samples_MC times for Monte", "= lr_hmc self.lr_scale = lr_scale self.update_s_each = update_s_each self.hmc=True self.save_hyperparameters('L', 'T', 'chains', 'sksd',", "to 1e-3. samples_MC (int, optional): number of MC samples for computing the ELBO.", "'gaussian'. likelihood_y (str, optional): target data likelihood type. Defaults to 'gaussian'. variance (float,", "index from the training set logging (bool): log metrics into Tensorboard (True). Default", "b in batch] x, observed_x, y, observed_y = batch x = x.view(-1, self.dim_x)", "likelihood_y = likelihood_y, variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size, lr=lr, samples_MC = samples_MC, data_path=data_path,", "standard VI training steps (before using HMC). Defaults to 18e3. lr_pre (float, optional):", "use HMC Args: batch (tuple): contains (data, observed_data, target, observed_target) hmc (bool): sample", "Carlo mu = mu.repeat(samples, 1, 1).transpose(0, 1) logvar = logvar.repeat(samples, 1, 1).transpose(0, 1)", "yt, xy, observed = self.preprocess_batch(batch) # xt is the preprocessed input (xt=x if", "1e-3. lr_hmc (float, optional): Learning rate for the HMC hyperparameters (matrix of step", "= latent_dim, arch=arch, dim_h=dim_h, likelihood_x = likelihood_x, likelihood_y = likelihood_y, variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y,", "0: self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad()", "def training_step(self, batch: tuple, batch_idx: int, logging: bool=True): \"\"\" Perform a traning step", "============= # def configure_optimizers(self): opt_vae = torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters()) + list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01)", "of samples. Defaults to 1. hmc (bool, optional): draw hmc samples or Gaussian", "1, prediction_metric='rmse', batch_size=128, lr=1e-3, samples_MC = 1, data_path='../data/', split_idx=0, L=5, T=10, chains=1, chains_sksd=30,", "on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('-rec_y', -rec_y, on_step=False, on_epoch=True, prog_bar=False, logger=True) for l, kl", "HH-VAEM, and is released under + # the \"MIT License Agreement\". Please see", "the VI training stage. Defaults to 1e-3. lr_encoder (float, optional): Learning rate for", "weight_decay=0.01) opt_hmc = torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale = torch.optim.Adam([self.HMC.log_inflation], lr=self.lr_scale) return [opt_vae, opt_decoder, opt_predictor,", "True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#,", "rec_y, kl \"\"\" if hmc==True: # Activate only encoder activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad", "on_epoch=True, prog_bar=False, logger=True) self.log('HMC_objective', -loss_1, on_step=False, on_epoch=True, prog_bar=True, logger=True) self.step_idx += 1 def", "predictor. Defaults to 1e-3. lr_hmc (float, optional): Learning rate for the HMC hyperparameters", "= True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder,", "optional): dimension of the hidden vectors. Defaults to 256. likelihood_x (str, optional): input", "self.encoder(xy) zT = self.sample_z(mu_z, logvar_z, samples=samples) loss_1 = -self.HMC.logp(zT) loss_1 = loss_1[loss_1!=0].mean() if", "optional): learning rate for the parameter optimization. Defaults to 1e-3. samples_MC (int, optional):", "-elbo if hmc==False: # returns elbo return loss_3, rec_x, rec_y, kl_mean else: #", "for l, kl in enumerate(kls): kl_mean[l]= kl[kl!=0].mean() loss_3 = -elbo if hmc==False: #", "= reparameterize(mu, torch.exp(logvar)) else: # sample from the true posterior z, _ =", "# Normalize the data xn = self.normalize_x(x) xo = xn * observed_x x_tilde", "============= HMCVAE ============= # class HMCVAE(BaseVAE): \"\"\" Implements a Hamiltonian VAE (HMC-VAE) as", "on_step=False, on_epoch=True, prog_bar=True, logger=True) self.step_idx += 1 def preprocess_batch(self, batch: tuple): \"\"\" Preprocessing", "list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01) opt_decoder = torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01) opt_predictor = torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01)", "optional): number of standard VI training steps (before using HMC). Defaults to 18e3.", "'base'. dim_h (int, optional): dimension of the hidden vectors. Defaults to 256. likelihood_x", "latent_dim) samples (int, optional): number of samples. Defaults to 1. hmc (bool, optional):", "(int, optional): length of the HMC chains. Defaults to 10. chains (int, optional):", "approx posterior parameterized by mu and logvar Args: mu (torch.Tensor): tensor with the", "optional): target data likelihood type. Defaults to 'gaussian'. variance (float, optional): fixed variance", "scale = torch.exp(self.HMC.log_inflation) self.log('scale', scale, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('SKSD', loss_2,", "\"\"\" Draw latent samples from a given approx posterior parameterized by mu and", "on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('-rec_x', -rec_x, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('-rec_y',", "encoder activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False # Get data", "observed_y], axis=1) xy = torch.cat([x_tilde, y_tilde], axis=1) observed = torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0)", "and HMC) activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad()", "of the prediction metric for validation ('rmse', 'accuracy'). Defaults to 'rmse'. batch_size (int,", "T=T, chains=chains, chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False self.L = L self.T = T self.chains =", "= 1, data_path='../data/', split_idx=0, L=5, T=10, chains=1, chains_sksd=30, sksd=1, pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3,", "step following https://arxiv.org/abs/2202.04599 - For the first pre_steps, optimize parameters by maximizing the", "elbo, logp and sksd # Activate decoder, predictor and hmc activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad", "scale, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('SKSD', loss_2, on_step=False, on_epoch=True, prog_bar=False, logger=True)", "dimension latent_dim (int, optional): dimension of the latent space. Defaults to 10. arch", "(int, optional): number of samples. Defaults to 1. hmc (bool, optional): draw hmc", "name of the architecture for encoder/decoder from the 'archs' file. Defaults to 'base'.", "prog_bar=True, logger=True) if logging: self.log('-rec_x', -rec_x, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('-rec_y', -rec_y, on_step=False,", "opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder, opt_predictor, opt_hmc]) opt_decoder.step() opt_predictor.step() opt_hmc.step() if self.sksd and self.step_idx", "from src.models.hmc import * # ============= HMCVAE ============= # class HMCVAE(BaseVAE): \"\"\" Implements", "(int, optional): number of Leapfrog steps. Defaults to 5. T (int, optional): length", "torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01) opt_predictor = torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01) opt_encoder = torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01)", "loss_1, loss_2 def training_step(self, batch: tuple, batch_idx: int, logging: bool=True): \"\"\" Perform a", "observed_y = batch xn = self.normalize_x(x) xt, yt, xy, observed = self.preprocess_batch(batch) #", "+= 1 def preprocess_batch(self, batch: tuple): \"\"\" Preprocessing operations for the batch (overrides", "logp=None) self.automatic_optimization=False self.L = L self.T = T self.chains = chains self.chains_sksd =", "to 1. prediction_metric (str, optional): name of the prediction metric for validation ('rmse',", "metric for validation ('rmse', 'accuracy'). Defaults to 'rmse'. batch_size (int, optional): batch size.", "xn * observed_x x_tilde = torch.cat([xo, observed_x], axis=1) y = y.view(-1, self.dim_y) observed_y", "target, observed_target) batch_idx (int): batch index from the training set logging (bool): log", "theta_x = self.decoder(z) x_hat = self.build_x_hat(xn, observed_x, theta_x) zx = torch.cat([z,x_hat],dim=-1) rec_x =", "target, observed_target) Returns: tuple: preprocessed batch, contains (data, observed_data, target, observed_target) \"\"\" batch", "1. data_path (str, optional): path to load/save the data. Defaults to '../data/'. split_idx", "pre_steps self.lr_pre = lr_pre self.lr_encoder = lr_encoder self.lr_decoder = lr_decoder self.lr_predictor = lr_predictor", "VI training steps (before using HMC). Defaults to 18e3. lr_pre (float, optional): learning", "= torch.zeros(len(kls)).to(self.device) for l, kl in enumerate(kls): kl_mean[l]= kl[kl!=0].mean() loss_3 = -elbo if", "to 1. pre_steps (float, optional): number of standard VI training steps (before using", "# Encoder again for not sharing gradients mu_z, logvar_z = self.encoder(xy) zT =", "function) for defining the HMC objective p(epsilon)(x, y) Args: batch (tuple): contains (data,", "): \"\"\" HMCVAE Initialization Args: dataset (str): name of the dataset (boston, mnist,", "Defaults to 18e3. lr_pre (float, optional): learning reate for all the parameters during", "deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False loss_2 = self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else: loss_2 =", "= batch xn = self.normalize_x(x) xt, yt, xy, observed = self.preprocess_batch(batch) # xt", "torch.exp(logvar)) else: # sample from the true posterior z, _ = self.HMC.generate_samples_HMC(mu, torch.exp(logvar),", "samples_MC = 1, data_path='../data/', split_idx=0, L=5, T=10, chains=1, chains_sksd=30, sksd=1, pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3,", "0.1. imbalanced_y (bool, optional): True for compensating imbalanced classification. Defaults to False. categories_y", "= self.forward(batch, hmc=False, samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step() self.log('ELBO', -loss_3, on_step=False, on_epoch=True, prog_bar=True, logger=True)", "preprocessed input (xt=x if no preprocessing) # observed is observed_x OR observed_y (for", "True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder, opt_predictor,", "hidden vectors. Defaults to 256. likelihood_x (str, optional): input data likelihood type. Defaults", "rate for the encoder parameters. Defaults to 1e-3. lr_decoder (float, optional): Learning rate", "(float, optional): Learning rate for the encoder parameters. Defaults to 1e-3. lr_decoder (float,", "likelihood type. Defaults to 'gaussian'. likelihood_y (str, optional): target data likelihood type. Defaults", "scale factor for q(eps|zy) using the SKSD regularizer (1) or not (0). Defaults", "samples \"\"\" if hmc==False or self.validation and self.global_step < self.pre_steps: # Repeat samples_MC", "Defaults to 30. sksd (int, optional): learn a scale factor for q(eps|zy) using", "pre_steps (float, optional): number of standard VI training steps (before using HMC). Defaults", "optional): number of parallel HMC chains for computing the SKSD. Defaults to 30.", "using HMC objective and SKSD Args: batch (tuple): contains (data, observed_data, target, observed_target)", "likelihood type. Defaults to 'gaussian'. variance (float, optional): fixed variance for Gaussian likelihoods.", "Draw latent samples from a given approx posterior parameterized by mu and logvar", "(encoder) activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad()", "likelihoods. Defaults to 0.1. imbalanced_y (bool, optional): True for compensating imbalanced classification. Defaults", "self.manual_backward(loss_3) opt_encoder.step() # Optimize theta_x, theta_y and phi (decoders and HMC) activate(self.decoder) activate(self.predictor)", "data. Defaults to '../data/'. split_idx (int, optional): idx of the training split. Defaults", "logvar = logvar.repeat(samples, 1, 1).transpose(0, 1) # Reparametrization z = reparameterize(mu, torch.exp(logvar)) else:", "is the preprocessed input (xt=x if no preprocessing) # observed is observed_x OR", "-> torch.Tensor: \"\"\" Draw latent samples from a given approx posterior parameterized by", "= T self.chains = chains self.chains_sksd = chains_sksd self.sksd = sksd self.pre_steps =", "chains=chains, chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False self.L = L self.T = T self.chains = chains", "logvar Args: mu (torch.Tensor): tensor with the means (batch_size, latent_dim) logvar (torch.Tensor): tensor", "'lr_predictor', 'lr_hmc', 'lr_scale', 'update_s_each') self.step_idx=0 # training step index # ============= Modified base", "Defaults to 1e-3. lr_hmc (float, optional): Learning rate for the HMC hyperparameters (matrix", "xt, yt, xy, observed = self.preprocess_batch(batch) # xt is the preprocessed input (xt=x", "(batch_size, latent_dim) logvar (torch.Tensor): tensor with the log variances (batch_size, latent_dim) samples (int,", "opt_predictor, opt_encoder, opt_hmc, opt_scale) = self.optimizers(use_pl_optimizer=True) if self.step_idx < self.pre_steps: self.hmc=False loss_3, rec_x,", "rec_y[rec_y!=0].mean() kl_mean = torch.zeros(len(kls)).to(self.device) for l, kl in enumerate(kls): kl_mean[l]= kl[kl!=0].mean() loss_3 =", "= likelihood_y, variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size, lr=lr, samples_MC = samples_MC, data_path=data_path, split_idx=split_idx)", "on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('SKSD', loss_2, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('HMC_objective',", "categories_y = 1, prediction_metric='rmse', batch_size=128, lr=1e-3, samples_MC = 1, data_path='../data/', split_idx=0, L=5, T=10,", "parallel HMC chains for computing the SKSD. Defaults to 30. sksd (int, optional):", "enumerate(kls): kl_mean[l]= kl[kl!=0].mean() loss_3 = -elbo if hmc==False: # returns elbo return loss_3,", "prog_bar=False, logger=True) else: self.hmc=True loss_3, loss_1, loss_2 = self.forward(batch, samples=self.chains) ##### Optimization #", "categories_y (int, optional): number of categories when the target is categorical. Defaults to", "'gaussian', variance=0.1, imbalanced_y = False, categories_y = 1, prediction_metric='rmse', batch_size=128, lr=1e-3, samples_MC =", "10. \"\"\" super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y, latent_dim = latent_dim, arch=arch, dim_h=dim_h, likelihood_x =", "for the encoder parameters. Defaults to 1e-3. lr_decoder (float, optional): Learning rate for", "y = y.view(-1, self.dim_y) observed_y = observed_y.view(-1, self.dim_y) # Normalize the target yn", "logvar.repeat(samples, 1, 1).transpose(0, 1) # Reparametrization z = reparameterize(mu, torch.exp(logvar)) else: # sample", "rights reserved. This file is part of the HH-VAEM, and is released under", "HMC objective p(epsilon)(x, y) Args: batch (tuple): contains (data, observed_data, target, observed_target) Returns:", "# Normalize the target yn = self.normalize_y(y) yon = yn * observed_y y_tilde", "\"\"\" def __init__(self, dataset: str, dim_x: int, dim_y: int, latent_dim = 10, arch='base',", "Please see the LICENSE file that should have + # been included as", "returns elbo return loss_3, rec_x, rec_y, kl_mean else: # returns elbo, logp and", "arch=arch, dim_h=dim_h, likelihood_x = likelihood_x, likelihood_y = likelihood_y, variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size,", "class HMCVAE(BaseVAE): \"\"\" Implements a Hamiltonian VAE (HMC-VAE) as described in https://arxiv.org/abs/2202.04599 \"\"\"", "samples. Defaults to 1. hmc (bool, optional): draw hmc samples or Gaussian samples", "self.step_idx += 1 def preprocess_batch(self, batch: tuple): \"\"\" Preprocessing operations for the batch", "theta_x, theta_y and phi (decoders and HMC) activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder)", "the decoder (p(x|z1)). Defaults to 1e-3. lr_predictor (float, optional): Learning rate for the", "Defaults to 256. likelihood_x (str, optional): input data likelihood type. Defaults to 'gaussian'.", "everything except scale self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False loss_2", "self.T = T self.chains = chains self.chains_sksd = chains_sksd self.sksd = sksd self.pre_steps", "\"\"\" HMCVAE Initialization Args: dataset (str): name of the dataset (boston, mnist, ...)", "hmc=True, samples=1) -> tuple: \"\"\" Forward data through the model. For the pretraining", "deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False # Get data x, observed_x, y,", "self.sample_z(mu_z, logvar_z, samples=samples, hmc=False) theta_x = self.decoder(z) x_hat = self.build_x_hat(xn, observed_x, theta_x) zx", "= observed_y.view(-1, self.dim_y) # Normalize the target yn = self.normalize_y(y) yon = yn", "observed_y = observed_y.view(-1, self.dim_y) # Normalize the target yn = self.normalize_y(y) yon =", "no preprocessing) # observed is observed_x OR observed_y (for not using kl if", "contains (data, observed_data, target, observed_target) \"\"\" batch = [b.to(self.device) for b in batch]", "log variances (batch_size, latent_dim) samples (int, optional): number of samples. Defaults to 1.", "to 1. chains_sksd (int, optional): number of parallel HMC chains for computing the", "weight_decay=0.01) opt_predictor = torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01) opt_encoder = torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01) opt_hmc =", "torch.cat([z,x_hat],dim=-1) rec_x = self.decoder.logp(xt, observed_x, z=z, theta=theta_x).sum(-1) rec_y = self.predictor.logp(yt, observed_y, z=zx).sum(-1) kls", "on_epoch=True, prog_bar=False, logger=True) for l, kl in enumerate(kls): self.log('kl_{:d}'.format(l), kl, on_step=False, on_epoch=True, prog_bar=False,", "self.HMC.log_inflation.requires_grad = False # Get data x, observed_x, y, observed_y = batch xn", "opt_predictor, opt_hmc]) opt_decoder.step() opt_predictor.step() opt_hmc.step() if self.sksd and self.step_idx % self.update_s_each == 0:", "True for compensating imbalanced classification. Defaults to False. categories_y (int, optional): number of", "# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base import * from src.models.hmc import * # ============= HMCVAE", "self.logp_func(xo, observed_x, yon, observed_y) return xn, yn, xy, observed def sample_z(self, mu: torch.Tensor,", "# Deactivate everything except scale self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad =", "yn, xy, observed def sample_z(self, mu: torch.Tensor, logvar: torch.Tensor, samples=1, hmc=True) -> torch.Tensor:", "# Repeat samples_MC times for Monte Carlo mu = mu.repeat(samples, 1, 1).transpose(0, 1)", "split_idx=0, L=5, T=10, chains=1, chains_sksd=30, sksd=1, pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3, lr_scale", "opt_hmc, opt_scale) = self.optimizers(use_pl_optimizer=True) if self.step_idx < self.pre_steps: self.hmc=False loss_3, rec_x, rec_y, kls", "# Copyright (c) 2022 by <NAME>, UC3M. + # All rights reserved. This", "split_idx=split_idx) self.HMC = HMC(dim=latent_dim, L=L, T=T, chains=chains, chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False self.L = L", "for validation ('rmse', 'accuracy'). Defaults to 'rmse'. batch_size (int, optional): batch size. Defaults", "parallel HMC chains. Defaults to 1. chains_sksd (int, optional): number of parallel HMC", "chains. Defaults to 1. chains_sksd (int, optional): number of parallel HMC chains for", "= lr_scale self.update_s_each = update_s_each self.hmc=True self.save_hyperparameters('L', 'T', 'chains', 'sksd', 'pre_steps', 'lr_pre', 'lr_encoder',", "observed_y, z=zx).sum(-1) kls = self.encoder.regularizer(mu_z, logvar_z, observed) elbo = rec_x + rec_y -", "to 10. arch (str, optional): name of the architecture for encoder/decoder from the", "encoder/decoder from the 'archs' file. Defaults to 'base'. dim_h (int, optional): dimension of", "True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False loss_2 = self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else: loss_2", "Optimize psi (encoder) activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad()", "observed_y = batch x = x.view(-1, self.dim_x) # Normalize the data xn =", "lr_hmc self.lr_scale = lr_scale self.update_s_each = update_s_each self.hmc=True self.save_hyperparameters('L', 'T', 'chains', 'sksd', 'pre_steps',", "HMC chains. Defaults to 10. chains (int, optional): number of parallel HMC chains.", "chains=samples) return z # ============= Modified PL functions ============= # def configure_optimizers(self): opt_vae", "for the HMC hyperparameters (matrix of step sizes). Defaults to 1e-3. lr_scale (_type_,", "opt_scale) opt_scale.step() scale = torch.exp(self.HMC.log_inflation) self.log('scale', scale, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging:", "to 1e-3. lr_scale (_type_, optional): Learning rate for the scale (inflation) factor Defaults", "def forward(self, batch: tuple, hmc=True, samples=1) -> tuple: \"\"\" Forward data through the", "tuple, batch_idx: int, logging: bool=True): \"\"\" Perform a traning step following https://arxiv.org/abs/2202.04599 -", "ELBO, and the rest using HMC objective and SKSD Args: batch (tuple): contains", "the preprocessed input (xt=x if no preprocessing) # observed is observed_x OR observed_y", "to 1. hmc (bool, optional): draw hmc samples or Gaussian samples from the", "= lr_encoder self.lr_decoder = lr_decoder self.lr_predictor = lr_predictor self.lr_hmc = lr_hmc self.lr_scale =", "= mu.repeat(samples, 1, 1).transpose(0, 1) logvar = logvar.repeat(samples, 1, 1).transpose(0, 1) # Reparametrization", "reparameterize(mu, torch.exp(logvar)) else: # sample from the true posterior z, _ = self.HMC.generate_samples_HMC(mu,", "Agreement\". Please see the LICENSE file that should have + # been included", "logvar_z, samples=samples) loss_1 = -self.HMC.logp(zT) loss_1 = loss_1[loss_1!=0].mean() if self.sksd==1: # Deactivate everything", "observed = torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0) # Define the HMC objective self.HMC.logp =", "list(self.predictor.parameters()) + list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01) opt_decoder = torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01) opt_predictor = torch.optim.Adam(list(self.predictor.parameters()),", "for computing the ELBO Returns: If hmc=False, returns: loss_VI, rec_x, rec_y, kl If", "on_step=False, on_epoch=True, prog_bar=False, logger=True) else: self.hmc=True loss_3, loss_1, loss_2 = self.forward(batch, samples=self.chains) #####", "torch.Tensor, logvar: torch.Tensor, samples=1, hmc=True) -> torch.Tensor: \"\"\" Draw latent samples from a", "theta=theta_x).sum(-1) rec_y = self.predictor.logp(yt, observed_y, z=zx).sum(-1) kls = self.encoder.regularizer(mu_z, logvar_z, observed) elbo =", "Defaults to 1e-3. lr_decoder (float, optional): Learning rate for the decoder (p(x|z1)). Defaults", "(overrides the base class function) for defining the HMC objective p(epsilon)(x, y) Args:", "L self.T = T self.chains = chains self.chains_sksd = chains_sksd self.sksd = sksd", "deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale)", "loss_2 def training_step(self, batch: tuple, batch_idx: int, logging: bool=True): \"\"\" Perform a traning", "(str, optional): path to load/save the data. Defaults to '../data/'. split_idx (int, optional):", "# Activate only encoder activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False", "optional): number of parallel HMC chains. Defaults to 1. chains_sksd (int, optional): number", "y.view(-1, self.dim_y) observed_y = observed_y.view(-1, self.dim_y) # Normalize the target yn = self.normalize_y(y)", "weight_decay=0.01) opt_encoder = torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01) opt_hmc = torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale = torch.optim.Adam([self.HMC.log_inflation],", "Args: batch (tuple): contains (data, observed_data, target, observed_target) batch_idx (int): batch index from", "'archs' file. Defaults to 'base'. dim_h (int, optional): dimension of the hidden vectors.", "name of the dataset (boston, mnist, ...) dim_x (int): input data dimension dim_y", "dimension of the hidden vectors. Defaults to 256. likelihood_x (str, optional): input data", "1e-2, update_s_each=10 ): \"\"\" HMCVAE Initialization Args: dataset (str): name of the dataset", "Returns: If hmc=False, returns: loss_VI, rec_x, rec_y, kl If hmc=True, returns: loss_VI, loss_HMC,", "rate for the scale (inflation) factor Defaults to 1e-2. update_s_each (int, optional): Interval", "the true posterior z, _ = self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples) return z # =============", "deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale) opt_scale.step()", "observed data) mu_z, logvar_z = self.encoder(xy) z = self.sample_z(mu_z, logvar_z, samples=samples, hmc=False) theta_x", "not sharing gradients mu_z, logvar_z = self.encoder(xy) zT = self.sample_z(mu_z, logvar_z, samples=samples) loss_1", "(tuple): contains (data, observed_data, target, observed_target) batch_idx (int): batch index from the training", "= torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0) # Define the HMC objective self.HMC.logp = self.logp_func(xo,", "-rec_x, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('-rec_y', -rec_y, on_step=False, on_epoch=True, prog_bar=False, logger=True) for l,", "torch.cat([yon, observed_y], axis=1) xy = torch.cat([x_tilde, y_tilde], axis=1) observed = torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1,", "not (0). Defaults to 1. pre_steps (float, optional): number of standard VI training", "categories when the target is categorical. Defaults to 1. prediction_metric (str, optional): name", "kl in enumerate(kls): kl_mean[l]= kl[kl!=0].mean() loss_3 = -elbo if hmc==False: # returns elbo", "opt_hmc = torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale = torch.optim.Adam([self.HMC.log_inflation], lr=self.lr_scale) return [opt_vae, opt_decoder, opt_predictor, opt_encoder,", "batch x = x.view(-1, self.dim_x) # Normalize the data xn = self.normalize_x(x) xo", "============= # def forward(self, batch: tuple, hmc=True, samples=1) -> tuple: \"\"\" Forward data", "theta_x) zx = torch.cat([z,x_hat],dim=-1) rec_x = self.decoder.logp(xt, observed_x, z=z, theta=theta_x).sum(-1) rec_y = self.predictor.logp(yt,", "batch: tuple): \"\"\" Preprocessing operations for the batch (overrides the base class function)", "If hmc=True, returns: loss_VI, loss_HMC, loss_SKSD, rec_x, rec_y, kl \"\"\" if hmc==True: #", "self.manual_backward(loss_2)#, opt_scale) opt_scale.step() scale = torch.exp(self.HMC.log_inflation) self.log('scale', scale, on_step=False, on_epoch=True, prog_bar=True, logger=True) if", "loss_1 = -self.HMC.logp(zT) loss_1 = loss_1[loss_1!=0].mean() if self.sksd==1: # Deactivate everything except scale", "= self.encoder(xy) zT = self.sample_z(mu_z, logvar_z, samples=samples) loss_1 = -self.HMC.logp(zT) loss_1 = loss_1[loss_1!=0].mean()", "batch: tuple, batch_idx: int, logging: bool=True): \"\"\" Perform a traning step following https://arxiv.org/abs/2202.04599", "optional): number of MC samples for computing the ELBO. Defaults to 1. data_path", "deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False loss_2 = self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else: loss_2 = None", "observed_target) Returns: tuple: preprocessed batch, contains (data, observed_data, target, observed_target) \"\"\" batch =", "(int, optional): number of parallel HMC chains. Defaults to 1. chains_sksd (int, optional):", "to 1e-2. update_s_each (int, optional): Interval of steps for optimizing the scale factor.", "is released under + # the \"MIT License Agreement\". Please see the LICENSE", "= False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step() # Optimize theta_x, theta_y", "import * # ============= HMCVAE ============= # class HMCVAE(BaseVAE): \"\"\" Implements a Hamiltonian", "latent_dim) logvar (torch.Tensor): tensor with the log variances (batch_size, latent_dim) samples (int, optional):", "a scale factor for q(eps|zy) using the SKSD regularizer (1) or not (0).", "opt_decoder.step() opt_predictor.step() opt_hmc.step() if self.sksd and self.step_idx % self.update_s_each == 0: self.HMC.log_inflation.requires_grad =", "tuple: preprocessed batch, contains (data, observed_data, target, observed_target) \"\"\" batch = [b.to(self.device) for", "the rest, use HMC Args: batch (tuple): contains (data, observed_data, target, observed_target) hmc", "computing the SKSD. Defaults to 30. sksd (int, optional): learn a scale factor", "opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder, opt_predictor, opt_hmc]) opt_decoder.step() opt_predictor.step() opt_hmc.step() if self.sksd and self.step_idx %", "vectors. Defaults to 256. likelihood_x (str, optional): input data likelihood type. Defaults to", "1e-3. lr_predictor (float, optional): Learning rate for the predictor. Defaults to 1e-3. lr_hmc", "< self.pre_steps: self.hmc=False loss_3, rec_x, rec_y, kls = self.forward(batch, hmc=False, samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3)", "dataset (boston, mnist, ...) dim_x (int): input data dimension dim_y (int): target data", "self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y, latent_dim = latent_dim, arch=arch, dim_h=dim_h, likelihood_x = likelihood_x, likelihood_y =", "preprocess_batch(self, batch: tuple): \"\"\" Preprocessing operations for the batch (overrides the base class", "the scale (inflation) factor Defaults to 1e-2. update_s_each (int, optional): Interval of steps", "of the dataset (boston, mnist, ...) dim_x (int): input data dimension dim_y (int):", "model. For the pretraining stage, use the ELBO. For the rest, use HMC", "pretraining stage, use the ELBO. For the rest, use HMC Args: batch (tuple):", "prog_bar=False, logger=True) self.log('HMC_objective', -loss_1, on_step=False, on_epoch=True, prog_bar=True, logger=True) self.step_idx += 1 def preprocess_batch(self,", "y_tilde = torch.cat([yon, observed_y], axis=1) xy = torch.cat([x_tilde, y_tilde], axis=1) observed = torch.logical_or(observed_x.sum(-1,", "HMC (True). Defaults to True samples (int): number of MC samples for computing", "samples for computing the ELBO Returns: If hmc=False, returns: loss_VI, rec_x, rec_y, kl", "been included as part of this package. + # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base import", "(matrix of step sizes). Defaults to 1e-3. lr_scale (_type_, optional): Learning rate for", "self.log('ELBO', -loss_3, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('-rec_x', -rec_x, on_step=False, on_epoch=True, prog_bar=False,", "update_s_each (int, optional): Interval of steps for optimizing the scale factor. Defaults to", "= None return loss_3, loss_1, loss_2 def training_step(self, batch: tuple, batch_idx: int, logging:", "on_epoch=True, prog_bar=False, logger=True) self.log('-rec_y', -rec_y, on_step=False, on_epoch=True, prog_bar=False, logger=True) for l, kl in", "= True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad()", "observed def sample_z(self, mu: torch.Tensor, logvar: torch.Tensor, samples=1, hmc=True) -> torch.Tensor: \"\"\" Draw", "Args: batch (tuple): contains (data, observed_data, target, observed_target) Returns: tuple: preprocessed batch, contains", "optimizing the scale factor. Defaults to 10. \"\"\" super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y, latent_dim", "x.view(-1, self.dim_x) # Normalize the data xn = self.normalize_x(x) xo = xn *", "logvar (torch.Tensor): tensor with the log variances (batch_size, latent_dim) samples (int, optional): number", "self.predictor.logp(yt, observed_y, z=zx).sum(-1) kls = self.encoder.regularizer(mu_z, logvar_z, observed) elbo = rec_x + rec_y", "rest, use HMC Args: batch (tuple): contains (data, observed_data, target, observed_target) hmc (bool):", "for defining the HMC objective p(epsilon)(x, y) Args: batch (tuple): contains (data, observed_data,", "rec_x = self.decoder.logp(xt, observed_x, z=z, theta=theta_x).sum(-1) rec_y = self.predictor.logp(yt, observed_y, z=zx).sum(-1) kls =", "samples or Gaussian samples from the proposal. Defaults to True. Returns: torch.Tensor: latent", "L=5, T=10, chains=1, chains_sksd=30, sksd=1, pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3, lr_scale =", "input (xt=x if no preprocessing) # observed is observed_x OR observed_y (for not", "lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3, lr_scale = 1e-2, update_s_each=10 ): \"\"\" HMCVAE Initialization Args: dataset", "= self.build_x_hat(xn, observed_x, theta_x) zx = torch.cat([z,x_hat],dim=-1) rec_x = self.decoder.logp(xt, observed_x, z=z, theta=theta_x).sum(-1)", "= elbo[elbo!=0].mean() rec_x = rec_x[rec_x!=0].mean() rec_y = rec_y[rec_y!=0].mean() kl_mean = torch.zeros(len(kls)).to(self.device) for l,", "likelihood_y = 'gaussian', variance=0.1, imbalanced_y = False, categories_y = 1, prediction_metric='rmse', batch_size=128, lr=1e-3,", "likelihood_x, likelihood_y = likelihood_y, variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size, lr=lr, samples_MC = samples_MC,", "int, logging: bool=True): \"\"\" Perform a traning step following https://arxiv.org/abs/2202.04599 - For the", "is part of the HH-VAEM, and is released under + # the \"MIT", "(int, optional): number of categories when the target is categorical. Defaults to 1.", "mu: torch.Tensor, logvar: torch.Tensor, samples=1, hmc=True) -> torch.Tensor: \"\"\" Draw latent samples from", "(str): name of the dataset (boston, mnist, ...) dim_x (int): input data dimension", "256. likelihood_x (str, optional): input data likelihood type. Defaults to 'gaussian'. likelihood_y (str,", "if hmc==True: # Activate only encoder activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad", "If hmc=False, returns: loss_VI, rec_x, rec_y, kl If hmc=True, returns: loss_VI, loss_HMC, loss_SKSD,", "functions ============= # def forward(self, batch: tuple, hmc=True, samples=1) -> tuple: \"\"\" Forward", "optional): learn a scale factor for q(eps|zy) using the SKSD regularizer (1) or", "L (int, optional): number of Leapfrog steps. Defaults to 5. T (int, optional):", "= torch.exp(self.HMC.log_inflation) self.log('scale', scale, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('SKSD', loss_2, on_step=False,", "observed = self.preprocess_batch(batch) # xt is the preprocessed input (xt=x if no preprocessing)", "or self.validation and self.global_step < self.pre_steps: # Repeat samples_MC times for Monte Carlo", "metrics into Tensorboard (True). Default True \"\"\" (opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc, opt_scale)", "opt_vae = torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters()) + list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01) opt_decoder = torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder,", "with the log variances (batch_size, latent_dim) samples (int, optional): number of samples. Defaults", "for computing the SKSD. Defaults to 30. sksd (int, optional): learn a scale", "the SKSD regularizer (1) or not (0). Defaults to 1. pre_steps (float, optional):", "activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False # Encoder again for not", "to 256. likelihood_x (str, optional): input data likelihood type. Defaults to 'gaussian'. likelihood_y", "dim_h=256, likelihood_x = 'gaussian', likelihood_y = 'gaussian', variance=0.1, imbalanced_y = False, categories_y =", "loss_1[loss_1!=0].mean() if self.sksd==1: # Deactivate everything except scale self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder)", "all the parameters during the VI training stage. Defaults to 1e-3. lr_encoder (float,", "= self.sample_z(mu_z, logvar_z, samples=samples, hmc=False) theta_x = self.decoder(z) x_hat = self.build_x_hat(xn, observed_x, theta_x)", "dim_h=dim_h, likelihood_x = likelihood_x, likelihood_y = likelihood_y, variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size, lr=lr,", "sksd self.pre_steps = pre_steps self.lr_pre = lr_pre self.lr_encoder = lr_encoder self.lr_decoder = lr_decoder", "batch_idx: int, logging: bool=True): \"\"\" Perform a traning step following https://arxiv.org/abs/2202.04599 - For", "rec_y - kls.sum(0).unsqueeze(-1) elbo = elbo[elbo!=0].mean() rec_x = rec_x[rec_x!=0].mean() rec_y = rec_y[rec_y!=0].mean() kl_mean", "torch.exp(logvar), chains=samples) return z # ============= Modified PL functions ============= # def configure_optimizers(self):", "for b in batch] x, observed_x, y, observed_y = batch x = x.view(-1,", "hmc=False, returns: loss_VI, rec_x, rec_y, kl If hmc=True, returns: loss_VI, loss_HMC, loss_SKSD, rec_x,", "path to load/save the data. Defaults to '../data/'. split_idx (int, optional): idx of", "dataset (str): name of the dataset (boston, mnist, ...) dim_x (int): input data", "lr=self.lr_encoder, weight_decay=0.01) opt_hmc = torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale = torch.optim.Adam([self.HMC.log_inflation], lr=self.lr_scale) return [opt_vae, opt_decoder,", "elbo = rec_x + rec_y - kls.sum(0).unsqueeze(-1) elbo = elbo[elbo!=0].mean() rec_x = rec_x[rec_x!=0].mean()", "\"\"\" (opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc, opt_scale) = self.optimizers(use_pl_optimizer=True) if self.step_idx < self.pre_steps:", "# def configure_optimizers(self): opt_vae = torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters()) + list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01) opt_decoder", "2022 by <NAME>, UC3M. + # All rights reserved. This file is part", "self.decoder.logp(xt, observed_x, z=z, theta=theta_x).sum(-1) rec_y = self.predictor.logp(yt, observed_y, z=zx).sum(-1) kls = self.encoder.regularizer(mu_z, logvar_z,", "computing the ELBO. Defaults to 1. data_path (str, optional): path to load/save the", "opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder, opt_predictor, opt_hmc]) opt_decoder.step() opt_predictor.step() opt_hmc.step() if", "imbalanced classification. Defaults to False. categories_y (int, optional): number of categories when the", "first pre_steps, optimize parameters by maximizing the ELBO - For the rest, optimize", "the prediction metric for validation ('rmse', 'accuracy'). Defaults to 'rmse'. batch_size (int, optional):", "batch] x, observed_x, y, observed_y = batch x = x.view(-1, self.dim_x) # Normalize", "= likelihood_x, likelihood_y = likelihood_y, variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size, lr=lr, samples_MC =", "hmc==True: # Activate only encoder activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad =", "parameter optimization. Defaults to 1e-3. samples_MC (int, optional): number of MC samples for", "prediction metric for validation ('rmse', 'accuracy'). Defaults to 'rmse'. batch_size (int, optional): batch", "except scale self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False loss_2 =", "p(epsilon)(x, y) Args: batch (tuple): contains (data, observed_data, target, observed_target) Returns: tuple: preprocessed", "optional): Learning rate for the scale (inflation) factor Defaults to 1e-2. update_s_each (int,", "through the model. For the pretraining stage, use the ELBO. For the rest,", "int, latent_dim = 10, arch='base', dim_h=256, likelihood_x = 'gaussian', likelihood_y = 'gaussian', variance=0.1,", "number of Leapfrog steps. Defaults to 5. T (int, optional): length of the", "and self.step_idx % self.update_s_each == 0: self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad", "tuple, hmc=True, samples=1) -> tuple: \"\"\" Forward data through the model. For the", "latent_dim (int, optional): dimension of the latent space. Defaults to 10. arch (str,", "10. arch (str, optional): name of the architecture for encoder/decoder from the 'archs'", "(int, optional): number of MC samples for computing the ELBO. Defaults to 1.", "latent samples from a given approx posterior parameterized by mu and logvar Args:", "the rest using HMC objective and SKSD Args: batch (tuple): contains (data, observed_data,", "axis=1) observed = torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0) # Define the HMC objective self.HMC.logp", "Defaults to 5. T (int, optional): length of the HMC chains. Defaults to", "observed_x, yon, observed_y) return xn, yn, xy, observed def sample_z(self, mu: torch.Tensor, logvar:", "target data dimension latent_dim (int, optional): dimension of the latent space. Defaults to", "tuple): \"\"\" Preprocessing operations for the batch (overrides the base class function) for", "License Agreement\". Please see the LICENSE file that should have + # been", "loss_VI, rec_x, rec_y, kl If hmc=True, returns: loss_VI, loss_HMC, loss_SKSD, rec_x, rec_y, kl", "optional): Interval of steps for optimizing the scale factor. Defaults to 10. \"\"\"", "to 1e-3. lr_encoder (float, optional): Learning rate for the encoder parameters. Defaults to", "1e-3. samples_MC (int, optional): number of MC samples for computing the ELBO. Defaults", "loss_1, loss_2 = self.forward(batch, samples=self.chains) ##### Optimization # Optimize psi (encoder) activate(self.encoder) deactivate(self.decoder)", "to 18e3. lr_pre (float, optional): learning reate for all the parameters during the", "for the predictor. Defaults to 1e-3. lr_hmc (float, optional): Learning rate for the", "False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step() # Optimize theta_x, theta_y and", "as described in https://arxiv.org/abs/2202.04599 \"\"\" def __init__(self, dataset: str, dim_x: int, dim_y: int,", "part of this package. + # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base import * from src.models.hmc", "'gaussian', likelihood_y = 'gaussian', variance=0.1, imbalanced_y = False, categories_y = 1, prediction_metric='rmse', batch_size=128,", "None return loss_3, loss_1, loss_2 def training_step(self, batch: tuple, batch_idx: int, logging: bool=True):", "https://arxiv.org/abs/2202.04599 - For the first pre_steps, optimize parameters by maximizing the ELBO -", "self.sample_z(mu_z, logvar_z, samples=samples) loss_1 = -self.HMC.logp(zT) loss_1 = loss_1[loss_1!=0].mean() if self.sksd==1: # Deactivate", "samples_MC = samples_MC, data_path=data_path, split_idx=split_idx) self.HMC = HMC(dim=latent_dim, L=L, T=T, chains=chains, chains_sksd=chains_sksd, logp=None)", "self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else: loss_2 = None return loss_3, loss_1, loss_2 def training_step(self, batch:", "pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3, lr_scale = 1e-2, update_s_each=10 ): \"\"\" HMCVAE", "(int): target data dimension latent_dim (int, optional): dimension of the latent space. Defaults", "samples_MC (int, optional): number of MC samples for computing the ELBO. Defaults to", "from the 'archs' file. Defaults to 'base'. dim_h (int, optional): dimension of the", "and is released under + # the \"MIT License Agreement\". Please see the", "UC3M. + # All rights reserved. This file is part of the HH-VAEM,", "opt_encoder.step() # Optimize theta_x, theta_y and phi (decoders and HMC) activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad", "= chains self.chains_sksd = chains_sksd self.sksd = sksd self.pre_steps = pre_steps self.lr_pre =", "hmc=True, returns: loss_VI, loss_HMC, loss_SKSD, rec_x, rec_y, kl \"\"\" if hmc==True: # Activate", "Defaults to 1e-3. samples_MC (int, optional): number of MC samples for computing the", "self.chains_sksd = chains_sksd self.sksd = sksd self.pre_steps = pre_steps self.lr_pre = lr_pre self.lr_encoder", "opt_decoder, opt_predictor, opt_encoder, opt_hmc, opt_scale) = self.optimizers(use_pl_optimizer=True) if self.step_idx < self.pre_steps: self.hmc=False loss_3,", "number of MC samples for computing the ELBO. Defaults to 1. data_path (str,", "the HMC objective self.HMC.logp = self.logp_func(xo, observed_x, yon, observed_y) return xn, yn, xy,", "loss_3, rec_x, rec_y, kls = self.forward(batch, hmc=False, samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step() self.log('ELBO', -loss_3,", "to 30. sksd (int, optional): learn a scale factor for q(eps|zy) using the", "to 'base'. dim_h (int, optional): dimension of the hidden vectors. Defaults to 256.", "# returns elbo, logp and sksd # Activate decoder, predictor and hmc activate(self.decoder)", "(int): batch index from the training set logging (bool): log metrics into Tensorboard", "False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale) opt_scale.step() scale = torch.exp(self.HMC.log_inflation) self.log('scale',", "(bool): sample posterior using HMC (True). Defaults to True samples (int): number of", "chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False self.L = L self.T = T self.chains = chains self.chains_sksd", "= 1, prediction_metric='rmse', batch_size=128, lr=1e-3, samples_MC = 1, data_path='../data/', split_idx=0, L=5, T=10, chains=1,", "src.models.base import * from src.models.hmc import * # ============= HMCVAE ============= # class", "l, kl in enumerate(kls): kl_mean[l]= kl[kl!=0].mean() loss_3 = -elbo if hmc==False: # returns", "chains for computing the SKSD. Defaults to 30. sksd (int, optional): learn a", "observed_data, target, observed_target) batch_idx (int): batch index from the training set logging (bool):", "to 0. L (int, optional): number of Leapfrog steps. Defaults to 5. T", "latent samples \"\"\" if hmc==False or self.validation and self.global_step < self.pre_steps: # Repeat", "sksd (int, optional): learn a scale factor for q(eps|zy) using the SKSD regularizer", "opt_encoder = torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01) opt_hmc = torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale = torch.optim.Adam([self.HMC.log_inflation], lr=self.lr_scale)", "(opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc, opt_scale) = self.optimizers(use_pl_optimizer=True) if self.step_idx < self.pre_steps: self.hmc=False", "Defaults to False. categories_y (int, optional): number of categories when the target is", "= 1e-2, update_s_each=10 ): \"\"\" HMCVAE Initialization Args: dataset (str): name of the", "False # Encoder again for not sharing gradients mu_z, logvar_z = self.encoder(xy) zT", "of the HH-VAEM, and is released under + # the \"MIT License Agreement\".", "= 'gaussian', likelihood_y = 'gaussian', variance=0.1, imbalanced_y = False, categories_y = 1, prediction_metric='rmse',", "should have + # been included as part of this package. + #", "else: self.hmc=True loss_3, loss_1, loss_2 = self.forward(batch, samples=self.chains) ##### Optimization # Optimize psi", "to True. Returns: torch.Tensor: latent samples \"\"\" if hmc==False or self.validation and self.global_step", "ELBO. For the rest, use HMC Args: batch (tuple): contains (data, observed_data, target,", "============= Modified base functions ============= # def forward(self, batch: tuple, hmc=True, samples=1) ->", "(int, optional): Interval of steps for optimizing the scale factor. Defaults to 10.", "lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3, lr_scale = 1e-2, update_s_each=10 ): \"\"\" HMCVAE Initialization", "learn a scale factor for q(eps|zy) using the SKSD regularizer (1) or not", "parameters. Defaults to 1e-3. lr_decoder (float, optional): Learning rate for the decoder (p(x|z1)).", "xn, yn, xy, observed def sample_z(self, mu: torch.Tensor, logvar: torch.Tensor, samples=1, hmc=True) ->", "(True). Default True \"\"\" (opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc, opt_scale) = self.optimizers(use_pl_optimizer=True) if", "Defaults to '../data/'. split_idx (int, optional): idx of the training split. Defaults to", "Defaults to 1e-3. lr_predictor (float, optional): Learning rate for the predictor. Defaults to", "1) # Reparametrization z = reparameterize(mu, torch.exp(logvar)) else: # sample from the true", "'lr_scale', 'update_s_each') self.step_idx=0 # training step index # ============= Modified base functions =============", "chains self.chains_sksd = chains_sksd self.sksd = sksd self.pre_steps = pre_steps self.lr_pre = lr_pre", "target, observed_target) \"\"\" batch = [b.to(self.device) for b in batch] x, observed_x, y,", "self.save_hyperparameters('L', 'T', 'chains', 'sksd', 'pre_steps', 'lr_pre', 'lr_encoder', 'lr_decoder', 'lr_predictor', 'lr_hmc', 'lr_scale', 'update_s_each') self.step_idx=0", "True \"\"\" (opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc, opt_scale) = self.optimizers(use_pl_optimizer=True) if self.step_idx <", "included as part of this package. + # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base import *", "dim_h (int, optional): dimension of the hidden vectors. Defaults to 256. likelihood_x (str,", "size. Defaults to 128. lr (float, optional): learning rate for the parameter optimization.", "data_path (str, optional): path to load/save the data. Defaults to '../data/'. split_idx (int,", "observed_x, z=z, theta=theta_x).sum(-1) rec_y = self.predictor.logp(yt, observed_y, z=zx).sum(-1) kls = self.encoder.regularizer(mu_z, logvar_z, observed)", "\"\"\" Perform a traning step following https://arxiv.org/abs/2202.04599 - For the first pre_steps, optimize", "kl[kl!=0].mean() loss_3 = -elbo if hmc==False: # returns elbo return loss_3, rec_x, rec_y,", "- For the first pre_steps, optimize parameters by maximizing the ELBO - For", "rec_x + rec_y - kls.sum(0).unsqueeze(-1) elbo = elbo[elbo!=0].mean() rec_x = rec_x[rec_x!=0].mean() rec_y =", "torch.exp(self.HMC.log_inflation) self.log('scale', scale, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('SKSD', loss_2, on_step=False, on_epoch=True,", "imbalanced_y (bool, optional): True for compensating imbalanced classification. Defaults to False. categories_y (int,", "Defaults to 1. prediction_metric (str, optional): name of the prediction metric for validation", "observed_y.sum(-1, keepdim=True)>0) # Define the HMC objective self.HMC.logp = self.logp_func(xo, observed_x, yon, observed_y)", "== 0: self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad()", "deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder, opt_predictor, opt_hmc])", "length of the HMC chains. Defaults to 10. chains (int, optional): number of", "rec_y, kl_mean else: # returns elbo, logp and sksd # Activate decoder, predictor", "Defaults to 'gaussian'. likelihood_y (str, optional): target data likelihood type. Defaults to 'gaussian'.", "fixed variance for Gaussian likelihoods. Defaults to 0.1. imbalanced_y (bool, optional): True for", "= samples_MC, data_path=data_path, split_idx=split_idx) self.HMC = HMC(dim=latent_dim, L=L, T=T, chains=chains, chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False", "Get data x, observed_x, y, observed_y = batch xn = self.normalize_x(x) xt, yt,", "= y.view(-1, self.dim_y) observed_y = observed_y.view(-1, self.dim_y) # Normalize the target yn =", "xn = self.normalize_x(x) xo = xn * observed_x x_tilde = torch.cat([xo, observed_x], axis=1)", "to 1. data_path (str, optional): path to load/save the data. Defaults to '../data/'.", "Learning rate for the encoder parameters. Defaults to 1e-3. lr_decoder (float, optional): Learning", "rec_y = rec_y[rec_y!=0].mean() kl_mean = torch.zeros(len(kls)).to(self.device) for l, kl in enumerate(kls): kl_mean[l]= kl[kl!=0].mean()", "given approx posterior parameterized by mu and logvar Args: mu (torch.Tensor): tensor with", "= lr_pre self.lr_encoder = lr_encoder self.lr_decoder = lr_decoder self.lr_predictor = lr_predictor self.lr_hmc =", "validation ('rmse', 'accuracy'). Defaults to 'rmse'. batch_size (int, optional): batch size. Defaults to", "= -elbo if hmc==False: # returns elbo return loss_3, rec_x, rec_y, kl_mean else:", "step index # ============= Modified base functions ============= # def forward(self, batch: tuple,", "on_epoch=True, prog_bar=True, logger=True) if logging: self.log('SKSD', loss_2, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('HMC_objective', -loss_1,", "opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step() self.log('ELBO', -loss_3, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('-rec_x', -rec_x,", "optional): number of samples. Defaults to 1. hmc (bool, optional): draw hmc samples", "logger=True) for l, kl in enumerate(kls): self.log('kl_{:d}'.format(l), kl, on_step=False, on_epoch=True, prog_bar=False, logger=True) else:", "kl \"\"\" if hmc==True: # Activate only encoder activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad =", "described in https://arxiv.org/abs/2202.04599 \"\"\" def __init__(self, dataset: str, dim_x: int, dim_y: int, latent_dim", "lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3, lr_scale = 1e-2, update_s_each=10 ): \"\"\" HMCVAE Initialization Args:", "maximizing the ELBO - For the rest, optimize encoder using ELBO, and the", "Define the HMC objective self.HMC.logp = self.logp_func(xo, observed_x, yon, observed_y) return xn, yn,", "Defaults to 0. L (int, optional): number of Leapfrog steps. Defaults to 5.", "self.pre_steps: self.hmc=False loss_3, rec_x, rec_y, kls = self.forward(batch, hmc=False, samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step()", "18e3. lr_pre (float, optional): learning reate for all the parameters during the VI", "dim_x=dim_x, dim_y=dim_y, latent_dim = latent_dim, arch=arch, dim_h=dim_h, likelihood_x = likelihood_x, likelihood_y = likelihood_y,", "observed_y y_tilde = torch.cat([yon, observed_y], axis=1) xy = torch.cat([x_tilde, y_tilde], axis=1) observed =", "1) logvar = logvar.repeat(samples, 1, 1).transpose(0, 1) # Reparametrization z = reparameterize(mu, torch.exp(logvar))", "(float, optional): learning rate for the parameter optimization. Defaults to 1e-3. samples_MC (int,", "from the proposal. Defaults to True. Returns: torch.Tensor: latent samples \"\"\" if hmc==False", "HMC objective and SKSD Args: batch (tuple): contains (data, observed_data, target, observed_target) batch_idx", "optional): learning reate for all the parameters during the VI training stage. Defaults", "pre_steps, optimize parameters by maximizing the ELBO - For the rest, optimize encoder", "SKSD. Defaults to 30. sksd (int, optional): learn a scale factor for q(eps|zy)", "xn = self.normalize_x(x) xt, yt, xy, observed = self.preprocess_batch(batch) # xt is the", "optional): path to load/save the data. Defaults to '../data/'. split_idx (int, optional): idx", "batch size. Defaults to 128. lr (float, optional): learning rate for the parameter", "to True samples (int): number of MC samples for computing the ELBO Returns:", "SKSD Args: batch (tuple): contains (data, observed_data, target, observed_target) batch_idx (int): batch index", "self.step_idx < self.pre_steps: self.hmc=False loss_3, rec_x, rec_y, kls = self.forward(batch, hmc=False, samples=self.samples_MC) opt_vae.zero_grad()", "HMC Args: batch (tuple): contains (data, observed_data, target, observed_target) hmc (bool): sample posterior", "Tensorboard (True). Default True \"\"\" (opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc, opt_scale) = self.optimizers(use_pl_optimizer=True)", "categorical. Defaults to 1. prediction_metric (str, optional): name of the prediction metric for", "Gaussian samples from the proposal. Defaults to True. Returns: torch.Tensor: latent samples \"\"\"", "(0). Defaults to 1. pre_steps (float, optional): number of standard VI training steps", "samples from the proposal. Defaults to True. Returns: torch.Tensor: latent samples \"\"\" if", "int, dim_y: int, latent_dim = 10, arch='base', dim_h=256, likelihood_x = 'gaussian', likelihood_y =", "return z # ============= Modified PL functions ============= # def configure_optimizers(self): opt_vae =", "the training split. Defaults to 0. L (int, optional): number of Leapfrog steps.", "(1) or not (0). Defaults to 1. pre_steps (float, optional): number of standard", "lr=self.lr_pre, weight_decay=0.01) opt_decoder = torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01) opt_predictor = torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01) opt_encoder", "1e-3. lr_decoder (float, optional): Learning rate for the decoder (p(x|z1)). Defaults to 1e-3.", "HMC hyperparameters (matrix of step sizes). Defaults to 1e-3. lr_scale (_type_, optional): Learning", "opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step() # Optimize theta_x, theta_y and phi", "regularizer (1) or not (0). Defaults to 1. pre_steps (float, optional): number of", "self.log('kl_{:d}'.format(l), kl, on_step=False, on_epoch=True, prog_bar=False, logger=True) else: self.hmc=True loss_3, loss_1, loss_2 = self.forward(batch,", "self.optimizers(use_pl_optimizer=True) if self.step_idx < self.pre_steps: self.hmc=False loss_3, rec_x, rec_y, kls = self.forward(batch, hmc=False,", "prog_bar=False, logger=True) self.log('-rec_y', -rec_y, on_step=False, on_epoch=True, prog_bar=False, logger=True) for l, kl in enumerate(kls):", "classification. Defaults to False. categories_y (int, optional): number of categories when the target", "+ # been included as part of this package. + # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from", "self.validation and self.global_step < self.pre_steps: # Repeat samples_MC times for Monte Carlo mu", "part of the HH-VAEM, and is released under + # the \"MIT License", "+ rec_y - kls.sum(0).unsqueeze(-1) elbo = elbo[elbo!=0].mean() rec_x = rec_x[rec_x!=0].mean() rec_y = rec_y[rec_y!=0].mean()", "l, kl in enumerate(kls): self.log('kl_{:d}'.format(l), kl, on_step=False, on_epoch=True, prog_bar=False, logger=True) else: self.hmc=True loss_3,", "by <NAME>, UC3M. + # All rights reserved. This file is part of", "lr_scale (_type_, optional): Learning rate for the scale (inflation) factor Defaults to 1e-2.", "(data, observed_data, target, observed_target) \"\"\" batch = [b.to(self.device) for b in batch] x,", "for q(eps|zy) using the SKSD regularizer (1) or not (0). Defaults to 1.", "using kl if no observed data) mu_z, logvar_z = self.encoder(xy) z = self.sample_z(mu_z,", "\"\"\" if hmc==False or self.validation and self.global_step < self.pre_steps: # Repeat samples_MC times", "self.log('SKSD', loss_2, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('HMC_objective', -loss_1, on_step=False, on_epoch=True, prog_bar=True, logger=True) self.step_idx", "(float, optional): Learning rate for the HMC hyperparameters (matrix of step sizes). Defaults", "observed_target) batch_idx (int): batch index from the training set logging (bool): log metrics", "to 1e-3. lr_decoder (float, optional): Learning rate for the decoder (p(x|z1)). Defaults to", "= lr_decoder self.lr_predictor = lr_predictor self.lr_hmc = lr_hmc self.lr_scale = lr_scale self.update_s_each =", "(c) 2022 by <NAME>, UC3M. + # All rights reserved. This file is", "computing the ELBO Returns: If hmc=False, returns: loss_VI, rec_x, rec_y, kl If hmc=True,", "VI training stage. Defaults to 1e-3. lr_encoder (float, optional): Learning rate for the", "axis=1) y = y.view(-1, self.dim_y) observed_y = observed_y.view(-1, self.dim_y) # Normalize the target", "self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step()", "= self.forward(batch, samples=self.chains) ##### Optimization # Optimize psi (encoder) activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad", "samples_MC times for Monte Carlo mu = mu.repeat(samples, 1, 1).transpose(0, 1) logvar =", "= torch.cat([x_tilde, y_tilde], axis=1) observed = torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0) # Define the", "if no observed data) mu_z, logvar_z = self.encoder(xy) z = self.sample_z(mu_z, logvar_z, samples=samples,", "Deactivate everything except scale self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False", "# def forward(self, batch: tuple, hmc=True, samples=1) -> tuple: \"\"\" Forward data through", "self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad()", "Forward data through the model. For the pretraining stage, use the ELBO. For", "self.update_s_each = update_s_each self.hmc=True self.save_hyperparameters('L', 'T', 'chains', 'sksd', 'pre_steps', 'lr_pre', 'lr_encoder', 'lr_decoder', 'lr_predictor',", "contains (data, observed_data, target, observed_target) hmc (bool): sample posterior using HMC (True). Defaults", "(inflation) factor Defaults to 1e-2. update_s_each (int, optional): Interval of steps for optimizing", "(str, optional): target data likelihood type. Defaults to 'gaussian'. variance (float, optional): fixed", "_ = self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples) return z # ============= Modified PL functions =============", "activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad()", "variance for Gaussian likelihoods. Defaults to 0.1. imbalanced_y (bool, optional): True for compensating", "Defaults to 1e-3. lr_encoder (float, optional): Learning rate for the encoder parameters. Defaults", "self.lr_hmc = lr_hmc self.lr_scale = lr_scale self.update_s_each = update_s_each self.hmc=True self.save_hyperparameters('L', 'T', 'chains',", "opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale) opt_scale.step() scale = torch.exp(self.HMC.log_inflation) self.log('scale', scale, on_step=False,", "rec_x, rec_y, kl If hmc=True, returns: loss_VI, loss_HMC, loss_SKSD, rec_x, rec_y, kl \"\"\"", "(int): input data dimension dim_y (int): target data dimension latent_dim (int, optional): dimension", "torch.Tensor: latent samples \"\"\" if hmc==False or self.validation and self.global_step < self.pre_steps: #", "dataset: str, dim_x: int, dim_y: int, latent_dim = 10, arch='base', dim_h=256, likelihood_x =", "self.preprocess_batch(batch) # xt is the preprocessed input (xt=x if no preprocessing) # observed", "+ list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01) opt_decoder = torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01) opt_predictor = torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor,", "= self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples) return z # ============= Modified PL functions ============= #", "chains_sksd=30, sksd=1, pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3, lr_scale = 1e-2, update_s_each=10 ):", "self.normalize_x(x) xo = xn * observed_x x_tilde = torch.cat([xo, observed_x], axis=1) y =", "hyperparameters (matrix of step sizes). Defaults to 1e-3. lr_scale (_type_, optional): Learning rate", "'rmse'. batch_size (int, optional): batch size. Defaults to 128. lr (float, optional): learning", "the parameters during the VI training stage. Defaults to 1e-3. lr_encoder (float, optional):", "tensor with the means (batch_size, latent_dim) logvar (torch.Tensor): tensor with the log variances", "to 1e-3. lr_hmc (float, optional): Learning rate for the HMC hyperparameters (matrix of", "Normalize the data xn = self.normalize_x(x) xo = xn * observed_x x_tilde =", "step sizes). Defaults to 1e-3. lr_scale (_type_, optional): Learning rate for the scale", "dim_x: int, dim_y: int, latent_dim = 10, arch='base', dim_h=256, likelihood_x = 'gaussian', likelihood_y", "prediction_metric (str, optional): name of the prediction metric for validation ('rmse', 'accuracy'). Defaults", "Defaults to True samples (int): number of MC samples for computing the ELBO", "(torch.Tensor): tensor with the means (batch_size, latent_dim) logvar (torch.Tensor): tensor with the log", "[b.to(self.device) for b in batch] x, observed_x, y, observed_y = batch x =", "= False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder, opt_predictor, opt_hmc]) opt_decoder.step() opt_predictor.step()", "for Monte Carlo mu = mu.repeat(samples, 1, 1).transpose(0, 1) logvar = logvar.repeat(samples, 1,", "self.manual_backward(loss_1)#, [opt_decoder, opt_predictor, opt_hmc]) opt_decoder.step() opt_predictor.step() opt_hmc.step() if self.sksd and self.step_idx % self.update_s_each", "package. + # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base import * from src.models.hmc import * #", "observed_x, y, observed_y = batch xn = self.normalize_x(x) xt, yt, xy, observed =", "from the true posterior z, _ = self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples) return z #", "for Gaussian likelihoods. Defaults to 0.1. imbalanced_y (bool, optional): True for compensating imbalanced", "observed_y.view(-1, self.dim_y) # Normalize the target yn = self.normalize_y(y) yon = yn *", "the \"MIT License Agreement\". Please see the LICENSE file that should have +", "= self.decoder(z) x_hat = self.build_x_hat(xn, observed_x, theta_x) zx = torch.cat([z,x_hat],dim=-1) rec_x = self.decoder.logp(xt,", "to False. categories_y (int, optional): number of categories when the target is categorical.", "have + # been included as part of this package. + # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", "lr_hmc=1e-3, lr_scale = 1e-2, update_s_each=10 ): \"\"\" HMCVAE Initialization Args: dataset (str): name", "load/save the data. Defaults to '../data/'. split_idx (int, optional): idx of the training", "y, observed_y = batch xn = self.normalize_x(x) xt, yt, xy, observed = self.preprocess_batch(batch)", "self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False # Encoder again for not sharing", "Normalize the target yn = self.normalize_y(y) yon = yn * observed_y y_tilde =", "loss_HMC, loss_SKSD, rec_x, rec_y, kl \"\"\" if hmc==True: # Activate only encoder activate(self.encoder)", "= False, categories_y = 1, prediction_metric='rmse', batch_size=128, lr=1e-3, samples_MC = 1, data_path='../data/', split_idx=0,", "if logging: self.log('SKSD', loss_2, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('HMC_objective', -loss_1, on_step=False, on_epoch=True, prog_bar=True,", "- kls.sum(0).unsqueeze(-1) elbo = elbo[elbo!=0].mean() rec_x = rec_x[rec_x!=0].mean() rec_y = rec_y[rec_y!=0].mean() kl_mean =", "self.step_idx=0 # training step index # ============= Modified base functions ============= # def", "samples from a given approx posterior parameterized by mu and logvar Args: mu", "the target is categorical. Defaults to 1. prediction_metric (str, optional): name of the", "target yn = self.normalize_y(y) yon = yn * observed_y y_tilde = torch.cat([yon, observed_y],", "mu_z, logvar_z = self.encoder(xy) zT = self.sample_z(mu_z, logvar_z, samples=samples) loss_1 = -self.HMC.logp(zT) loss_1", "'lr_pre', 'lr_encoder', 'lr_decoder', 'lr_predictor', 'lr_hmc', 'lr_scale', 'update_s_each') self.step_idx=0 # training step index #", "sharing gradients mu_z, logvar_z = self.encoder(xy) zT = self.sample_z(mu_z, logvar_z, samples=samples) loss_1 =", "zT = self.sample_z(mu_z, logvar_z, samples=samples) loss_1 = -self.HMC.logp(zT) loss_1 = loss_1[loss_1!=0].mean() if self.sksd==1:", "torch.Tensor: \"\"\" Draw latent samples from a given approx posterior parameterized by mu", "prediction_metric=prediction_metric, batch_size=batch_size, lr=lr, samples_MC = samples_MC, data_path=data_path, split_idx=split_idx) self.HMC = HMC(dim=latent_dim, L=L, T=T,", "samples for computing the ELBO. Defaults to 1. data_path (str, optional): path to", "parameters during the VI training stage. Defaults to 1e-3. lr_encoder (float, optional): Learning", "(data, observed_data, target, observed_target) Returns: tuple: preprocessed batch, contains (data, observed_data, target, observed_target)", "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base import * from src.models.hmc import * # ============= HMCVAE =============", "= False loss_2 = self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else: loss_2 = None return loss_3, loss_1,", "to 5. T (int, optional): length of the HMC chains. Defaults to 10.", "'update_s_each') self.step_idx=0 # training step index # ============= Modified base functions ============= #", "reate for all the parameters during the VI training stage. Defaults to 1e-3.", "kl_mean[l]= kl[kl!=0].mean() loss_3 = -elbo if hmc==False: # returns elbo return loss_3, rec_x,", "VAE (HMC-VAE) as described in https://arxiv.org/abs/2202.04599 \"\"\" def __init__(self, dataset: str, dim_x: int,", "to '../data/'. split_idx (int, optional): idx of the training split. Defaults to 0.", "str, dim_x: int, dim_y: int, latent_dim = 10, arch='base', dim_h=256, likelihood_x = 'gaussian',", "logging (bool): log metrics into Tensorboard (True). Default True \"\"\" (opt_vae, opt_decoder, opt_predictor,", "logger=True) self.log('HMC_objective', -loss_1, on_step=False, on_epoch=True, prog_bar=True, logger=True) self.step_idx += 1 def preprocess_batch(self, batch:", "loss_2 = None return loss_3, loss_1, loss_2 def training_step(self, batch: tuple, batch_idx: int,", "by maximizing the ELBO - For the rest, optimize encoder using ELBO, and", "for optimizing the scale factor. Defaults to 10. \"\"\" super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y,", "psi (encoder) activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad()", "kl_mean = torch.zeros(len(kls)).to(self.device) for l, kl in enumerate(kls): kl_mean[l]= kl[kl!=0].mean() loss_3 = -elbo", "the target yn = self.normalize_y(y) yon = yn * observed_y y_tilde = torch.cat([yon,", "target data likelihood type. Defaults to 'gaussian'. variance (float, optional): fixed variance for", "weight_decay=0.01) opt_decoder = torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01) opt_predictor = torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01) opt_encoder =", "self.dim_y) observed_y = observed_y.view(-1, self.dim_y) # Normalize the target yn = self.normalize_y(y) yon", "torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01) opt_hmc = torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale = torch.optim.Adam([self.HMC.log_inflation], lr=self.lr_scale) return [opt_vae,", "chains (int, optional): number of parallel HMC chains. Defaults to 1. chains_sksd (int,", "data_path=data_path, split_idx=split_idx) self.HMC = HMC(dim=latent_dim, L=L, T=T, chains=chains, chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False self.L =", "preprocessing) # observed is observed_x OR observed_y (for not using kl if no", "observed_target) \"\"\" batch = [b.to(self.device) for b in batch] x, observed_x, y, observed_y", "the scale factor. Defaults to 10. \"\"\" super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y, latent_dim =", "and sksd # Activate decoder, predictor and hmc activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True", "HMC objective self.HMC.logp = self.logp_func(xo, observed_x, yon, observed_y) return xn, yn, xy, observed", "(data, observed_data, target, observed_target) batch_idx (int): batch index from the training set logging", "chains_sksd (int, optional): number of parallel HMC chains for computing the SKSD. Defaults", "else: loss_2 = None return loss_3, loss_1, loss_2 def training_step(self, batch: tuple, batch_idx:", "the data. Defaults to '../data/'. split_idx (int, optional): idx of the training split.", "# been included as part of this package. + # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base", "= rec_x[rec_x!=0].mean() rec_y = rec_y[rec_y!=0].mean() kl_mean = torch.zeros(len(kls)).to(self.device) for l, kl in enumerate(kls):", "batch_size=batch_size, lr=lr, samples_MC = samples_MC, data_path=data_path, split_idx=split_idx) self.HMC = HMC(dim=latent_dim, L=L, T=T, chains=chains,", "contains (data, observed_data, target, observed_target) batch_idx (int): batch index from the training set", "the training set logging (bool): log metrics into Tensorboard (True). Default True \"\"\"", "(batch_size, latent_dim) samples (int, optional): number of samples. Defaults to 1. hmc (bool,", "see the LICENSE file that should have + # been included as part", "= torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters()) + list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01) opt_decoder = torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01)", "the architecture for encoder/decoder from the 'archs' file. Defaults to 'base'. dim_h (int,", "False # Get data x, observed_x, y, observed_y = batch xn = self.normalize_x(x)", "loss_2 = self.forward(batch, samples=self.chains) ##### Optimization # Optimize psi (encoder) activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor)", "Defaults to 'rmse'. batch_size (int, optional): batch size. Defaults to 128. lr (float,", "return xn, yn, xy, observed def sample_z(self, mu: torch.Tensor, logvar: torch.Tensor, samples=1, hmc=True)", "the ELBO Returns: If hmc=False, returns: loss_VI, rec_x, rec_y, kl If hmc=True, returns:", "Returns: torch.Tensor: latent samples \"\"\" if hmc==False or self.validation and self.global_step < self.pre_steps:", "training set logging (bool): log metrics into Tensorboard (True). Default True \"\"\" (opt_vae,", "objective and SKSD Args: batch (tuple): contains (data, observed_data, target, observed_target) batch_idx (int):", "True samples (int): number of MC samples for computing the ELBO Returns: If", "-self.HMC.logp(zT) loss_1 = loss_1[loss_1!=0].mean() if self.sksd==1: # Deactivate everything except scale self.HMC.log_inflation.requires_grad =", "prediction_metric='rmse', batch_size=128, lr=1e-3, samples_MC = 1, data_path='../data/', split_idx=0, L=5, T=10, chains=1, chains_sksd=30, sksd=1,", "variance (float, optional): fixed variance for Gaussian likelihoods. Defaults to 0.1. imbalanced_y (bool,", "batch (overrides the base class function) for defining the HMC objective p(epsilon)(x, y)", "for compensating imbalanced classification. Defaults to False. categories_y (int, optional): number of categories", "T=10, chains=1, chains_sksd=30, sksd=1, pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3, lr_scale = 1e-2,", "optimization. Defaults to 1e-3. samples_MC (int, optional): number of MC samples for computing", "the HMC chains. Defaults to 10. chains (int, optional): number of parallel HMC", "self.chains = chains self.chains_sksd = chains_sksd self.sksd = sksd self.pre_steps = pre_steps self.lr_pre", "Repeat samples_MC times for Monte Carlo mu = mu.repeat(samples, 1, 1).transpose(0, 1) logvar", "architecture for encoder/decoder from the 'archs' file. Defaults to 'base'. dim_h (int, optional):", "1, 1).transpose(0, 1) logvar = logvar.repeat(samples, 1, 1).transpose(0, 1) # Reparametrization z =", "False. categories_y (int, optional): number of categories when the target is categorical. Defaults", "decoder, predictor and hmc activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False", "deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False # Encoder again for not sharing gradients mu_z, logvar_z", "+ list(self.predictor.parameters()) + list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01) opt_decoder = torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01) opt_predictor =", "(bool, optional): True for compensating imbalanced classification. Defaults to False. categories_y (int, optional):", "============= # class HMCVAE(BaseVAE): \"\"\" Implements a Hamiltonian VAE (HMC-VAE) as described in", "1).transpose(0, 1) logvar = logvar.repeat(samples, 1, 1).transpose(0, 1) # Reparametrization z = reparameterize(mu,", "target, observed_target) hmc (bool): sample posterior using HMC (True). Defaults to True samples", "and logvar Args: mu (torch.Tensor): tensor with the means (batch_size, latent_dim) logvar (torch.Tensor):", "Reparametrization z = reparameterize(mu, torch.exp(logvar)) else: # sample from the true posterior z,", "loss_3, rec_x, rec_y, kl_mean else: # returns elbo, logp and sksd # Activate", "= False self.HMC.log_inflation.requires_grad = False # Get data x, observed_x, y, observed_y =", "logger=True) self.step_idx += 1 def preprocess_batch(self, batch: tuple): \"\"\" Preprocessing operations for the", "observed is observed_x OR observed_y (for not using kl if no observed data)", "batch = [b.to(self.device) for b in batch] x, observed_x, y, observed_y = batch", "self.pre_steps: # Repeat samples_MC times for Monte Carlo mu = mu.repeat(samples, 1, 1).transpose(0,", "number of samples. Defaults to 1. hmc (bool, optional): draw hmc samples or", "x, observed_x, y, observed_y = batch xn = self.normalize_x(x) xt, yt, xy, observed", "= True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False loss_2 = self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else:", "imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size, lr=lr, samples_MC = samples_MC, data_path=data_path, split_idx=split_idx) self.HMC = HMC(dim=latent_dim,", "contains (data, observed_data, target, observed_target) Returns: tuple: preprocessed batch, contains (data, observed_data, target,", "1. chains_sksd (int, optional): number of parallel HMC chains for computing the SKSD.", "Monte Carlo mu = mu.repeat(samples, 1, 1).transpose(0, 1) logvar = logvar.repeat(samples, 1, 1).transpose(0,", "= batch x = x.view(-1, self.dim_x) # Normalize the data xn = self.normalize_x(x)", "(int, optional): batch size. Defaults to 128. lr (float, optional): learning rate for", "= False self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step() #", "with the means (batch_size, latent_dim) logvar (torch.Tensor): tensor with the log variances (batch_size,", "to 'rmse'. batch_size (int, optional): batch size. Defaults to 128. lr (float, optional):", "rec_x, rec_y, kl \"\"\" if hmc==True: # Activate only encoder activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor)", "'gaussian'. variance (float, optional): fixed variance for Gaussian likelihoods. Defaults to 0.1. imbalanced_y", "rec_x = rec_x[rec_x!=0].mean() rec_y = rec_y[rec_y!=0].mean() kl_mean = torch.zeros(len(kls)).to(self.device) for l, kl in", "HMCVAE(BaseVAE): \"\"\" Implements a Hamiltonian VAE (HMC-VAE) as described in https://arxiv.org/abs/2202.04599 \"\"\" def", "the pretraining stage, use the ELBO. For the rest, use HMC Args: batch", "the model. For the pretraining stage, use the ELBO. For the rest, use", "of standard VI training steps (before using HMC). Defaults to 18e3. lr_pre (float,", "this package. + # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base import * from src.models.hmc import *", "MC samples for computing the ELBO Returns: If hmc=False, returns: loss_VI, rec_x, rec_y,", "(int, optional): learn a scale factor for q(eps|zy) using the SKSD regularizer (1)", "rest, optimize encoder using ELBO, and the rest using HMC objective and SKSD", "Defaults to 10. \"\"\" super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y, latent_dim = latent_dim, arch=arch, dim_h=dim_h,", "0. L (int, optional): number of Leapfrog steps. Defaults to 5. T (int,", "for l, kl in enumerate(kls): self.log('kl_{:d}'.format(l), kl, on_step=False, on_epoch=True, prog_bar=False, logger=True) else: self.hmc=True", "data xn = self.normalize_x(x) xo = xn * observed_x x_tilde = torch.cat([xo, observed_x],", "sksd=1, pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3, lr_scale = 1e-2, update_s_each=10 ): \"\"\"", "and hmc activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False # Encoder", "lr_decoder (float, optional): Learning rate for the decoder (p(x|z1)). Defaults to 1e-3. lr_predictor", "-loss_3, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('-rec_x', -rec_x, on_step=False, on_epoch=True, prog_bar=False, logger=True)", "optional): fixed variance for Gaussian likelihoods. Defaults to 0.1. imbalanced_y (bool, optional): True", "(float, optional): fixed variance for Gaussian likelihoods. Defaults to 0.1. imbalanced_y (bool, optional):", "in https://arxiv.org/abs/2202.04599 \"\"\" def __init__(self, dataset: str, dim_x: int, dim_y: int, latent_dim =", "self.lr_scale = lr_scale self.update_s_each = update_s_each self.hmc=True self.save_hyperparameters('L', 'T', 'chains', 'sksd', 'pre_steps', 'lr_pre',", "deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad()", "to 'gaussian'. likelihood_y (str, optional): target data likelihood type. Defaults to 'gaussian'. variance", "traning step following https://arxiv.org/abs/2202.04599 - For the first pre_steps, optimize parameters by maximizing", "= torch.cat([xo, observed_x], axis=1) y = y.view(-1, self.dim_y) observed_y = observed_y.view(-1, self.dim_y) #", "'../data/'. split_idx (int, optional): idx of the training split. Defaults to 0. L", "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright (c) 2022 by <NAME>, UC3M. + # All rights reserved.", "hmc=False, samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step() self.log('ELBO', -loss_3, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging:", "# Optimize theta_x, theta_y and phi (decoders and HMC) activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad =", "lr_encoder (float, optional): Learning rate for the encoder parameters. Defaults to 1e-3. lr_decoder", "'lr_decoder', 'lr_predictor', 'lr_hmc', 'lr_scale', 'update_s_each') self.step_idx=0 # training step index # ============= Modified", "forward(self, batch: tuple, hmc=True, samples=1) -> tuple: \"\"\" Forward data through the model.", "of parallel HMC chains for computing the SKSD. Defaults to 30. sksd (int,", "file. Defaults to 'base'. dim_h (int, optional): dimension of the hidden vectors. Defaults", "mnist, ...) dim_x (int): input data dimension dim_y (int): target data dimension latent_dim", "# ============= HMCVAE ============= # class HMCVAE(BaseVAE): \"\"\" Implements a Hamiltonian VAE (HMC-VAE)", "activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False # Encoder again for", "number of parallel HMC chains for computing the SKSD. Defaults to 30. sksd", "yon, observed_y) return xn, yn, xy, observed def sample_z(self, mu: torch.Tensor, logvar: torch.Tensor,", "def preprocess_batch(self, batch: tuple): \"\"\" Preprocessing operations for the batch (overrides the base", "objective p(epsilon)(x, y) Args: batch (tuple): contains (data, observed_data, target, observed_target) Returns: tuple:", "- For the rest, optimize encoder using ELBO, and the rest using HMC", "on_epoch=True, prog_bar=False, logger=True) else: self.hmc=True loss_3, loss_1, loss_2 = self.forward(batch, samples=self.chains) ##### Optimization", "proposal. Defaults to True. Returns: torch.Tensor: latent samples \"\"\" if hmc==False or self.validation", "posterior z, _ = self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples) return z # ============= Modified PL", "y, observed_y = batch x = x.view(-1, self.dim_x) # Normalize the data xn", "This file is part of the HH-VAEM, and is released under + #", "self.step_idx % self.update_s_each == 0: self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad =", "batch xn = self.normalize_x(x) xt, yt, xy, observed = self.preprocess_batch(batch) # xt is", "self.manual_backward(loss_3) opt_vae.step() self.log('ELBO', -loss_3, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('-rec_x', -rec_x, on_step=False,", "class function) for defining the HMC objective p(epsilon)(x, y) Args: batch (tuple): contains", "the ELBO - For the rest, optimize encoder using ELBO, and the rest", "lr_predictor self.lr_hmc = lr_hmc self.lr_scale = lr_scale self.update_s_each = update_s_each self.hmc=True self.save_hyperparameters('L', 'T',", "to 10. chains (int, optional): number of parallel HMC chains. Defaults to 1.", "no observed data) mu_z, logvar_z = self.encoder(xy) z = self.sample_z(mu_z, logvar_z, samples=samples, hmc=False)", "Learning rate for the scale (inflation) factor Defaults to 1e-2. update_s_each (int, optional):", "logvar_z, observed) elbo = rec_x + rec_y - kls.sum(0).unsqueeze(-1) elbo = elbo[elbo!=0].mean() rec_x", "latent_dim = 10, arch='base', dim_h=256, likelihood_x = 'gaussian', likelihood_y = 'gaussian', variance=0.1, imbalanced_y", "to 1e-3. lr_predictor (float, optional): Learning rate for the predictor. Defaults to 1e-3.", "of this package. + # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base import * from src.models.hmc import", "variance=0.1, imbalanced_y = False, categories_y = 1, prediction_metric='rmse', batch_size=128, lr=1e-3, samples_MC = 1,", "and SKSD Args: batch (tuple): contains (data, observed_data, target, observed_target) batch_idx (int): batch", "loss_3, loss_1, loss_2 = self.forward(batch, samples=self.chains) ##### Optimization # Optimize psi (encoder) activate(self.encoder)", "only encoder activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False # Get", "reserved. This file is part of the HH-VAEM, and is released under +", "Defaults to 1e-3. lr_scale (_type_, optional): Learning rate for the scale (inflation) factor", "prog_bar=True, logger=True) if logging: self.log('SKSD', loss_2, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('HMC_objective', -loss_1, on_step=False,", "likelihood_x = 'gaussian', likelihood_y = 'gaussian', variance=0.1, imbalanced_y = False, categories_y = 1,", "(int): number of MC samples for computing the ELBO Returns: If hmc=False, returns:", "in enumerate(kls): kl_mean[l]= kl[kl!=0].mean() loss_3 = -elbo if hmc==False: # returns elbo return", "mu and logvar Args: mu (torch.Tensor): tensor with the means (batch_size, latent_dim) logvar", "opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale) opt_scale.step() scale = torch.exp(self.HMC.log_inflation) self.log('scale', scale, on_step=False, on_epoch=True, prog_bar=True,", "\"\"\" super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y, latent_dim = latent_dim, arch=arch, dim_h=dim_h, likelihood_x = likelihood_x,", "or not (0). Defaults to 1. pre_steps (float, optional): number of standard VI", "lr_encoder self.lr_decoder = lr_decoder self.lr_predictor = lr_predictor self.lr_hmc = lr_hmc self.lr_scale = lr_scale", "observed_x, y, observed_y = batch x = x.view(-1, self.dim_x) # Normalize the data", "torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01) opt_encoder = torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01) opt_hmc = torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale", "batch_size=128, lr=1e-3, samples_MC = 1, data_path='../data/', split_idx=0, L=5, T=10, chains=1, chains_sksd=30, sksd=1, pre_steps=2e3,", "1e-3. lr_scale (_type_, optional): Learning rate for the scale (inflation) factor Defaults to", "# Define the HMC objective self.HMC.logp = self.logp_func(xo, observed_x, yon, observed_y) return xn,", "self.pre_steps = pre_steps self.lr_pre = lr_pre self.lr_encoder = lr_encoder self.lr_decoder = lr_decoder self.lr_predictor", "if self.sksd and self.step_idx % self.update_s_each == 0: self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder)", "again for not sharing gradients mu_z, logvar_z = self.encoder(xy) zT = self.sample_z(mu_z, logvar_z,", "logging: bool=True): \"\"\" Perform a traning step following https://arxiv.org/abs/2202.04599 - For the first", "observed_y (for not using kl if no observed data) mu_z, logvar_z = self.encoder(xy)", "sample_z(self, mu: torch.Tensor, logvar: torch.Tensor, samples=1, hmc=True) -> torch.Tensor: \"\"\" Draw latent samples", "Defaults to 128. lr (float, optional): learning rate for the parameter optimization. Defaults", "= update_s_each self.hmc=True self.save_hyperparameters('L', 'T', 'chains', 'sksd', 'pre_steps', 'lr_pre', 'lr_encoder', 'lr_decoder', 'lr_predictor', 'lr_hmc',", "and self.global_step < self.pre_steps: # Repeat samples_MC times for Monte Carlo mu =", "self.normalize_x(x) xt, yt, xy, observed = self.preprocess_batch(batch) # xt is the preprocessed input", "x_tilde = torch.cat([xo, observed_x], axis=1) y = y.view(-1, self.dim_y) observed_y = observed_y.view(-1, self.dim_y)", "* # ============= HMCVAE ============= # class HMCVAE(BaseVAE): \"\"\" Implements a Hamiltonian VAE", "= self.decoder.logp(xt, observed_x, z=z, theta=theta_x).sum(-1) rec_y = self.predictor.logp(yt, observed_y, z=zx).sum(-1) kls = self.encoder.regularizer(mu_z,", "self.lr_decoder = lr_decoder self.lr_predictor = lr_predictor self.lr_hmc = lr_hmc self.lr_scale = lr_scale self.update_s_each", "the parameter optimization. Defaults to 1e-3. samples_MC (int, optional): number of MC samples", "self.global_step < self.pre_steps: # Repeat samples_MC times for Monte Carlo mu = mu.repeat(samples,", "super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y, latent_dim = latent_dim, arch=arch, dim_h=dim_h, likelihood_x = likelihood_x, likelihood_y", "False, categories_y = 1, prediction_metric='rmse', batch_size=128, lr=1e-3, samples_MC = 1, data_path='../data/', split_idx=0, L=5,", "batch index from the training set logging (bool): log metrics into Tensorboard (True).", "'pre_steps', 'lr_pre', 'lr_encoder', 'lr_decoder', 'lr_predictor', 'lr_hmc', 'lr_scale', 'update_s_each') self.step_idx=0 # training step index", "dimension of the latent space. Defaults to 10. arch (str, optional): name of", "the rest, optimize encoder using ELBO, and the rest using HMC objective and", "L=L, T=T, chains=chains, chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False self.L = L self.T = T self.chains", "Defaults to 10. chains (int, optional): number of parallel HMC chains. Defaults to", "1e-3. lr_encoder (float, optional): Learning rate for the encoder parameters. Defaults to 1e-3.", "kls = self.forward(batch, hmc=False, samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step() self.log('ELBO', -loss_3, on_step=False, on_epoch=True, prog_bar=True,", "the ELBO. For the rest, use HMC Args: batch (tuple): contains (data, observed_data,", "\"\"\" batch = [b.to(self.device) for b in batch] x, observed_x, y, observed_y =", "of the hidden vectors. Defaults to 256. likelihood_x (str, optional): input data likelihood", "For the rest, use HMC Args: batch (tuple): contains (data, observed_data, target, observed_target)", "elbo = elbo[elbo!=0].mean() rec_x = rec_x[rec_x!=0].mean() rec_y = rec_y[rec_y!=0].mean() kl_mean = torch.zeros(len(kls)).to(self.device) for", "data dimension latent_dim (int, optional): dimension of the latent space. Defaults to 10.", "imbalanced_y = False, categories_y = 1, prediction_metric='rmse', batch_size=128, lr=1e-3, samples_MC = 1, data_path='../data/',", "rec_x[rec_x!=0].mean() rec_y = rec_y[rec_y!=0].mean() kl_mean = torch.zeros(len(kls)).to(self.device) for l, kl in enumerate(kls): kl_mean[l]=", "self.automatic_optimization=False self.L = L self.T = T self.chains = chains self.chains_sksd = chains_sksd", "# Optimize psi (encoder) activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False", "Defaults to True. Returns: torch.Tensor: latent samples \"\"\" if hmc==False or self.validation and", "\"\"\" Forward data through the model. For the pretraining stage, use the ELBO.", "Default True \"\"\" (opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc, opt_scale) = self.optimizers(use_pl_optimizer=True) if self.step_idx", "optional): Learning rate for the predictor. Defaults to 1e-3. lr_hmc (float, optional): Learning", "decoder (p(x|z1)). Defaults to 1e-3. lr_predictor (float, optional): Learning rate for the predictor.", "name of the prediction metric for validation ('rmse', 'accuracy'). Defaults to 'rmse'. batch_size", "lr_pre self.lr_encoder = lr_encoder self.lr_decoder = lr_decoder self.lr_predictor = lr_predictor self.lr_hmc = lr_hmc", "categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size, lr=lr, samples_MC = samples_MC, data_path=data_path, split_idx=split_idx) self.HMC = HMC(dim=latent_dim, L=L,", "hmc=False) theta_x = self.decoder(z) x_hat = self.build_x_hat(xn, observed_x, theta_x) zx = torch.cat([z,x_hat],dim=-1) rec_x", "opt_predictor.step() opt_hmc.step() if self.sksd and self.step_idx % self.update_s_each == 0: self.HMC.log_inflation.requires_grad = True", "ELBO - For the rest, optimize encoder using ELBO, and the rest using", "(data, observed_data, target, observed_target) hmc (bool): sample posterior using HMC (True). Defaults to", "observed_x OR observed_y (for not using kl if no observed data) mu_z, logvar_z", "'chains', 'sksd', 'pre_steps', 'lr_pre', 'lr_encoder', 'lr_decoder', 'lr_predictor', 'lr_hmc', 'lr_scale', 'update_s_each') self.step_idx=0 # training", "data x, observed_x, y, observed_y = batch xn = self.normalize_x(x) xt, yt, xy,", "mu = mu.repeat(samples, 1, 1).transpose(0, 1) logvar = logvar.repeat(samples, 1, 1).transpose(0, 1) #", "opt_hmc]) opt_decoder.step() opt_predictor.step() opt_hmc.step() if self.sksd and self.step_idx % self.update_s_each == 0: self.HMC.log_inflation.requires_grad", "+ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base import * from src.models.hmc import * # =============", "torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters()) + list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01) opt_decoder = torch.optim.Adam(list(self.decoder.parameters()), lr=self.lr_decoder, weight_decay=0.01) opt_predictor", "(before using HMC). Defaults to 18e3. lr_pre (float, optional): learning reate for all", "training step index # ============= Modified base functions ============= # def forward(self, batch:", "deactivate(self.predictor) self.HMC.log_eps.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale) opt_scale.step() scale", "training steps (before using HMC). Defaults to 18e3. lr_pre (float, optional): learning reate", "= torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale = torch.optim.Adam([self.HMC.log_inflation], lr=self.lr_scale) return [opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc,", "Args: dataset (str): name of the dataset (boston, mnist, ...) dim_x (int): input", "= -self.HMC.logp(zT) loss_1 = loss_1[loss_1!=0].mean() if self.sksd==1: # Deactivate everything except scale self.HMC.log_inflation.requires_grad", "deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False # Get data x, observed_x,", "mu_z, logvar_z = self.encoder(xy) z = self.sample_z(mu_z, logvar_z, samples=samples, hmc=False) theta_x = self.decoder(z)", "phi (decoders and HMC) activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False", "for not sharing gradients mu_z, logvar_z = self.encoder(xy) zT = self.sample_z(mu_z, logvar_z, samples=samples)", "training split. Defaults to 0. L (int, optional): number of Leapfrog steps. Defaults", "torch.cat([xo, observed_x], axis=1) y = y.view(-1, self.dim_y) observed_y = observed_y.view(-1, self.dim_y) # Normalize", "set logging (bool): log metrics into Tensorboard (True). Default True \"\"\" (opt_vae, opt_decoder,", "Activate only encoder activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False #", "= lr_predictor self.lr_hmc = lr_hmc self.lr_scale = lr_scale self.update_s_each = update_s_each self.hmc=True self.save_hyperparameters('L',", "else: # returns elbo, logp and sksd # Activate decoder, predictor and hmc", "of categories when the target is categorical. Defaults to 1. prediction_metric (str, optional):", "opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder, opt_predictor, opt_hmc]) opt_decoder.step() opt_predictor.step() opt_hmc.step() if self.sksd and", "of MC samples for computing the ELBO. Defaults to 1. data_path (str, optional):", "Defaults to 1. pre_steps (float, optional): number of standard VI training steps (before", "type. Defaults to 'gaussian'. likelihood_y (str, optional): target data likelihood type. Defaults to", "loss_3, loss_1, loss_2 def training_step(self, batch: tuple, batch_idx: int, logging: bool=True): \"\"\" Perform", "activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad()", "= True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False # Encoder again for not sharing gradients", "For the first pre_steps, optimize parameters by maximizing the ELBO - For the", "dim_x (int): input data dimension dim_y (int): target data dimension latent_dim (int, optional):", "space. Defaults to 10. arch (str, optional): name of the architecture for encoder/decoder", "observed_x x_tilde = torch.cat([xo, observed_x], axis=1) y = y.view(-1, self.dim_y) observed_y = observed_y.view(-1,", "z, _ = self.HMC.generate_samples_HMC(mu, torch.exp(logvar), chains=samples) return z # ============= Modified PL functions", "for all the parameters during the VI training stage. Defaults to 1e-3. lr_encoder", "Learning rate for the HMC hyperparameters (matrix of step sizes). Defaults to 1e-3.", "chains=1, chains_sksd=30, sksd=1, pre_steps=2e3, lr_pre=1e-3, lr_encoder=1e-3, lr_decoder=1e-3, lr_predictor=1e-3, lr_hmc=1e-3, lr_scale = 1e-2, update_s_each=10", "base class function) for defining the HMC objective p(epsilon)(x, y) Args: batch (tuple):", "SKSD regularizer (1) or not (0). Defaults to 1. pre_steps (float, optional): number", "from src.models.base import * from src.models.hmc import * # ============= HMCVAE ============= #", "HMC chains. Defaults to 1. chains_sksd (int, optional): number of parallel HMC chains", "(boston, mnist, ...) dim_x (int): input data dimension dim_y (int): target data dimension", "likelihood_y (str, optional): target data likelihood type. Defaults to 'gaussian'. variance (float, optional):", "number of parallel HMC chains. Defaults to 1. chains_sksd (int, optional): number of", "deactivate(self.predictor) self.HMC.log_eps.requires_grad = False loss_2 = self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else: loss_2 = None return", "observed_data, target, observed_target) hmc (bool): sample posterior using HMC (True). Defaults to True", "logger=True) if logging: self.log('-rec_x', -rec_x, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('-rec_y', -rec_y, on_step=False, on_epoch=True,", "lr_decoder self.lr_predictor = lr_predictor self.lr_hmc = lr_hmc self.lr_scale = lr_scale self.update_s_each = update_s_each", "= torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01) opt_encoder = torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01) opt_hmc = torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc)", "observed_data, target, observed_target) \"\"\" batch = [b.to(self.device) for b in batch] x, observed_x,", "returns: loss_VI, rec_x, rec_y, kl If hmc=True, returns: loss_VI, loss_HMC, loss_SKSD, rec_x, rec_y,", "samples=self.chains) ##### Optimization # Optimize psi (encoder) activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False", "variances (batch_size, latent_dim) samples (int, optional): number of samples. Defaults to 1. hmc", "< self.pre_steps: # Repeat samples_MC times for Monte Carlo mu = mu.repeat(samples, 1,", "False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder, opt_predictor, opt_hmc]) opt_decoder.step() opt_predictor.step() opt_hmc.step()", "= 10, arch='base', dim_h=256, likelihood_x = 'gaussian', likelihood_y = 'gaussian', variance=0.1, imbalanced_y =", "enumerate(kls): self.log('kl_{:d}'.format(l), kl, on_step=False, on_epoch=True, prog_bar=False, logger=True) else: self.hmc=True loss_3, loss_1, loss_2 =", "the encoder parameters. Defaults to 1e-3. lr_decoder (float, optional): Learning rate for the", "__init__(self, dataset: str, dim_x: int, dim_y: int, latent_dim = 10, arch='base', dim_h=256, likelihood_x", "opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder, opt_predictor, opt_hmc]) opt_decoder.step() opt_predictor.step() opt_hmc.step() if self.sksd", "(float, optional): Learning rate for the predictor. Defaults to 1e-3. lr_hmc (float, optional):", "Returns: tuple: preprocessed batch, contains (data, observed_data, target, observed_target) \"\"\" batch = [b.to(self.device)", "hmc=True) -> torch.Tensor: \"\"\" Draw latent samples from a given approx posterior parameterized", "loss_SKSD, rec_x, rec_y, kl \"\"\" if hmc==True: # Activate only encoder activate(self.encoder) deactivate(self.decoder)", "Interval of steps for optimizing the scale factor. Defaults to 10. \"\"\" super(HMCVAE,", "= self.sample_z(mu_z, logvar_z, samples=samples) loss_1 = -self.HMC.logp(zT) loss_1 = loss_1[loss_1!=0].mean() if self.sksd==1: #", "<NAME>, UC3M. + # All rights reserved. This file is part of the", "opt_encoder, opt_hmc, opt_scale) = self.optimizers(use_pl_optimizer=True) if self.step_idx < self.pre_steps: self.hmc=False loss_3, rec_x, rec_y,", "on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('HMC_objective', -loss_1, on_step=False, on_epoch=True, prog_bar=True, logger=True) self.step_idx += 1", "the batch (overrides the base class function) for defining the HMC objective p(epsilon)(x,", "input data likelihood type. Defaults to 'gaussian'. likelihood_y (str, optional): target data likelihood", "scale (inflation) factor Defaults to 1e-2. update_s_each (int, optional): Interval of steps for", "# Get data x, observed_x, y, observed_y = batch xn = self.normalize_x(x) xt,", "the data xn = self.normalize_x(x) xo = xn * observed_x x_tilde = torch.cat([xo,", "Modified PL functions ============= # def configure_optimizers(self): opt_vae = torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters()) +", "= loss_1[loss_1!=0].mean() if self.sksd==1: # Deactivate everything except scale self.HMC.log_inflation.requires_grad = True deactivate(self.encoder)", "optional): batch size. Defaults to 128. lr (float, optional): learning rate for the", "(int, optional): number of parallel HMC chains for computing the SKSD. Defaults to", "Defaults to 'base'. dim_h (int, optional): dimension of the hidden vectors. Defaults to", "1).transpose(0, 1) # Reparametrization z = reparameterize(mu, torch.exp(logvar)) else: # sample from the", "sizes). Defaults to 1e-3. lr_scale (_type_, optional): Learning rate for the scale (inflation)", "self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#, [opt_decoder, opt_predictor, opt_hmc]) opt_decoder.step()", "torch.cat([x_tilde, y_tilde], axis=1) observed = torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0) # Define the HMC", "(p(x|z1)). Defaults to 1e-3. lr_predictor (float, optional): Learning rate for the predictor. Defaults", "mu (torch.Tensor): tensor with the means (batch_size, latent_dim) logvar (torch.Tensor): tensor with the", "xt is the preprocessed input (xt=x if no preprocessing) # observed is observed_x", "the means (batch_size, latent_dim) logvar (torch.Tensor): tensor with the log variances (batch_size, latent_dim)", "use the ELBO. For the rest, use HMC Args: batch (tuple): contains (data,", "gradients mu_z, logvar_z = self.encoder(xy) zT = self.sample_z(mu_z, logvar_z, samples=samples) loss_1 = -self.HMC.logp(zT)", "= self.encoder.regularizer(mu_z, logvar_z, observed) elbo = rec_x + rec_y - kls.sum(0).unsqueeze(-1) elbo =", "(float, optional): number of standard VI training steps (before using HMC). Defaults to", "1. prediction_metric (str, optional): name of the prediction metric for validation ('rmse', 'accuracy').", "update_s_each=10 ): \"\"\" HMCVAE Initialization Args: dataset (str): name of the dataset (boston,", "return loss_3, rec_x, rec_y, kl_mean else: # returns elbo, logp and sksd #", "torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0) # Define the HMC objective self.HMC.logp = self.logp_func(xo, observed_x,", "lr_pre (float, optional): learning reate for all the parameters during the VI training", "logvar_z = self.encoder(xy) zT = self.sample_z(mu_z, logvar_z, samples=samples) loss_1 = -self.HMC.logp(zT) loss_1 =", "number of categories when the target is categorical. Defaults to 1. prediction_metric (str,", "idx of the training split. Defaults to 0. L (int, optional): number of", "index # ============= Modified base functions ============= # def forward(self, batch: tuple, hmc=True,", "posterior using HMC (True). Defaults to True samples (int): number of MC samples", "opt_predictor = torch.optim.Adam(list(self.predictor.parameters()), lr=self.lr_predictor, weight_decay=0.01) opt_encoder = torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01) opt_hmc = torch.optim.Adam([self.HMC.log_eps],", "opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale) opt_scale.step() scale = torch.exp(self.HMC.log_inflation) self.log('scale', scale,", "True. Returns: torch.Tensor: latent samples \"\"\" if hmc==False or self.validation and self.global_step <", "self.log('-rec_y', -rec_y, on_step=False, on_epoch=True, prog_bar=False, logger=True) for l, kl in enumerate(kls): self.log('kl_{:d}'.format(l), kl,", "self.normalize_y(y) yon = yn * observed_y y_tilde = torch.cat([yon, observed_y], axis=1) xy =", "\"\"\" Preprocessing operations for the batch (overrides the base class function) for defining", "times for Monte Carlo mu = mu.repeat(samples, 1, 1).transpose(0, 1) logvar = logvar.repeat(samples,", "preprocessed batch, contains (data, observed_data, target, observed_target) \"\"\" batch = [b.to(self.device) for b", "self.encoder.regularizer(mu_z, logvar_z, observed) elbo = rec_x + rec_y - kls.sum(0).unsqueeze(-1) elbo = elbo[elbo!=0].mean()", "self.dim_y) # Normalize the target yn = self.normalize_y(y) yon = yn * observed_y", "Defaults to 10. arch (str, optional): name of the architecture for encoder/decoder from", "Learning rate for the decoder (p(x|z1)). Defaults to 1e-3. lr_predictor (float, optional): Learning", "the HMC objective p(epsilon)(x, y) Args: batch (tuple): contains (data, observed_data, target, observed_target)", "= False # Get data x, observed_x, y, observed_y = batch xn =", "LICENSE file that should have + # been included as part of this", "('rmse', 'accuracy'). Defaults to 'rmse'. batch_size (int, optional): batch size. Defaults to 128.", "observed_y) return xn, yn, xy, observed def sample_z(self, mu: torch.Tensor, logvar: torch.Tensor, samples=1,", "HMCVAE ============= # class HMCVAE(BaseVAE): \"\"\" Implements a Hamiltonian VAE (HMC-VAE) as described", "= self.encoder(xy) z = self.sample_z(mu_z, logvar_z, samples=samples, hmc=False) theta_x = self.decoder(z) x_hat =", "the first pre_steps, optimize parameters by maximizing the ELBO - For the rest,", "of MC samples for computing the ELBO Returns: If hmc=False, returns: loss_VI, rec_x,", "optimize encoder using ELBO, and the rest using HMC objective and SKSD Args:", "batch (tuple): contains (data, observed_data, target, observed_target) Returns: tuple: preprocessed batch, contains (data,", "self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_1)#,", "= self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else: loss_2 = None return loss_3, loss_1, loss_2 def training_step(self,", "deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3)", "# class HMCVAE(BaseVAE): \"\"\" Implements a Hamiltonian VAE (HMC-VAE) as described in https://arxiv.org/abs/2202.04599", "MC samples for computing the ELBO. Defaults to 1. data_path (str, optional): path", "self.forward(batch, hmc=False, samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step() self.log('ELBO', -loss_3, on_step=False, on_epoch=True, prog_bar=True, logger=True) if", "to 128. lr (float, optional): learning rate for the parameter optimization. Defaults to", "Defaults to 'gaussian'. variance (float, optional): fixed variance for Gaussian likelihoods. Defaults to", "xy, observed def sample_z(self, mu: torch.Tensor, logvar: torch.Tensor, samples=1, hmc=True) -> torch.Tensor: \"\"\"", "* from src.models.hmc import * # ============= HMCVAE ============= # class HMCVAE(BaseVAE): \"\"\"", "the log variances (batch_size, latent_dim) samples (int, optional): number of samples. Defaults to", "samples (int): number of MC samples for computing the ELBO Returns: If hmc=False,", "Modified base functions ============= # def forward(self, batch: tuple, hmc=True, samples=1) -> tuple:", "# xt is the preprocessed input (xt=x if no preprocessing) # observed is", "tuple: \"\"\" Forward data through the model. For the pretraining stage, use the", "opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale) opt_scale.step() scale = torch.exp(self.HMC.log_inflation) self.log('scale', scale, on_step=False, on_epoch=True, prog_bar=True, logger=True)", "optional): length of the HMC chains. Defaults to 10. chains (int, optional): number", "rate for the decoder (p(x|z1)). Defaults to 1e-3. lr_predictor (float, optional): Learning rate", "torch.zeros(len(kls)).to(self.device) for l, kl in enumerate(kls): kl_mean[l]= kl[kl!=0].mean() loss_3 = -elbo if hmc==False:", "-rec_y, on_step=False, on_epoch=True, prog_bar=False, logger=True) for l, kl in enumerate(kls): self.log('kl_{:d}'.format(l), kl, on_step=False,", "Optimization # Optimize psi (encoder) activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad =", "optional): name of the architecture for encoder/decoder from the 'archs' file. Defaults to", "the 'archs' file. Defaults to 'base'. dim_h (int, optional): dimension of the hidden", "type. Defaults to 'gaussian'. variance (float, optional): fixed variance for Gaussian likelihoods. Defaults", "logger=True) else: self.hmc=True loss_3, loss_1, loss_2 = self.forward(batch, samples=self.chains) ##### Optimization # Optimize", "lr (float, optional): learning rate for the parameter optimization. Defaults to 1e-3. samples_MC", "observed_x, theta_x) zx = torch.cat([z,x_hat],dim=-1) rec_x = self.decoder.logp(xt, observed_x, z=z, theta=theta_x).sum(-1) rec_y =", "activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad()", "into Tensorboard (True). Default True \"\"\" (opt_vae, opt_decoder, opt_predictor, opt_encoder, opt_hmc, opt_scale) =", "False self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_3) opt_encoder.step() # Optimize", "= self.preprocess_batch(batch) # xt is the preprocessed input (xt=x if no preprocessing) #", "self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False # Get data x, observed_x, y, observed_y", "+ # the \"MIT License Agreement\". Please see the LICENSE file that should", "base functions ============= # def forward(self, batch: tuple, hmc=True, samples=1) -> tuple: \"\"\"", "1. hmc (bool, optional): draw hmc samples or Gaussian samples from the proposal.", "configure_optimizers(self): opt_vae = torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters()) + list(self.encoder.parameters()), lr=self.lr_pre, weight_decay=0.01) opt_decoder = torch.optim.Adam(list(self.decoder.parameters()),", "logger=True) if logging: self.log('SKSD', loss_2, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('HMC_objective', -loss_1, on_step=False, on_epoch=True,", "\"\"\" Implements a Hamiltonian VAE (HMC-VAE) as described in https://arxiv.org/abs/2202.04599 \"\"\" def __init__(self,", "False loss_2 = self.HMC.evaluate_sksd(mu_z, torch.exp(logvar_z)) else: loss_2 = None return loss_3, loss_1, loss_2", "PL functions ============= # def configure_optimizers(self): opt_vae = torch.optim.Adam(list(self.decoder.parameters()) + list(self.predictor.parameters()) + list(self.encoder.parameters()),", "= rec_x + rec_y - kls.sum(0).unsqueeze(-1) elbo = elbo[elbo!=0].mean() rec_x = rec_x[rec_x!=0].mean() rec_y", "samples=1) -> tuple: \"\"\" Forward data through the model. For the pretraining stage,", "operations for the batch (overrides the base class function) for defining the HMC", "of the training split. Defaults to 0. L (int, optional): number of Leapfrog", "yn * observed_y y_tilde = torch.cat([yon, observed_y], axis=1) xy = torch.cat([x_tilde, y_tilde], axis=1)", "data dimension dim_y (int): target data dimension latent_dim (int, optional): dimension of the", "Defaults to 1. hmc (bool, optional): draw hmc samples or Gaussian samples from", "= False opt_encoder.zero_grad() opt_decoder.zero_grad() opt_predictor.zero_grad() opt_hmc.zero_grad() opt_scale.zero_grad() self.manual_backward(loss_2)#, opt_scale) opt_scale.step() scale = torch.exp(self.HMC.log_inflation)", "by mu and logvar Args: mu (torch.Tensor): tensor with the means (batch_size, latent_dim)", "'lr_hmc', 'lr_scale', 'update_s_each') self.step_idx=0 # training step index # ============= Modified base functions", "parameters by maximizing the ELBO - For the rest, optimize encoder using ELBO,", "(float, optional): learning reate for all the parameters during the VI training stage.", "Defaults to 1. chains_sksd (int, optional): number of parallel HMC chains for computing", "yn = self.normalize_y(y) yon = yn * observed_y y_tilde = torch.cat([yon, observed_y], axis=1)", "optional): idx of the training split. Defaults to 0. L (int, optional): number", "10, arch='base', dim_h=256, likelihood_x = 'gaussian', likelihood_y = 'gaussian', variance=0.1, imbalanced_y = False,", "(bool, optional): draw hmc samples or Gaussian samples from the proposal. Defaults to", "Defaults to 1e-2. update_s_each (int, optional): Interval of steps for optimizing the scale", "sksd # Activate decoder, predictor and hmc activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder)", "Defaults to 1. data_path (str, optional): path to load/save the data. Defaults to", "file that should have + # been included as part of this package.", "y_tilde], axis=1) observed = torch.logical_or(observed_x.sum(-1, keepdim=True)>0, observed_y.sum(-1, keepdim=True)>0) # Define the HMC objective", "to 'gaussian'. variance (float, optional): fixed variance for Gaussian likelihoods. Defaults to 0.1.", "if self.sksd==1: # Deactivate everything except scale self.HMC.log_inflation.requires_grad = True deactivate(self.encoder) deactivate(self.decoder) deactivate(self.predictor)", "Perform a traning step following https://arxiv.org/abs/2202.04599 - For the first pre_steps, optimize parameters", "Activate decoder, predictor and hmc activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad =", "(decoders and HMC) activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False opt_encoder.zero_grad()", "elbo return loss_3, rec_x, rec_y, kl_mean else: # returns elbo, logp and sksd", "rec_x, rec_y, kls = self.forward(batch, hmc=False, samples=self.samples_MC) opt_vae.zero_grad() self.manual_backward(loss_3) opt_vae.step() self.log('ELBO', -loss_3, on_step=False,", "for the parameter optimization. Defaults to 1e-3. samples_MC (int, optional): number of MC", "released under + # the \"MIT License Agreement\". Please see the LICENSE file", "optional): Learning rate for the encoder parameters. Defaults to 1e-3. lr_decoder (float, optional):", "self.sksd = sksd self.pre_steps = pre_steps self.lr_pre = lr_pre self.lr_encoder = lr_encoder self.lr_decoder", "to 0.1. imbalanced_y (bool, optional): True for compensating imbalanced classification. Defaults to False.", "if hmc==False: # returns elbo return loss_3, rec_x, rec_y, kl_mean else: # returns", "of the latent space. Defaults to 10. arch (str, optional): name of the", "kls = self.encoder.regularizer(mu_z, logvar_z, observed) elbo = rec_x + rec_y - kls.sum(0).unsqueeze(-1) elbo", "xo = xn * observed_x x_tilde = torch.cat([xo, observed_x], axis=1) y = y.view(-1,", "parameterized by mu and logvar Args: mu (torch.Tensor): tensor with the means (batch_size,", "encoder using ELBO, and the rest using HMC objective and SKSD Args: batch", "# training step index # ============= Modified base functions ============= # def forward(self,", "number of MC samples for computing the ELBO Returns: If hmc=False, returns: loss_VI,", "(int, optional): dimension of the hidden vectors. Defaults to 256. likelihood_x (str, optional):", "kl, on_step=False, on_epoch=True, prog_bar=False, logger=True) else: self.hmc=True loss_3, loss_1, loss_2 = self.forward(batch, samples=self.chains)", "as part of this package. + # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ from src.models.base import * from", "data likelihood type. Defaults to 'gaussian'. likelihood_y (str, optional): target data likelihood type.", "= 'gaussian', variance=0.1, imbalanced_y = False, categories_y = 1, prediction_metric='rmse', batch_size=128, lr=1e-3, samples_MC", "Implements a Hamiltonian VAE (HMC-VAE) as described in https://arxiv.org/abs/2202.04599 \"\"\" def __init__(self, dataset:", "in batch] x, observed_x, y, observed_y = batch x = x.view(-1, self.dim_x) #", "samples_MC, data_path=data_path, split_idx=split_idx) self.HMC = HMC(dim=latent_dim, L=L, T=T, chains=chains, chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False self.L", "self.forward(batch, samples=self.chains) ##### Optimization # Optimize psi (encoder) activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad =", "optional): number of categories when the target is categorical. Defaults to 1. prediction_metric", "activate(self.encoder) deactivate(self.decoder) deactivate(self.predictor) self.HMC.log_eps.requires_grad = False self.HMC.log_inflation.requires_grad = False # Get data x,", "'accuracy'). Defaults to 'rmse'. batch_size (int, optional): batch size. Defaults to 128. lr", "hmc activate(self.decoder) activate(self.predictor) self.HMC.log_eps.requires_grad = True deactivate(self.encoder) self.HMC.log_inflation.requires_grad = False # Encoder again", "1, 1).transpose(0, 1) # Reparametrization z = reparameterize(mu, torch.exp(logvar)) else: # sample from", "lr_predictor (float, optional): Learning rate for the predictor. Defaults to 1e-3. lr_hmc (float,", "= torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01) opt_hmc = torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale = torch.optim.Adam([self.HMC.log_inflation], lr=self.lr_scale) return", "rate for the HMC hyperparameters (matrix of step sizes). Defaults to 1e-3. lr_scale", "Gaussian likelihoods. Defaults to 0.1. imbalanced_y (bool, optional): True for compensating imbalanced classification.", "self.lr_encoder = lr_encoder self.lr_decoder = lr_decoder self.lr_predictor = lr_predictor self.lr_hmc = lr_hmc self.lr_scale", "False self.HMC.log_inflation.requires_grad = False # Get data x, observed_x, y, observed_y = batch", "rate for the parameter optimization. Defaults to 1e-3. samples_MC (int, optional): number of", "and the rest using HMC objective and SKSD Args: batch (tuple): contains (data,", "optional): dimension of the latent space. Defaults to 10. arch (str, optional): name", "variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric, batch_size=batch_size, lr=lr, samples_MC = samples_MC, data_path=data_path, split_idx=split_idx) self.HMC =", "logvar_z, samples=samples, hmc=False) theta_x = self.decoder(z) x_hat = self.build_x_hat(xn, observed_x, theta_x) zx =", "For the rest, optimize encoder using ELBO, and the rest using HMC objective", "loss_VI, loss_HMC, loss_SKSD, rec_x, rec_y, kl \"\"\" if hmc==True: # Activate only encoder", "self.encoder(xy) z = self.sample_z(mu_z, logvar_z, samples=samples, hmc=False) theta_x = self.decoder(z) x_hat = self.build_x_hat(xn,", "scale factor. Defaults to 10. \"\"\" super(HMCVAE, self).__init__(dataset=dataset, dim_x=dim_x, dim_y=dim_y, latent_dim = latent_dim,", "the ELBO. Defaults to 1. data_path (str, optional): path to load/save the data.", "objective self.HMC.logp = self.logp_func(xo, observed_x, yon, observed_y) return xn, yn, xy, observed def", "Learning rate for the predictor. Defaults to 1e-3. lr_hmc (float, optional): Learning rate", "logging: self.log('-rec_x', -rec_x, on_step=False, on_epoch=True, prog_bar=False, logger=True) self.log('-rec_y', -rec_y, on_step=False, on_epoch=True, prog_bar=False, logger=True)", "self.L = L self.T = T self.chains = chains self.chains_sksd = chains_sksd self.sksd", "latent_dim, arch=arch, dim_h=dim_h, likelihood_x = likelihood_x, likelihood_y = likelihood_y, variance=variance, imbalanced_y=imbalanced_y, categories_y=categories_y, prediction_metric=prediction_metric,", "HMC chains for computing the SKSD. Defaults to 30. sksd (int, optional): learn", "optional): input data likelihood type. Defaults to 'gaussian'. likelihood_y (str, optional): target data", "zx = torch.cat([z,x_hat],dim=-1) rec_x = self.decoder.logp(xt, observed_x, z=z, theta=theta_x).sum(-1) rec_y = self.predictor.logp(yt, observed_y,", "= [b.to(self.device) for b in batch] x, observed_x, y, observed_y = batch x", "on_epoch=True, prog_bar=True, logger=True) self.step_idx += 1 def preprocess_batch(self, batch: tuple): \"\"\" Preprocessing operations", "HMC). Defaults to 18e3. lr_pre (float, optional): learning reate for all the parameters", "self.log('scale', scale, on_step=False, on_epoch=True, prog_bar=True, logger=True) if logging: self.log('SKSD', loss_2, on_step=False, on_epoch=True, prog_bar=False,", "batch (tuple): contains (data, observed_data, target, observed_target) batch_idx (int): batch index from the", "= HMC(dim=latent_dim, L=L, T=T, chains=chains, chains_sksd=chains_sksd, logp=None) self.automatic_optimization=False self.L = L self.T =", "data likelihood type. Defaults to 'gaussian'. variance (float, optional): fixed variance for Gaussian", "lr=self.lr_predictor, weight_decay=0.01) opt_encoder = torch.optim.Adam(list(self.encoder.parameters()), lr=self.lr_encoder, weight_decay=0.01) opt_hmc = torch.optim.Adam([self.HMC.log_eps], lr=self.lr_hmc) opt_scale =" ]
[ "Class ############################################################################################################ class analyzepenalties: def __init__(self): self.logger = logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind = 2*\"", "Additiveness\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay in enumerate(drivePlays): play", "is None: play.yds.yards = nextYards else: if play.yds.yards is None: play.yds.yards = nextYards", "sure...\") if nextYards == 0 and play.yds.yards == 0: penaltyyards = 0 if", "Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) self.logger.debug(\"{0}Analyzing Penalty Additiveness -> Done\".format(self.ind)) def", "play.yds.yards = nextYards else: if play.yds.yards is None: play.yds.yards = nextYards else: print(\"Not", "> 0: if nextYards == 15: penaltyyards = 15 play.yds.yards = 0 elif", "== 15: penaltyyards = -15 play.yds.yards = 0 if nextYards == penaltyyards: if", "play.yds.yards and nextYards == penaltyyards: continue self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name, nextYards, play.yds.yards,", "== penaltyyards: continue self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name, nextYards, play.yds.yards, penaltyyards, play.text)) self.logger.debug(\"{0}Analyzing", "utf-8 -*- \"\"\" Created on Mon Apr 22 18:29:44 2019 @author: tgadfort \"\"\"", "0 if sum([x in play.text for x in [\"Personal Foul\", \"Unsportsmanlike Conduct\", \"Face", "== 0 and penaltyyards is not None: play.yds.yards = penaltyyards elif play.yds.yards ==", "= nextYards else: print(\"Not sure...\") if nextYards == 0 and play.yds.yards == 0:", "############################################################################################################ class analyzepenalties: def __init__(self): self.logger = logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind = 2*\" \"", "logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind = 2*\" \" self.sep = \"======================================================\" self.dc = debugclass() self.py", "Created on Mon Apr 22 18:29:44 2019 @author: tgadfort \"\"\" from debug import", "else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) self.logger.debug(\"{0}Analyzing Penalty", "None: play.yds.yards = nextYards else: if play.yds.yards is None: play.yds.yards = nextYards else:", "penaltyyards == nextYards: play.yds.yards = 0 continue else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext", "enumerate(drivePlays): play = drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards = play.penalty.yards playyards", "Done\".format(self.ind)) def penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays =", "Foul\", \"Unsportsmanlike Conduct\", \"Face Mask\"]]) > 0: if nextYards == 15: penaltyyards =", "deepcopy, copy # create logger import logging module_logger = logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ## Drive", "playyards #from copy import deepcopy, copy # create logger import logging module_logger =", "False: continue penaltyyards = self.py.findPenaltyYards(play.text) nextYards = drivePlay.nextDiffYards if isinstance(play, noplay): if play.yds.yards", "driveData.plays for ipl,drivePlay in enumerate(drivePlays): play = drivePlay.play if play.penalty.isPenalty is False: continue", "from playTypes import noplay from playYards import playyards #from copy import deepcopy, copy", "else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) else: self.logger.debug(\"{0}Penalty", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on Mon Apr 22", "Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay", "and penaltyyards == nextYards: play.yds.yards = 0 continue else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay", "debugclass() self.py = playyards() def isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind)) for idr,driveData", "= logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind = 2*\" \" self.sep = \"======================================================\" self.dc = debugclass()", "playyards() def isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays", "def isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays =", "nextYards = drivePlay.nextDiffYards if isinstance(play, noplay): if play.yds.yards == 0 and penaltyyards is", "Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards,", "def penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays", "isinstance(play, noplay): if play.yds.yards == 0 and penaltyyards is not None: play.yds.yards =", "= nextYards else: if play.yds.yards is None: play.yds.yards = nextYards else: print(\"Not sure...\")", "0 if nextYards == penaltyyards: if play.yds.yards == 0: play.yds.yards = nextYards play.penalty.yards", "penaltyyards elif play.yds.yards == 0 and penaltyyards is None: play.yds.yards = nextYards else:", "self.dc = debugclass() self.py = playyards() def isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind))", "import playyards #from copy import deepcopy, copy # create logger import logging module_logger", "0 and penaltyyards is not None: play.yds.yards = penaltyyards elif play.yds.yards == 0", "-15 play.yds.yards = 0 if nextYards == penaltyyards: if play.yds.yards == 0: play.yds.yards", "and penaltyyards is not None: play.yds.yards = penaltyyards elif play.yds.yards == 0 and", "-> Done\".format(self.ind)) def penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays", "print(\"Not sure...\") if nextYards == 0 and play.yds.yards == 0: penaltyyards = 0", "0 elif nextYards == 15: penaltyyards = -15 play.yds.yards = 0 if nextYards", "15: penaltyyards = -15 play.yds.yards = 0 if nextYards == penaltyyards: if play.yds.yards", "-*- coding: utf-8 -*- \"\"\" Created on Mon Apr 22 18:29:44 2019 @author:", "15: penaltyyards = 15 play.yds.yards = 0 elif nextYards == 15: penaltyyards =", "if play.yds.yards == 0: play.yds.yards = nextYards play.penalty.yards = penaltyyards if nextYards ==", "nextYards == play.yds.yards and nextYards == penaltyyards: continue self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name,", "if isinstance(play, noplay): if play.yds.yards == 0 and penaltyyards is not None: play.yds.yards", "play = drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards = play.penalty.yards playyards =", "nextYards = drivePlay.nextDiffYards if all([penaltyyards, playyards, nextYards]): if penaltyyards + playyards == nextYards:", "sum([x in play.text for x in [\"Personal Foul\", \"Unsportsmanlike Conduct\", \"Face Mask\"]]) >", "# -*- coding: utf-8 -*- \"\"\" Created on Mon Apr 22 18:29:44 2019", "continue elif penaltyyards == playyards and penaltyyards == nextYards: play.yds.yards = 0 continue", "\" self.sep = \"======================================================\" self.dc = debugclass() self.py = playyards() def isPenaltyAdditive(self, gameData):", "nextYards: play.yds.yards = 0 continue else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards,", "__init__(self): self.logger = logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind = 2*\" \" self.sep = \"======================================================\" self.dc", "all([penaltyyards, playyards, nextYards]): if penaltyyards + playyards == nextYards: continue elif penaltyyards ==", "2*\" \" self.sep = \"======================================================\" self.dc = debugclass() self.py = playyards() def isPenaltyAdditive(self,", "Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext", "self.__class__)) self.ind = 2*\" \" self.sep = \"======================================================\" self.dc = debugclass() self.py =", "== 0: play.yds.yards = nextYards play.penalty.yards = penaltyyards if nextYards == play.yds.yards and", "Penalty Additiveness\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay in enumerate(drivePlays):", "= penaltyyards if nextYards == play.yds.yards and nextYards == penaltyyards: continue self.logger.debug(\"{0}Penalty Analysis:", "penaltyyards if nextYards == play.yds.yards and nextYards == penaltyyards: continue self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind,", "self.ind = 2*\" \" self.sep = \"======================================================\" self.dc = debugclass() self.py = playyards()", "= play.yds.yards nextYards = drivePlay.nextDiffYards if all([penaltyyards, playyards, nextYards]): if penaltyyards + playyards", "in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay in enumerate(drivePlays): play = drivePlay.play if", "Mask\"]]) > 0: if nextYards == 15: penaltyyards = 15 play.yds.yards = 0", "False: continue penaltyyards = play.penalty.yards playyards = play.yds.yards nextYards = drivePlay.nextDiffYards if all([penaltyyards,", "import noplay from playYards import playyards #from copy import deepcopy, copy # create", "= \"======================================================\" self.dc = debugclass() self.py = playyards() def isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing", "# create logger import logging module_logger = logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ## Drive Class ############################################################################################################", "is False: continue penaltyyards = self.py.findPenaltyYards(play.text) nextYards = drivePlay.nextDiffYards if isinstance(play, noplay): if", "from debug import debugclass from playTypes import noplay from playYards import playyards #from", "= nextYards play.penalty.yards = penaltyyards if nextYards == play.yds.yards and nextYards == penaltyyards:", "self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name, nextYards, play.yds.yards, penaltyyards, play.text)) self.logger.debug(\"{0}Analyzing Penalties -> Done\".format(self.ind))", "0: play.yds.yards = nextYards play.penalty.yards = penaltyyards if nextYards == play.yds.yards and nextYards", "gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for", "is not None: play.yds.yards = penaltyyards elif play.yds.yards == 0 and penaltyyards is", "0: if nextYards == 15: penaltyyards = 15 play.yds.yards = 0 elif nextYards", "for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay in enumerate(drivePlays): play =", "playyards, nextYards]): if penaltyyards + playyards == nextYards: continue elif penaltyyards == playyards", "Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) self.logger.debug(\"{0}Analyzing Penalty Additiveness -> Done\".format(self.ind)) def penalties(self, gameData):", "and nextYards == penaltyyards: continue self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name, nextYards, play.yds.yards, penaltyyards,", "Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) self.logger.debug(\"{0}Analyzing Penalty Additiveness -> Done\".format(self.ind))", "penaltyyards == playyards and penaltyyards == nextYards: play.yds.yards = 0 continue else: self.logger.debug(\"{0}Penalty", "Conduct\", \"Face Mask\"]]) > 0: if nextYards == 15: penaltyyards = 15 play.yds.yards", "= 2*\" \" self.sep = \"======================================================\" self.dc = debugclass() self.py = playyards() def", "= 0 continue else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards,", "\"\"\" Created on Mon Apr 22 18:29:44 2019 @author: tgadfort \"\"\" from debug", "nextYards play.penalty.yards = penaltyyards if nextYards == play.yds.yards and nextYards == penaltyyards: continue", "self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay", "if nextYards == 0 and play.yds.yards == 0: penaltyyards = 0 if sum([x", "self.py = playyards() def isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind)) for idr,driveData in", "Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) else: self.logger.debug(\"{0}Penalty Analysis: Penalty", "nextYards == 0 and play.yds.yards == 0: penaltyyards = 0 if sum([x in", "nextYards == penaltyyards: if play.yds.yards == 0: play.yds.yards = nextYards play.penalty.yards = penaltyyards", "elif penaltyyards == playyards and penaltyyards == nextYards: play.yds.yards = 0 continue else:", "penaltyyards is None: play.yds.yards = nextYards else: if play.yds.yards is None: play.yds.yards =", "\"======================================================\" self.dc = debugclass() self.py = playyards() def isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty", "Additiveness -> Done\".format(self.ind)) def penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for idr,driveData in enumerate(gameData):", "play.yds.yards == 0: penaltyyards = 0 if sum([x in play.text for x in", "penaltyyards = -15 play.yds.yards = 0 if nextYards == penaltyyards: if play.yds.yards ==", "play.yds.yards is None: play.yds.yards = nextYards else: print(\"Not sure...\") if nextYards == 0", "if nextYards == penaltyyards: if play.yds.yards == 0: play.yds.yards = nextYards play.penalty.yards =", "== penaltyyards: if play.yds.yards == 0: play.yds.yards = nextYards play.penalty.yards = penaltyyards if", "penaltyyards = 0 if sum([x in play.text for x in [\"Personal Foul\", \"Unsportsmanlike", "nextYards: continue elif penaltyyards == playyards and penaltyyards == nextYards: play.yds.yards = 0", "= penaltyyards elif play.yds.yards == 0 and penaltyyards is None: play.yds.yards = nextYards", "in enumerate(drivePlays): play = drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards = play.penalty.yards", "== nextYards: continue elif penaltyyards == playyards and penaltyyards == nextYards: play.yds.yards =", "is None: play.yds.yards = nextYards else: print(\"Not sure...\") if nextYards == 0 and", "analyzepenalties: def __init__(self): self.logger = logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind = 2*\" \" self.sep =", "0: penaltyyards = 0 if sum([x in play.text for x in [\"Personal Foul\",", "-*- \"\"\" Created on Mon Apr 22 18:29:44 2019 @author: tgadfort \"\"\" from", "if penaltyyards + playyards == nextYards: continue elif penaltyyards == playyards and penaltyyards", "@author: tgadfort \"\"\" from debug import debugclass from playTypes import noplay from playYards", "elif play.yds.yards == 0 and penaltyyards is None: play.yds.yards = nextYards else: if", "for x in [\"Personal Foul\", \"Unsportsmanlike Conduct\", \"Face Mask\"]]) > 0: if nextYards", "penaltyyards: if play.yds.yards == 0: play.yds.yards = nextYards play.penalty.yards = penaltyyards if nextYards", "penaltyyards: continue self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name, nextYards, play.yds.yards, penaltyyards, play.text)) self.logger.debug(\"{0}Analyzing Penalties", "python3 # -*- coding: utf-8 -*- \"\"\" Created on Mon Apr 22 18:29:44", "play.yds.yards = 0 if nextYards == penaltyyards: if play.yds.yards == 0: play.yds.yards =", "module_logger = logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ## Drive Class ############################################################################################################ class analyzepenalties: def __init__(self): self.logger", "= playyards() def isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind)) for idr,driveData in enumerate(gameData):", "== 0 and penaltyyards is None: play.yds.yards = nextYards else: if play.yds.yards is", "play.penalty.isPenalty is False: continue penaltyyards = self.py.findPenaltyYards(play.text) nextYards = drivePlay.nextDiffYards if isinstance(play, noplay):", "= drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards = play.penalty.yards playyards = play.yds.yards", "import deepcopy, copy # create logger import logging module_logger = logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ##", "penaltyyards is not None: play.yds.yards = penaltyyards elif play.yds.yards == 0 and penaltyyards", "self.py.findPenaltyYards(play.text) nextYards = drivePlay.nextDiffYards if isinstance(play, noplay): if play.yds.yards == 0 and penaltyyards", "== 0 and play.yds.yards == 0: penaltyyards = 0 if sum([x in play.text", "= self.py.findPenaltyYards(play.text) nextYards = drivePlay.nextDiffYards if isinstance(play, noplay): if play.yds.yards == 0 and", "penaltyyards = 15 play.yds.yards = 0 elif nextYards == 15: penaltyyards = -15", "Drive Class ############################################################################################################ class analyzepenalties: def __init__(self): self.logger = logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind =", "penaltyyards, playyards, nextYards, play.text)) else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards,", "play.text)) else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) self.logger.debug(\"{0}Analyzing", "= drivePlay.nextDiffYards if isinstance(play, noplay): if play.yds.yards == 0 and penaltyyards is not", "if nextYards == play.yds.yards and nextYards == penaltyyards: continue self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty,", "= drivePlay.nextDiffYards if all([penaltyyards, playyards, nextYards]): if penaltyyards + playyards == nextYards: continue", "is False: continue penaltyyards = play.penalty.yards playyards = play.yds.yards nextYards = drivePlay.nextDiffYards if", "else: if play.yds.yards is None: play.yds.yards = nextYards else: print(\"Not sure...\") if nextYards", "else: print(\"Not sure...\") if nextYards == 0 and play.yds.yards == 0: penaltyyards =", "continue self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name, nextYards, play.yds.yards, penaltyyards, play.text)) self.logger.debug(\"{0}Analyzing Penalties ->", "play.penalty.yards = penaltyyards if nextYards == play.yds.yards and nextYards == penaltyyards: continue self.logger.debug(\"{0}Penalty", "play.yds.yards = nextYards else: print(\"Not sure...\") if nextYards == 0 and play.yds.yards ==", "if play.penalty.isPenalty is False: continue penaltyyards = self.py.findPenaltyYards(play.text) nextYards = drivePlay.nextDiffYards if isinstance(play,", "penaltyyards + playyards == nextYards: continue elif penaltyyards == playyards and penaltyyards ==", "Mon Apr 22 18:29:44 2019 @author: tgadfort \"\"\" from debug import debugclass from", "= logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ## Drive Class ############################################################################################################ class analyzepenalties: def __init__(self): self.logger =", "on Mon Apr 22 18:29:44 2019 @author: tgadfort \"\"\" from debug import debugclass", "drivePlay.nextDiffYards if all([penaltyyards, playyards, nextYards]): if penaltyyards + playyards == nextYards: continue elif", "0 continue else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text))", "playYards import playyards #from copy import deepcopy, copy # create logger import logging", "Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name, nextYards, play.yds.yards, penaltyyards, play.text)) self.logger.debug(\"{0}Analyzing Penalties -> Done\".format(self.ind)) return", "gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay", "if play.yds.yards is None: play.yds.yards = nextYards else: print(\"Not sure...\") if nextYards ==", "tgadfort \"\"\" from debug import debugclass from playTypes import noplay from playYards import", "drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards = self.py.findPenaltyYards(play.text) nextYards = drivePlay.nextDiffYards if", "\"\"\" from debug import debugclass from playTypes import noplay from playYards import playyards", "= play.penalty.yards playyards = play.yds.yards nextYards = drivePlay.nextDiffYards if all([penaltyyards, playyards, nextYards]): if", "if nextYards == 15: penaltyyards = 15 play.yds.yards = 0 elif nextYards ==", "nextYards, play.text)) else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text))", "Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) self.logger.debug(\"{0}Analyzing Penalty Additiveness ->", "self.sep = \"======================================================\" self.dc = debugclass() self.py = playyards() def isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep))", "Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) self.logger.debug(\"{0}Analyzing Penalty Additiveness -> Done\".format(self.ind)) def penalties(self,", "play.yds.yards = nextYards play.penalty.yards = penaltyyards if nextYards == play.yds.yards and nextYards ==", "logger import logging module_logger = logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ## Drive Class ############################################################################################################ class analyzepenalties:", "class analyzepenalties: def __init__(self): self.logger = logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind = 2*\" \" self.sep", "play.text)) self.logger.debug(\"{0}Analyzing Penalty Additiveness -> Done\".format(self.ind)) def penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for", "Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name, nextYards, play.yds.yards, penaltyyards, play.text)) self.logger.debug(\"{0}Analyzing Penalties -> Done\".format(self.ind)) return gameData", "15 play.yds.yards = 0 elif nextYards == 15: penaltyyards = -15 play.yds.yards =", "and penaltyyards is None: play.yds.yards = nextYards else: if play.yds.yards is None: play.yds.yards", "debugclass from playTypes import noplay from playYards import playyards #from copy import deepcopy,", "continue penaltyyards = self.py.findPenaltyYards(play.text) nextYards = drivePlay.nextDiffYards if isinstance(play, noplay): if play.yds.yards ==", "self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) else: self.logger.debug(\"{0}Penalty Analysis:", "playTypes import noplay from playYards import playyards #from copy import deepcopy, copy #", "drivePlays = driveData.plays for ipl,drivePlay in enumerate(drivePlays): play = drivePlay.play if play.penalty.isPenalty is", "nextYards == 15: penaltyyards = 15 play.yds.yards = 0 elif nextYards == 15:", "nextYards == 15: penaltyyards = -15 play.yds.yards = 0 if nextYards == penaltyyards:", "drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards = play.penalty.yards playyards = play.yds.yards nextYards", "playyards = play.yds.yards nextYards = drivePlay.nextDiffYards if all([penaltyyards, playyards, nextYards]): if penaltyyards +", "play.yds.yards nextYards = drivePlay.nextDiffYards if all([penaltyyards, playyards, nextYards]): if penaltyyards + playyards ==", "nextYards, play.text)) self.logger.debug(\"{0}Analyzing Penalty Additiveness -> Done\".format(self.ind)) def penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind))", "for ipl,drivePlay in enumerate(drivePlays): play = drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards", "penaltyyards = play.penalty.yards playyards = play.yds.yards nextYards = drivePlay.nextDiffYards if all([penaltyyards, playyards, nextYards]):", "Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind,", "in [\"Personal Foul\", \"Unsportsmanlike Conduct\", \"Face Mask\"]]) > 0: if nextYards == 15:", "[\"Personal Foul\", \"Unsportsmanlike Conduct\", \"Face Mask\"]]) > 0: if nextYards == 15: penaltyyards", "2019 @author: tgadfort \"\"\" from debug import debugclass from playTypes import noplay from", "penaltyyards, playyards, nextYards, play.text)) self.logger.debug(\"{0}Analyzing Penalty Additiveness -> Done\".format(self.ind)) def penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep))", "in enumerate(drivePlays): play = drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards = self.py.findPenaltyYards(play.text)", "= 0 if nextYards == penaltyyards: if play.yds.yards == 0: play.yds.yards = nextYards", "nextYards == penaltyyards: continue self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name, nextYards, play.yds.yards, penaltyyards, play.text))", "## Drive Class ############################################################################################################ class analyzepenalties: def __init__(self): self.logger = logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind", "playyards, nextYards, play.text)) else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards,", "play.penalty.isPenalty is False: continue penaltyyards = play.penalty.yards playyards = play.yds.yards nextYards = drivePlay.nextDiffYards", "in play.text for x in [\"Personal Foul\", \"Unsportsmanlike Conduct\", \"Face Mask\"]]) > 0:", "if play.yds.yards == 0 and penaltyyards is not None: play.yds.yards = penaltyyards elif", "drivePlay.nextDiffYards if isinstance(play, noplay): if play.yds.yards == 0 and penaltyyards is not None:", "def __init__(self): self.logger = logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind = 2*\" \" self.sep = \"======================================================\"", "\"Face Mask\"]]) > 0: if nextYards == 15: penaltyyards = 15 play.yds.yards =", "18:29:44 2019 @author: tgadfort \"\"\" from debug import debugclass from playTypes import noplay", "== playyards and penaltyyards == nextYards: play.yds.yards = 0 continue else: self.logger.debug(\"{0}Penalty Analysis:", "if sum([x in play.text for x in [\"Personal Foul\", \"Unsportsmanlike Conduct\", \"Face Mask\"]])", "isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays", "nextYards]): if penaltyyards + playyards == nextYards: continue elif penaltyyards == playyards and", "import debugclass from playTypes import noplay from playYards import playyards #from copy import", "noplay): if play.yds.yards == 0 and penaltyyards is not None: play.yds.yards = penaltyyards", "Penalties\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay in enumerate(drivePlays): play", "== 15: penaltyyards = 15 play.yds.yards = 0 elif nextYards == 15: penaltyyards", "import logging module_logger = logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ## Drive Class ############################################################################################################ class analyzepenalties: def", "= driveData.plays for ipl,drivePlay in enumerate(drivePlays): play = drivePlay.play if play.penalty.isPenalty is False:", "== nextYards: play.yds.yards = 0 continue else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind,", "nextYards else: if play.yds.yards is None: play.yds.yards = nextYards else: print(\"Not sure...\") if", "play.yds.yards = 0 elif nextYards == 15: penaltyyards = -15 play.yds.yards = 0", "Apr 22 18:29:44 2019 @author: tgadfort \"\"\" from debug import debugclass from playTypes", "debug import debugclass from playTypes import noplay from playYards import playyards #from copy", "coding: utf-8 -*- \"\"\" Created on Mon Apr 22 18:29:44 2019 @author: tgadfort", "playyards and penaltyyards == nextYards: play.yds.yards = 0 continue else: self.logger.debug(\"{0}Penalty Analysis: Penalty", "None: play.yds.yards = penaltyyards elif play.yds.yards == 0 and penaltyyards is None: play.yds.yards", "penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for", "= -15 play.yds.yards = 0 if nextYards == penaltyyards: if play.yds.yards == 0:", "ipl,drivePlay in enumerate(drivePlays): play = drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards =", "play.yds.yards == 0 and penaltyyards is not None: play.yds.yards = penaltyyards elif play.yds.yards", "play.yds.yards == 0: play.yds.yards = nextYards play.penalty.yards = penaltyyards if nextYards == play.yds.yards", "if play.penalty.isPenalty is False: continue penaltyyards = play.penalty.yards playyards = play.yds.yards nextYards =", "elif nextYards == 15: penaltyyards = -15 play.yds.yards = 0 if nextYards ==", "enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay in enumerate(drivePlays): play = drivePlay.play if play.penalty.isPenalty", "copy import deepcopy, copy # create logger import logging module_logger = logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################", "logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ## Drive Class ############################################################################################################ class analyzepenalties: def __init__(self): self.logger = logging.getLogger('log.{0}.{1}'.format(__name__,", "#from copy import deepcopy, copy # create logger import logging module_logger = logging.getLogger('log.{0}'.format(__name__))", "from playYards import playyards #from copy import deepcopy, copy # create logger import", "noplay from playYards import playyards #from copy import deepcopy, copy # create logger", "if all([penaltyyards, playyards, nextYards]): if penaltyyards + playyards == nextYards: continue elif penaltyyards", "= 0 if sum([x in play.text for x in [\"Personal Foul\", \"Unsportsmanlike Conduct\",", "22 18:29:44 2019 @author: tgadfort \"\"\" from debug import debugclass from playTypes import", "play.yds.yards = penaltyyards elif play.yds.yards == 0 and penaltyyards is None: play.yds.yards =", "continue penaltyyards = play.penalty.yards playyards = play.yds.yards nextYards = drivePlay.nextDiffYards if all([penaltyyards, playyards,", "= 15 play.yds.yards = 0 elif nextYards == 15: penaltyyards = -15 play.yds.yards", "self.logger = logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__)) self.ind = 2*\" \" self.sep = \"======================================================\" self.dc =", "play.yds.yards = 0 continue else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards,", "playyards, nextYards, play.text)) self.logger.debug(\"{0}Analyzing Penalty Additiveness -> Done\".format(self.ind)) def penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing", "play = drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards = self.py.findPenaltyYards(play.text) nextYards =", "idr,driveData in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay in enumerate(drivePlays): play = drivePlay.play", "playyards == nextYards: continue elif penaltyyards == playyards and penaltyyards == nextYards: play.yds.yards", "self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) self.logger.debug(\"{0}Analyzing Penalty Additiveness", "Penalty Additiveness -> Done\".format(self.ind)) def penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for idr,driveData in", "self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay in", "= debugclass() self.py = playyards() def isPenaltyAdditive(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalty Additiveness\".format(self.ind)) for", "continue else: self.logger.debug(\"{0}Penalty Analysis: Penalty Yards=={1}\\tPlay Yards=={2}\\tNext Yards=={3}\\tText=={4}\".format(self.ind, penaltyyards, playyards, nextYards, play.text)) else:", "0 and play.yds.yards == 0: penaltyyards = 0 if sum([x in play.text for", "+ playyards == nextYards: continue elif penaltyyards == playyards and penaltyyards == nextYards:", "nextYards else: print(\"Not sure...\") if nextYards == 0 and play.yds.yards == 0: penaltyyards", "0 and penaltyyards is None: play.yds.yards = nextYards else: if play.yds.yards is None:", "and play.yds.yards == 0: penaltyyards = 0 if sum([x in play.text for x", "== 0: penaltyyards = 0 if sum([x in play.text for x in [\"Personal", "= 0 elif nextYards == 15: penaltyyards = -15 play.yds.yards = 0 if", "\"Unsportsmanlike Conduct\", \"Face Mask\"]]) > 0: if nextYards == 15: penaltyyards = 15", "play.text for x in [\"Personal Foul\", \"Unsportsmanlike Conduct\", \"Face Mask\"]]) > 0: if", "create logger import logging module_logger = logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ## Drive Class ############################################################################################################ class", "copy # create logger import logging module_logger = logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ## Drive Class", "penaltyyards = self.py.findPenaltyYards(play.text) nextYards = drivePlay.nextDiffYards if isinstance(play, noplay): if play.yds.yards == 0", "self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay in enumerate(drivePlays):", "not None: play.yds.yards = penaltyyards elif play.yds.yards == 0 and penaltyyards is None:", "self.logger.debug(\"{0}Analyzing Penalty Additiveness -> Done\".format(self.ind)) def penalties(self, gameData): self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for idr,driveData", "play.yds.yards == 0 and penaltyyards is None: play.yds.yards = nextYards else: if play.yds.yards", "enumerate(drivePlays): play = drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards = self.py.findPenaltyYards(play.text) nextYards", "logging module_logger = logging.getLogger('log.{0}'.format(__name__)) ############################################################################################################ ## Drive Class ############################################################################################################ class analyzepenalties: def __init__(self):", "############################################################################################################ ## Drive Class ############################################################################################################ class analyzepenalties: def __init__(self): self.logger = logging.getLogger('log.{0}.{1}'.format(__name__, self.__class__))", "self.logger.debug(\"\\n{0}\".format(2*self.sep)) self.logger.debug(\"{0}Analyzing Penalties\".format(self.ind)) for idr,driveData in enumerate(gameData): drivePlays = driveData.plays for ipl,drivePlay in", "= drivePlay.play if play.penalty.isPenalty is False: continue penaltyyards = self.py.findPenaltyYards(play.text) nextYards = drivePlay.nextDiffYards", "play.penalty.yards playyards = play.yds.yards nextYards = drivePlay.nextDiffYards if all([penaltyyards, playyards, nextYards]): if penaltyyards", "== play.yds.yards and nextYards == penaltyyards: continue self.logger.debug(\"{0}Penalty Analysis: Penalty=={1}\\tPlay=={2}\\tNext=={3}\\tYards=={4}\\tPYards=={5}\\tText=={6}\".format(self.ind, play.penalty.isPenalty, play.name, nextYards,", "x in [\"Personal Foul\", \"Unsportsmanlike Conduct\", \"Face Mask\"]]) > 0: if nextYards ==", "None: play.yds.yards = nextYards else: print(\"Not sure...\") if nextYards == 0 and play.yds.yards" ]
[ "skill.cast(target) # Billing for fighter in fighters: # Start billing by order for", "f.died_turn), reverse=True) for index, fighter in enumerate(score_board): if fighter.is_alive(): status = '存活({hp}HP)'.format(hp=fighter.HP) else:", "= Fighter('k', is_npc=True) allFighters = [zcx, iii, j, k] battle(allFighters) # player1.report_wealth() #", "{mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP, f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2) # Deaths for fighter in fighters_this_turn: if", "fighters: fighter.init_turn() if fighter.is_alive(): fighters_this_turn.append(fighter) # toimpr magical nb, in right place ?", "nb to global setting prj.caster.killed_someone() # Output turn info # Moves for fighter", "'存活({hp}HP)'.format(hp=fighter.HP) else: killers = [] for pj in fighter.lethal_projectiles: killer = '{owner}的{skill}'. \\", "zcx = Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1) iii = Fighter('i', is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2) j =", "1 enemy if len(target_list) == 1: target = target_list[0] else: while True: for", "c_money = 1 # c_exp = 1 # loot_item_dict = enemy.loot['item_dict'] # elif", "prj.caster.killed_someone() # Output turn info # Moves for fighter in fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}'", "j = Fighter('j', is_npc=True) k = Fighter('k', is_npc=True) allFighters = [zcx, iii, j,", "prjs = fighter.incoming_projectiles[category][tag] if prjs: for prj in prjs: prj.billing() # All billed", "for fighter in fighters_this_turn: if not fighter.is_alive(): print('{f} 卒'.format(f=fighter.name)) turn += 1 continue", "# c_exp = 0.5 # loot_item_dict = {} # elif battle_result == 'LOSE':", "# Start billing by order for category in ['potion', 'arrow']: for tag in", "= [] for pj in fighter.lethal_projectiles: killer = '{owner}的{skill}'. \\ format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer)", "= '{owner}的{skill}'. \\ format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer) killers_msg = '&'.join(killers) status = '卒(Turn{t}, {hp}HP,", "target_name = input_args[1] if len(input_args) > 1 else '' if key in player.get_available_skills():", "Fighter('j', is_npc=True) k = Fighter('k', is_npc=True) allFighters = [zcx, iii, j, k] battle(allFighters)", "killers.append(killer) killers_msg = '&'.join(killers) status = '卒(Turn{t}, {hp}HP, 被{killer}所杀)' \\ .format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg)", "# loot_item_dict = enemy.loot['item_dict'] # elif battle_result == 'TIE': # c_money = 0", "proj skill.cast(target) # Billing for fighter in fighters: # Start billing by order", "Moves for fighter in fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP, f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2) #", "= set alive false, record turn, leave death message fighter.go_die(turn) fighters_remain -= 1", "== 'A': target = random.choice(target_list) # Player input skill else: player = fighter", "c_exp = 0.5 # loot_item_dict = {} # elif battle_result == 'LOSE': #", "# loot_item_dict = {} # elif battle_result == 'LOSE': # c_money = 0", "paras fighters_this_turn = [] for fighter in fighters: fighter.init_turn() if fighter.is_alive(): fighters_this_turn.append(fighter) #", "= '&'.join(killers) status = '卒(Turn{t}, {hp}HP, 被{killer}所杀)' \\ .format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name,", "print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP, f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2) # Deaths for fighter in fighters_this_turn:", "Turn #turn # Init turn # Construct fighters participate in this turn #", "sorted(fighters, key=lambda f: (f.score, f.died_turn), reverse=True) for index, fighter in enumerate(score_board): if fighter.is_alive():", "1: # fighter.gain_score(1) # Choose skill for fighter in fighters_this_turn: # NPC choose", "target if skill.phase_type == 'A': target = random.choice(target_list) # Player input skill else:", "= random.choice(target_list) # Player input skill else: player = fighter target_list = list(set(fighters_this_turn)", "# Exit battle_process # Battle result score_board = sorted(fighters, key=lambda f: (f.score, f.died_turn),", "[glove1, glove2] zcx = Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1) iii = Fighter('i', is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2)", "Deaths for fighter in fighters_this_turn: if not fighter.is_alive(): print('{f} 卒'.format(f=fighter.name)) turn += 1", "fighters_this_turn = [] for fighter in fighters: fighter.init_turn() if fighter.is_alive(): fighters_this_turn.append(fighter) # toimpr", "1 # killer gain score for killing for prj in fighter.lethal_projectiles: # toImpr", ">= 2: # Enter Turn #turn print('\\n#{t}'.format(t=turn)) # Begin Turn #turn # Init", "fighters: # Start billing by order for category in ['potion', 'arrow']: for tag", "= 1 # Init turns # fighters_this_turn = list(fighters) fighters_remain = len(fighters) while", "int turns for 1 battle, default 10 :param fighters: list of fighter :return:", "'LOSE': # c_money = 0 # c_exp = 0 # loot_item_dict = {}", "len(target_list) == 1: target = target_list[0] else: while True: for target_fighter in target_list:", "fighters participate in this turn # & Init fighter turn paras fighters_this_turn =", "billed # Check new death if fighter.is_alive() and fighter.HP <= 0: # fighter", "fighters_remain -= 1 # killer gain score for killing for prj in fighter.lethal_projectiles:", "Turns begin turn = 1 # Init turns # fighters_this_turn = list(fighters) fighters_remain", "an A skill, choose its target if skill.phase_type == 'A': target = random.choice(target_list)", "1: target = target_list[0] else: while True: for target_fighter in target_list: if target_fighter.name", "prjs: for prj in prjs: prj.billing() # All billed # Check new death", "fighters: list of fighter :return: None \"\"\" # Enter battle_process print('Enter battle_process') #", "target = random.choice(target_list) # Player input skill else: player = fighter target_list =", ":param max_turn: int turns for 1 battle, default 10 :param fighters: list of", "fighters: fighter.init_battle() fighter.report_status() # Turns begin turn = 1 # Init turns #", "death message fighter.go_die(turn) fighters_remain -= 1 # killer gain score for killing for", "false, record turn, leave death message fighter.go_die(turn) fighters_remain -= 1 # killer gain", "1 # Init turns # fighters_this_turn = list(fighters) fighters_remain = len(fighters) while turn", "Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1) iii = Fighter('i', is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2) j = Fighter('j', is_npc=True)", "enemy, battle_result) # toAdd loot system # def distribute_loot(player, enemy, battle_result): # \"\"\"", "this turn # & Init fighter turn paras fighters_this_turn = [] for fighter", "Fighter('i', is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2) j = Fighter('j', is_npc=True) k = Fighter('k', is_npc=True) allFighters", "# c_money = 0 # c_exp = 0 # loot_item_dict = {} #", ":param enemy: obj # :param battle_result: string 'WIN'/'LOSE'/'TIE' # :return: None # \"\"\"", "fighter.lethal_projectiles: # toImpr move magical nb to global setting prj.caster.killed_someone() # Output turn", ".format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score, status=status)) # distribute_loot(player, enemy, battle_result) # toAdd", "Check new death if fighter.is_alive() and fighter.HP <= 0: # fighter will die", "in player.get_available_skills(): break skill = player.BATTLESKILLBOOK[key] # If it's an A skill, choose", "while True: for target_fighter in target_list: if target_fighter.name == target_name: target = target_fighter", "if __name__ == \"__main__\": glove1 = create_item('A2') glove2 = create_item('A2') # toAdd item", "'卒(Turn{t}, {hp}HP, 被{killer}所杀)' \\ .format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score, status=status)) # distribute_loot(player,", "# Cast skill = record move, create proj, deliver proj skill.cast(target) # Billing", "player.BATTLESKILLBOOK[key] # If it's an A skill, choose its target if skill.phase_type ==", "Choose skill for fighter in fighters_this_turn: # NPC choose skill if fighter.is_npc: npc", "player.get_available_skills(): break skill = player.BATTLESKILLBOOK[key] # If it's an A skill, choose its", "input skill else: player = fighter target_list = list(set(fighters_this_turn) - {player}) target =", "print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score, status=status)) # distribute_loot(player, enemy, battle_result) # toAdd loot system #", "- {npc}) key = random.choice(npc.get_available_skills()) skill = npc.BATTLESKILLBOOK[key] # If it's an A", ":param fighters: list of fighter :return: None \"\"\" # Enter battle_process print('Enter battle_process')", "break target_name = input('target...') # Cast skill = record move, create proj, deliver", "battle result # :param player: obj # :param enemy: obj # :param battle_result:", "# & Init fighter turn paras fighters_this_turn = [] for fighter in fighters:", "target = target_fighter if target: break target_name = input('target...') # Cast skill =", "'heal', 'damage']: prjs = fighter.incoming_projectiles[category][tag] if prjs: for prj in prjs: prj.billing() #", "in fighters: # Start billing by order for category in ['potion', 'arrow']: for", "loot system # def distribute_loot(player, enemy, battle_result): # \"\"\" # Distribute enemy loot", "fighter in fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP, f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2) # Deaths for", "? # if turn != 1: # fighter.gain_score(1) # Choose skill for fighter", "in fighters_this_turn: # NPC choose skill if fighter.is_npc: npc = fighter target =", "in target_list: if target_fighter.name == target_name: target = target_fighter if target: break target_name", "zcx.equip_item(glove1) iii = Fighter('i', is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2) j = Fighter('j', is_npc=True) k =", "break skill = player.BATTLESKILLBOOK[key] # If it's an A skill, choose its target", "== 'A': # Auto choose target when only 1 enemy if len(target_list) ==", "enemy: obj # :param battle_result: string 'WIN'/'LOSE'/'TIE' # :return: None # \"\"\" #", "= [] for fighter in fighters: fighter.init_turn() if fighter.is_alive(): fighters_this_turn.append(fighter) # toimpr magical", "global setting prj.caster.killed_someone() # Output turn info # Moves for fighter in fighters:", "and fighters_remain >= 2: # Enter Turn #turn print('\\n#{t}'.format(t=turn)) # Begin Turn #turn", "> 1 else '' if key in player.get_available_skills(): break skill = player.BATTLESKILLBOOK[key] #", "skill.phase_type == 'A': target = random.choice(target_list) # Player input skill else: player =", "= create_item('A2') # toAdd item database # game_items = [glove1, glove2] zcx =", "alive false, record turn, leave death message fighter.go_die(turn) fighters_remain -= 1 # killer", "+= 1 continue # Exit turns print('\\nExit turns') # Exit battle_process # Battle", "Init fighter turn paras fighters_this_turn = [] for fighter in fighters: fighter.init_turn() if", "enemy if len(target_list) == 1: target = target_list[0] else: while True: for target_fighter", "None \"\"\" # Enter battle_process print('Enter battle_process') # Begin battle_process # Init skills", "fighter.report_status() # Turns begin turn = 1 # Init turns # fighters_this_turn =", "= len(fighters) while turn <= max_turn and fighters_remain >= 2: # Enter Turn", "target_fighter.name == target_name: target = target_fighter if target: break target_name = input('target...') #", "billing by order for category in ['potion', 'arrow']: for tag in ['fill', 'drain',", "for fighter in fighters: fighter.init_turn() if fighter.is_alive(): fighters_this_turn.append(fighter) # toimpr magical nb, in", "input_args[1] if len(input_args) > 1 else '' if key in player.get_available_skills(): break skill", "turn # Construct fighters participate in this turn # & Init fighter turn", "= record move, create proj, deliver proj skill.cast(target) # Billing for fighter in", "elif battle_result == 'TIE': # c_money = 0 # c_exp = 0.5 #", "tag in ['fill', 'drain', 'heal', 'damage']: prjs = fighter.incoming_projectiles[category][tag] if prjs: for prj", "time from Character import * from Item import create_item def battle(fighters, max_turn=10): \"\"\"", "# toAdd item database # game_items = [glove1, glove2] zcx = Fighter('zcx') zcx.put_in_item(glove1)", ":param battle_result: string 'WIN'/'LOSE'/'TIE' # :return: None # \"\"\" # if battle_result ==", "if skill.phase_type == 'A': target = random.choice(target_list) # Player input skill else: player", "= Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1) iii = Fighter('i', is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2) j = Fighter('j',", "and fighter.HP <= 0: # fighter will die # fighter did die #", "= list(fighters) fighters_remain = len(fighters) while turn <= max_turn and fighters_remain >= 2:", "fighters_remain = len(fighters) while turn <= max_turn and fighters_remain >= 2: # Enter", "list(set(fighters_this_turn) - {player}) target = '' # dummy? target_name = '' # dummy?", "= input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args = input_raw.strip().split() key = input_args[0].upper() target_name = input_args[1] if", "fighter.is_npc: npc = fighter target = '' target_list = list(set(fighters_this_turn) - {npc}) key", "Player input skill else: player = fighter target_list = list(set(fighters_this_turn) - {player}) target", "target_name = '' # dummy? key = '' # dummy? while True: input_raw", "target_list: if target_fighter.name == target_name: target = target_fighter if target: break target_name =", "from Character import * from Item import create_item def battle(fighters, max_turn=10): \"\"\" Battle", "# dummy? key = '' # dummy? while True: input_raw = input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills())))", "1 continue # Exit turns print('\\nExit turns') # Exit battle_process # Battle result", "magical nb to global setting prj.caster.killed_someone() # Output turn info # Moves for", "toAdd item database # game_items = [glove1, glove2] zcx = Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1)", "fighters_this_turn = list(fighters) fighters_remain = len(fighters) while turn <= max_turn and fighters_remain >=", "# Moves for fighter in fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP, f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2)", "create_item('A2') # toAdd item database # game_items = [glove1, glove2] zcx = Fighter('zcx')", "k = Fighter('k', is_npc=True) allFighters = [zcx, iii, j, k] battle(allFighters) # player1.report_wealth()", "in fighters_this_turn: if not fighter.is_alive(): print('{f} 卒'.format(f=fighter.name)) turn += 1 continue # Exit", "== 1: target = target_list[0] else: while True: for target_fighter in target_list: if", "iii.equip_item(glove2) j = Fighter('j', is_npc=True) k = Fighter('k', is_npc=True) allFighters = [zcx, iii,", "'' if key in player.get_available_skills(): break skill = player.BATTLESKILLBOOK[key] # If it's an", "format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer) killers_msg = '&'.join(killers) status = '卒(Turn{t}, {hp}HP, 被{killer}所杀)' \\ .format(t=fighter.died_turn,", "# Output turn info # Moves for fighter in fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP,", ".format(hp=fighter.HP, mp=fighter.MP, f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2) # Deaths for fighter in fighters_this_turn: if not", "Begin Turn #turn # Init turn # Construct fighters participate in this turn", "Begin battle_process # Init skills (for n) for fighter in fighters: fighter.init_battle() fighter.report_status()", "else: while True: for target_fighter in target_list: if target_fighter.name == target_name: target =", "f: (f.score, f.died_turn), reverse=True) for index, fighter in enumerate(score_board): if fighter.is_alive(): status =", "dummy? while True: input_raw = input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args = input_raw.strip().split() key = input_args[0].upper()", "fighter :return: None \"\"\" # Enter battle_process print('Enter battle_process') # Begin battle_process #", "# player.get_item(loot_item, loot_item_dict[loot_item]) # toImpr separated gameplay if __name__ == \"__main__\": glove1 =", "print('\\nExit turns') # Exit battle_process # Battle result score_board = sorted(fighters, key=lambda f:", "import create_item def battle(fighters, max_turn=10): \"\"\" Battle process start->loot :param max_turn: int turns", "len(fighters) while turn <= max_turn and fighters_remain >= 2: # Enter Turn #turn", "Billing for fighter in fighters: # Start billing by order for category in", "input('target...') # Cast skill = record move, create proj, deliver proj skill.cast(target) #", "prj in fighter.lethal_projectiles: # toImpr move magical nb to global setting prj.caster.killed_someone() #", "{hp}HP, 被{killer}所杀)' \\ .format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score, status=status)) # distribute_loot(player, enemy,", "battle_process # Battle result score_board = sorted(fighters, key=lambda f: (f.score, f.died_turn), reverse=True) for", "for prj in prjs: prj.billing() # All billed # Check new death if", "Exit battle_process # Battle result score_board = sorted(fighters, key=lambda f: (f.score, f.died_turn), reverse=True)", "# c_exp = 1 # loot_item_dict = enemy.loot['item_dict'] # elif battle_result == 'TIE':", "[] for fighter in fighters: fighter.init_turn() if fighter.is_alive(): fighters_this_turn.append(fighter) # toimpr magical nb,", "# Init turn # Construct fighters participate in this turn # & Init", "prj in prjs: prj.billing() # All billed # Check new death if fighter.is_alive()", "if prjs: for prj in prjs: prj.billing() # All billed # Check new", "begin turn = 1 # Init turns # fighters_this_turn = list(fighters) fighters_remain =", "enemy.loot['item_dict'] # elif battle_result == 'TIE': # c_money = 0 # c_exp =", "glove2 = create_item('A2') # toAdd item database # game_items = [glove1, glove2] zcx", "choose its target if skill.phase_type == 'A': target = random.choice(target_list) # Player input", "battle_result == 'LOSE': # c_money = 0 # c_exp = 0 # loot_item_dict", "target = '' # dummy? target_name = '' # dummy? key = ''", "battle_process') # Begin battle_process # Init skills (for n) for fighter in fighters:", "fighter.gain_score(1) # Choose skill for fighter in fighters_this_turn: # NPC choose skill if", "A skill, choose its target if skill.phase_type == 'A': # Auto choose target", "score=fighter.score, status=status)) # distribute_loot(player, enemy, battle_result) # toAdd loot system # def distribute_loot(player,", ":return: None # \"\"\" # if battle_result == 'WIN': # c_money = 1", "= [glove1, glove2] zcx = Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1) iii = Fighter('i', is_npc=True) iii.put_in_item(glove2)", "= '卒(Turn{t}, {hp}HP, 被{killer}所杀)' \\ .format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score, status=status)) #", "A skill, choose its target if skill.phase_type == 'A': target = random.choice(target_list) #", "killer gain score for killing for prj in fighter.lethal_projectiles: # toImpr move magical", "loot_item_dict.keys(): # player.get_item(loot_item, loot_item_dict[loot_item]) # toImpr separated gameplay if __name__ == \"__main__\": glove1", "'arrow']: for tag in ['fill', 'drain', 'heal', 'damage']: prjs = fighter.incoming_projectiles[category][tag] if prjs:", "enemy loot to player according to battle result # :param player: obj #", "info # Moves for fighter in fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP, f=fighter.name, m=str(fighter.last_move)))", "loot_item_dict = {} # # else: # return # # player.add_money(enemy.loot['money'] * c_money)", "# :param battle_result: string 'WIN'/'LOSE'/'TIE' # :return: None # \"\"\" # if battle_result", "iii = Fighter('i', is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2) j = Fighter('j', is_npc=True) k = Fighter('k',", "& Init fighter turn paras fighters_this_turn = [] for fighter in fighters: fighter.init_turn()", "Enter battle_process print('Enter battle_process') # Begin battle_process # Init skills (for n) for", "# dummy? target_name = '' # dummy? key = '' # dummy? while", "# toimpr magical nb, in right place ? # if turn != 1:", "if target_fighter.name == target_name: target = target_fighter if target: break target_name = input('target...')", "\\ .format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score, status=status)) # distribute_loot(player, enemy, battle_result) #", "0.5 # loot_item_dict = {} # elif battle_result == 'LOSE': # c_money =", "= create_item('A2') glove2 = create_item('A2') # toAdd item database # game_items = [glove1,", "c_money) # player.add_exp(enemy.loot['EXP'] * c_exp) # for loot_item in loot_item_dict.keys(): # player.get_item(loot_item, loot_item_dict[loot_item])", "# toImpr separated gameplay if __name__ == \"__main__\": glove1 = create_item('A2') glove2 =", "else: player = fighter target_list = list(set(fighters_this_turn) - {player}) target = '' #", "\"__main__\": glove1 = create_item('A2') glove2 = create_item('A2') # toAdd item database # game_items", "while True: input_raw = input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args = input_raw.strip().split() key = input_args[0].upper() target_name", "<= max_turn and fighters_remain >= 2: # Enter Turn #turn print('\\n#{t}'.format(t=turn)) # Begin", "fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP, f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2) # Deaths for fighter in", "turn, leave death message fighter.go_die(turn) fighters_remain -= 1 # killer gain score for", "turn # & Init fighter turn paras fighters_this_turn = [] for fighter in", "input_args = input_raw.strip().split() key = input_args[0].upper() target_name = input_args[1] if len(input_args) > 1", "only 1 enemy if len(target_list) == 1: target = target_list[0] else: while True:", "= fighter.incoming_projectiles[category][tag] if prjs: for prj in prjs: prj.billing() # All billed #", "c_exp) # for loot_item in loot_item_dict.keys(): # player.get_item(loot_item, loot_item_dict[loot_item]) # toImpr separated gameplay", "skill if fighter.is_npc: npc = fighter target = '' target_list = list(set(fighters_this_turn) -", "for fighter in fighters: # Start billing by order for category in ['potion',", "turn info # Moves for fighter in fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP, f=fighter.name,", "toImpr move magical nb to global setting prj.caster.killed_someone() # Output turn info #", "toImpr separated gameplay if __name__ == \"__main__\": glove1 = create_item('A2') glove2 = create_item('A2')", "# toAdd loot system # def distribute_loot(player, enemy, battle_result): # \"\"\" # Distribute", "is_npc=True) k = Fighter('k', is_npc=True) allFighters = [zcx, iii, j, k] battle(allFighters) #", "by order for category in ['potion', 'arrow']: for tag in ['fill', 'drain', 'heal',", "killers_msg = '&'.join(killers) status = '卒(Turn{t}, {hp}HP, 被{killer}所杀)' \\ .format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1,", "['potion', 'arrow']: for tag in ['fill', 'drain', 'heal', 'damage']: prjs = fighter.incoming_projectiles[category][tag] if", "= 0 # loot_item_dict = {} # # else: # return # #", "= 0 # c_exp = 0 # loot_item_dict = {} # # else:", "# player.add_exp(enemy.loot['EXP'] * c_exp) # for loot_item in loot_item_dict.keys(): # player.get_item(loot_item, loot_item_dict[loot_item]) #", "fighter.is_alive(): status = '存活({hp}HP)'.format(hp=fighter.HP) else: killers = [] for pj in fighter.lethal_projectiles: killer", "target: break target_name = input('target...') # Cast skill = record move, create proj,", "fighters_this_turn.append(fighter) # toimpr magical nb, in right place ? # if turn !=", "key = '' # dummy? while True: input_raw = input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args =", "for fighter in fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP, f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2) # Deaths", "battle_result) # toAdd loot system # def distribute_loot(player, enemy, battle_result): # \"\"\" #", "2: # Enter Turn #turn print('\\n#{t}'.format(t=turn)) # Begin Turn #turn # Init turn", "loot_item_dict = {} # elif battle_result == 'LOSE': # c_money = 0 #", "else: # return # # player.add_money(enemy.loot['money'] * c_money) # player.add_exp(enemy.loot['EXP'] * c_exp) #", "# killer gain score for killing for prj in fighter.lethal_projectiles: # toImpr move", "= 0.5 # loot_item_dict = {} # elif battle_result == 'LOSE': # c_money", "= '存活({hp}HP)'.format(hp=fighter.HP) else: killers = [] for pj in fighter.lethal_projectiles: killer = '{owner}的{skill}'.", "for fighter in fighters: fighter.init_battle() fighter.report_status() # Turns begin turn = 1 #", "1 battle, default 10 :param fighters: list of fighter :return: None \"\"\" #", "skill else: player = fighter target_list = list(set(fighters_this_turn) - {player}) target = ''", "did die # go_die = set alive false, record turn, leave death message", "n) for fighter in fighters: fighter.init_battle() fighter.report_status() # Turns begin turn = 1", "record turn, leave death message fighter.go_die(turn) fighters_remain -= 1 # killer gain score", "status = '卒(Turn{t}, {hp}HP, 被{killer}所杀)' \\ .format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score, status=status))", "fighter.incoming_projectiles[category][tag] if prjs: for prj in prjs: prj.billing() # All billed # Check", "gameplay if __name__ == \"__main__\": glove1 = create_item('A2') glove2 = create_item('A2') # toAdd", "game_items = [glove1, glove2] zcx = Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1) iii = Fighter('i', is_npc=True)", "list of fighter :return: None \"\"\" # Enter battle_process print('Enter battle_process') # Begin", "create_item('A2') glove2 = create_item('A2') # toAdd item database # game_items = [glove1, glove2]", "battle_result: string 'WIN'/'LOSE'/'TIE' # :return: None # \"\"\" # if battle_result == 'WIN':", "<= 0: # fighter will die # fighter did die # go_die =", "is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2) j = Fighter('j', is_npc=True) k = Fighter('k', is_npc=True) allFighters =", "# All billed # Check new death if fighter.is_alive() and fighter.HP <= 0:", "# def distribute_loot(player, enemy, battle_result): # \"\"\" # Distribute enemy loot to player", "to player according to battle result # :param player: obj # :param enemy:", "set alive false, record turn, leave death message fighter.go_die(turn) fighters_remain -= 1 #", "# Enter Turn #turn print('\\n#{t}'.format(t=turn)) # Begin Turn #turn # Init turn #", "All billed # Check new death if fighter.is_alive() and fighter.HP <= 0: #", "fighter.is_alive(): print('{f} 卒'.format(f=fighter.name)) turn += 1 continue # Exit turns print('\\nExit turns') #", "for fighter in fighters_this_turn: # NPC choose skill if fighter.is_npc: npc = fighter", "toimpr magical nb, in right place ? # if turn != 1: #", "according to battle result # :param player: obj # :param enemy: obj #", "message fighter.go_die(turn) fighters_remain -= 1 # killer gain score for killing for prj", "1 # loot_item_dict = enemy.loot['item_dict'] # elif battle_result == 'TIE': # c_money =", "Distribute enemy loot to player according to battle result # :param player: obj", "index, fighter in enumerate(score_board): if fighter.is_alive(): status = '存活({hp}HP)'.format(hp=fighter.HP) else: killers = []", "battle_process # Init skills (for n) for fighter in fighters: fighter.init_battle() fighter.report_status() #", "item database # game_items = [glove1, glove2] zcx = Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1) iii", "skill, choose its target if skill.phase_type == 'A': # Auto choose target when", "key=lambda f: (f.score, f.died_turn), reverse=True) for index, fighter in enumerate(score_board): if fighter.is_alive(): status", "= enemy.loot['item_dict'] # elif battle_result == 'TIE': # c_money = 0 # c_exp", "\"\"\" # if battle_result == 'WIN': # c_money = 1 # c_exp =", "# go_die = set alive false, record turn, leave death message fighter.go_die(turn) fighters_remain", "= Fighter('i', is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2) j = Fighter('j', is_npc=True) k = Fighter('k', is_npc=True)", "new death if fighter.is_alive() and fighter.HP <= 0: # fighter will die #", "# player.add_money(enemy.loot['money'] * c_money) # player.add_exp(enemy.loot['EXP'] * c_exp) # for loot_item in loot_item_dict.keys():", "# game_items = [glove1, glove2] zcx = Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1) iii = Fighter('i',", "status = '存活({hp}HP)'.format(hp=fighter.HP) else: killers = [] for pj in fighter.lethal_projectiles: killer =", "skills (for n) for fighter in fighters: fighter.init_battle() fighter.report_status() # Turns begin turn", "'' # dummy? target_name = '' # dummy? key = '' # dummy?", "== \"__main__\": glove1 = create_item('A2') glove2 = create_item('A2') # toAdd item database #", "list(set(fighters_this_turn) - {npc}) key = random.choice(npc.get_available_skills()) skill = npc.BATTLESKILLBOOK[key] # If it's an", "create_item def battle(fighters, max_turn=10): \"\"\" Battle process start->loot :param max_turn: int turns for", "# Enter battle_process print('Enter battle_process') # Begin battle_process # Init skills (for n)", "# return # # player.add_money(enemy.loot['money'] * c_money) # player.add_exp(enemy.loot['EXP'] * c_exp) # for", "skill = record move, create proj, deliver proj skill.cast(target) # Billing for fighter", "NPC choose skill if fighter.is_npc: npc = fighter target = '' target_list =", "# Init skills (for n) for fighter in fighters: fighter.init_battle() fighter.report_status() # Turns", "in loot_item_dict.keys(): # player.get_item(loot_item, loot_item_dict[loot_item]) # toImpr separated gameplay if __name__ == \"__main__\":", "an A skill, choose its target if skill.phase_type == 'A': # Auto choose", "proj, deliver proj skill.cast(target) # Billing for fighter in fighters: # Start billing", "c_exp = 1 # loot_item_dict = enemy.loot['item_dict'] # elif battle_result == 'TIE': #", "in fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP, f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2) # Deaths for fighter", "* c_money) # player.add_exp(enemy.loot['EXP'] * c_exp) # for loot_item in loot_item_dict.keys(): # player.get_item(loot_item,", "Output turn info # Moves for fighter in fighters: print('{hp}hp {mp}mp\\t[{f}]|\\t{m}' .format(hp=fighter.HP, mp=fighter.MP,", "of fighter :return: None \"\"\" # Enter battle_process print('Enter battle_process') # Begin battle_process", "nb, in right place ? # if turn != 1: # fighter.gain_score(1) #", "'drain', 'heal', 'damage']: prjs = fighter.incoming_projectiles[category][tag] if prjs: for prj in prjs: prj.billing()", "player.get_item(loot_item, loot_item_dict[loot_item]) # toImpr separated gameplay if __name__ == \"__main__\": glove1 = create_item('A2')", "Auto choose target when only 1 enemy if len(target_list) == 1: target =", "gain score for killing for prj in fighter.lethal_projectiles: # toImpr move magical nb", "fighter in fighters_this_turn: # NPC choose skill if fighter.is_npc: npc = fighter target", "prjs: prj.billing() # All billed # Check new death if fighter.is_alive() and fighter.HP", "# Exit turns print('\\nExit turns') # Exit battle_process # Battle result score_board =", "* from Item import create_item def battle(fighters, max_turn=10): \"\"\" Battle process start->loot :param", "= target_fighter if target: break target_name = input('target...') # Cast skill = record", "# fighter did die # go_die = set alive false, record turn, leave", "enumerate(score_board): if fighter.is_alive(): status = '存活({hp}HP)'.format(hp=fighter.HP) else: killers = [] for pj in", "magical nb, in right place ? # if turn != 1: # fighter.gain_score(1)", "= '' # dummy? while True: input_raw = input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args = input_raw.strip().split()", "turn <= max_turn and fighters_remain >= 2: # Enter Turn #turn print('\\n#{t}'.format(t=turn)) #", "# c_exp = 0 # loot_item_dict = {} # # else: # return", "record move, create proj, deliver proj skill.cast(target) # Billing for fighter in fighters:", "# \"\"\" # if battle_result == 'WIN': # c_money = 1 # c_exp", "turn = 1 # Init turns # fighters_this_turn = list(fighters) fighters_remain = len(fighters)", "= {} # # else: # return # # player.add_money(enemy.loot['money'] * c_money) #", "{} # # else: # return # # player.add_money(enemy.loot['money'] * c_money) # player.add_exp(enemy.loot['EXP']", "if fighter.is_npc: npc = fighter target = '' target_list = list(set(fighters_this_turn) - {npc})", "for loot_item in loot_item_dict.keys(): # player.get_item(loot_item, loot_item_dict[loot_item]) # toImpr separated gameplay if __name__", "# NPC choose skill if fighter.is_npc: npc = fighter target = '' target_list", "# Turns begin turn = 1 # Init turns # fighters_this_turn = list(fighters)", "# Check new death if fighter.is_alive() and fighter.HP <= 0: # fighter will", "'{owner}的{skill}'. \\ format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer) killers_msg = '&'.join(killers) status = '卒(Turn{t}, {hp}HP, 被{killer}所杀)'", "\"\"\" Battle process start->loot :param max_turn: int turns for 1 battle, default 10", "# :param player: obj # :param enemy: obj # :param battle_result: string 'WIN'/'LOSE'/'TIE'", ".format(s=str(player.get_available_skills()))) input_args = input_raw.strip().split() key = input_args[0].upper() target_name = input_args[1] if len(input_args) >", "in fighters: fighter.init_turn() if fighter.is_alive(): fighters_this_turn.append(fighter) # toimpr magical nb, in right place", "# If it's an A skill, choose its target if skill.phase_type == 'A':", "= input_args[0].upper() target_name = input_args[1] if len(input_args) > 1 else '' if key", "reverse=True) for index, fighter in enumerate(score_board): if fighter.is_alive(): status = '存活({hp}HP)'.format(hp=fighter.HP) else: killers", "status=status)) # distribute_loot(player, enemy, battle_result) # toAdd loot system # def distribute_loot(player, enemy,", "for category in ['potion', 'arrow']: for tag in ['fill', 'drain', 'heal', 'damage']: prjs", "distribute_loot(player, enemy, battle_result): # \"\"\" # Distribute enemy loot to player according to", "its target if skill.phase_type == 'A': # Auto choose target when only 1", "[] for pj in fighter.lethal_projectiles: killer = '{owner}的{skill}'. \\ format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer) killers_msg", "被{killer}所杀)' \\ .format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score, status=status)) # distribute_loot(player, enemy, battle_result)", "m=str(fighter.last_move))) time.sleep(0.2) # Deaths for fighter in fighters_this_turn: if not fighter.is_alive(): print('{f} 卒'.format(f=fighter.name))", "player = fighter target_list = list(set(fighters_this_turn) - {player}) target = '' # dummy?", "# # player.add_money(enemy.loot['money'] * c_money) # player.add_exp(enemy.loot['EXP'] * c_exp) # for loot_item in", "skill, choose its target if skill.phase_type == 'A': target = random.choice(target_list) # Player", "skill for fighter in fighters_this_turn: # NPC choose skill if fighter.is_npc: npc =", "in right place ? # if turn != 1: # fighter.gain_score(1) # Choose", "(for n) for fighter in fighters: fighter.init_battle() fighter.report_status() # Turns begin turn =", "if len(target_list) == 1: target = target_list[0] else: while True: for target_fighter in", "= '' target_list = list(set(fighters_this_turn) - {npc}) key = random.choice(npc.get_available_skills()) skill = npc.BATTLESKILLBOOK[key]", "dummy? key = '' # dummy? while True: input_raw = input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args", "== 'TIE': # c_money = 0 # c_exp = 0.5 # loot_item_dict =", "__name__ == \"__main__\": glove1 = create_item('A2') glove2 = create_item('A2') # toAdd item database", "right place ? # if turn != 1: # fighter.gain_score(1) # Choose skill", "-= 1 # killer gain score for killing for prj in fighter.lethal_projectiles: #", "def battle(fighters, max_turn=10): \"\"\" Battle process start->loot :param max_turn: int turns for 1", "# toImpr move magical nb to global setting prj.caster.killed_someone() # Output turn info", "= list(set(fighters_this_turn) - {npc}) key = random.choice(npc.get_available_skills()) skill = npc.BATTLESKILLBOOK[key] # If it's", "score_board = sorted(fighters, key=lambda f: (f.score, f.died_turn), reverse=True) for index, fighter in enumerate(score_board):", "None # \"\"\" # if battle_result == 'WIN': # c_money = 1 #", "turns') # Exit battle_process # Battle result score_board = sorted(fighters, key=lambda f: (f.score,", "== 'WIN': # c_money = 1 # c_exp = 1 # loot_item_dict =", "fighter target_list = list(set(fighters_this_turn) - {player}) target = '' # dummy? target_name =", "target_list = list(set(fighters_this_turn) - {player}) target = '' # dummy? target_name = ''", "Battle result score_board = sorted(fighters, key=lambda f: (f.score, f.died_turn), reverse=True) for index, fighter", "npc.BATTLESKILLBOOK[key] # If it's an A skill, choose its target if skill.phase_type ==", "c_money = 0 # c_exp = 0 # loot_item_dict = {} # #", "category in ['potion', 'arrow']: for tag in ['fill', 'drain', 'heal', 'damage']: prjs =", "(f.score, f.died_turn), reverse=True) for index, fighter in enumerate(score_board): if fighter.is_alive(): status = '存活({hp}HP)'.format(hp=fighter.HP)", "for target_fighter in target_list: if target_fighter.name == target_name: target = target_fighter if target:", "killer = '{owner}的{skill}'. \\ format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer) killers_msg = '&'.join(killers) status = '卒(Turn{t},", "1 # c_exp = 1 # loot_item_dict = enemy.loot['item_dict'] # elif battle_result ==", "print('Enter battle_process') # Begin battle_process # Init skills (for n) for fighter in", "input_raw = input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args = input_raw.strip().split() key = input_args[0].upper() target_name = input_args[1]", "for killing for prj in fighter.lethal_projectiles: # toImpr move magical nb to global", "process start->loot :param max_turn: int turns for 1 battle, default 10 :param fighters:", "glove2] zcx = Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1) iii = Fighter('i', is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2) j", "distribute_loot(player, enemy, battle_result) # toAdd loot system # def distribute_loot(player, enemy, battle_result): #", "it's an A skill, choose its target if skill.phase_type == 'A': target =", "fighter did die # go_die = set alive false, record turn, leave death", "'WIN': # c_money = 1 # c_exp = 1 # loot_item_dict = enemy.loot['item_dict']", "random import time from Character import * from Item import create_item def battle(fighters,", "10 :param fighters: list of fighter :return: None \"\"\" # Enter battle_process print('Enter", "hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score, status=status)) # distribute_loot(player, enemy, battle_result) # toAdd loot", "turn != 1: # fighter.gain_score(1) # Choose skill for fighter in fighters_this_turn: #", "start->loot :param max_turn: int turns for 1 battle, default 10 :param fighters: list", "fighter in fighters: fighter.init_battle() fighter.report_status() # Turns begin turn = 1 # Init", "Start billing by order for category in ['potion', 'arrow']: for tag in ['fill',", "len(input_args) > 1 else '' if key in player.get_available_skills(): break skill = player.BATTLESKILLBOOK[key]", "- {player}) target = '' # dummy? target_name = '' # dummy? key", "'TIE': # c_money = 0 # c_exp = 0.5 # loot_item_dict = {}", "npc = fighter target = '' target_list = list(set(fighters_this_turn) - {npc}) key =", "= 1 # loot_item_dict = enemy.loot['item_dict'] # elif battle_result == 'TIE': # c_money", "# # else: # return # # player.add_money(enemy.loot['money'] * c_money) # player.add_exp(enemy.loot['EXP'] *", "loot_item_dict = enemy.loot['item_dict'] # elif battle_result == 'TIE': # c_money = 0 #", "obj # :param battle_result: string 'WIN'/'LOSE'/'TIE' # :return: None # \"\"\" # if", "zcx.put_in_item(glove1) zcx.equip_item(glove1) iii = Fighter('i', is_npc=True) iii.put_in_item(glove2) iii.equip_item(glove2) j = Fighter('j', is_npc=True) k", "if fighter.is_alive(): fighters_this_turn.append(fighter) # toimpr magical nb, in right place ? # if", "turns print('\\nExit turns') # Exit battle_process # Battle result score_board = sorted(fighters, key=lambda", "0 # c_exp = 0 # loot_item_dict = {} # # else: #", "default 10 :param fighters: list of fighter :return: None \"\"\" # Enter battle_process", "turn += 1 continue # Exit turns print('\\nExit turns') # Exit battle_process #", "in prjs: prj.billing() # All billed # Check new death if fighter.is_alive() and", "return # # player.add_money(enemy.loot['money'] * c_money) # player.add_exp(enemy.loot['EXP'] * c_exp) # for loot_item", "# Init turns # fighters_this_turn = list(fighters) fighters_remain = len(fighters) while turn <=", "from Item import create_item def battle(fighters, max_turn=10): \"\"\" Battle process start->loot :param max_turn:", "key = input_args[0].upper() target_name = input_args[1] if len(input_args) > 1 else '' if", "If it's an A skill, choose its target if skill.phase_type == 'A': target", "move, create proj, deliver proj skill.cast(target) # Billing for fighter in fighters: #", "# c_money = 0 # c_exp = 0.5 # loot_item_dict = {} #", "= 0 # c_exp = 0.5 # loot_item_dict = {} # elif battle_result", "while turn <= max_turn and fighters_remain >= 2: # Enter Turn #turn print('\\n#{t}'.format(t=turn))", "player according to battle result # :param player: obj # :param enemy: obj", "fighters_remain >= 2: # Enter Turn #turn print('\\n#{t}'.format(t=turn)) # Begin Turn #turn #", "elif battle_result == 'LOSE': # c_money = 0 # c_exp = 0 #", "place ? # if turn != 1: # fighter.gain_score(1) # Choose skill for", "random.choice(target_list) # Player input skill else: player = fighter target_list = list(set(fighters_this_turn) -", ":param player: obj # :param enemy: obj # :param battle_result: string 'WIN'/'LOSE'/'TIE' #", "Turn #turn print('\\n#{t}'.format(t=turn)) # Begin Turn #turn # Init turn # Construct fighters", "'&'.join(killers) status = '卒(Turn{t}, {hp}HP, 被{killer}所杀)' \\ .format(t=fighter.died_turn, hp=fighter.HP, killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score,", "Fighter('k', is_npc=True) allFighters = [zcx, iii, j, k] battle(allFighters) # player1.report_wealth() # print(player1.level)", "target_list = list(set(fighters_this_turn) - {npc}) key = random.choice(npc.get_available_skills()) skill = npc.BATTLESKILLBOOK[key] # If", "fighter will die # fighter did die # go_die = set alive false,", "= '' # dummy? target_name = '' # dummy? key = '' #", "'A': # Auto choose target when only 1 enemy if len(target_list) == 1:", "import random import time from Character import * from Item import create_item def", "player.add_exp(enemy.loot['EXP'] * c_exp) # for loot_item in loot_item_dict.keys(): # player.get_item(loot_item, loot_item_dict[loot_item]) # toImpr", "fighter.HP <= 0: # fighter will die # fighter did die # go_die", "death if fighter.is_alive() and fighter.HP <= 0: # fighter will die # fighter", "Battle process start->loot :param max_turn: int turns for 1 battle, default 10 :param", "fighter in fighters: # Start billing by order for category in ['potion', 'arrow']:", "random.choice(npc.get_available_skills()) skill = npc.BATTLESKILLBOOK[key] # If it's an A skill, choose its target", "= 1 # c_exp = 1 # loot_item_dict = enemy.loot['item_dict'] # elif battle_result", "string 'WIN'/'LOSE'/'TIE' # :return: None # \"\"\" # if battle_result == 'WIN': #", "killing for prj in fighter.lethal_projectiles: # toImpr move magical nb to global setting", "Character import * from Item import create_item def battle(fighters, max_turn=10): \"\"\" Battle process", "choose skill if fighter.is_npc: npc = fighter target = '' target_list = list(set(fighters_this_turn)", "dummy? target_name = '' # dummy? key = '' # dummy? while True:", "else: killers = [] for pj in fighter.lethal_projectiles: killer = '{owner}的{skill}'. \\ format(owner=pj.caster.name,", "fighter target = '' target_list = list(set(fighters_this_turn) - {npc}) key = random.choice(npc.get_available_skills()) skill", "battle, default 10 :param fighters: list of fighter :return: None \"\"\" # Enter", "= input('target...') # Cast skill = record move, create proj, deliver proj skill.cast(target)", "= list(set(fighters_this_turn) - {player}) target = '' # dummy? target_name = '' #", "result # :param player: obj # :param enemy: obj # :param battle_result: string", "True: input_raw = input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args = input_raw.strip().split() key = input_args[0].upper() target_name =", "die # fighter did die # go_die = set alive false, record turn,", "skill=pj.skill.alias) killers.append(killer) killers_msg = '&'.join(killers) status = '卒(Turn{t}, {hp}HP, 被{killer}所杀)' \\ .format(t=fighter.died_turn, hp=fighter.HP,", "deliver proj skill.cast(target) # Billing for fighter in fighters: # Start billing by", "order for category in ['potion', 'arrow']: for tag in ['fill', 'drain', 'heal', 'damage']:", "fighter in fighters: fighter.init_turn() if fighter.is_alive(): fighters_this_turn.append(fighter) # toimpr magical nb, in right", "target = '' target_list = list(set(fighters_this_turn) - {npc}) key = random.choice(npc.get_available_skills()) skill =", "prj.billing() # All billed # Check new death if fighter.is_alive() and fighter.HP <=", "def distribute_loot(player, enemy, battle_result): # \"\"\" # Distribute enemy loot to player according", "= random.choice(npc.get_available_skills()) skill = npc.BATTLESKILLBOOK[key] # If it's an A skill, choose its", "max_turn: int turns for 1 battle, default 10 :param fighters: list of fighter", "f=fighter.name, score=fighter.score, status=status)) # distribute_loot(player, enemy, battle_result) # toAdd loot system # def", "\\ format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer) killers_msg = '&'.join(killers) status = '卒(Turn{t}, {hp}HP, 被{killer}所杀)' \\", "fighter.is_alive() and fighter.HP <= 0: # fighter will die # fighter did die", "Enter Turn #turn print('\\n#{t}'.format(t=turn)) # Begin Turn #turn # Init turn # Construct", "battle_result == 'WIN': # c_money = 1 # c_exp = 1 # loot_item_dict", "{} # elif battle_result == 'LOSE': # c_money = 0 # c_exp =", "import time from Character import * from Item import create_item def battle(fighters, max_turn=10):", "c_money = 0 # c_exp = 0.5 # loot_item_dict = {} # elif", "fighter.go_die(turn) fighters_remain -= 1 # killer gain score for killing for prj in", "to battle result # :param player: obj # :param enemy: obj # :param", "player: obj # :param enemy: obj # :param battle_result: string 'WIN'/'LOSE'/'TIE' # :return:", "Init turn # Construct fighters participate in this turn # & Init fighter", "target_fighter in target_list: if target_fighter.name == target_name: target = target_fighter if target: break", "battle_result == 'TIE': # c_money = 0 # c_exp = 0.5 # loot_item_dict", "# dummy? while True: input_raw = input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args = input_raw.strip().split() key =", "# Battle result score_board = sorted(fighters, key=lambda f: (f.score, f.died_turn), reverse=True) for index,", "battle_result): # \"\"\" # Distribute enemy loot to player according to battle result", "time.sleep(0.2) # Deaths for fighter in fighters_this_turn: if not fighter.is_alive(): print('{f} 卒'.format(f=fighter.name)) turn", "\"\"\" # Enter battle_process print('Enter battle_process') # Begin battle_process # Init skills (for", "for tag in ['fill', 'drain', 'heal', 'damage']: prjs = fighter.incoming_projectiles[category][tag] if prjs: for", "to global setting prj.caster.killed_someone() # Output turn info # Moves for fighter in", "# if turn != 1: # fighter.gain_score(1) # Choose skill for fighter in", "#turn # Init turn # Construct fighters participate in this turn # &", "Item import create_item def battle(fighters, max_turn=10): \"\"\" Battle process start->loot :param max_turn: int", "in fighter.lethal_projectiles: # toImpr move magical nb to global setting prj.caster.killed_someone() # Output", "skill.phase_type == 'A': # Auto choose target when only 1 enemy if len(target_list)", "in ['potion', 'arrow']: for tag in ['fill', 'drain', 'heal', 'damage']: prjs = fighter.incoming_projectiles[category][tag]", "= player.BATTLESKILLBOOK[key] # If it's an A skill, choose its target if skill.phase_type", "target if skill.phase_type == 'A': # Auto choose target when only 1 enemy", "fighter in fighters_this_turn: if not fighter.is_alive(): print('{f} 卒'.format(f=fighter.name)) turn += 1 continue #", "print('\\n#{t}'.format(t=turn)) # Begin Turn #turn # Init turn # Construct fighters participate in", "target_name: target = target_fighter if target: break target_name = input('target...') # Cast skill", "== 'LOSE': # c_money = 0 # c_exp = 0 # loot_item_dict =", "if key in player.get_available_skills(): break skill = player.BATTLESKILLBOOK[key] # If it's an A", "choose its target if skill.phase_type == 'A': # Auto choose target when only", "f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2) # Deaths for fighter in fighters_this_turn: if not fighter.is_alive(): print('{f}", "participate in this turn # & Init fighter turn paras fighters_this_turn = []", "# Begin battle_process # Init skills (for n) for fighter in fighters: fighter.init_battle()", "else '' if key in player.get_available_skills(): break skill = player.BATTLESKILLBOOK[key] # If it's", "# Deaths for fighter in fighters_this_turn: if not fighter.is_alive(): print('{f} 卒'.format(f=fighter.name)) turn +=", "go_die = set alive false, record turn, leave death message fighter.go_die(turn) fighters_remain -=", "in enumerate(score_board): if fighter.is_alive(): status = '存活({hp}HP)'.format(hp=fighter.HP) else: killers = [] for pj", "# :return: None # \"\"\" # if battle_result == 'WIN': # c_money =", "separated gameplay if __name__ == \"__main__\": glove1 = create_item('A2') glove2 = create_item('A2') #", "score for killing for prj in fighter.lethal_projectiles: # toImpr move magical nb to", "in fighter.lethal_projectiles: killer = '{owner}的{skill}'. \\ format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer) killers_msg = '&'.join(killers) status", "max_turn=10): \"\"\" Battle process start->loot :param max_turn: int turns for 1 battle, default", "loot_item_dict[loot_item]) # toImpr separated gameplay if __name__ == \"__main__\": glove1 = create_item('A2') glove2", "'damage']: prjs = fighter.incoming_projectiles[category][tag] if prjs: for prj in prjs: prj.billing() # All", "True: for target_fighter in target_list: if target_fighter.name == target_name: target = target_fighter if", "target_name = input('target...') # Cast skill = record move, create proj, deliver proj", "# for loot_item in loot_item_dict.keys(): # player.get_item(loot_item, loot_item_dict[loot_item]) # toImpr separated gameplay if", "player.add_money(enemy.loot['money'] * c_money) # player.add_exp(enemy.loot['EXP'] * c_exp) # for loot_item in loot_item_dict.keys(): #", "database # game_items = [glove1, glove2] zcx = Fighter('zcx') zcx.put_in_item(glove1) zcx.equip_item(glove1) iii =", "# else: # return # # player.add_money(enemy.loot['money'] * c_money) # player.add_exp(enemy.loot['EXP'] * c_exp)", "it's an A skill, choose its target if skill.phase_type == 'A': # Auto", "will die # fighter did die # go_die = set alive false, record", "fighter.lethal_projectiles: killer = '{owner}的{skill}'. \\ format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer) killers_msg = '&'.join(killers) status =", "# Distribute enemy loot to player according to battle result # :param player:", "input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args = input_raw.strip().split() key = input_args[0].upper() target_name = input_args[1] if len(input_args)", "loot to player according to battle result # :param player: obj # :param", "turns for 1 battle, default 10 :param fighters: list of fighter :return: None", "0 # c_exp = 0.5 # loot_item_dict = {} # elif battle_result ==", "= input_args[1] if len(input_args) > 1 else '' if key in player.get_available_skills(): break", "= sorted(fighters, key=lambda f: (f.score, f.died_turn), reverse=True) for index, fighter in enumerate(score_board): if", "= fighter target_list = list(set(fighters_this_turn) - {player}) target = '' # dummy? target_name", "input_args[0].upper() target_name = input_args[1] if len(input_args) > 1 else '' if key in", "['fill', 'drain', 'heal', 'damage']: prjs = fighter.incoming_projectiles[category][tag] if prjs: for prj in prjs:", "glove1 = create_item('A2') glove2 = create_item('A2') # toAdd item database # game_items =", "'A': target = random.choice(target_list) # Player input skill else: player = fighter target_list", "key = random.choice(npc.get_available_skills()) skill = npc.BATTLESKILLBOOK[key] # If it's an A skill, choose", "# c_money = 1 # c_exp = 1 # loot_item_dict = enemy.loot['item_dict'] #", "max_turn and fighters_remain >= 2: # Enter Turn #turn print('\\n#{t}'.format(t=turn)) # Begin Turn", "print('{f} 卒'.format(f=fighter.name)) turn += 1 continue # Exit turns print('\\nExit turns') # Exit", "Init turns # fighters_this_turn = list(fighters) fighters_remain = len(fighters) while turn <= max_turn", "# elif battle_result == 'TIE': # c_money = 0 # c_exp = 0.5", "0 # loot_item_dict = {} # # else: # return # # player.add_money(enemy.loot['money']", "skill = player.BATTLESKILLBOOK[key] # If it's an A skill, choose its target if", "'' # dummy? key = '' # dummy? while True: input_raw = input('BoLoBoLo...{s}:'", "if not fighter.is_alive(): print('{f} 卒'.format(f=fighter.name)) turn += 1 continue # Exit turns print('\\nExit", "if len(input_args) > 1 else '' if key in player.get_available_skills(): break skill =", "* c_exp) # for loot_item in loot_item_dict.keys(): # player.get_item(loot_item, loot_item_dict[loot_item]) # toImpr separated", "skill = npc.BATTLESKILLBOOK[key] # If it's an A skill, choose its target if", "== target_name: target = target_fighter if target: break target_name = input('target...') # Cast", "choose target when only 1 enemy if len(target_list) == 1: target = target_list[0]", "fighter.init_battle() fighter.report_status() # Turns begin turn = 1 # Init turns # fighters_this_turn", "if skill.phase_type == 'A': # Auto choose target when only 1 enemy if", "killer=killers_msg) print('#{i}\\t{f}\\t\\t*{score}*\\t\\t{status}'.format(i=index+1, f=fighter.name, score=fighter.score, status=status)) # distribute_loot(player, enemy, battle_result) # toAdd loot system", "# fighter will die # fighter did die # go_die = set alive", "for index, fighter in enumerate(score_board): if fighter.is_alive(): status = '存活({hp}HP)'.format(hp=fighter.HP) else: killers =", "if target: break target_name = input('target...') # Cast skill = record move, create", "not fighter.is_alive(): print('{f} 卒'.format(f=fighter.name)) turn += 1 continue # Exit turns print('\\nExit turns')", "mp=fighter.MP, f=fighter.name, m=str(fighter.last_move))) time.sleep(0.2) # Deaths for fighter in fighters_this_turn: if not fighter.is_alive():", "\"\"\" # Distribute enemy loot to player according to battle result # :param", "0: # fighter will die # fighter did die # go_die = set", "Construct fighters participate in this turn # & Init fighter turn paras fighters_this_turn", "loot_item in loot_item_dict.keys(): # player.get_item(loot_item, loot_item_dict[loot_item]) # toImpr separated gameplay if __name__ ==", ":return: None \"\"\" # Enter battle_process print('Enter battle_process') # Begin battle_process # Init", "if turn != 1: # fighter.gain_score(1) # Choose skill for fighter in fighters_this_turn:", "create proj, deliver proj skill.cast(target) # Billing for fighter in fighters: # Start", "#turn print('\\n#{t}'.format(t=turn)) # Begin Turn #turn # Init turn # Construct fighters participate", "'' target_list = list(set(fighters_this_turn) - {npc}) key = random.choice(npc.get_available_skills()) skill = npc.BATTLESKILLBOOK[key] #", "{player}) target = '' # dummy? target_name = '' # dummy? key =", "# if battle_result == 'WIN': # c_money = 1 # c_exp = 1", "fighter in enumerate(score_board): if fighter.is_alive(): status = '存活({hp}HP)'.format(hp=fighter.HP) else: killers = [] for", "Init skills (for n) for fighter in fighters: fighter.init_battle() fighter.report_status() # Turns begin", "system # def distribute_loot(player, enemy, battle_result): # \"\"\" # Distribute enemy loot to", "for pj in fighter.lethal_projectiles: killer = '{owner}的{skill}'. \\ format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer) killers_msg =", "= npc.BATTLESKILLBOOK[key] # If it's an A skill, choose its target if skill.phase_type", "= target_list[0] else: while True: for target_fighter in target_list: if target_fighter.name == target_name:", "toAdd loot system # def distribute_loot(player, enemy, battle_result): # \"\"\" # Distribute enemy", "battle_process print('Enter battle_process') # Begin battle_process # Init skills (for n) for fighter", "1 else '' if key in player.get_available_skills(): break skill = player.BATTLESKILLBOOK[key] # If", "{npc}) key = random.choice(npc.get_available_skills()) skill = npc.BATTLESKILLBOOK[key] # If it's an A skill,", "killers = [] for pj in fighter.lethal_projectiles: killer = '{owner}的{skill}'. \\ format(owner=pj.caster.name, skill=pj.skill.alias)", "obj # :param enemy: obj # :param battle_result: string 'WIN'/'LOSE'/'TIE' # :return: None", "die # go_die = set alive false, record turn, leave death message fighter.go_die(turn)", "result score_board = sorted(fighters, key=lambda f: (f.score, f.died_turn), reverse=True) for index, fighter in", "fighter.is_alive(): fighters_this_turn.append(fighter) # toimpr magical nb, in right place ? # if turn", "fighter turn paras fighters_this_turn = [] for fighter in fighters: fighter.init_turn() if fighter.is_alive():", "battle(fighters, max_turn=10): \"\"\" Battle process start->loot :param max_turn: int turns for 1 battle,", "Cast skill = record move, create proj, deliver proj skill.cast(target) # Billing for", "c_exp = 0 # loot_item_dict = {} # # else: # return #", "for prj in fighter.lethal_projectiles: # toImpr move magical nb to global setting prj.caster.killed_someone()", "list(fighters) fighters_remain = len(fighters) while turn <= max_turn and fighters_remain >= 2: #", "fighters_this_turn: if not fighter.is_alive(): print('{f} 卒'.format(f=fighter.name)) turn += 1 continue # Exit turns", "target_list[0] else: while True: for target_fighter in target_list: if target_fighter.name == target_name: target", "in fighters: fighter.init_battle() fighter.report_status() # Turns begin turn = 1 # Init turns", "# Construct fighters participate in this turn # & Init fighter turn paras", "'' # dummy? while True: input_raw = input('BoLoBoLo...{s}:' .format(s=str(player.get_available_skills()))) input_args = input_raw.strip().split() key", "# :param enemy: obj # :param battle_result: string 'WIN'/'LOSE'/'TIE' # :return: None #", "import * from Item import create_item def battle(fighters, max_turn=10): \"\"\" Battle process start->loot", "= Fighter('j', is_npc=True) k = Fighter('k', is_npc=True) allFighters = [zcx, iii, j, k]", "turns # fighters_this_turn = list(fighters) fighters_remain = len(fighters) while turn <= max_turn and", "= fighter target = '' target_list = list(set(fighters_this_turn) - {npc}) key = random.choice(npc.get_available_skills())", "when only 1 enemy if len(target_list) == 1: target = target_list[0] else: while", "enemy, battle_result): # \"\"\" # Distribute enemy loot to player according to battle", "If it's an A skill, choose its target if skill.phase_type == 'A': #", "target when only 1 enemy if len(target_list) == 1: target = target_list[0] else:", "turn paras fighters_this_turn = [] for fighter in fighters: fighter.init_turn() if fighter.is_alive(): fighters_this_turn.append(fighter)", "if battle_result == 'WIN': # c_money = 1 # c_exp = 1 #", "key in player.get_available_skills(): break skill = player.BATTLESKILLBOOK[key] # If it's an A skill,", "iii.put_in_item(glove2) iii.equip_item(glove2) j = Fighter('j', is_npc=True) k = Fighter('k', is_npc=True) allFighters = [zcx,", "fighter.init_turn() if fighter.is_alive(): fighters_this_turn.append(fighter) # toimpr magical nb, in right place ? #", "input_raw.strip().split() key = input_args[0].upper() target_name = input_args[1] if len(input_args) > 1 else ''", "for 1 battle, default 10 :param fighters: list of fighter :return: None \"\"\"", "Exit turns print('\\nExit turns') # Exit battle_process # Battle result score_board = sorted(fighters,", "# \"\"\" # Distribute enemy loot to player according to battle result #", "pj in fighter.lethal_projectiles: killer = '{owner}的{skill}'. \\ format(owner=pj.caster.name, skill=pj.skill.alias) killers.append(killer) killers_msg = '&'.join(killers)", "# distribute_loot(player, enemy, battle_result) # toAdd loot system # def distribute_loot(player, enemy, battle_result):", "in this turn # & Init fighter turn paras fighters_this_turn = [] for", "# Begin Turn #turn # Init turn # Construct fighters participate in this", "= '' # dummy? key = '' # dummy? while True: input_raw =", "# fighter.gain_score(1) # Choose skill for fighter in fighters_this_turn: # NPC choose skill", "!= 1: # fighter.gain_score(1) # Choose skill for fighter in fighters_this_turn: # NPC", "= input_raw.strip().split() key = input_args[0].upper() target_name = input_args[1] if len(input_args) > 1 else", "target = target_list[0] else: while True: for target_fighter in target_list: if target_fighter.name ==", "# loot_item_dict = {} # # else: # return # # player.add_money(enemy.loot['money'] *", "continue # Exit turns print('\\nExit turns') # Exit battle_process # Battle result score_board", "# fighters_this_turn = list(fighters) fighters_remain = len(fighters) while turn <= max_turn and fighters_remain", "fighters_this_turn: # NPC choose skill if fighter.is_npc: npc = fighter target = ''", "move magical nb to global setting prj.caster.killed_someone() # Output turn info # Moves", "target_fighter if target: break target_name = input('target...') # Cast skill = record move,", "= {} # elif battle_result == 'LOSE': # c_money = 0 # c_exp", "if fighter.is_alive() and fighter.HP <= 0: # fighter will die # fighter did", "setting prj.caster.killed_someone() # Output turn info # Moves for fighter in fighters: print('{hp}hp", "# Choose skill for fighter in fighters_this_turn: # NPC choose skill if fighter.is_npc:", "leave death message fighter.go_die(turn) fighters_remain -= 1 # killer gain score for killing", "# elif battle_result == 'LOSE': # c_money = 0 # c_exp = 0", "# Player input skill else: player = fighter target_list = list(set(fighters_this_turn) - {player})", "in ['fill', 'drain', 'heal', 'damage']: prjs = fighter.incoming_projectiles[category][tag] if prjs: for prj in", "if fighter.is_alive(): status = '存活({hp}HP)'.format(hp=fighter.HP) else: killers = [] for pj in fighter.lethal_projectiles:", "'WIN'/'LOSE'/'TIE' # :return: None # \"\"\" # if battle_result == 'WIN': # c_money", "its target if skill.phase_type == 'A': target = random.choice(target_list) # Player input skill", "卒'.format(f=fighter.name)) turn += 1 continue # Exit turns print('\\nExit turns') # Exit battle_process", "# Billing for fighter in fighters: # Start billing by order for category", "# Auto choose target when only 1 enemy if len(target_list) == 1: target" ]
[ "vocab = frommat['vocab'] # Xtest Mtx print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices = np.unique(M[:,0],return_inverse=True)", "from scipy.special import gammaln frommat = spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain = frommat['X_train_woSTOP'] # Xtest", "frommat['Y_train'] # Xtest Mtx yTest = frommat['Y_test'] # Xtest Mtx vocab = frommat['vocab']", "idx, val in enumerate(u): # print(idx, val) # xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass", "yTest = frommat['Y_test'] # Xtest Mtx vocab = frommat['vocab'] # Xtest Mtx print(len(vocab))", "csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices), vocablen)) print(xProcessed) alpha = 2*gammaln(tune+1) - gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum =", "= xProcessed.multiply(rowsum.power(-1)) # print(WordProb) # if (special): # for idx, val in enumerate(u):", "enumerate(u): # print(idx, val) # xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass return [xProcessed,alpha] #tuning", "[xProcessed,alpha] #tuning = [150,200] itune = 150 print(\"tuning at :\"+str(itune)) [xTrainProce,alpha] = RRNpreprocessing(xTrain,itune,len(vocab))", "gammaln frommat = spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain = frommat['X_train_woSTOP'] # Xtest Mtx yTrain =", "frommat['Y_test'] # Xtest Mtx vocab = frommat['vocab'] # Xtest Mtx print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False):", "as np import scipy.io as spio from scipy.sparse import csr_matrix from scipy.special import", "import gammaln frommat = spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain = frommat['X_train_woSTOP'] # Xtest Mtx yTrain", "# print(WordProb) # if (special): # for idx, val in enumerate(u): # print(idx,", "= frommat['vocab'] # Xtest Mtx print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices = np.unique(M[:,0],return_inverse=True) xProcessed", "import svm from sklearn.datasets import load_files import numpy as np import scipy.io as", "itune = 150 print(\"tuning at :\"+str(itune)) [xTrainProce,alpha] = RRNpreprocessing(xTrain,itune,len(vocab)) print(\"Alpha is: \"+ str(alpha))", "sklearn.datasets import load_files import numpy as np import scipy.io as spio from scipy.sparse", "150 print(\"tuning at :\"+str(itune)) [xTrainProce,alpha] = RRNpreprocessing(xTrain,itune,len(vocab)) print(\"Alpha is: \"+ str(alpha)) print(\"Xtrain is", "Mtx yTest = frommat['Y_test'] # Xtest Mtx vocab = frommat['vocab'] # Xtest Mtx", "# if (special): # for idx, val in enumerate(u): # print(idx, val) #", "= spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain = frommat['X_train_woSTOP'] # Xtest Mtx yTrain = frommat['X_test_woSTOP'] #", "frommat['vocab'] # Xtest Mtx print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices = np.unique(M[:,0],return_inverse=True) xProcessed =", "Xtest Mtx vocab = frommat['vocab'] # Xtest Mtx print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices", "def RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices = np.unique(M[:,0],return_inverse=True) xProcessed = csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices), vocablen)) print(xProcessed)", "= 150 print(\"tuning at :\"+str(itune)) [xTrainProce,alpha] = RRNpreprocessing(xTrain,itune,len(vocab)) print(\"Alpha is: \"+ str(alpha)) print(\"Xtrain", "# xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass return [xProcessed,alpha] #tuning = [150,200] itune =", "spio from scipy.sparse import csr_matrix from scipy.special import gammaln frommat = spio.loadmat('sbowen_woStop.mat', squeeze_me=True)", "numpy as np import scipy.io as spio from scipy.sparse import csr_matrix from scipy.special", "svm from sklearn.datasets import load_files import numpy as np import scipy.io as spio", "2*gammaln(tune+1) - gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum = xProcessed.sum(axis=1) WordProb = xProcessed.multiply(rowsum.power(-1)) # print(WordProb) #", "xProcessed.multiply(rowsum.power(-1)) # print(WordProb) # if (special): # for idx, val in enumerate(u): #", "squeeze_me=True) xTrain = frommat['X_train_woSTOP'] # Xtest Mtx yTrain = frommat['X_test_woSTOP'] # Xtest Mtx", "print(xProcessed) alpha = 2*gammaln(tune+1) - gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum = xProcessed.sum(axis=1) WordProb = xProcessed.multiply(rowsum.power(-1))", "= frommat['X_test_woSTOP'] # Xtest Mtx xTest = frommat['Y_train'] # Xtest Mtx yTest =", "xProcessed.sum(axis=1) WordProb = xProcessed.multiply(rowsum.power(-1)) # print(WordProb) # if (special): # for idx, val", "rowsum = xProcessed.sum(axis=1) WordProb = xProcessed.multiply(rowsum.power(-1)) # print(WordProb) # if (special): # for", "in enumerate(u): # print(idx, val) # xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass return [xProcessed,alpha]", "spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain = frommat['X_train_woSTOP'] # Xtest Mtx yTrain = frommat['X_test_woSTOP'] # Xtest", "frommat = spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain = frommat['X_train_woSTOP'] # Xtest Mtx yTrain = frommat['X_test_woSTOP']", "val in enumerate(u): # print(idx, val) # xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass return", "= frommat['Y_test'] # Xtest Mtx vocab = frommat['vocab'] # Xtest Mtx print(len(vocab)) def", "= np.unique(M[:,0],return_inverse=True) xProcessed = csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices), vocablen)) print(xProcessed) alpha = 2*gammaln(tune+1) -", "= csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices), vocablen)) print(xProcessed) alpha = 2*gammaln(tune+1) - gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum", "val) # xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass return [xProcessed,alpha] #tuning = [150,200] itune", "print(xProcessed.sum(axis=1)) rowsum = xProcessed.sum(axis=1) WordProb = xProcessed.multiply(rowsum.power(-1)) # print(WordProb) # if (special): #", "Mtx xTest = frommat['Y_train'] # Xtest Mtx yTest = frommat['Y_test'] # Xtest Mtx", "sklearn import svm from sklearn.datasets import load_files import numpy as np import scipy.io", "xTest = frommat['Y_train'] # Xtest Mtx yTest = frommat['Y_test'] # Xtest Mtx vocab", "= 2*gammaln(tune+1) - gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum = xProcessed.sum(axis=1) WordProb = xProcessed.multiply(rowsum.power(-1)) # print(WordProb)", "pass return [xProcessed,alpha] #tuning = [150,200] itune = 150 print(\"tuning at :\"+str(itune)) [xTrainProce,alpha]", "#tuning = [150,200] itune = 150 print(\"tuning at :\"+str(itune)) [xTrainProce,alpha] = RRNpreprocessing(xTrain,itune,len(vocab)) print(\"Alpha", "from scipy.sparse import csr_matrix from scipy.special import gammaln frommat = spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain", "Mtx print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices = np.unique(M[:,0],return_inverse=True) xProcessed = csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices),", "Xtest Mtx xTest = frommat['Y_train'] # Xtest Mtx yTest = frommat['Y_test'] # Xtest", "scipy.io as spio from scipy.sparse import csr_matrix from scipy.special import gammaln frommat =", "# Xtest Mtx vocab = frommat['vocab'] # Xtest Mtx print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False): u,", "= [150,200] itune = 150 print(\"tuning at :\"+str(itune)) [xTrainProce,alpha] = RRNpreprocessing(xTrain,itune,len(vocab)) print(\"Alpha is:", "# Xtest Mtx yTrain = frommat['X_test_woSTOP'] # Xtest Mtx xTest = frommat['Y_train'] #", "import csr_matrix from scipy.special import gammaln frommat = spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain = frommat['X_train_woSTOP']", "print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices = np.unique(M[:,0],return_inverse=True) xProcessed = csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices), vocablen))", "= np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass return [xProcessed,alpha] #tuning = [150,200] itune = 150 print(\"tuning", "xTrain = frommat['X_train_woSTOP'] # Xtest Mtx yTrain = frommat['X_test_woSTOP'] # Xtest Mtx xTest", "u, doc_indices = np.unique(M[:,0],return_inverse=True) xProcessed = csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices), vocablen)) print(xProcessed) alpha =", "gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum = xProcessed.sum(axis=1) WordProb = xProcessed.multiply(rowsum.power(-1)) # print(WordProb) # if (special):", "print(idx, val) # xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass return [xProcessed,alpha] #tuning = [150,200]", "scipy.special import gammaln frommat = spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain = frommat['X_train_woSTOP'] # Xtest Mtx", "Mtx yTrain = frommat['X_test_woSTOP'] # Xtest Mtx xTest = frommat['Y_train'] # Xtest Mtx", "alpha = 2*gammaln(tune+1) - gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum = xProcessed.sum(axis=1) WordProb = xProcessed.multiply(rowsum.power(-1)) #", "print(\"tuning at :\"+str(itune)) [xTrainProce,alpha] = RRNpreprocessing(xTrain,itune,len(vocab)) print(\"Alpha is: \"+ str(alpha)) print(\"Xtrain is :\"+str(xTrainProce))", "WordProb = xProcessed.multiply(rowsum.power(-1)) # print(WordProb) # if (special): # for idx, val in", "xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass return [xProcessed,alpha] #tuning = [150,200] itune = 150", "print(WordProb) # if (special): # for idx, val in enumerate(u): # print(idx, val)", "scipy.sparse import csr_matrix from scipy.special import gammaln frommat = spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain =", "RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices = np.unique(M[:,0],return_inverse=True) xProcessed = csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices), vocablen)) print(xProcessed) alpha", "np import scipy.io as spio from scipy.sparse import csr_matrix from scipy.special import gammaln", "import numpy as np import scipy.io as spio from scipy.sparse import csr_matrix from", "frommat['X_test_woSTOP'] # Xtest Mtx xTest = frommat['Y_train'] # Xtest Mtx yTest = frommat['Y_test']", "import load_files import numpy as np import scipy.io as spio from scipy.sparse import", "= frommat['Y_train'] # Xtest Mtx yTest = frommat['Y_test'] # Xtest Mtx vocab =", "from sklearn.datasets import load_files import numpy as np import scipy.io as spio from", "load_files import numpy as np import scipy.io as spio from scipy.sparse import csr_matrix", "csr_matrix from scipy.special import gammaln frommat = spio.loadmat('sbowen_woStop.mat', squeeze_me=True) xTrain = frommat['X_train_woSTOP'] #", "as spio from scipy.sparse import csr_matrix from scipy.special import gammaln frommat = spio.loadmat('sbowen_woStop.mat',", "# Xtest Mtx xTest = frommat['Y_train'] # Xtest Mtx yTest = frommat['Y_test'] #", "- gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum = xProcessed.sum(axis=1) WordProb = xProcessed.multiply(rowsum.power(-1)) # print(WordProb) # if", "<gh_stars>0 from sklearn import svm from sklearn.datasets import load_files import numpy as np", "# for idx, val in enumerate(u): # print(idx, val) # xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:])", "return [xProcessed,alpha] #tuning = [150,200] itune = 150 print(\"tuning at :\"+str(itune)) [xTrainProce,alpha] =", "Xtest Mtx print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices = np.unique(M[:,0],return_inverse=True) xProcessed = csr_matrix((M[:,2], (doc_indices,M[:,1])),", "if (special): # for idx, val in enumerate(u): # print(idx, val) # xProcessed[idx,:]", "= xProcessed.sum(axis=1) WordProb = xProcessed.multiply(rowsum.power(-1)) # print(WordProb) # if (special): # for idx,", "(special): # for idx, val in enumerate(u): # print(idx, val) # xProcessed[idx,:] =", "vocablen)) print(xProcessed) alpha = 2*gammaln(tune+1) - gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum = xProcessed.sum(axis=1) WordProb =", "for idx, val in enumerate(u): # print(idx, val) # xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) #", "xProcessed = csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices), vocablen)) print(xProcessed) alpha = 2*gammaln(tune+1) - gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1))", "Xtest Mtx yTrain = frommat['X_test_woSTOP'] # Xtest Mtx xTest = frommat['Y_train'] # Xtest", "= frommat['X_train_woSTOP'] # Xtest Mtx yTrain = frommat['X_test_woSTOP'] # Xtest Mtx xTest =", "# Xtest Mtx yTest = frommat['Y_test'] # Xtest Mtx vocab = frommat['vocab'] #", "(doc_indices,M[:,1])), shape=(len(doc_indices), vocablen)) print(xProcessed) alpha = 2*gammaln(tune+1) - gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum = xProcessed.sum(axis=1)", "# print(idx, val) # xProcessed[idx,:] = np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass return [xProcessed,alpha] #tuning =", "doc_indices = np.unique(M[:,0],return_inverse=True) xProcessed = csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices), vocablen)) print(xProcessed) alpha = 2*gammaln(tune+1)", "# pass return [xProcessed,alpha] #tuning = [150,200] itune = 150 print(\"tuning at :\"+str(itune))", "np.random.choice(xProcessed[idx,:],tune,WordProb[idx,:]) # pass return [xProcessed,alpha] #tuning = [150,200] itune = 150 print(\"tuning at", "[150,200] itune = 150 print(\"tuning at :\"+str(itune)) [xTrainProce,alpha] = RRNpreprocessing(xTrain,itune,len(vocab)) print(\"Alpha is: \"+", "Xtest Mtx yTest = frommat['Y_test'] # Xtest Mtx vocab = frommat['vocab'] # Xtest", "yTrain = frommat['X_test_woSTOP'] # Xtest Mtx xTest = frommat['Y_train'] # Xtest Mtx yTest", "from sklearn import svm from sklearn.datasets import load_files import numpy as np import", "shape=(len(doc_indices), vocablen)) print(xProcessed) alpha = 2*gammaln(tune+1) - gammaln(2*tune+vocablen) print(xProcessed.sum(axis=1)) rowsum = xProcessed.sum(axis=1) WordProb", "import scipy.io as spio from scipy.sparse import csr_matrix from scipy.special import gammaln frommat", "# Xtest Mtx print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices = np.unique(M[:,0],return_inverse=True) xProcessed = csr_matrix((M[:,2],", "frommat['X_train_woSTOP'] # Xtest Mtx yTrain = frommat['X_test_woSTOP'] # Xtest Mtx xTest = frommat['Y_train']", "np.unique(M[:,0],return_inverse=True) xProcessed = csr_matrix((M[:,2], (doc_indices,M[:,1])), shape=(len(doc_indices), vocablen)) print(xProcessed) alpha = 2*gammaln(tune+1) - gammaln(2*tune+vocablen)", "Mtx vocab = frommat['vocab'] # Xtest Mtx print(len(vocab)) def RRNpreprocessing(M,tune,vocablen,special=False): u, doc_indices =" ]
[ "bs4 import BeautifulSoup import xlsxwriter workbook= xlsxwriter.Workbook(\"data.xlsx\") worksheet = workbook.add_worksheet() f = open('rough.html',\"r\")", "0 for row in rows: a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno, 1, a[2].text) worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):])", "= 0 for row in rows: a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno, 1, a[2].text) worksheet.write(rowno, 2,", "3, a[3].text) worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno, 5, a[3].text) worksheet.write(rowno, 6, td[6].text) rowno=rowno+1 workbook.close()", "rows=tbody.find_all('tr') rowno = 0 for row in rows: a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno, 1, a[2].text)", "2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno, 5, a[3].text) worksheet.write(rowno, 6,", "workbook= xlsxwriter.Workbook(\"data.xlsx\") worksheet = workbook.add_worksheet() f = open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data) div = soup.find('div',", "1, a[2].text) worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno, 5,", "rows: a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno, 1, a[2].text) worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno,", "= open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data) div = soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') rowno =", "from bs4 import BeautifulSoup import xlsxwriter workbook= xlsxwriter.Workbook(\"data.xlsx\") worksheet = workbook.add_worksheet() f =", "data=f.read() soup=BeautifulSoup(data) div = soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') rowno = 0 for", "= workbook.add_worksheet() f = open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data) div = soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody')", "xlsxwriter workbook= xlsxwriter.Workbook(\"data.xlsx\") worksheet = workbook.add_worksheet() f = open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data) div =", "tbody=div.find('tbody') rows=tbody.find_all('tr') rowno = 0 for row in rows: a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno, 1,", "a[2].text) worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno, 5, a[3].text)", "div = soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') rowno = 0 for row in", "for row in rows: a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno, 1, a[2].text) worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno,", "import xlsxwriter workbook= xlsxwriter.Workbook(\"data.xlsx\") worksheet = workbook.add_worksheet() f = open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data) div", "worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno, 5, a[3].text) worksheet.write(rowno, 6, td[6].text) rowno=rowno+1", "open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data) div = soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') rowno = 0", "worksheet.write(rowno, 1, a[2].text) worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno,", "soup=BeautifulSoup(data) div = soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') rowno = 0 for row", "worksheet = workbook.add_worksheet() f = open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data) div = soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table')", "table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') rowno = 0 for row in rows: a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno,", "BeautifulSoup import xlsxwriter workbook= xlsxwriter.Workbook(\"data.xlsx\") worksheet = workbook.add_worksheet() f = open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data)", "f = open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data) div = soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') rowno", "= soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') rowno = 0 for row in rows:", "td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno, 5, a[3].text) worksheet.write(rowno, 6, td[6].text)", "xlsxwriter.Workbook(\"data.xlsx\") worksheet = workbook.add_worksheet() f = open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data) div = soup.find('div', {\"class\":'dataTables_scroll'})", "a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno, 1, a[2].text) worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno, 4,", "a[3].text) worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno, 5, a[3].text) worksheet.write(rowno, 6, td[6].text) rowno=rowno+1 workbook.close() print", "import BeautifulSoup import xlsxwriter workbook= xlsxwriter.Workbook(\"data.xlsx\") worksheet = workbook.add_worksheet() f = open('rough.html',\"r\") data=f.read()", "worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno, 5, a[3].text) worksheet.write(rowno, 6, td[6].text) rowno=rowno+1 workbook.close() print \"Done\"", "soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') rowno = 0 for row in rows: a=row.find_all('a')", "worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno, 4, a[4].text) worksheet.write(rowno, 5, a[3].text) worksheet.write(rowno,", "td=row.find_all('td') worksheet.write(rowno, 1, a[2].text) worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3, a[3].text) worksheet.write(rowno, 4, a[4].text)", "workbook.add_worksheet() f = open('rough.html',\"r\") data=f.read() soup=BeautifulSoup(data) div = soup.find('div', {\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr')", "row in rows: a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno, 1, a[2].text) worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3,", "in rows: a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno, 1, a[2].text) worksheet.write(rowno, 2, td[3].text[td[3].text.find('P:'):]) worksheet.write(rowno, 3, a[3].text)", "{\"class\":'dataTables_scroll'}) table=div.find('table') tbody=div.find('tbody') rows=tbody.find_all('tr') rowno = 0 for row in rows: a=row.find_all('a') td=row.find_all('td')", "rowno = 0 for row in rows: a=row.find_all('a') td=row.find_all('td') worksheet.write(rowno, 1, a[2].text) worksheet.write(rowno," ]
[ "not None: folder_module = cls.folder_module() if folder_module == 'options': s += '--%s' %", "% cls.cmd_short if cls.option is not None: folder_module = cls.folder_module() if folder_module ==", "required to be set to something else default = None # Option name", "Base class for option plugins \"\"\" # Default value, if default is None,", "30: s += ' ' * (30 - len(s)) else: s += '\\n'", "+= ' ' * (30 - len(s)) else: s += '\\n' + '", "# Command line argument name cmd_argument = None # Description, duhh description =", "return value @classmethod def folder_module(cls): return cls.__module__.split('.')[-2] @classmethod def get_doc_line(cls): s = '", "cls.cmd_short is not None: s += '-%s ' % cls.cmd_short if cls.option is", "Command line argument name cmd_argument = None # Description, duhh description = ''", "s += '=%s' % cls.cmd_argument if len(s) < 30: s += ' '", "cls.cmd_argument if len(s) < 30: s += ' ' * (30 - len(s))", "= '' @staticmethod def parse(value): return value @classmethod def folder_module(cls): return cls.__module__.split('.')[-2] @classmethod", "folder_module = cls.folder_module() if folder_module == 'options': s += '--%s' % cls.option else:", "plugin import Plugin class Option(Plugin): \"\"\" Base class for option plugins \"\"\" #", "+= '=%s' % cls.cmd_argument if len(s) < 30: s += ' ' *", "plugins \"\"\" # Default value, if default is None, option is required to", "# Option name option = None # Short command line option cmd_short =", "Description, duhh description = '' @staticmethod def parse(value): return value @classmethod def folder_module(cls):", "None: s += '-%s ' % cls.cmd_short if cls.option is not None: folder_module", "value @classmethod def folder_module(cls): return cls.__module__.split('.')[-2] @classmethod def get_doc_line(cls): s = ' '*4", "s += '-%s ' % cls.cmd_short if cls.option is not None: folder_module =", "from plugin import Plugin class Option(Plugin): \"\"\" Base class for option plugins \"\"\"", "value, if default is None, option is required to be set to something", "Option(Plugin): \"\"\" Base class for option plugins \"\"\" # Default value, if default", "folder_module == 'options': s += '--%s' % cls.option else: s += '--%s.%s' %", "+= '--%s' % cls.option else: s += '--%s.%s' % (folder_module, cls.option) if cls.cmd_argument", "not None: s += '-%s ' % cls.cmd_short if cls.option is not None:", "' * (30 - len(s)) else: s += '\\n' + ' ' *", "name cmd_argument = None # Description, duhh description = '' @staticmethod def parse(value):", "cls.option else: s += '--%s.%s' % (folder_module, cls.option) if cls.cmd_argument is not None:", "option is required to be set to something else default = None #", "@staticmethod def parse(value): return value @classmethod def folder_module(cls): return cls.__module__.split('.')[-2] @classmethod def get_doc_line(cls):", "default is None, option is required to be set to something else default", "get_doc_line(cls): s = ' '*4 if cls.cmd_short is not None: s += '-%s", "if default is None, option is required to be set to something else", "is required to be set to something else default = None # Option", "Short command line option cmd_short = None # Command line argument name cmd_argument", "# Description, duhh description = '' @staticmethod def parse(value): return value @classmethod def", "' ' * (30 - len(s)) else: s += '\\n' + ' '", "cls.__module__.split('.')[-2] @classmethod def get_doc_line(cls): s = ' '*4 if cls.cmd_short is not None:", "if len(s) < 30: s += ' ' * (30 - len(s)) else:", "option plugins \"\"\" # Default value, if default is None, option is required", "else: s += '\\n' + ' ' * 30 s += cls.description return", "% (folder_module, cls.option) if cls.cmd_argument is not None: s += '=%s' % cls.cmd_argument", "None: s += '=%s' % cls.cmd_argument if len(s) < 30: s += '", "return cls.__module__.split('.')[-2] @classmethod def get_doc_line(cls): s = ' '*4 if cls.cmd_short is not", "s = ' '*4 if cls.cmd_short is not None: s += '-%s '", "else: s += '--%s.%s' % (folder_module, cls.option) if cls.cmd_argument is not None: s", "@classmethod def folder_module(cls): return cls.__module__.split('.')[-2] @classmethod def get_doc_line(cls): s = ' '*4 if", "' % cls.cmd_short if cls.option is not None: folder_module = cls.folder_module() if folder_module", "cmd_short = None # Command line argument name cmd_argument = None # Description,", "\"\"\" # Default value, if default is None, option is required to be", "None, option is required to be set to something else default = None", "be set to something else default = None # Option name option =", "# Default value, if default is None, option is required to be set", "None # Description, duhh description = '' @staticmethod def parse(value): return value @classmethod", "+= '-%s ' % cls.cmd_short if cls.option is not None: folder_module = cls.folder_module()", "def parse(value): return value @classmethod def folder_module(cls): return cls.__module__.split('.')[-2] @classmethod def get_doc_line(cls): s", "else default = None # Option name option = None # Short command", "# Short command line option cmd_short = None # Command line argument name", "cls.cmd_argument is not None: s += '=%s' % cls.cmd_argument if len(s) < 30:", "(folder_module, cls.option) if cls.cmd_argument is not None: s += '=%s' % cls.cmd_argument if", "to something else default = None # Option name option = None #", "' '*4 if cls.cmd_short is not None: s += '-%s ' % cls.cmd_short", "parse(value): return value @classmethod def folder_module(cls): return cls.__module__.split('.')[-2] @classmethod def get_doc_line(cls): s =", "'=%s' % cls.cmd_argument if len(s) < 30: s += ' ' * (30", "== 'options': s += '--%s' % cls.option else: s += '--%s.%s' % (folder_module,", "not None: s += '=%s' % cls.cmd_argument if len(s) < 30: s +=", "= None # Command line argument name cmd_argument = None # Description, duhh", "cls.folder_module() if folder_module == 'options': s += '--%s' % cls.option else: s +=", "option cmd_short = None # Command line argument name cmd_argument = None #", "cls.cmd_short if cls.option is not None: folder_module = cls.folder_module() if folder_module == 'options':", "Default value, if default is None, option is required to be set to", "is None, option is required to be set to something else default =", "'options': s += '--%s' % cls.option else: s += '--%s.%s' % (folder_module, cls.option)", "'--%s' % cls.option else: s += '--%s.%s' % (folder_module, cls.option) if cls.cmd_argument is", "line option cmd_short = None # Command line argument name cmd_argument = None", "s += ' ' * (30 - len(s)) else: s += '\\n' +", "= None # Option name option = None # Short command line option", "argument name cmd_argument = None # Description, duhh description = '' @staticmethod def", "set to something else default = None # Option name option = None", "* (30 - len(s)) else: s += '\\n' + ' ' * 30", "None # Option name option = None # Short command line option cmd_short", "cls.option) if cls.cmd_argument is not None: s += '=%s' % cls.cmd_argument if len(s)", "'*4 if cls.cmd_short is not None: s += '-%s ' % cls.cmd_short if", "for option plugins \"\"\" # Default value, if default is None, option is", "'' @staticmethod def parse(value): return value @classmethod def folder_module(cls): return cls.__module__.split('.')[-2] @classmethod def", "duhh description = '' @staticmethod def parse(value): return value @classmethod def folder_module(cls): return", "default = None # Option name option = None # Short command line", "Plugin class Option(Plugin): \"\"\" Base class for option plugins \"\"\" # Default value,", "def folder_module(cls): return cls.__module__.split('.')[-2] @classmethod def get_doc_line(cls): s = ' '*4 if cls.cmd_short", "None # Command line argument name cmd_argument = None # Description, duhh description", "% cls.cmd_argument if len(s) < 30: s += ' ' * (30 -", "s += '\\n' + ' ' * 30 s += cls.description return s", "'--%s.%s' % (folder_module, cls.option) if cls.cmd_argument is not None: s += '=%s' %", "import Plugin class Option(Plugin): \"\"\" Base class for option plugins \"\"\" # Default", "something else default = None # Option name option = None # Short", "class for option plugins \"\"\" # Default value, if default is None, option", "description = '' @staticmethod def parse(value): return value @classmethod def folder_module(cls): return cls.__module__.split('.')[-2]", "\"\"\" Base class for option plugins \"\"\" # Default value, if default is", "= ' '*4 if cls.cmd_short is not None: s += '-%s ' %", "cmd_argument = None # Description, duhh description = '' @staticmethod def parse(value): return", "- len(s)) else: s += '\\n' + ' ' * 30 s +=", "is not None: s += '=%s' % cls.cmd_argument if len(s) < 30: s", "Option name option = None # Short command line option cmd_short = None", "None # Short command line option cmd_short = None # Command line argument", "cls.option is not None: folder_module = cls.folder_module() if folder_module == 'options': s +=", "is not None: folder_module = cls.folder_module() if folder_module == 'options': s += '--%s'", "to be set to something else default = None # Option name option", "@classmethod def get_doc_line(cls): s = ' '*4 if cls.cmd_short is not None: s", "if cls.cmd_argument is not None: s += '=%s' % cls.cmd_argument if len(s) <", "= cls.folder_module() if folder_module == 'options': s += '--%s' % cls.option else: s", "command line option cmd_short = None # Command line argument name cmd_argument =", "< 30: s += ' ' * (30 - len(s)) else: s +=", "def get_doc_line(cls): s = ' '*4 if cls.cmd_short is not None: s +=", "= None # Description, duhh description = '' @staticmethod def parse(value): return value", "+= '--%s.%s' % (folder_module, cls.option) if cls.cmd_argument is not None: s += '=%s'", "line argument name cmd_argument = None # Description, duhh description = '' @staticmethod", "% cls.option else: s += '--%s.%s' % (folder_module, cls.option) if cls.cmd_argument is not", "None: folder_module = cls.folder_module() if folder_module == 'options': s += '--%s' % cls.option", "'-%s ' % cls.cmd_short if cls.option is not None: folder_module = cls.folder_module() if", "len(s) < 30: s += ' ' * (30 - len(s)) else: s", "if cls.cmd_short is not None: s += '-%s ' % cls.cmd_short if cls.option", "len(s)) else: s += '\\n' + ' ' * 30 s += cls.description", "name option = None # Short command line option cmd_short = None #", "(30 - len(s)) else: s += '\\n' + ' ' * 30 s", "is not None: s += '-%s ' % cls.cmd_short if cls.option is not", "option = None # Short command line option cmd_short = None # Command", "class Option(Plugin): \"\"\" Base class for option plugins \"\"\" # Default value, if", "s += '--%s.%s' % (folder_module, cls.option) if cls.cmd_argument is not None: s +=", "folder_module(cls): return cls.__module__.split('.')[-2] @classmethod def get_doc_line(cls): s = ' '*4 if cls.cmd_short is", "if cls.option is not None: folder_module = cls.folder_module() if folder_module == 'options': s", "= None # Short command line option cmd_short = None # Command line", "if folder_module == 'options': s += '--%s' % cls.option else: s += '--%s.%s'", "s += '--%s' % cls.option else: s += '--%s.%s' % (folder_module, cls.option) if" ]
[ "if not xstr or not ystr: return \"\" x, xs, y, ys =", "\"\"\" if not xstr or not ystr: return \"\" x, xs, y, ys", "not xstr or not ystr: return \"\" x, xs, y, ys = xstr[0],", "not ystr: return \"\" x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:]", "def lcs(xstr, ystr): \"\"\" lcs('thisisatest', 'testing123testing') 'tsitest' \"\"\" if not xstr or not", "x == y: return x + lcs(xs, ys) else: return max(lcs(xstr, ys), lcs(xs,", "xstr or not ystr: return \"\" x, xs, y, ys = xstr[0], xstr[1:],", "if x == y: return x + lcs(xs, ys) else: return max(lcs(xstr, ys),", "ystr[0], ystr[1:] if x == y: return x + lcs(xs, ys) else: return", "xstr[1:], ystr[0], ystr[1:] if x == y: return x + lcs(xs, ys) else:", "lcs(xstr, ystr): \"\"\" lcs('thisisatest', 'testing123testing') 'tsitest' \"\"\" if not xstr or not ystr:", "xstr[0], xstr[1:], ystr[0], ystr[1:] if x == y: return x + lcs(xs, ys)", "= xstr[0], xstr[1:], ystr[0], ystr[1:] if x == y: return x + lcs(xs,", "ystr[1:] if x == y: return x + lcs(xs, ys) else: return max(lcs(xstr,", "return \"\" x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:] if x", "ystr: return \"\" x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:] if", "ys = xstr[0], xstr[1:], ystr[0], ystr[1:] if x == y: return x +", "ystr): \"\"\" lcs('thisisatest', 'testing123testing') 'tsitest' \"\"\" if not xstr or not ystr: return", "xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:] if x == y: return", "\"\" x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:] if x ==", "lcs('thisisatest', 'testing123testing') 'tsitest' \"\"\" if not xstr or not ystr: return \"\" x,", "y: return x + lcs(xs, ys) else: return max(lcs(xstr, ys), lcs(xs, ystr), key=len)", "x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:] if x == y:", "'tsitest' \"\"\" if not xstr or not ystr: return \"\" x, xs, y,", "y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:] if x == y: return x", "== y: return x + lcs(xs, ys) else: return max(lcs(xstr, ys), lcs(xs, ystr),", "\"\"\" lcs('thisisatest', 'testing123testing') 'tsitest' \"\"\" if not xstr or not ystr: return \"\"", "or not ystr: return \"\" x, xs, y, ys = xstr[0], xstr[1:], ystr[0],", "<gh_stars>0 def lcs(xstr, ystr): \"\"\" lcs('thisisatest', 'testing123testing') 'tsitest' \"\"\" if not xstr or", "'testing123testing') 'tsitest' \"\"\" if not xstr or not ystr: return \"\" x, xs," ]
[ "import functionDetailGetter #fileLists = fileListGetter('../snippets/tmp-repo/') fileLists = fileListGetter('tmp-repo') for i in functionDetailGetter(fileLists): print", "os import shutil from pygit2 import clone_repository try: shutil.rmtree('tmp-repo') except: pass try: repo", "shutil.rmtree('tmp-repo') except: pass try: repo = clone_repository(input_var,'tmp-repo') except: pass from fileListGetter import fileListGetter", "from fileListGetter import fileListGetter from functionDetailGetter import functionDetailGetter #fileLists = fileListGetter('../snippets/tmp-repo/') fileLists =", "fileListGetter from functionDetailGetter import functionDetailGetter #fileLists = fileListGetter('../snippets/tmp-repo/') fileLists = fileListGetter('tmp-repo') for i", "clone_repository(input_var,'tmp-repo') except: pass from fileListGetter import fileListGetter from functionDetailGetter import functionDetailGetter #fileLists =", "import fileListGetter from functionDetailGetter import functionDetailGetter #fileLists = fileListGetter('../snippets/tmp-repo/') fileLists = fileListGetter('tmp-repo') for", "#input_var='https://github.com/softwaresaved/docandcover/' input_var='https://github.com/Axelrod-Python/Axelrod' import os import shutil from pygit2 import clone_repository try: shutil.rmtree('tmp-repo') except:", "from functionDetailGetter import functionDetailGetter #fileLists = fileListGetter('../snippets/tmp-repo/') fileLists = fileListGetter('tmp-repo') for i in", "import shutil from pygit2 import clone_repository try: shutil.rmtree('tmp-repo') except: pass try: repo =", "input_var='https://github.com/Axelrod-Python/Axelrod' import os import shutil from pygit2 import clone_repository try: shutil.rmtree('tmp-repo') except: pass", "functionDetailGetter #fileLists = fileListGetter('../snippets/tmp-repo/') fileLists = fileListGetter('tmp-repo') for i in functionDetailGetter(fileLists): print i", "import clone_repository try: shutil.rmtree('tmp-repo') except: pass try: repo = clone_repository(input_var,'tmp-repo') except: pass from", "from pygit2 import clone_repository try: shutil.rmtree('tmp-repo') except: pass try: repo = clone_repository(input_var,'tmp-repo') except:", "shutil from pygit2 import clone_repository try: shutil.rmtree('tmp-repo') except: pass try: repo = clone_repository(input_var,'tmp-repo')", "#fileLists = fileListGetter('../snippets/tmp-repo/') fileLists = fileListGetter('tmp-repo') for i in functionDetailGetter(fileLists): print i #printFileLists(fileLists)", "import os import shutil from pygit2 import clone_repository try: shutil.rmtree('tmp-repo') except: pass try:", "= clone_repository(input_var,'tmp-repo') except: pass from fileListGetter import fileListGetter from functionDetailGetter import functionDetailGetter #fileLists", "fileListGetter import fileListGetter from functionDetailGetter import functionDetailGetter #fileLists = fileListGetter('../snippets/tmp-repo/') fileLists = fileListGetter('tmp-repo')", "pass from fileListGetter import fileListGetter from functionDetailGetter import functionDetailGetter #fileLists = fileListGetter('../snippets/tmp-repo/') fileLists", "except: pass try: repo = clone_repository(input_var,'tmp-repo') except: pass from fileListGetter import fileListGetter from", "except: pass from fileListGetter import fileListGetter from functionDetailGetter import functionDetailGetter #fileLists = fileListGetter('../snippets/tmp-repo/')", "try: shutil.rmtree('tmp-repo') except: pass try: repo = clone_repository(input_var,'tmp-repo') except: pass from fileListGetter import", "repo = clone_repository(input_var,'tmp-repo') except: pass from fileListGetter import fileListGetter from functionDetailGetter import functionDetailGetter", "try: repo = clone_repository(input_var,'tmp-repo') except: pass from fileListGetter import fileListGetter from functionDetailGetter import", "pygit2 import clone_repository try: shutil.rmtree('tmp-repo') except: pass try: repo = clone_repository(input_var,'tmp-repo') except: pass", "pass try: repo = clone_repository(input_var,'tmp-repo') except: pass from fileListGetter import fileListGetter from functionDetailGetter", "clone_repository try: shutil.rmtree('tmp-repo') except: pass try: repo = clone_repository(input_var,'tmp-repo') except: pass from fileListGetter", "functionDetailGetter import functionDetailGetter #fileLists = fileListGetter('../snippets/tmp-repo/') fileLists = fileListGetter('tmp-repo') for i in functionDetailGetter(fileLists):" ]
[ "model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos',", "), migrations.AddField( model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/', verbose_name='Imagen'), ), migrations.AlterField( model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING,", "), migrations.AlterField( model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ), migrations.AlterField( model_name='galeriavideos', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL,", "name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ), migrations.AlterField( model_name='galeriavideos', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ), ]", "from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone", "[ ('galerias', '0002_auto_20190805_1410'), ] operations = [ migrations.AddField( model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ),", "= [ migrations.AddField( model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True), preserve_default=False,", "migrations.AddField( model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/', verbose_name='Imagen'),", "field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now),", "by Django 2.1.7 on 2019-08-06 16:38 import ckeditor_uploader.fields from django.conf import settings from", "django.utils.timezone import sorl.thumbnail.fields class Migration(migrations.Migration): dependencies = [ ('galerias', '0002_auto_20190805_1410'), ] operations =", "model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/', verbose_name='Imagen'), ), migrations.AlterField( model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'),", "name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='descripcion',", "settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import sorl.thumbnail.fields class", "] operations = [ migrations.AddField( model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='aprobado',", "model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='galeriavideos',", "import django.db.models.deletion import django.utils.timezone import sorl.thumbnail.fields class Migration(migrations.Migration): dependencies = [ ('galerias', '0002_auto_20190805_1410'),", "migrations.AddField( model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField(", "import sorl.thumbnail.fields class Migration(migrations.Migration): dependencies = [ ('galerias', '0002_auto_20190805_1410'), ] operations = [", "sorl.thumbnail.fields class Migration(migrations.Migration): dependencies = [ ('galerias', '0002_auto_20190805_1410'), ] operations = [ migrations.AddField(", "django.db import migrations, models import django.db.models.deletion import django.utils.timezone import sorl.thumbnail.fields class Migration(migrations.Migration): dependencies", "model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ), migrations.AlterField( model_name='galeriavideos', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ),", "name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/', verbose_name='Imagen'), ), migrations.AlterField( model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ),", "models import django.db.models.deletion import django.utils.timezone import sorl.thumbnail.fields class Migration(migrations.Migration): dependencies = [ ('galerias',", "), migrations.AddField( model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/',", "operations = [ migrations.AddField( model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True),", "django.db.models.deletion import django.utils.timezone import sorl.thumbnail.fields class Migration(migrations.Migration): dependencies = [ ('galerias', '0002_auto_20190805_1410'), ]", "preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/', verbose_name='Imagen'), ), migrations.AlterField( model_name='galeriaimagenes', name='usuario',", "# Generated by Django 2.1.7 on 2019-08-06 16:38 import ckeditor_uploader.fields from django.conf import", "Migration(migrations.Migration): dependencies = [ ('galerias', '0002_auto_20190805_1410'), ] operations = [ migrations.AddField( model_name='galeriaimagenes', name='aprobado',", "import migrations, models import django.db.models.deletion import django.utils.timezone import sorl.thumbnail.fields class Migration(migrations.Migration): dependencies =", "name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='portada',", "class Migration(migrations.Migration): dependencies = [ ('galerias', '0002_auto_20190805_1410'), ] operations = [ migrations.AddField( model_name='galeriaimagenes',", "'0002_auto_20190805_1410'), ] operations = [ migrations.AddField( model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos',", "Generated by Django 2.1.7 on 2019-08-06 16:38 import ckeditor_uploader.fields from django.conf import settings", "null=True, upload_to='galerias/', verbose_name='Imagen'), ), migrations.AlterField( model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ), migrations.AlterField( model_name='galeriavideos',", "2019-08-06 16:38 import ckeditor_uploader.fields from django.conf import settings from django.db import migrations, models", "Django 2.1.7 on 2019-08-06 16:38 import ckeditor_uploader.fields from django.conf import settings from django.db", "name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/', verbose_name='Imagen'), ), migrations.AlterField(", "2.1.7 on 2019-08-06 16:38 import ckeditor_uploader.fields from django.conf import settings from django.db import", "field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/', verbose_name='Imagen'), ), migrations.AlterField( model_name='galeriaimagenes',", "migrations.AlterField( model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ), migrations.AlterField( model_name='galeriavideos', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'),", "import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import sorl.thumbnail.fields", "field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True,", "import ckeditor_uploader.fields from django.conf import settings from django.db import migrations, models import django.db.models.deletion", "preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False,", "preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True,", "on 2019-08-06 16:38 import ckeditor_uploader.fields from django.conf import settings from django.db import migrations,", "('galerias', '0002_auto_20190805_1410'), ] operations = [ migrations.AddField( model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField(", "model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/', verbose_name='Imagen'), ),", "16:38 import ckeditor_uploader.fields from django.conf import settings from django.db import migrations, models import", "upload_to='galerias/', verbose_name='Imagen'), ), migrations.AlterField( model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ), migrations.AlterField( model_name='galeriavideos', name='usuario',", "ckeditor_uploader.fields from django.conf import settings from django.db import migrations, models import django.db.models.deletion import", "[ migrations.AddField( model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ),", "from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import sorl.thumbnail.fields class Migration(migrations.Migration):", "verbose_name='Imagen'), ), migrations.AlterField( model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ), migrations.AlterField( model_name='galeriavideos', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING,", "= [ ('galerias', '0002_auto_20190805_1410'), ] operations = [ migrations.AddField( model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True), preserve_default=False,", "field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/', verbose_name='Imagen'), ), migrations.AlterField( model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ), migrations.AlterField(", "migrations.AddField( model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField(", "migrations, models import django.db.models.deletion import django.utils.timezone import sorl.thumbnail.fields class Migration(migrations.Migration): dependencies = [", "dependencies = [ ('galerias', '0002_auto_20190805_1410'), ] operations = [ migrations.AddField( model_name='galeriaimagenes', name='aprobado', field=models.BooleanField(default=True),", "), migrations.AddField( model_name='galeriavideos', name='aprobado', field=models.BooleanField(default=True), preserve_default=False, ), migrations.AddField( model_name='galeriavideos', name='descripcion', field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now), preserve_default=False, ),", "migrations.AddField( model_name='galeriavideos', name='portada', field=sorl.thumbnail.fields.ImageField(blank=True, null=True, upload_to='galerias/', verbose_name='Imagen'), ), migrations.AlterField( model_name='galeriaimagenes', name='usuario', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL,", "import django.utils.timezone import sorl.thumbnail.fields class Migration(migrations.Migration): dependencies = [ ('galerias', '0002_auto_20190805_1410'), ] operations", "django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import" ]
[ "__all__ = ('json_schema', 'json_payload', 'JsonParser') P = TypeVar('P') def json_schema(schema: Union[Schema, Type[Schema]], cls:", "def location(self): return 'body' @property def media_type(self): return 'application/json' async def parse(self, request:", "ujson.loads(body) except (TypeError, ValueError) as e: raise DecodeError('Invalid json body') from e return", "json_payload(schema: Union[Schema, Type[Schema]], unknown=EXCLUDE) -> Type[Mapping]: return json_schema(schema, Mapping, unknown=unknown) class JsonParser(SchemaParser): __slots__", "'json_payload', 'JsonParser') P = TypeVar('P') def json_schema(schema: Union[Schema, Type[Schema]], cls: P, unknown: str", "'JsonParser') P = TypeVar('P') def json_schema(schema: Union[Schema, Type[Schema]], cls: P, unknown: str =", "P = TypeVar('P') def json_schema(schema: Union[Schema, Type[Schema]], cls: P, unknown: str = EXCLUDE)", "'body' @property def media_type(self): return 'application/json' async def parse(self, request: Request): body =", "except (TypeError, ValueError) as e: raise DecodeError('Invalid json body') from e return self.schema.load(data,", "class JsonParser(SchemaParser): __slots__ = () @property def location(self): return 'body' @property def media_type(self):", "starlette.requests import Request from star_resty.exceptions import DecodeError from .base import SchemaParser, set_parser __all__", "data = ujson.loads(body) except (TypeError, ValueError) as e: raise DecodeError('Invalid json body') from", "Type, TypeVar, Union import ujson from marshmallow import EXCLUDE, Schema from starlette.requests import", "from .base import SchemaParser, set_parser __all__ = ('json_schema', 'json_payload', 'JsonParser') P = TypeVar('P')", "await request.body() if body is None: data = {} else: try: data =", "exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def json_payload(schema: Union[Schema, Type[Schema]], unknown=EXCLUDE) -> Type[Mapping]: return json_schema(schema, Mapping, unknown=unknown)", "from star_resty.exceptions import DecodeError from .base import SchemaParser, set_parser __all__ = ('json_schema', 'json_payload',", "Mapping, Type, TypeVar, Union import ujson from marshmallow import EXCLUDE, Schema from starlette.requests", "return json_schema(schema, Mapping, unknown=unknown) class JsonParser(SchemaParser): __slots__ = () @property def location(self): return", "= EXCLUDE) -> P: return types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def json_payload(schema: Union[Schema, Type[Schema]],", "return 'application/json' async def parse(self, request: Request): body = await request.body() if body", "unknown=unknown))) def json_payload(schema: Union[Schema, Type[Schema]], unknown=EXCLUDE) -> Type[Mapping]: return json_schema(schema, Mapping, unknown=unknown) class", "(cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def json_payload(schema: Union[Schema, Type[Schema]], unknown=EXCLUDE) -> Type[Mapping]: return json_schema(schema, Mapping,", "else: try: data = ujson.loads(body) except (TypeError, ValueError) as e: raise DecodeError('Invalid json", "async def parse(self, request: Request): body = await request.body() if body is None:", "Request from star_resty.exceptions import DecodeError from .base import SchemaParser, set_parser __all__ = ('json_schema',", "import ujson from marshmallow import EXCLUDE, Schema from starlette.requests import Request from star_resty.exceptions", "import Mapping, Type, TypeVar, Union import ujson from marshmallow import EXCLUDE, Schema from", "if body is None: data = {} else: try: data = ujson.loads(body) except", "SchemaParser, set_parser __all__ = ('json_schema', 'json_payload', 'JsonParser') P = TypeVar('P') def json_schema(schema: Union[Schema,", "typing import Mapping, Type, TypeVar, Union import ujson from marshmallow import EXCLUDE, Schema", "from starlette.requests import Request from star_resty.exceptions import DecodeError from .base import SchemaParser, set_parser", "= TypeVar('P') def json_schema(schema: Union[Schema, Type[Schema]], cls: P, unknown: str = EXCLUDE) ->", "body = await request.body() if body is None: data = {} else: try:", "marshmallow import EXCLUDE, Schema from starlette.requests import Request from star_resty.exceptions import DecodeError from", "json_schema(schema, Mapping, unknown=unknown) class JsonParser(SchemaParser): __slots__ = () @property def location(self): return 'body'", "-> P: return types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def json_payload(schema: Union[Schema, Type[Schema]], unknown=EXCLUDE) ->", "Union import ujson from marshmallow import EXCLUDE, Schema from starlette.requests import Request from", "set_parser __all__ = ('json_schema', 'json_payload', 'JsonParser') P = TypeVar('P') def json_schema(schema: Union[Schema, Type[Schema]],", "Union[Schema, Type[Schema]], cls: P, unknown: str = EXCLUDE) -> P: return types.new_class('JsonInputParams', (cls,),", "media_type(self): return 'application/json' async def parse(self, request: Request): body = await request.body() if", "from typing import Mapping, Type, TypeVar, Union import ujson from marshmallow import EXCLUDE,", "<gh_stars>1-10 import types from typing import Mapping, Type, TypeVar, Union import ujson from", "return 'body' @property def media_type(self): return 'application/json' async def parse(self, request: Request): body", "P: return types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def json_payload(schema: Union[Schema, Type[Schema]], unknown=EXCLUDE) -> Type[Mapping]:", "None: data = {} else: try: data = ujson.loads(body) except (TypeError, ValueError) as", "request: Request): body = await request.body() if body is None: data = {}", "Request): body = await request.body() if body is None: data = {} else:", "location(self): return 'body' @property def media_type(self): return 'application/json' async def parse(self, request: Request):", "DecodeError from .base import SchemaParser, set_parser __all__ = ('json_schema', 'json_payload', 'JsonParser') P =", "def json_schema(schema: Union[Schema, Type[Schema]], cls: P, unknown: str = EXCLUDE) -> P: return", "TypeVar, Union import ujson from marshmallow import EXCLUDE, Schema from starlette.requests import Request", "unknown=unknown) class JsonParser(SchemaParser): __slots__ = () @property def location(self): return 'body' @property def", "= {} else: try: data = ujson.loads(body) except (TypeError, ValueError) as e: raise", "Union[Schema, Type[Schema]], unknown=EXCLUDE) -> Type[Mapping]: return json_schema(schema, Mapping, unknown=unknown) class JsonParser(SchemaParser): __slots__ =", "Schema from starlette.requests import Request from star_resty.exceptions import DecodeError from .base import SchemaParser,", "Type[Schema]], unknown=EXCLUDE) -> Type[Mapping]: return json_schema(schema, Mapping, unknown=unknown) class JsonParser(SchemaParser): __slots__ = ()", ".base import SchemaParser, set_parser __all__ = ('json_schema', 'json_payload', 'JsonParser') P = TypeVar('P') def", "ujson from marshmallow import EXCLUDE, Schema from starlette.requests import Request from star_resty.exceptions import", "EXCLUDE, Schema from starlette.requests import Request from star_resty.exceptions import DecodeError from .base import", "import types from typing import Mapping, Type, TypeVar, Union import ujson from marshmallow", "cls: P, unknown: str = EXCLUDE) -> P: return types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown)))", "unknown: str = EXCLUDE) -> P: return types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def json_payload(schema:", "-> Type[Mapping]: return json_schema(schema, Mapping, unknown=unknown) class JsonParser(SchemaParser): __slots__ = () @property def", "P, unknown: str = EXCLUDE) -> P: return types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def", "JsonParser(SchemaParser): __slots__ = () @property def location(self): return 'body' @property def media_type(self): return", "{} else: try: data = ujson.loads(body) except (TypeError, ValueError) as e: raise DecodeError('Invalid", "is None: data = {} else: try: data = ujson.loads(body) except (TypeError, ValueError)", "('json_schema', 'json_payload', 'JsonParser') P = TypeVar('P') def json_schema(schema: Union[Schema, Type[Schema]], cls: P, unknown:", "import EXCLUDE, Schema from starlette.requests import Request from star_resty.exceptions import DecodeError from .base", "def media_type(self): return 'application/json' async def parse(self, request: Request): body = await request.body()", "from marshmallow import EXCLUDE, Schema from starlette.requests import Request from star_resty.exceptions import DecodeError", "Mapping, unknown=unknown) class JsonParser(SchemaParser): __slots__ = () @property def location(self): return 'body' @property", "body is None: data = {} else: try: data = ujson.loads(body) except (TypeError,", "'application/json' async def parse(self, request: Request): body = await request.body() if body is", "def parse(self, request: Request): body = await request.body() if body is None: data", "() @property def location(self): return 'body' @property def media_type(self): return 'application/json' async def", "data = {} else: try: data = ujson.loads(body) except (TypeError, ValueError) as e:", "@property def location(self): return 'body' @property def media_type(self): return 'application/json' async def parse(self,", "return types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def json_payload(schema: Union[Schema, Type[Schema]], unknown=EXCLUDE) -> Type[Mapping]: return", "= () @property def location(self): return 'body' @property def media_type(self): return 'application/json' async", "= await request.body() if body is None: data = {} else: try: data", "json_schema(schema: Union[Schema, Type[Schema]], cls: P, unknown: str = EXCLUDE) -> P: return types.new_class('JsonInputParams',", "request.body() if body is None: data = {} else: try: data = ujson.loads(body)", "str = EXCLUDE) -> P: return types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def json_payload(schema: Union[Schema,", "__slots__ = () @property def location(self): return 'body' @property def media_type(self): return 'application/json'", "= ujson.loads(body) except (TypeError, ValueError) as e: raise DecodeError('Invalid json body') from e", "@property def media_type(self): return 'application/json' async def parse(self, request: Request): body = await", "= ('json_schema', 'json_payload', 'JsonParser') P = TypeVar('P') def json_schema(schema: Union[Schema, Type[Schema]], cls: P,", "types from typing import Mapping, Type, TypeVar, Union import ujson from marshmallow import", "Type[Schema]], cls: P, unknown: str = EXCLUDE) -> P: return types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema,", "types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def json_payload(schema: Union[Schema, Type[Schema]], unknown=EXCLUDE) -> Type[Mapping]: return json_schema(schema,", "def json_payload(schema: Union[Schema, Type[Schema]], unknown=EXCLUDE) -> Type[Mapping]: return json_schema(schema, Mapping, unknown=unknown) class JsonParser(SchemaParser):", "import Request from star_resty.exceptions import DecodeError from .base import SchemaParser, set_parser __all__ =", "import DecodeError from .base import SchemaParser, set_parser __all__ = ('json_schema', 'json_payload', 'JsonParser') P", "unknown=EXCLUDE) -> Type[Mapping]: return json_schema(schema, Mapping, unknown=unknown) class JsonParser(SchemaParser): __slots__ = () @property", "star_resty.exceptions import DecodeError from .base import SchemaParser, set_parser __all__ = ('json_schema', 'json_payload', 'JsonParser')", "(TypeError, ValueError) as e: raise DecodeError('Invalid json body') from e return self.schema.load(data, unknown=self.unknown)", "EXCLUDE) -> P: return types.new_class('JsonInputParams', (cls,), exec_body=set_parser(JsonParser.create(schema, unknown=unknown))) def json_payload(schema: Union[Schema, Type[Schema]], unknown=EXCLUDE)", "Type[Mapping]: return json_schema(schema, Mapping, unknown=unknown) class JsonParser(SchemaParser): __slots__ = () @property def location(self):", "try: data = ujson.loads(body) except (TypeError, ValueError) as e: raise DecodeError('Invalid json body')", "import SchemaParser, set_parser __all__ = ('json_schema', 'json_payload', 'JsonParser') P = TypeVar('P') def json_schema(schema:", "parse(self, request: Request): body = await request.body() if body is None: data =", "TypeVar('P') def json_schema(schema: Union[Schema, Type[Schema]], cls: P, unknown: str = EXCLUDE) -> P:" ]
[ "by an application. Instead of relying on subclasses it creates objects by copying", "def __init__(self, value: str = \"default\", **attrs: Any) -> None: self.value = value", "def clone(self, **attrs: Any) -> None: \"\"\"Clone a prototype and update inner attributes", "-> Dict[str, Prototype]: \"\"\"Get all objects\"\"\" return self._objects def register_object(self, name: str, obj:", "an object\"\"\" self._objects[name] = obj def unregister_object(self, name: str) -> None: \"\"\"Unregister an", "aims to reduce the number of classes required by an application. Instead of", "None: \"\"\" >>> dispatcher = PrototypeDispatcher() >>> prototype = Prototype() >>> d =", "application can vary, it can be useful to keep a Dispatcher (aka, Registry", "= prototype.clone() >>> a = prototype.clone(value='a-value', category='a') >>> b = a.clone(value='b-value', is_checked=True) >>>", "is_checked=True) >>> dispatcher.register_object('objecta', a) >>> dispatcher.register_object('objectb', b) >>> dispatcher.register_object('default', d) >>> [{n: p.value}", "and when instantiation is expensive. *What does this example do? When the number", ">>> a = prototype.clone(value='a-value', category='a') >>> b = a.clone(value='b-value', is_checked=True) >>> dispatcher.register_object('objecta', a)", "cloning prototype. \"\"\" from typing import Any, Dict class Prototype: def __init__(self, value:", "Registry or Manager). This allows clients to query the Dispatcher for a prototype", "about? This patterns aims to reduce the number of classes required by an", "few different combinations of state, and when instantiation is expensive. *What does this", "in dispatcher.get_objects().items()] [{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}] >>> print(b.category, b.is_checked) a True", "pattern about? This patterns aims to reduce the number of classes required by", "to derive new kinds of objects, when instances of the class have only", "def unregister_object(self, name: str) -> None: \"\"\"Unregister an object\"\"\" del self._objects[name] def main()", "name: str) -> None: \"\"\"Unregister an object\"\"\" del self._objects[name] def main() -> None:", "an application can vary, it can be useful to keep a Dispatcher (aka,", "new kinds of objects, when instances of the class have only a few", "the class have only a few different combinations of state, and when instantiation", "copying a prototypical instance at run-time. This is useful as it makes it", "derive new kinds of objects, when instances of the class have only a", "# Python in Practice, <NAME>field # copy.deepcopy can be used instead of next", "for n, p in dispatcher.get_objects().items()] [{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}] >>> print(b.category,", "on subclasses it creates objects by copying a prototypical instance at run-time. This", "self.value = value self.__dict__.update(attrs) def clone(self, **attrs: Any) -> None: \"\"\"Clone a prototype", "= {} def get_objects(self) -> Dict[str, Prototype]: \"\"\"Get all objects\"\"\" return self._objects def", "Dispatcher for a prototype before cloning a new instance. Below provides an example", "None: \"\"\"Clone a prototype and update inner attributes dictionary\"\"\" # Python in Practice,", "this example do? When the number of prototypes in an application can vary,", "before cloning a new instance. Below provides an example of such Dispatcher, which", "next line. obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class PrototypeDispatcher: def __init__(self): self._objects", "class PrototypeDispatcher: def __init__(self): self._objects = {} def get_objects(self) -> Dict[str, Prototype]: \"\"\"Get", ">>> dispatcher.register_object('objecta', a) >>> dispatcher.register_object('objectb', b) >>> dispatcher.register_object('default', d) >>> [{n: p.value} for", "{'objectb': 'b-value'}, {'default': 'default'}] >>> print(b.category, b.is_checked) a True \"\"\" if __name__ ==", "copies of the prototype: 'default', 'objecta' and 'objectb'. *TL;DR Creates new object instances", "for a prototype before cloning a new instance. Below provides an example of", "useful as it makes it easier to derive new kinds of objects, when", "Dict[str, Prototype]: \"\"\"Get all objects\"\"\" return self._objects def register_object(self, name: str, obj: Prototype)", "obj def unregister_object(self, name: str) -> None: \"\"\"Unregister an object\"\"\" del self._objects[name] def", "dispatcher = PrototypeDispatcher() >>> prototype = Prototype() >>> d = prototype.clone() >>> a", "value: str = \"default\", **attrs: Any) -> None: self.value = value self.__dict__.update(attrs) def", "-> None: \"\"\"Clone a prototype and update inner attributes dictionary\"\"\" # Python in", "None: \"\"\"Register an object\"\"\" self._objects[name] = obj def unregister_object(self, name: str) -> None:", "clients to query the Dispatcher for a prototype before cloning a new instance.", "prototype. \"\"\" from typing import Any, Dict class Prototype: def __init__(self, value: str", "None: \"\"\"Unregister an object\"\"\" del self._objects[name] def main() -> None: \"\"\" >>> dispatcher", "Any) -> None: self.value = value self.__dict__.update(attrs) def clone(self, **attrs: Any) -> None:", ">>> dispatcher = PrototypeDispatcher() >>> prototype = Prototype() >>> d = prototype.clone() >>>", "at run-time. This is useful as it makes it easier to derive new", "p in dispatcher.get_objects().items()] [{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}] >>> print(b.category, b.is_checked) a", "allows clients to query the Dispatcher for a prototype before cloning a new", "main() -> None: \"\"\" >>> dispatcher = PrototypeDispatcher() >>> prototype = Prototype() >>>", "object\"\"\" self._objects[name] = obj def unregister_object(self, name: str) -> None: \"\"\"Unregister an object\"\"\"", "required by an application. Instead of relying on subclasses it creates objects by", "easier to derive new kinds of objects, when instances of the class have", "relying on subclasses it creates objects by copying a prototypical instance at run-time.", "'objecta' and 'objectb'. *TL;DR Creates new object instances by cloning prototype. \"\"\" from", "dictionary\"\"\" # Python in Practice, <NAME>field # copy.deepcopy can be used instead of", "attributes dictionary\"\"\" # Python in Practice, <NAME>field # copy.deepcopy can be used instead", "objects by copying a prototypical instance at run-time. This is useful as it", "(aka, Registry or Manager). This allows clients to query the Dispatcher for a", "obj class PrototypeDispatcher: def __init__(self): self._objects = {} def get_objects(self) -> Dict[str, Prototype]:", "it makes it easier to derive new kinds of objects, when instances of", "copy.deepcopy can be used instead of next line. obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return", "obj.__dict__.update(attrs) return obj class PrototypeDispatcher: def __init__(self): self._objects = {} def get_objects(self) ->", "= a.clone(value='b-value', is_checked=True) >>> dispatcher.register_object('objecta', a) >>> dispatcher.register_object('objectb', b) >>> dispatcher.register_object('default', d) >>>", "dispatcher.register_object('objecta', a) >>> dispatcher.register_object('objectb', b) >>> dispatcher.register_object('default', d) >>> [{n: p.value} for n,", "def __init__(self): self._objects = {} def get_objects(self) -> Dict[str, Prototype]: \"\"\"Get all objects\"\"\"", "such Dispatcher, which contains three copies of the prototype: 'default', 'objecta' and 'objectb'.", "def get_objects(self) -> Dict[str, Prototype]: \"\"\"Get all objects\"\"\" return self._objects def register_object(self, name:", "of relying on subclasses it creates objects by copying a prototypical instance at", "Instead of relying on subclasses it creates objects by copying a prototypical instance", "typing import Any, Dict class Prototype: def __init__(self, value: str = \"default\", **attrs:", "prototype.clone(value='a-value', category='a') >>> b = a.clone(value='b-value', is_checked=True) >>> dispatcher.register_object('objecta', a) >>> dispatcher.register_object('objectb', b)", "a Dispatcher (aka, Registry or Manager). This allows clients to query the Dispatcher", "of prototypes in an application can vary, it can be useful to keep", "prototypical instance at run-time. This is useful as it makes it easier to", "or Manager). This allows clients to query the Dispatcher for a prototype before", "[{n: p.value} for n, p in dispatcher.get_objects().items()] [{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}]", "kinds of objects, when instances of the class have only a few different", "of objects, when instances of the class have only a few different combinations", "Python in Practice, <NAME>field # copy.deepcopy can be used instead of next line.", "objects, when instances of the class have only a few different combinations of", "an example of such Dispatcher, which contains three copies of the prototype: 'default',", "is this pattern about? This patterns aims to reduce the number of classes", "vary, it can be useful to keep a Dispatcher (aka, Registry or Manager).", "def register_object(self, name: str, obj: Prototype) -> None: \"\"\"Register an object\"\"\" self._objects[name] =", "be used instead of next line. obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class", "'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}] >>> print(b.category, b.is_checked) a True \"\"\" if __name__", "PrototypeDispatcher() >>> prototype = Prototype() >>> d = prototype.clone() >>> a = prototype.clone(value='a-value',", "b) >>> dispatcher.register_object('default', d) >>> [{n: p.value} for n, p in dispatcher.get_objects().items()] [{'objecta':", "it can be useful to keep a Dispatcher (aka, Registry or Manager). This", "is useful as it makes it easier to derive new kinds of objects,", "prototypes in an application can vary, it can be useful to keep a", "str) -> None: \"\"\"Unregister an object\"\"\" del self._objects[name] def main() -> None: \"\"\"", "query the Dispatcher for a prototype before cloning a new instance. Below provides", "Any) -> None: \"\"\"Clone a prototype and update inner attributes dictionary\"\"\" # Python", "an object\"\"\" del self._objects[name] def main() -> None: \"\"\" >>> dispatcher = PrototypeDispatcher()", "'b-value'}, {'default': 'default'}] >>> print(b.category, b.is_checked) a True \"\"\" if __name__ == \"__main__\":", "keep a Dispatcher (aka, Registry or Manager). This allows clients to query the", "__init__(self, value: str = \"default\", **attrs: Any) -> None: self.value = value self.__dict__.update(attrs)", "prototype: 'default', 'objecta' and 'objectb'. *TL;DR Creates new object instances by cloning prototype.", "instances of the class have only a few different combinations of state, and", "number of prototypes in an application can vary, it can be useful to", "a few different combinations of state, and when instantiation is expensive. *What does", "prototype = Prototype() >>> d = prototype.clone() >>> a = prototype.clone(value='a-value', category='a') >>>", "which contains three copies of the prototype: 'default', 'objecta' and 'objectb'. *TL;DR Creates", ">>> d = prototype.clone() >>> a = prototype.clone(value='a-value', category='a') >>> b = a.clone(value='b-value',", "when instances of the class have only a few different combinations of state,", "be useful to keep a Dispatcher (aka, Registry or Manager). This allows clients", "inner attributes dictionary\"\"\" # Python in Practice, <NAME>field # copy.deepcopy can be used", "Practice, <NAME>field # copy.deepcopy can be used instead of next line. obj =", "can be used instead of next line. obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj", "-> None: \"\"\"Register an object\"\"\" self._objects[name] = obj def unregister_object(self, name: str) ->", "n, p in dispatcher.get_objects().items()] [{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}] >>> print(b.category, b.is_checked)", ">>> dispatcher.register_object('default', d) >>> [{n: p.value} for n, p in dispatcher.get_objects().items()] [{'objecta': 'a-value'},", "new object instances by cloning prototype. \"\"\" from typing import Any, Dict class", "unregister_object(self, name: str) -> None: \"\"\"Unregister an object\"\"\" del self._objects[name] def main() ->", "category='a') >>> b = a.clone(value='b-value', is_checked=True) >>> dispatcher.register_object('objecta', a) >>> dispatcher.register_object('objectb', b) >>>", "= obj def unregister_object(self, name: str) -> None: \"\"\"Unregister an object\"\"\" del self._objects[name]", "expensive. *What does this example do? When the number of prototypes in an", "in Practice, <NAME>field # copy.deepcopy can be used instead of next line. obj", "a = prototype.clone(value='a-value', category='a') >>> b = a.clone(value='b-value', is_checked=True) >>> dispatcher.register_object('objecta', a) >>>", "a) >>> dispatcher.register_object('objectb', b) >>> dispatcher.register_object('default', d) >>> [{n: p.value} for n, p", "application. Instead of relying on subclasses it creates objects by copying a prototypical", "p.value} for n, p in dispatcher.get_objects().items()] [{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}] >>>", "different combinations of state, and when instantiation is expensive. *What does this example", "\"\"\"Register an object\"\"\" self._objects[name] = obj def unregister_object(self, name: str) -> None: \"\"\"Unregister", "patterns aims to reduce the number of classes required by an application. Instead", "class have only a few different combinations of state, and when instantiation is", "-> None: \"\"\"Unregister an object\"\"\" del self._objects[name] def main() -> None: \"\"\" >>>", "This is useful as it makes it easier to derive new kinds of", "d) >>> [{n: p.value} for n, p in dispatcher.get_objects().items()] [{'objecta': 'a-value'}, {'objectb': 'b-value'},", "name: str, obj: Prototype) -> None: \"\"\"Register an object\"\"\" self._objects[name] = obj def", "when instantiation is expensive. *What does this example do? When the number of", "of classes required by an application. Instead of relying on subclasses it creates", "# copy.deepcopy can be used instead of next line. obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs)", "= self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class PrototypeDispatcher: def __init__(self): self._objects = {} def", "a new instance. Below provides an example of such Dispatcher, which contains three", "have only a few different combinations of state, and when instantiation is expensive.", "all objects\"\"\" return self._objects def register_object(self, name: str, obj: Prototype) -> None: \"\"\"Register", "Dispatcher, which contains three copies of the prototype: 'default', 'objecta' and 'objectb'. *TL;DR", ">>> dispatcher.register_object('objectb', b) >>> dispatcher.register_object('default', d) >>> [{n: p.value} for n, p in", "\"\"\" from typing import Any, Dict class Prototype: def __init__(self, value: str =", "by copying a prototypical instance at run-time. This is useful as it makes", "object\"\"\" del self._objects[name] def main() -> None: \"\"\" >>> dispatcher = PrototypeDispatcher() >>>", "<reponame>eengineergz/Lambda \"\"\" *What is this pattern about? This patterns aims to reduce the", "dispatcher.register_object('objectb', b) >>> dispatcher.register_object('default', d) >>> [{n: p.value} for n, p in dispatcher.get_objects().items()]", "state, and when instantiation is expensive. *What does this example do? When the", "value self.__dict__.update(attrs) def clone(self, **attrs: Any) -> None: \"\"\"Clone a prototype and update", "**attrs: Any) -> None: \"\"\"Clone a prototype and update inner attributes dictionary\"\"\" #", ">>> [{n: p.value} for n, p in dispatcher.get_objects().items()] [{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default':", "'objectb'. *TL;DR Creates new object instances by cloning prototype. \"\"\" from typing import", "example do? When the number of prototypes in an application can vary, it", "the number of prototypes in an application can vary, it can be useful", "import Any, Dict class Prototype: def __init__(self, value: str = \"default\", **attrs: Any)", "Prototype) -> None: \"\"\"Register an object\"\"\" self._objects[name] = obj def unregister_object(self, name: str)", "self._objects def register_object(self, name: str, obj: Prototype) -> None: \"\"\"Register an object\"\"\" self._objects[name]", "prototype before cloning a new instance. Below provides an example of such Dispatcher,", "*What is this pattern about? This patterns aims to reduce the number of", "an application. Instead of relying on subclasses it creates objects by copying a", "*What does this example do? When the number of prototypes in an application", "Dict class Prototype: def __init__(self, value: str = \"default\", **attrs: Any) -> None:", "<NAME>field # copy.deepcopy can be used instead of next line. obj = self.__class__(**self.__dict__)", "of the class have only a few different combinations of state, and when", "get_objects(self) -> Dict[str, Prototype]: \"\"\"Get all objects\"\"\" return self._objects def register_object(self, name: str,", "subclasses it creates objects by copying a prototypical instance at run-time. This is", "def main() -> None: \"\"\" >>> dispatcher = PrototypeDispatcher() >>> prototype = Prototype()", "b = a.clone(value='b-value', is_checked=True) >>> dispatcher.register_object('objecta', a) >>> dispatcher.register_object('objectb', b) >>> dispatcher.register_object('default', d)", "instance. Below provides an example of such Dispatcher, which contains three copies of", "self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class PrototypeDispatcher: def __init__(self): self._objects = {} def get_objects(self)", "Any, Dict class Prototype: def __init__(self, value: str = \"default\", **attrs: Any) ->", "a prototype and update inner attributes dictionary\"\"\" # Python in Practice, <NAME>field #", "= \"default\", **attrs: Any) -> None: self.value = value self.__dict__.update(attrs) def clone(self, **attrs:", "to query the Dispatcher for a prototype before cloning a new instance. Below", "dispatcher.get_objects().items()] [{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}] >>> print(b.category, b.is_checked) a True \"\"\"", "to reduce the number of classes required by an application. Instead of relying", "can vary, it can be useful to keep a Dispatcher (aka, Registry or", "reduce the number of classes required by an application. Instead of relying on", "classes required by an application. Instead of relying on subclasses it creates objects", "\"\"\" *What is this pattern about? This patterns aims to reduce the number", "This patterns aims to reduce the number of classes required by an application.", "only a few different combinations of state, and when instantiation is expensive. *What", "Manager). This allows clients to query the Dispatcher for a prototype before cloning", "this pattern about? This patterns aims to reduce the number of classes required", "Below provides an example of such Dispatcher, which contains three copies of the", "*TL;DR Creates new object instances by cloning prototype. \"\"\" from typing import Any,", "by cloning prototype. \"\"\" from typing import Any, Dict class Prototype: def __init__(self,", "obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class PrototypeDispatcher: def __init__(self): self._objects = {}", "in an application can vary, it can be useful to keep a Dispatcher", "__init__(self): self._objects = {} def get_objects(self) -> Dict[str, Prototype]: \"\"\"Get all objects\"\"\" return", "the number of classes required by an application. Instead of relying on subclasses", "three copies of the prototype: 'default', 'objecta' and 'objectb'. *TL;DR Creates new object", "line. obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class PrototypeDispatcher: def __init__(self): self._objects =", "{'default': 'default'}] >>> print(b.category, b.is_checked) a True \"\"\" if __name__ == \"__main__\": import", "\"\"\"Clone a prototype and update inner attributes dictionary\"\"\" # Python in Practice, <NAME>field", "None: self.value = value self.__dict__.update(attrs) def clone(self, **attrs: Any) -> None: \"\"\"Clone a", "objects\"\"\" return self._objects def register_object(self, name: str, obj: Prototype) -> None: \"\"\"Register an", "= PrototypeDispatcher() >>> prototype = Prototype() >>> d = prototype.clone() >>> a =", "instance at run-time. This is useful as it makes it easier to derive", ">>> print(b.category, b.is_checked) a True \"\"\" if __name__ == \"__main__\": import doctest doctest.testmod()", "Prototype: def __init__(self, value: str = \"default\", **attrs: Any) -> None: self.value =", "Prototype() >>> d = prototype.clone() >>> a = prototype.clone(value='a-value', category='a') >>> b =", "register_object(self, name: str, obj: Prototype) -> None: \"\"\"Register an object\"\"\" self._objects[name] = obj", "cloning a new instance. Below provides an example of such Dispatcher, which contains", "prototype and update inner attributes dictionary\"\"\" # Python in Practice, <NAME>field # copy.deepcopy", "as it makes it easier to derive new kinds of objects, when instances", "makes it easier to derive new kinds of objects, when instances of the", "from typing import Any, Dict class Prototype: def __init__(self, value: str = \"default\",", "\"\"\" >>> dispatcher = PrototypeDispatcher() >>> prototype = Prototype() >>> d = prototype.clone()", "self._objects = {} def get_objects(self) -> Dict[str, Prototype]: \"\"\"Get all objects\"\"\" return self._objects", "the Dispatcher for a prototype before cloning a new instance. Below provides an", "number of classes required by an application. Instead of relying on subclasses it", "and 'objectb'. *TL;DR Creates new object instances by cloning prototype. \"\"\" from typing", "PrototypeDispatcher: def __init__(self): self._objects = {} def get_objects(self) -> Dict[str, Prototype]: \"\"\"Get all", "example of such Dispatcher, which contains three copies of the prototype: 'default', 'objecta'", "\"\"\"Get all objects\"\"\" return self._objects def register_object(self, name: str, obj: Prototype) -> None:", "\"\"\"Unregister an object\"\"\" del self._objects[name] def main() -> None: \"\"\" >>> dispatcher =", "str, obj: Prototype) -> None: \"\"\"Register an object\"\"\" self._objects[name] = obj def unregister_object(self,", "to keep a Dispatcher (aka, Registry or Manager). This allows clients to query", "self._objects[name] = obj def unregister_object(self, name: str) -> None: \"\"\"Unregister an object\"\"\" del", "provides an example of such Dispatcher, which contains three copies of the prototype:", "= Prototype() >>> d = prototype.clone() >>> a = prototype.clone(value='a-value', category='a') >>> b", "new instance. Below provides an example of such Dispatcher, which contains three copies", "a.clone(value='b-value', is_checked=True) >>> dispatcher.register_object('objecta', a) >>> dispatcher.register_object('objectb', b) >>> dispatcher.register_object('default', d) >>> [{n:", "= prototype.clone(value='a-value', category='a') >>> b = a.clone(value='b-value', is_checked=True) >>> dispatcher.register_object('objecta', a) >>> dispatcher.register_object('objectb',", "-> None: self.value = value self.__dict__.update(attrs) def clone(self, **attrs: Any) -> None: \"\"\"Clone", "class Prototype: def __init__(self, value: str = \"default\", **attrs: Any) -> None: self.value", "str = \"default\", **attrs: Any) -> None: self.value = value self.__dict__.update(attrs) def clone(self,", "and update inner attributes dictionary\"\"\" # Python in Practice, <NAME>field # copy.deepcopy can", "dispatcher.register_object('default', d) >>> [{n: p.value} for n, p in dispatcher.get_objects().items()] [{'objecta': 'a-value'}, {'objectb':", "When the number of prototypes in an application can vary, it can be", "a prototypical instance at run-time. This is useful as it makes it easier", "object instances by cloning prototype. \"\"\" from typing import Any, Dict class Prototype:", "useful to keep a Dispatcher (aka, Registry or Manager). This allows clients to", "does this example do? When the number of prototypes in an application can", "instances by cloning prototype. \"\"\" from typing import Any, Dict class Prototype: def", "of next line. obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class PrototypeDispatcher: def __init__(self):", "of such Dispatcher, which contains three copies of the prototype: 'default', 'objecta' and", "obj: Prototype) -> None: \"\"\"Register an object\"\"\" self._objects[name] = obj def unregister_object(self, name:", "d = prototype.clone() >>> a = prototype.clone(value='a-value', category='a') >>> b = a.clone(value='b-value', is_checked=True)", "it creates objects by copying a prototypical instance at run-time. This is useful", "'default'}] >>> print(b.category, b.is_checked) a True \"\"\" if __name__ == \"__main__\": import doctest", "of the prototype: 'default', 'objecta' and 'objectb'. *TL;DR Creates new object instances by", "{} def get_objects(self) -> Dict[str, Prototype]: \"\"\"Get all objects\"\"\" return self._objects def register_object(self,", "This allows clients to query the Dispatcher for a prototype before cloning a", "the prototype: 'default', 'objecta' and 'objectb'. *TL;DR Creates new object instances by cloning", "can be useful to keep a Dispatcher (aka, Registry or Manager). This allows", "self.__dict__.update(attrs) def clone(self, **attrs: Any) -> None: \"\"\"Clone a prototype and update inner", "Prototype]: \"\"\"Get all objects\"\"\" return self._objects def register_object(self, name: str, obj: Prototype) ->", "instantiation is expensive. *What does this example do? When the number of prototypes", "do? When the number of prototypes in an application can vary, it can", "a prototype before cloning a new instance. Below provides an example of such", "-> None: \"\"\" >>> dispatcher = PrototypeDispatcher() >>> prototype = Prototype() >>> d", "= value self.__dict__.update(attrs) def clone(self, **attrs: Any) -> None: \"\"\"Clone a prototype and", "of state, and when instantiation is expensive. *What does this example do? When", "contains three copies of the prototype: 'default', 'objecta' and 'objectb'. *TL;DR Creates new", "del self._objects[name] def main() -> None: \"\"\" >>> dispatcher = PrototypeDispatcher() >>> prototype", "clone(self, **attrs: Any) -> None: \"\"\"Clone a prototype and update inner attributes dictionary\"\"\"", "\"default\", **attrs: Any) -> None: self.value = value self.__dict__.update(attrs) def clone(self, **attrs: Any)", "combinations of state, and when instantiation is expensive. *What does this example do?", "[{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}] >>> print(b.category, b.is_checked) a True \"\"\" if", "creates objects by copying a prototypical instance at run-time. This is useful as", ">>> b = a.clone(value='b-value', is_checked=True) >>> dispatcher.register_object('objecta', a) >>> dispatcher.register_object('objectb', b) >>> dispatcher.register_object('default',", "Dispatcher (aka, Registry or Manager). This allows clients to query the Dispatcher for", "update inner attributes dictionary\"\"\" # Python in Practice, <NAME>field # copy.deepcopy can be", "return obj class PrototypeDispatcher: def __init__(self): self._objects = {} def get_objects(self) -> Dict[str,", "run-time. This is useful as it makes it easier to derive new kinds", "self._objects[name] def main() -> None: \"\"\" >>> dispatcher = PrototypeDispatcher() >>> prototype =", ">>> prototype = Prototype() >>> d = prototype.clone() >>> a = prototype.clone(value='a-value', category='a')", "it easier to derive new kinds of objects, when instances of the class", "return self._objects def register_object(self, name: str, obj: Prototype) -> None: \"\"\"Register an object\"\"\"", "instead of next line. obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class PrototypeDispatcher: def", "prototype.clone() >>> a = prototype.clone(value='a-value', category='a') >>> b = a.clone(value='b-value', is_checked=True) >>> dispatcher.register_object('objecta',", "Creates new object instances by cloning prototype. \"\"\" from typing import Any, Dict", "**attrs: Any) -> None: self.value = value self.__dict__.update(attrs) def clone(self, **attrs: Any) ->", "used instead of next line. obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class PrototypeDispatcher:", "is expensive. *What does this example do? When the number of prototypes in", "'default', 'objecta' and 'objectb'. *TL;DR Creates new object instances by cloning prototype. \"\"\"" ]
[ "import os from urllib.parse import urljoin import argparse import requests from bs4 import", "= BeautifulSoup(html_text, 'html.parser') paper_elms = paper_elms + page_soup.findAll('dt', {'class': 'ptitle'}) time.sleep(args.delay) return paper_elms", "page_soup = BeautifulSoup(html_text, 'html.parser') return page_soup.findAll('dt', {'class': 'ptitle'}) else: paper_elms = [] for", "user_agent = \"CVPR-Explorer\" headers = { 'User-Agent': user_agent } cvpr_base_url = \"https://openaccess.thecvf.com\" cvpr_year", "{ \"paper_title\": paper_title, \"paper_info_link\": paper_info_link, \"paper_link\": paper_link, \"paper_abstract\": paper_abstract } time.sleep(args.delay) except Exception", "the CVPR year to compile into a library.\"\"\") parser.add_argument('-d', '--delay', required=False, default=0.25, help=\"\"\"Specifies", "page_link in page_links: url = urljoin(base_url, page_link) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text,", "\"Day 1: \" in soup.select_one('dd').text: paper_elms = get_paged_papers(soup, cvpr_base_url) else: paper_elms = soup.findAll('dt',", "found.\") print(\"Compiling library...\") papers = {} for i in tqdm(range(len(paper_elms))): paper_elm = paper_elms[i]", "print(\"Compiling library...\") papers = {} for i in tqdm(range(len(paper_elms))): paper_elm = paper_elms[i] try:", "year to compile into a library.\"\"\") parser.add_argument('-d', '--delay', required=False, default=0.25, help=\"\"\"Specifies the delay", "all_papers) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') return page_soup.findAll('dt', {'class': 'ptitle'}) else:", "= paper_elm.findAll('a')[0] paper_info_link = urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title = paper_anchor.contents[0] html_text = requests.get(paper_info_link).text soup", "'html.parser') return page_soup.findAll('dt', {'class': 'ptitle'}) else: paper_elms = [] for page_link in page_links:", "= paper_anchor.contents[0] html_text = requests.get(paper_info_link).text soup = BeautifulSoup(html_text, \"html.parser\") paper_abstract = soup.find('div', {'id':", "\" in soup.select_one('dd').text: paper_elms = get_paged_papers(soup, cvpr_base_url) else: paper_elms = soup.findAll('dt', {'class': 'ptitle'})", "{ 'User-Agent': user_agent } cvpr_base_url = \"https://openaccess.thecvf.com\" cvpr_year = args.year cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\"", "bs4 import BeautifulSoup from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument('year', type=int, help=\"\"\"Specifies", "print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing library...\") if not os.path.isdir(\"./libraries\"): os.mkdir(\"./libraries\") with open(f\"./libraries/cvpr{cvpr_year}.json\", \"w\") as f:", "= urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title = paper_anchor.contents[0] html_text = requests.get(paper_info_link).text soup = BeautifulSoup(html_text, \"html.parser\")", "if \"all\" in page_link: all_papers = page_link break else: page_links.append(page_link) if all_papers: url", "= BeautifulSoup(html_text, \"html.parser\") paper_abstract = soup.find('div', {'id': 'abstract'}).contents[0] paper_link = soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link", "import BeautifulSoup from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument('year', type=int, help=\"\"\"Specifies the", "string for publication requests.\"\"\") args = parser.parse_args() def get_paged_papers(soup, base_url): all_papers = False", "paper_abstract = soup.find('div', {'id': 'abstract'}).contents[0] paper_link = soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link = urljoin(cvpr_base_url, paper_link)", "} time.sleep(args.delay) except Exception as e: print(\"\\n\\n--> ERROR <--\") print(e) print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing", "default=0.25, help=\"\"\"Specifies the delay between publications requests.\"\"\") parser.add_argument('-u', '--useragent', required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies the", "} cvpr_base_url = \"https://openaccess.thecvf.com\" cvpr_year = args.year cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text = requests.get(cvpr_url).text", "= False page_links = [] for page in soup.findAll('dd'): page_link = page.findAll(\"a\")[0].get('href') if", "except Exception as e: print(\"\\n\\n--> ERROR <--\") print(e) print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing library...\") if", "BeautifulSoup from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument('year', type=int, help=\"\"\"Specifies the CVPR", "requests from bs4 import BeautifulSoup from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument('year',", "library...\") if not os.path.isdir(\"./libraries\"): os.mkdir(\"./libraries\") with open(f\"./libraries/cvpr{cvpr_year}.json\", \"w\") as f: f.write(json.dumps(papers, indent=4)) print(\"Done!\")", "= urljoin(base_url, all_papers) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') return page_soup.findAll('dt', {'class':", "as e: print(\"\\n\\n--> ERROR <--\") print(e) print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing library...\") if not os.path.isdir(\"./libraries\"):", "from urllib.parse import urljoin import argparse import requests from bs4 import BeautifulSoup from", "page_link) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') paper_elms = paper_elms + page_soup.findAll('dt',", "paper_info_link = urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title = paper_anchor.contents[0] html_text = requests.get(paper_info_link).text soup = BeautifulSoup(html_text,", "= BeautifulSoup(html_text, 'html.parser') return page_soup.findAll('dt', {'class': 'ptitle'}) else: paper_elms = [] for page_link", "CVPR year to compile into a library.\"\"\") parser.add_argument('-d', '--delay', required=False, default=0.25, help=\"\"\"Specifies the", "__name__ == \"__main__\": user_agent = \"CVPR-Explorer\" headers = { 'User-Agent': user_agent } cvpr_base_url", "\"paper_abstract\": paper_abstract } time.sleep(args.delay) except Exception as e: print(\"\\n\\n--> ERROR <--\") print(e) print(\"\\n\\n\")", "False page_links = [] for page in soup.findAll('dd'): page_link = page.findAll(\"a\")[0].get('href') if \"all\"", "= \"CVPR-Explorer\" headers = { 'User-Agent': user_agent } cvpr_base_url = \"https://openaccess.thecvf.com\" cvpr_year =", "= \"https://openaccess.thecvf.com\" cvpr_year = args.year cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text = requests.get(cvpr_url).text soup =", "page_link break else: page_links.append(page_link) if all_papers: url = urljoin(base_url, all_papers) html_text = requests.get(url).text", "\"paper_info_link\": paper_info_link, \"paper_link\": paper_link, \"paper_abstract\": paper_abstract } time.sleep(args.delay) except Exception as e: print(\"\\n\\n-->", "else: paper_elms = soup.findAll('dt', {'class': 'ptitle'}) print(len(paper_elms), \"publications found.\") print(\"Compiling library...\") papers =", "urllib.parse import urljoin import argparse import requests from bs4 import BeautifulSoup from tqdm", "required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies the user-agent string for publication requests.\"\"\") args = parser.parse_args() def", "[] for page in soup.findAll('dd'): page_link = page.findAll(\"a\")[0].get('href') if \"all\" in page_link: all_papers", "paper_elms = paper_elms + page_soup.findAll('dt', {'class': 'ptitle'}) time.sleep(args.delay) return paper_elms if __name__ ==", "url = urljoin(base_url, all_papers) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') return page_soup.findAll('dt',", "base_url): all_papers = False page_links = [] for page in soup.findAll('dd'): page_link =", "soup = BeautifulSoup(html_text, \"html.parser\") paper_abstract = soup.find('div', {'id': 'abstract'}).contents[0] paper_link = soup.findAll(\"a\", string=\"pdf\")[0].get('href')", "parser.add_argument('-u', '--useragent', required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies the user-agent string for publication requests.\"\"\") args =", "page_soup = BeautifulSoup(html_text, 'html.parser') paper_elms = paper_elms + page_soup.findAll('dt', {'class': 'ptitle'}) time.sleep(args.delay) return", "page_link = page.findAll(\"a\")[0].get('href') if \"all\" in page_link: all_papers = page_link break else: page_links.append(page_link)", "requests.\"\"\") parser.add_argument('-u', '--useragent', required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies the user-agent string for publication requests.\"\"\") args", "page_soup.findAll('dt', {'class': 'ptitle'}) time.sleep(args.delay) return paper_elms if __name__ == \"__main__\": user_agent = \"CVPR-Explorer\"", "return paper_elms if __name__ == \"__main__\": user_agent = \"CVPR-Explorer\" headers = { 'User-Agent':", "in tqdm(range(len(paper_elms))): paper_elm = paper_elms[i] try: paper_anchor = paper_elm.findAll('a')[0] paper_info_link = urljoin(cvpr_base_url, paper_anchor.get('href'))", "= get_paged_papers(soup, cvpr_base_url) else: paper_elms = soup.findAll('dt', {'class': 'ptitle'}) print(len(paper_elms), \"publications found.\") print(\"Compiling", "'abstract'}).contents[0] paper_link = soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link = urljoin(cvpr_base_url, paper_link) papers[i] = { \"paper_title\":", "publication requests.\"\"\") args = parser.parse_args() def get_paged_papers(soup, base_url): all_papers = False page_links =", "all_papers = page_link break else: page_links.append(page_link) if all_papers: url = urljoin(base_url, all_papers) html_text", "\"__main__\": user_agent = \"CVPR-Explorer\" headers = { 'User-Agent': user_agent } cvpr_base_url = \"https://openaccess.thecvf.com\"", "= soup.find('div', {'id': 'abstract'}).contents[0] paper_link = soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link = urljoin(cvpr_base_url, paper_link) papers[i]", "print(\"\\n\\n--> ERROR <--\") print(e) print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing library...\") if not os.path.isdir(\"./libraries\"): os.mkdir(\"./libraries\") with", "print(e) print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing library...\") if not os.path.isdir(\"./libraries\"): os.mkdir(\"./libraries\") with open(f\"./libraries/cvpr{cvpr_year}.json\", \"w\") as", "the delay between publications requests.\"\"\") parser.add_argument('-u', '--useragent', required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies the user-agent string", "papers = {} for i in tqdm(range(len(paper_elms))): paper_elm = paper_elms[i] try: paper_anchor =", "html_text = requests.get(paper_info_link).text soup = BeautifulSoup(html_text, \"html.parser\") paper_abstract = soup.find('div', {'id': 'abstract'}).contents[0] paper_link", "into a library.\"\"\") parser.add_argument('-d', '--delay', required=False, default=0.25, help=\"\"\"Specifies the delay between publications requests.\"\"\")", "i in tqdm(range(len(paper_elms))): paper_elm = paper_elms[i] try: paper_anchor = paper_elm.findAll('a')[0] paper_info_link = urljoin(cvpr_base_url,", "help=\"\"\"Specifies the user-agent string for publication requests.\"\"\") args = parser.parse_args() def get_paged_papers(soup, base_url):", "= argparse.ArgumentParser() parser.add_argument('year', type=int, help=\"\"\"Specifies the CVPR year to compile into a library.\"\"\")", "all_papers: url = urljoin(base_url, all_papers) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') return", "from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument('year', type=int, help=\"\"\"Specifies the CVPR year", "{'class': 'ptitle'}) time.sleep(args.delay) return paper_elms if __name__ == \"__main__\": user_agent = \"CVPR-Explorer\" headers", "page_links = [] for page in soup.findAll('dd'): page_link = page.findAll(\"a\")[0].get('href') if \"all\" in", "Exception as e: print(\"\\n\\n--> ERROR <--\") print(e) print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing library...\") if not", "BeautifulSoup(html_text, 'html.parser') return page_soup.findAll('dt', {'class': 'ptitle'}) else: paper_elms = [] for page_link in", "papers[i] = { \"paper_title\": paper_title, \"paper_info_link\": paper_info_link, \"paper_link\": paper_link, \"paper_abstract\": paper_abstract } time.sleep(args.delay)", "page_links: url = urljoin(base_url, page_link) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') paper_elms", "CVPR {args.year}\") if \"Day 1: \" in soup.select_one('dd').text: paper_elms = get_paged_papers(soup, cvpr_base_url) else:", "requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') paper_elms = paper_elms + page_soup.findAll('dt', {'class': 'ptitle'}) time.sleep(args.delay)", "= [] for page in soup.findAll('dd'): page_link = page.findAll(\"a\")[0].get('href') if \"all\" in page_link:", "{} for i in tqdm(range(len(paper_elms))): paper_elm = paper_elms[i] try: paper_anchor = paper_elm.findAll('a')[0] paper_info_link", "library...\") papers = {} for i in tqdm(range(len(paper_elms))): paper_elm = paper_elms[i] try: paper_anchor", "user_agent } cvpr_base_url = \"https://openaccess.thecvf.com\" cvpr_year = args.year cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text =", "\"paper_link\": paper_link, \"paper_abstract\": paper_abstract } time.sleep(args.delay) except Exception as e: print(\"\\n\\n--> ERROR <--\")", "= parser.parse_args() def get_paged_papers(soup, base_url): all_papers = False page_links = [] for page", "\"all\" in page_link: all_papers = page_link break else: page_links.append(page_link) if all_papers: url =", "for page in soup.findAll('dd'): page_link = page.findAll(\"a\")[0].get('href') if \"all\" in page_link: all_papers =", "cvpr_year = args.year cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text = requests.get(cvpr_url).text soup = BeautifulSoup(html_text, 'html.parser')", "args.year cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text = requests.get(cvpr_url).text soup = BeautifulSoup(html_text, 'html.parser') print(f\"Getting the", "html_text = requests.get(cvpr_url).text soup = BeautifulSoup(html_text, 'html.parser') print(f\"Getting the publication list for CVPR", "'ptitle'}) print(len(paper_elms), \"publications found.\") print(\"Compiling library...\") papers = {} for i in tqdm(range(len(paper_elms))):", "time.sleep(args.delay) print(\"Writing library...\") if not os.path.isdir(\"./libraries\"): os.mkdir(\"./libraries\") with open(f\"./libraries/cvpr{cvpr_year}.json\", \"w\") as f: f.write(json.dumps(papers,", "import requests from bs4 import BeautifulSoup from tqdm import tqdm parser = argparse.ArgumentParser()", "= soup.findAll('dt', {'class': 'ptitle'}) print(len(paper_elms), \"publications found.\") print(\"Compiling library...\") papers = {} for", "for i in tqdm(range(len(paper_elms))): paper_elm = paper_elms[i] try: paper_anchor = paper_elm.findAll('a')[0] paper_info_link =", "\"publications found.\") print(\"Compiling library...\") papers = {} for i in tqdm(range(len(paper_elms))): paper_elm =", "soup = BeautifulSoup(html_text, 'html.parser') print(f\"Getting the publication list for CVPR {args.year}\") if \"Day", "paper_link = soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link = urljoin(cvpr_base_url, paper_link) papers[i] = { \"paper_title\": paper_title,", "page_links.append(page_link) if all_papers: url = urljoin(base_url, all_papers) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text,", "all_papers = False page_links = [] for page in soup.findAll('dd'): page_link = page.findAll(\"a\")[0].get('href')", "html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') paper_elms = paper_elms + page_soup.findAll('dt', {'class':", "[] for page_link in page_links: url = urljoin(base_url, page_link) html_text = requests.get(url).text page_soup", "cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text = requests.get(cvpr_url).text soup = BeautifulSoup(html_text, 'html.parser') print(f\"Getting the publication", "BeautifulSoup(html_text, \"html.parser\") paper_abstract = soup.find('div', {'id': 'abstract'}).contents[0] paper_link = soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link =", "for page_link in page_links: url = urljoin(base_url, page_link) html_text = requests.get(url).text page_soup =", "tqdm(range(len(paper_elms))): paper_elm = paper_elms[i] try: paper_anchor = paper_elm.findAll('a')[0] paper_info_link = urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title", "urljoin(base_url, page_link) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') paper_elms = paper_elms +", "os from urllib.parse import urljoin import argparse import requests from bs4 import BeautifulSoup", "in page_link: all_papers = page_link break else: page_links.append(page_link) if all_papers: url = urljoin(base_url,", "parser.add_argument('year', type=int, help=\"\"\"Specifies the CVPR year to compile into a library.\"\"\") parser.add_argument('-d', '--delay',", "= requests.get(cvpr_url).text soup = BeautifulSoup(html_text, 'html.parser') print(f\"Getting the publication list for CVPR {args.year}\")", "BeautifulSoup(html_text, 'html.parser') print(f\"Getting the publication list for CVPR {args.year}\") if \"Day 1: \"", "page in soup.findAll('dd'): page_link = page.findAll(\"a\")[0].get('href') if \"all\" in page_link: all_papers = page_link", "= paper_elms[i] try: paper_anchor = paper_elm.findAll('a')[0] paper_info_link = urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title = paper_anchor.contents[0]", "paper_elms = get_paged_papers(soup, cvpr_base_url) else: paper_elms = soup.findAll('dt', {'class': 'ptitle'}) print(len(paper_elms), \"publications found.\")", "a library.\"\"\") parser.add_argument('-d', '--delay', required=False, default=0.25, help=\"\"\"Specifies the delay between publications requests.\"\"\") parser.add_argument('-u',", "'--useragent', required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies the user-agent string for publication requests.\"\"\") args = parser.parse_args()", "'--delay', required=False, default=0.25, help=\"\"\"Specifies the delay between publications requests.\"\"\") parser.add_argument('-u', '--useragent', required=False, default=\"CVPR-Explorer\",", "break else: page_links.append(page_link) if all_papers: url = urljoin(base_url, all_papers) html_text = requests.get(url).text page_soup", "import json import time import os from urllib.parse import urljoin import argparse import", "= soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link = urljoin(cvpr_base_url, paper_link) papers[i] = { \"paper_title\": paper_title, \"paper_info_link\":", "if all_papers: url = urljoin(base_url, all_papers) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser')", "cvpr_base_url = \"https://openaccess.thecvf.com\" cvpr_year = args.year cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text = requests.get(cvpr_url).text soup", "for CVPR {args.year}\") if \"Day 1: \" in soup.select_one('dd').text: paper_elms = get_paged_papers(soup, cvpr_base_url)", "paper_elm = paper_elms[i] try: paper_anchor = paper_elm.findAll('a')[0] paper_info_link = urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title =", "= BeautifulSoup(html_text, 'html.parser') print(f\"Getting the publication list for CVPR {args.year}\") if \"Day 1:", "url = urljoin(base_url, page_link) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') paper_elms =", "paper_anchor.get('href')) paper_title = paper_anchor.contents[0] html_text = requests.get(paper_info_link).text soup = BeautifulSoup(html_text, \"html.parser\") paper_abstract =", "paper_elm.findAll('a')[0] paper_info_link = urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title = paper_anchor.contents[0] html_text = requests.get(paper_info_link).text soup =", "paper_anchor.contents[0] html_text = requests.get(paper_info_link).text soup = BeautifulSoup(html_text, \"html.parser\") paper_abstract = soup.find('div', {'id': 'abstract'}).contents[0]", "required=False, default=0.25, help=\"\"\"Specifies the delay between publications requests.\"\"\") parser.add_argument('-u', '--useragent', required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies", "time import os from urllib.parse import urljoin import argparse import requests from bs4", "\"https://openaccess.thecvf.com\" cvpr_year = args.year cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text = requests.get(cvpr_url).text soup = BeautifulSoup(html_text,", "= paper_elms + page_soup.findAll('dt', {'class': 'ptitle'}) time.sleep(args.delay) return paper_elms if __name__ == \"__main__\":", "'html.parser') paper_elms = paper_elms + page_soup.findAll('dt', {'class': 'ptitle'}) time.sleep(args.delay) return paper_elms if __name__", "if __name__ == \"__main__\": user_agent = \"CVPR-Explorer\" headers = { 'User-Agent': user_agent }", "'html.parser') print(f\"Getting the publication list for CVPR {args.year}\") if \"Day 1: \" in", "import argparse import requests from bs4 import BeautifulSoup from tqdm import tqdm parser", "= {} for i in tqdm(range(len(paper_elms))): paper_elm = paper_elms[i] try: paper_anchor = paper_elm.findAll('a')[0]", "publication list for CVPR {args.year}\") if \"Day 1: \" in soup.select_one('dd').text: paper_elms =", "'ptitle'}) else: paper_elms = [] for page_link in page_links: url = urljoin(base_url, page_link)", "print(len(paper_elms), \"publications found.\") print(\"Compiling library...\") papers = {} for i in tqdm(range(len(paper_elms))): paper_elm", "between publications requests.\"\"\") parser.add_argument('-u', '--useragent', required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies the user-agent string for publication", "urljoin(base_url, all_papers) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') return page_soup.findAll('dt', {'class': 'ptitle'})", "soup.findAll('dd'): page_link = page.findAll(\"a\")[0].get('href') if \"all\" in page_link: all_papers = page_link break else:", "= requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') paper_elms = paper_elms + page_soup.findAll('dt', {'class': 'ptitle'})", "+ page_soup.findAll('dt', {'class': 'ptitle'}) time.sleep(args.delay) return paper_elms if __name__ == \"__main__\": user_agent =", "{'id': 'abstract'}).contents[0] paper_link = soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link = urljoin(cvpr_base_url, paper_link) papers[i] = {", "= { 'User-Agent': user_agent } cvpr_base_url = \"https://openaccess.thecvf.com\" cvpr_year = args.year cvpr_url =", "requests.get(cvpr_url).text soup = BeautifulSoup(html_text, 'html.parser') print(f\"Getting the publication list for CVPR {args.year}\") if", "\"paper_title\": paper_title, \"paper_info_link\": paper_info_link, \"paper_link\": paper_link, \"paper_abstract\": paper_abstract } time.sleep(args.delay) except Exception as", "list for CVPR {args.year}\") if \"Day 1: \" in soup.select_one('dd').text: paper_elms = get_paged_papers(soup,", "delay between publications requests.\"\"\") parser.add_argument('-u', '--useragent', required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies the user-agent string for", "paper_anchor = paper_elm.findAll('a')[0] paper_info_link = urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title = paper_anchor.contents[0] html_text = requests.get(paper_info_link).text", "json import time import os from urllib.parse import urljoin import argparse import requests", "the user-agent string for publication requests.\"\"\") args = parser.parse_args() def get_paged_papers(soup, base_url): all_papers", "page.findAll(\"a\")[0].get('href') if \"all\" in page_link: all_papers = page_link break else: page_links.append(page_link) if all_papers:", "type=int, help=\"\"\"Specifies the CVPR year to compile into a library.\"\"\") parser.add_argument('-d', '--delay', required=False,", "f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text = requests.get(cvpr_url).text soup = BeautifulSoup(html_text, 'html.parser') print(f\"Getting the publication list for", "{args.year}\") if \"Day 1: \" in soup.select_one('dd').text: paper_elms = get_paged_papers(soup, cvpr_base_url) else: paper_elms", "help=\"\"\"Specifies the CVPR year to compile into a library.\"\"\") parser.add_argument('-d', '--delay', required=False, default=0.25,", "urljoin(cvpr_base_url, paper_link) papers[i] = { \"paper_title\": paper_title, \"paper_info_link\": paper_info_link, \"paper_link\": paper_link, \"paper_abstract\": paper_abstract", "paper_info_link, \"paper_link\": paper_link, \"paper_abstract\": paper_abstract } time.sleep(args.delay) except Exception as e: print(\"\\n\\n--> ERROR", "e: print(\"\\n\\n--> ERROR <--\") print(e) print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing library...\") if not os.path.isdir(\"./libraries\"): os.mkdir(\"./libraries\")", "argparse import requests from bs4 import BeautifulSoup from tqdm import tqdm parser =", "paper_link = urljoin(cvpr_base_url, paper_link) papers[i] = { \"paper_title\": paper_title, \"paper_info_link\": paper_info_link, \"paper_link\": paper_link,", "= [] for page_link in page_links: url = urljoin(base_url, page_link) html_text = requests.get(url).text", "requests.get(paper_info_link).text soup = BeautifulSoup(html_text, \"html.parser\") paper_abstract = soup.find('div', {'id': 'abstract'}).contents[0] paper_link = soup.findAll(\"a\",", "\"CVPR-Explorer\" headers = { 'User-Agent': user_agent } cvpr_base_url = \"https://openaccess.thecvf.com\" cvpr_year = args.year", "in soup.select_one('dd').text: paper_elms = get_paged_papers(soup, cvpr_base_url) else: paper_elms = soup.findAll('dt', {'class': 'ptitle'}) print(len(paper_elms),", "= { \"paper_title\": paper_title, \"paper_info_link\": paper_info_link, \"paper_link\": paper_link, \"paper_abstract\": paper_abstract } time.sleep(args.delay) except", "requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') return page_soup.findAll('dt', {'class': 'ptitle'}) else: paper_elms = []", "print(f\"Getting the publication list for CVPR {args.year}\") if \"Day 1: \" in soup.select_one('dd').text:", "{'class': 'ptitle'}) print(len(paper_elms), \"publications found.\") print(\"Compiling library...\") papers = {} for i in", "'User-Agent': user_agent } cvpr_base_url = \"https://openaccess.thecvf.com\" cvpr_year = args.year cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text", "paper_elms[i] try: paper_anchor = paper_elm.findAll('a')[0] paper_info_link = urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title = paper_anchor.contents[0] html_text", "= urljoin(base_url, page_link) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') paper_elms = paper_elms", "paper_elms if __name__ == \"__main__\": user_agent = \"CVPR-Explorer\" headers = { 'User-Agent': user_agent", "help=\"\"\"Specifies the delay between publications requests.\"\"\") parser.add_argument('-u', '--useragent', required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies the user-agent", "get_paged_papers(soup, base_url): all_papers = False page_links = [] for page in soup.findAll('dd'): page_link", "paper_elms + page_soup.findAll('dt', {'class': 'ptitle'}) time.sleep(args.delay) return paper_elms if __name__ == \"__main__\": user_agent", "paper_abstract } time.sleep(args.delay) except Exception as e: print(\"\\n\\n--> ERROR <--\") print(e) print(\"\\n\\n\") time.sleep(args.delay)", "for publication requests.\"\"\") args = parser.parse_args() def get_paged_papers(soup, base_url): all_papers = False page_links", "<reponame>Brikwerk/cvpr-explorer import json import time import os from urllib.parse import urljoin import argparse", "headers = { 'User-Agent': user_agent } cvpr_base_url = \"https://openaccess.thecvf.com\" cvpr_year = args.year cvpr_url", "in soup.findAll('dd'): page_link = page.findAll(\"a\")[0].get('href') if \"all\" in page_link: all_papers = page_link break", "import tqdm parser = argparse.ArgumentParser() parser.add_argument('year', type=int, help=\"\"\"Specifies the CVPR year to compile", "page_link: all_papers = page_link break else: page_links.append(page_link) if all_papers: url = urljoin(base_url, all_papers)", "= f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text = requests.get(cvpr_url).text soup = BeautifulSoup(html_text, 'html.parser') print(f\"Getting the publication list", "args = parser.parse_args() def get_paged_papers(soup, base_url): all_papers = False page_links = [] for", "== \"__main__\": user_agent = \"CVPR-Explorer\" headers = { 'User-Agent': user_agent } cvpr_base_url =", "import urljoin import argparse import requests from bs4 import BeautifulSoup from tqdm import", "urljoin import argparse import requests from bs4 import BeautifulSoup from tqdm import tqdm", "= page_link break else: page_links.append(page_link) if all_papers: url = urljoin(base_url, all_papers) html_text =", "else: paper_elms = [] for page_link in page_links: url = urljoin(base_url, page_link) html_text", "time.sleep(args.delay) except Exception as e: print(\"\\n\\n--> ERROR <--\") print(e) print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing library...\")", "soup.find('div', {'id': 'abstract'}).contents[0] paper_link = soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link = urljoin(cvpr_base_url, paper_link) papers[i] =", "compile into a library.\"\"\") parser.add_argument('-d', '--delay', required=False, default=0.25, help=\"\"\"Specifies the delay between publications", "try: paper_anchor = paper_elm.findAll('a')[0] paper_info_link = urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title = paper_anchor.contents[0] html_text =", "= requests.get(paper_info_link).text soup = BeautifulSoup(html_text, \"html.parser\") paper_abstract = soup.find('div', {'id': 'abstract'}).contents[0] paper_link =", "soup.findAll('dt', {'class': 'ptitle'}) print(len(paper_elms), \"publications found.\") print(\"Compiling library...\") papers = {} for i", "print(\"Writing library...\") if not os.path.isdir(\"./libraries\"): os.mkdir(\"./libraries\") with open(f\"./libraries/cvpr{cvpr_year}.json\", \"w\") as f: f.write(json.dumps(papers, indent=4))", "1: \" in soup.select_one('dd').text: paper_elms = get_paged_papers(soup, cvpr_base_url) else: paper_elms = soup.findAll('dt', {'class':", "else: page_links.append(page_link) if all_papers: url = urljoin(base_url, all_papers) html_text = requests.get(url).text page_soup =", "\"html.parser\") paper_abstract = soup.find('div', {'id': 'abstract'}).contents[0] paper_link = soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link = urljoin(cvpr_base_url,", "parser.parse_args() def get_paged_papers(soup, base_url): all_papers = False page_links = [] for page in", "paper_title = paper_anchor.contents[0] html_text = requests.get(paper_info_link).text soup = BeautifulSoup(html_text, \"html.parser\") paper_abstract = soup.find('div',", "string=\"pdf\")[0].get('href') paper_link = urljoin(cvpr_base_url, paper_link) papers[i] = { \"paper_title\": paper_title, \"paper_info_link\": paper_info_link, \"paper_link\":", "to compile into a library.\"\"\") parser.add_argument('-d', '--delay', required=False, default=0.25, help=\"\"\"Specifies the delay between", "= page.findAll(\"a\")[0].get('href') if \"all\" in page_link: all_papers = page_link break else: page_links.append(page_link) if", "html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') return page_soup.findAll('dt', {'class': 'ptitle'}) else: paper_elms", "argparse.ArgumentParser() parser.add_argument('year', type=int, help=\"\"\"Specifies the CVPR year to compile into a library.\"\"\") parser.add_argument('-d',", "<--\") print(e) print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing library...\") if not os.path.isdir(\"./libraries\"): os.mkdir(\"./libraries\") with open(f\"./libraries/cvpr{cvpr_year}.json\", \"w\")", "paper_elms = soup.findAll('dt', {'class': 'ptitle'}) print(len(paper_elms), \"publications found.\") print(\"Compiling library...\") papers = {}", "time.sleep(args.delay) return paper_elms if __name__ == \"__main__\": user_agent = \"CVPR-Explorer\" headers = {", "soup.findAll(\"a\", string=\"pdf\")[0].get('href') paper_link = urljoin(cvpr_base_url, paper_link) papers[i] = { \"paper_title\": paper_title, \"paper_info_link\": paper_info_link,", "the publication list for CVPR {args.year}\") if \"Day 1: \" in soup.select_one('dd').text: paper_elms", "default=\"CVPR-Explorer\", help=\"\"\"Specifies the user-agent string for publication requests.\"\"\") args = parser.parse_args() def get_paged_papers(soup,", "'ptitle'}) time.sleep(args.delay) return paper_elms if __name__ == \"__main__\": user_agent = \"CVPR-Explorer\" headers =", "= urljoin(cvpr_base_url, paper_link) papers[i] = { \"paper_title\": paper_title, \"paper_info_link\": paper_info_link, \"paper_link\": paper_link, \"paper_abstract\":", "from bs4 import BeautifulSoup from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument('year', type=int,", "cvpr_base_url) else: paper_elms = soup.findAll('dt', {'class': 'ptitle'}) print(len(paper_elms), \"publications found.\") print(\"Compiling library...\") papers", "paper_link, \"paper_abstract\": paper_abstract } time.sleep(args.delay) except Exception as e: print(\"\\n\\n--> ERROR <--\") print(e)", "library.\"\"\") parser.add_argument('-d', '--delay', required=False, default=0.25, help=\"\"\"Specifies the delay between publications requests.\"\"\") parser.add_argument('-u', '--useragent',", "page_soup.findAll('dt', {'class': 'ptitle'}) else: paper_elms = [] for page_link in page_links: url =", "get_paged_papers(soup, cvpr_base_url) else: paper_elms = soup.findAll('dt', {'class': 'ptitle'}) print(len(paper_elms), \"publications found.\") print(\"Compiling library...\")", "if \"Day 1: \" in soup.select_one('dd').text: paper_elms = get_paged_papers(soup, cvpr_base_url) else: paper_elms =", "urljoin(cvpr_base_url, paper_anchor.get('href')) paper_title = paper_anchor.contents[0] html_text = requests.get(paper_info_link).text soup = BeautifulSoup(html_text, \"html.parser\") paper_abstract", "paper_link) papers[i] = { \"paper_title\": paper_title, \"paper_info_link\": paper_info_link, \"paper_link\": paper_link, \"paper_abstract\": paper_abstract }", "paper_title, \"paper_info_link\": paper_info_link, \"paper_link\": paper_link, \"paper_abstract\": paper_abstract } time.sleep(args.delay) except Exception as e:", "paper_elms = [] for page_link in page_links: url = urljoin(base_url, page_link) html_text =", "requests.\"\"\") args = parser.parse_args() def get_paged_papers(soup, base_url): all_papers = False page_links = []", "ERROR <--\") print(e) print(\"\\n\\n\") time.sleep(args.delay) print(\"Writing library...\") if not os.path.isdir(\"./libraries\"): os.mkdir(\"./libraries\") with open(f\"./libraries/cvpr{cvpr_year}.json\",", "def get_paged_papers(soup, base_url): all_papers = False page_links = [] for page in soup.findAll('dd'):", "parser = argparse.ArgumentParser() parser.add_argument('year', type=int, help=\"\"\"Specifies the CVPR year to compile into a", "{'class': 'ptitle'}) else: paper_elms = [] for page_link in page_links: url = urljoin(base_url,", "soup.select_one('dd').text: paper_elms = get_paged_papers(soup, cvpr_base_url) else: paper_elms = soup.findAll('dt', {'class': 'ptitle'}) print(len(paper_elms), \"publications", "parser.add_argument('-d', '--delay', required=False, default=0.25, help=\"\"\"Specifies the delay between publications requests.\"\"\") parser.add_argument('-u', '--useragent', required=False,", "publications requests.\"\"\") parser.add_argument('-u', '--useragent', required=False, default=\"CVPR-Explorer\", help=\"\"\"Specifies the user-agent string for publication requests.\"\"\")", "in page_links: url = urljoin(base_url, page_link) html_text = requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser')", "= requests.get(url).text page_soup = BeautifulSoup(html_text, 'html.parser') return page_soup.findAll('dt', {'class': 'ptitle'}) else: paper_elms =", "user-agent string for publication requests.\"\"\") args = parser.parse_args() def get_paged_papers(soup, base_url): all_papers =", "= args.year cvpr_url = f\"{cvpr_base_url}/CVPR{cvpr_year}\" html_text = requests.get(cvpr_url).text soup = BeautifulSoup(html_text, 'html.parser') print(f\"Getting", "tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument('year', type=int, help=\"\"\"Specifies the CVPR year to", "BeautifulSoup(html_text, 'html.parser') paper_elms = paper_elms + page_soup.findAll('dt', {'class': 'ptitle'}) time.sleep(args.delay) return paper_elms if", "import time import os from urllib.parse import urljoin import argparse import requests from", "return page_soup.findAll('dt', {'class': 'ptitle'}) else: paper_elms = [] for page_link in page_links: url", "tqdm parser = argparse.ArgumentParser() parser.add_argument('year', type=int, help=\"\"\"Specifies the CVPR year to compile into" ]
[ "-> triangle (20 ,28) -> triangle (48) -> triangle () return -> print(48)", "[]): print(i) ''' triangle(3,5,7,9) -> triangle (8,12,16) -> triangle (20 ,28) -> triangle", "result for i in triangle([1,2,3,4,5], []): print(i) ''' triangle(3,5,7,9) -> triangle (8,12,16) ->", "if len(array)>0 else result for i in triangle([1,2,3,4,5], []): print(i) ''' triangle(3,5,7,9) ->", "(8,12,16) -> triangle (20 ,28) -> triangle (48) -> triangle () return ->", "-> triangle () return -> print(48) -> print(20, 28) ->print(8,12,16) ->print(3,5,7,9) ->print(1,2,3,4,5) '''", "array = [array[i-1]+array[i] for i in range(1, len(array))] return triangle(array , result) if", "triangle (20 ,28) -> triangle (48) -> triangle () return -> print(48) ->", "triangle (8,12,16) -> triangle (20 ,28) -> triangle (48) -> triangle () return", "[array[i-1]+array[i] for i in range(1, len(array))] return triangle(array , result) if len(array)>0 else", "in range(1, len(array))] return triangle(array , result) if len(array)>0 else result for i", "(48) -> triangle () return -> print(48) -> print(20, 28) ->print(8,12,16) ->print(3,5,7,9) ->print(1,2,3,4,5)", ",28) -> triangle (48) -> triangle () return -> print(48) -> print(20, 28)", "triangle(3,5,7,9) -> triangle (8,12,16) -> triangle (20 ,28) -> triangle (48) -> triangle", "range(1, len(array))] return triangle(array , result) if len(array)>0 else result for i in", "''' triangle(3,5,7,9) -> triangle (8,12,16) -> triangle (20 ,28) -> triangle (48) ->", "<gh_stars>10-100 def triangle(array, result): result.insert(0,array) array = [array[i-1]+array[i] for i in range(1, len(array))]", "i in range(1, len(array))] return triangle(array , result) if len(array)>0 else result for", "triangle([1,2,3,4,5], []): print(i) ''' triangle(3,5,7,9) -> triangle (8,12,16) -> triangle (20 ,28) ->", "else result for i in triangle([1,2,3,4,5], []): print(i) ''' triangle(3,5,7,9) -> triangle (8,12,16)", "-> triangle (8,12,16) -> triangle (20 ,28) -> triangle (48) -> triangle ()", "len(array)>0 else result for i in triangle([1,2,3,4,5], []): print(i) ''' triangle(3,5,7,9) -> triangle", "= [array[i-1]+array[i] for i in range(1, len(array))] return triangle(array , result) if len(array)>0", "for i in range(1, len(array))] return triangle(array , result) if len(array)>0 else result", "def triangle(array, result): result.insert(0,array) array = [array[i-1]+array[i] for i in range(1, len(array))] return", "triangle(array, result): result.insert(0,array) array = [array[i-1]+array[i] for i in range(1, len(array))] return triangle(array", "result) if len(array)>0 else result for i in triangle([1,2,3,4,5], []): print(i) ''' triangle(3,5,7,9)", "len(array))] return triangle(array , result) if len(array)>0 else result for i in triangle([1,2,3,4,5],", "for i in triangle([1,2,3,4,5], []): print(i) ''' triangle(3,5,7,9) -> triangle (8,12,16) -> triangle", "triangle (48) -> triangle () return -> print(48) -> print(20, 28) ->print(8,12,16) ->print(3,5,7,9)", "result): result.insert(0,array) array = [array[i-1]+array[i] for i in range(1, len(array))] return triangle(array ,", "result.insert(0,array) array = [array[i-1]+array[i] for i in range(1, len(array))] return triangle(array , result)", "return triangle(array , result) if len(array)>0 else result for i in triangle([1,2,3,4,5], []):", "print(i) ''' triangle(3,5,7,9) -> triangle (8,12,16) -> triangle (20 ,28) -> triangle (48)", "triangle(array , result) if len(array)>0 else result for i in triangle([1,2,3,4,5], []): print(i)", ", result) if len(array)>0 else result for i in triangle([1,2,3,4,5], []): print(i) '''", "in triangle([1,2,3,4,5], []): print(i) ''' triangle(3,5,7,9) -> triangle (8,12,16) -> triangle (20 ,28)", "(20 ,28) -> triangle (48) -> triangle () return -> print(48) -> print(20,", "-> triangle (48) -> triangle () return -> print(48) -> print(20, 28) ->print(8,12,16)", "i in triangle([1,2,3,4,5], []): print(i) ''' triangle(3,5,7,9) -> triangle (8,12,16) -> triangle (20" ]
[ "= uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0, r1,", "r3 = uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_read(UC_ARM_REG_R4) r5 = uc.reg_read(UC_ARM_REG_R5) r7 = uc.reg_read(UC_ARM_REG_R7) sp", "uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0, r1, r2,", "print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0, r1, r2, r3,", "= uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_read(UC_ARM_REG_R4) r5 = uc.reg_read(UC_ARM_REG_R5) r7 = uc.reg_read(UC_ARM_REG_R7) sp =", "0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0, r1, r2, r3, r4, r5, r7, pc, sp)) def", "r2 = uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_read(UC_ARM_REG_R4) r5 = uc.reg_read(UC_ARM_REG_R5) r7", "uc.reg_read(UC_ARM_REG_R7) sp = uc.reg_read(UC_ARM_REG_SP) pc = uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5:", "uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_read(UC_ARM_REG_R4) r5 = uc.reg_read(UC_ARM_REG_R5)", "uc.reg_read(UC_ARM_REG_R5) r7 = uc.reg_read(UC_ARM_REG_R7) sp = uc.reg_read(UC_ARM_REG_SP) pc = uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2:", "pc = uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0,", "stop(uc): print_context(uc) input(\"...\") def print_context(uc): print(\"==== State ====\") r0 = uc.reg_read(UC_ARM_REG_R0) r1 =", "r0 = uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3) r4", "0x{:x}\\nsp: 0x{:x}\".format(r0, r1, r2, r3, r4, r5, r7, pc, sp)) def breakpoint(uc): import", "= uc.reg_read(UC_ARM_REG_R4) r5 = uc.reg_read(UC_ARM_REG_R5) r7 = uc.reg_read(UC_ARM_REG_R7) sp = uc.reg_read(UC_ARM_REG_SP) pc =", "sp = uc.reg_read(UC_ARM_REG_SP) pc = uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7:", "= uc.reg_read(UC_ARM_REG_R7) sp = uc.reg_read(UC_ARM_REG_SP) pc = uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4:", "r1, r2, r3, r4, r5, r7, pc, sp)) def breakpoint(uc): import ipdb; ipdb.set_trace()", "r1 = uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_read(UC_ARM_REG_R4) r5", "from unicorn.arm_const import * def stop(uc): print_context(uc) input(\"...\") def print_context(uc): print(\"==== State ====\")", "import * def stop(uc): print_context(uc) input(\"...\") def print_context(uc): print(\"==== State ====\") r0 =", "input(\"...\") def print_context(uc): print(\"==== State ====\") r0 = uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1) r2", "= uc.reg_read(UC_ARM_REG_R5) r7 = uc.reg_read(UC_ARM_REG_R7) sp = uc.reg_read(UC_ARM_REG_SP) pc = uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1:", "0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0, r1, r2, r3, r4,", "0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0, r1, r2, r3, r4, r5, r7, pc,", "uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_read(UC_ARM_REG_R4) r5 = uc.reg_read(UC_ARM_REG_R5) r7 = uc.reg_read(UC_ARM_REG_R7)", "0x{:x}\".format(r0, r1, r2, r3, r4, r5, r7, pc, sp)) def breakpoint(uc): import ipdb;", "0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0, r1, r2, r3, r4, r5,", "r5 = uc.reg_read(UC_ARM_REG_R5) r7 = uc.reg_read(UC_ARM_REG_R7) sp = uc.reg_read(UC_ARM_REG_SP) pc = uc.reg_read(UC_ARM_REG_PC) print(\"r0:", "= uc.reg_read(UC_ARM_REG_SP) pc = uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc:", "0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0, r1, r2, r3, r4, r5, r7, pc, sp)) def breakpoint(uc):", "uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_read(UC_ARM_REG_R4)", "uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_read(UC_ARM_REG_R4) r5 = uc.reg_read(UC_ARM_REG_R5) r7 = uc.reg_read(UC_ARM_REG_R7) sp = uc.reg_read(UC_ARM_REG_SP)", "r7 = uc.reg_read(UC_ARM_REG_R7) sp = uc.reg_read(UC_ARM_REG_SP) pc = uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3:", "0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0, r1, r2, r3, r4, r5, r7, pc, sp))", "====\") r0 = uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3)", "= uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_read(UC_ARM_REG_R4) r5 =", "<gh_stars>100-1000 from unicorn.arm_const import * def stop(uc): print_context(uc) input(\"...\") def print_context(uc): print(\"==== State", "= uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_read(UC_ARM_REG_R4) r5 = uc.reg_read(UC_ARM_REG_R5) r7 =", "def stop(uc): print_context(uc) input(\"...\") def print_context(uc): print(\"==== State ====\") r0 = uc.reg_read(UC_ARM_REG_R0) r1", "r4 = uc.reg_read(UC_ARM_REG_R4) r5 = uc.reg_read(UC_ARM_REG_R5) r7 = uc.reg_read(UC_ARM_REG_R7) sp = uc.reg_read(UC_ARM_REG_SP) pc", "0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp: 0x{:x}\".format(r0, r1, r2, r3, r4, r5, r7,", "print_context(uc) input(\"...\") def print_context(uc): print(\"==== State ====\") r0 = uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1)", "def print_context(uc): print(\"==== State ====\") r0 = uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1) r2 =", "uc.reg_read(UC_ARM_REG_SP) pc = uc.reg_read(UC_ARM_REG_PC) print(\"r0: 0x{:x}\\nr1: 0x{:x}\\nr2: 0x{:x}\\nr3: 0x{:x}\\nr4: 0x{:x}\\nr5: 0x{:x}\\nr7: 0x{:x}\\npc: 0x{:x}\\nsp:", "State ====\") r0 = uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2) r3 =", "= uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3) r4 =", "print_context(uc): print(\"==== State ====\") r0 = uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2)", "* def stop(uc): print_context(uc) input(\"...\") def print_context(uc): print(\"==== State ====\") r0 = uc.reg_read(UC_ARM_REG_R0)", "print(\"==== State ====\") r0 = uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2) r3", "unicorn.arm_const import * def stop(uc): print_context(uc) input(\"...\") def print_context(uc): print(\"==== State ====\") r0", "uc.reg_read(UC_ARM_REG_R4) r5 = uc.reg_read(UC_ARM_REG_R5) r7 = uc.reg_read(UC_ARM_REG_R7) sp = uc.reg_read(UC_ARM_REG_SP) pc = uc.reg_read(UC_ARM_REG_PC)" ]
[ "self.setStyleSheet('QFrame { border-radius: 10px; }') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def paintEvent(self, event): \"\"\" Override base", "import Qt from Qt.QtWidgets import QSizePolicy, QFrame from Qt.QtGui import QPainter, QPainterPath class", "paintEvent(self, event): \"\"\" Override base QFrame paintEvent function :param event: QPaintEvent \"\"\" painter", "from Qt.QtCore import Qt from Qt.QtWidgets import QSizePolicy, QFrame from Qt.QtGui import QPainter,", "= pixmap self.setStyleSheet('QFrame { border-radius: 10px; }') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def paintEvent(self, event): \"\"\"", "import QPainter, QPainterPath class WelcomeFrame(QFrame, object): def __init__(self, pixmap, parent=None): super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground)", "from __future__ import print_function, division, absolute_import from Qt.QtCore import Qt from Qt.QtWidgets import", "QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path = QPainterPath() path.addRoundedRect(0, 0, self.width(), self.height(), 10, 10) painter.setClipPath(path) painter.drawPixmap(0,", "Qt from Qt.QtWidgets import QSizePolicy, QFrame from Qt.QtGui import QPainter, QPainterPath class WelcomeFrame(QFrame,", "QPaintEvent \"\"\" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path = QPainterPath() path.addRoundedRect(0, 0, self.width(), self.height(),", "self._pixmap = pixmap self.setStyleSheet('QFrame { border-radius: 10px; }') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def paintEvent(self, event):", "10px; }') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def paintEvent(self, event): \"\"\" Override base QFrame paintEvent function", "self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap = pixmap self.setStyleSheet('QFrame { border-radius: 10px; }') self.setSizePolicy(QSizePolicy.Expanding,", "path = QPainterPath() path.addRoundedRect(0, 0, self.width(), self.height(), 10, 10) painter.setClipPath(path) painter.drawPixmap(0, 0, self.width(),", "# -*- coding: utf-8 -*- \"\"\" Module that contains frame widget implementation \"\"\"", "def paintEvent(self, event): \"\"\" Override base QFrame paintEvent function :param event: QPaintEvent \"\"\"", "division, absolute_import from Qt.QtCore import Qt from Qt.QtWidgets import QSizePolicy, QFrame from Qt.QtGui", "class WelcomeFrame(QFrame, object): def __init__(self, pixmap, parent=None): super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap", "object): def __init__(self, pixmap, parent=None): super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap = pixmap", "from Qt.QtWidgets import QSizePolicy, QFrame from Qt.QtGui import QPainter, QPainterPath class WelcomeFrame(QFrame, object):", "coding: utf-8 -*- \"\"\" Module that contains frame widget implementation \"\"\" from __future__", "{ border-radius: 10px; }') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def paintEvent(self, event): \"\"\" Override base QFrame", "def __init__(self, pixmap, parent=None): super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap = pixmap self.setStyleSheet('QFrame", "Override base QFrame paintEvent function :param event: QPaintEvent \"\"\" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing)", "}') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def paintEvent(self, event): \"\"\" Override base QFrame paintEvent function :param", "-*- \"\"\" Module that contains frame widget implementation \"\"\" from __future__ import print_function,", "import QSizePolicy, QFrame from Qt.QtGui import QPainter, QPainterPath class WelcomeFrame(QFrame, object): def __init__(self,", "QSizePolicy.Expanding) def paintEvent(self, event): \"\"\" Override base QFrame paintEvent function :param event: QPaintEvent", "WelcomeFrame(QFrame, object): def __init__(self, pixmap, parent=None): super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap =", "\"\"\" Module that contains frame widget implementation \"\"\" from __future__ import print_function, division,", "parent=None): super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap = pixmap self.setStyleSheet('QFrame { border-radius: 10px;", "__init__(self, pixmap, parent=None): super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap = pixmap self.setStyleSheet('QFrame {", "pixmap self.setStyleSheet('QFrame { border-radius: 10px; }') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def paintEvent(self, event): \"\"\" Override", "that contains frame widget implementation \"\"\" from __future__ import print_function, division, absolute_import from", "\"\"\" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path = QPainterPath() path.addRoundedRect(0, 0, self.width(), self.height(), 10,", "from Qt.QtGui import QPainter, QPainterPath class WelcomeFrame(QFrame, object): def __init__(self, pixmap, parent=None): super(WelcomeFrame,", "QSizePolicy, QFrame from Qt.QtGui import QPainter, QPainterPath class WelcomeFrame(QFrame, object): def __init__(self, pixmap,", "paintEvent function :param event: QPaintEvent \"\"\" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path = QPainterPath()", "self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap = pixmap self.setStyleSheet('QFrame { border-radius: 10px; }') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def", "function :param event: QPaintEvent \"\"\" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path = QPainterPath() path.addRoundedRect(0,", "event): \"\"\" Override base QFrame paintEvent function :param event: QPaintEvent \"\"\" painter =", "print_function, division, absolute_import from Qt.QtCore import Qt from Qt.QtWidgets import QSizePolicy, QFrame from", "QPainterPath class WelcomeFrame(QFrame, object): def __init__(self, pixmap, parent=None): super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain)", "absolute_import from Qt.QtCore import Qt from Qt.QtWidgets import QSizePolicy, QFrame from Qt.QtGui import", "Qt.QtWidgets import QSizePolicy, QFrame from Qt.QtGui import QPainter, QPainterPath class WelcomeFrame(QFrame, object): def", "painter.setRenderHint(QPainter.Antialiasing) path = QPainterPath() path.addRoundedRect(0, 0, self.width(), self.height(), 10, 10) painter.setClipPath(path) painter.drawPixmap(0, 0,", "= QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path = QPainterPath() path.addRoundedRect(0, 0, self.width(), self.height(), 10, 10) painter.setClipPath(path)", "QFrame from Qt.QtGui import QPainter, QPainterPath class WelcomeFrame(QFrame, object): def __init__(self, pixmap, parent=None):", "utf-8 -*- \"\"\" Module that contains frame widget implementation \"\"\" from __future__ import", "__future__ import print_function, division, absolute_import from Qt.QtCore import Qt from Qt.QtWidgets import QSizePolicy,", "\"\"\" from __future__ import print_function, division, absolute_import from Qt.QtCore import Qt from Qt.QtWidgets", "self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap = pixmap self.setStyleSheet('QFrame { border-radius: 10px; }') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)", "contains frame widget implementation \"\"\" from __future__ import print_function, division, absolute_import from Qt.QtCore", "= QPainterPath() path.addRoundedRect(0, 0, self.width(), self.height(), 10, 10) painter.setClipPath(path) painter.drawPixmap(0, 0, self.width(), self.height(),", "import print_function, division, absolute_import from Qt.QtCore import Qt from Qt.QtWidgets import QSizePolicy, QFrame", "super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap = pixmap self.setStyleSheet('QFrame { border-radius: 10px; }')", "-*- coding: utf-8 -*- \"\"\" Module that contains frame widget implementation \"\"\" from", "\"\"\" Override base QFrame paintEvent function :param event: QPaintEvent \"\"\" painter = QPainter(self)", "self.setFrameShadow(QFrame.Plain) self._pixmap = pixmap self.setStyleSheet('QFrame { border-radius: 10px; }') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def paintEvent(self,", ":param event: QPaintEvent \"\"\" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path = QPainterPath() path.addRoundedRect(0, 0,", "QPainter, QPainterPath class WelcomeFrame(QFrame, object): def __init__(self, pixmap, parent=None): super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame)", "implementation \"\"\" from __future__ import print_function, division, absolute_import from Qt.QtCore import Qt from", "Qt.QtGui import QPainter, QPainterPath class WelcomeFrame(QFrame, object): def __init__(self, pixmap, parent=None): super(WelcomeFrame, self).__init__(parent)", "self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def paintEvent(self, event): \"\"\" Override base QFrame paintEvent function :param event:", "border-radius: 10px; }') self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def paintEvent(self, event): \"\"\" Override base QFrame paintEvent", "pixmap, parent=None): super(WelcomeFrame, self).__init__(parent) self.setAttribute(Qt.WA_TranslucentBackground) self.setFrameShape(QFrame.NoFrame) self.setFrameShadow(QFrame.Plain) self._pixmap = pixmap self.setStyleSheet('QFrame { border-radius:", "QPainterPath() path.addRoundedRect(0, 0, self.width(), self.height(), 10, 10) painter.setClipPath(path) painter.drawPixmap(0, 0, self.width(), self.height(), self._pixmap)", "Module that contains frame widget implementation \"\"\" from __future__ import print_function, division, absolute_import", "Qt.QtCore import Qt from Qt.QtWidgets import QSizePolicy, QFrame from Qt.QtGui import QPainter, QPainterPath", "base QFrame paintEvent function :param event: QPaintEvent \"\"\" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path", "QFrame paintEvent function :param event: QPaintEvent \"\"\" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path =", "#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" Module that contains frame widget", "python # -*- coding: utf-8 -*- \"\"\" Module that contains frame widget implementation", "event: QPaintEvent \"\"\" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path = QPainterPath() path.addRoundedRect(0, 0, self.width(),", "frame widget implementation \"\"\" from __future__ import print_function, division, absolute_import from Qt.QtCore import", "painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) path = QPainterPath() path.addRoundedRect(0, 0, self.width(), self.height(), 10, 10)", "widget implementation \"\"\" from __future__ import print_function, division, absolute_import from Qt.QtCore import Qt" ]
[ "dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name) ) try: if data['SIGABRT'] == data['SIGIOT']: del data['SIGIOT'] except KeyError:", "hi, pydiatra! else: queue.put([stdout, stderr]) sys.exit(0) def assert_emit_tags(path, etags, *, options=()): etags =", "return (t.tag for t in etags) def get_coverage_for_function(fn): for etag in etags_from_tagstring(fn, ''):", "= re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self, code, path, rest): self._s = s = '{code}: {path}:", "'.po', '.pot', '.pop') # .pop is a special extension to trigger unknown-file-type class", "THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "== 0: return stdout if rc < 0: message = ['command was interrupted", "for t in etags) def get_coverage_for_function(fn): for etag in etags_from_tagstring(fn, ''): yield etag.tag", "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "try: file = open(path + '.gen', encoding='UTF-8', errors='ignore') # pylint: disable=consider-using-with except FileNotFoundError:", "start=here) yield _test_file, path test_file.redundant = True # not needed if the plugin", "special extension to trigger unknown-file-type class Plugin(nose.plugins.Plugin): name = 'po-plugin' enabled = True", "if path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here), '')): return True def loadTestsFromFile(self, path): if self.wantFile(path): yield", "semi-active waiting is ugly, but there doesn't seem be any # obvious better", "sys.exit(1) raise # hi, pydiatra! else: queue.put([stdout, stderr]) sys.exit(0) def assert_emit_tags(path, etags, *,", "etag is None: if comments_only: break else: raise TestFileSyntaxError(orig_line) etags += [etag] return", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "filenames: if not filename.endswith(test_file_extensions): continue yield os.path.join(root, filename) def test_file(): for filename in", "extension to trigger unknown-file-type class Plugin(nose.plugins.Plugin): name = 'po-plugin' enabled = True def", "= file.read() sys.argv = [prog] + list(options) + [path] orig_stdout = sys.stdout orig_stderr", "def _parse_test_header_file(file, path, *, comments_only): etags = [] options = [] for n,", "the Software without restriction, including without limitation the rights # to use, copy,", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN", "'.pot', '.pop') # .pop is a special extension to trigger unknown-file-type class Plugin(nose.plugins.Plugin):", "return queue.get(timeout=1) # This semi-active waiting is ugly, but there doesn't seem be", "diff[3:] raise AssertionError('\\n'.join(message)) elif expected_failure: raise AssertionError('unexpected success') class TestFileSyntaxError(Exception): pass def _parse_test_header_file(file,", "break if line.startswith('--'): options += shlex.split(line) else: etag = parse_etag(line, path) if etag", "def get_coverage_for_function(fn): for etag in etags_from_tagstring(fn, ''): yield etag.tag def _get_test_filenames(): for root,", "def this(): ''' Return function that called this function. (Hopefully!) ''' return globals()[inspect.stack()[1][0].f_code.co_name]", "ETag(match.group(1), path, match.group(2)) return t def etags_from_tagstring(obj, path): try: docstring = obj.tagstring except", "person obtaining a copy # of this software and associated documentation files (the", "yield _test_file, path test_file.redundant = True # not needed if the plugin is", "if os.getuid() == 0: raise nose.SkipTest('this test must not be run as root')", "else: commandline = shlex.split(commandline) commandline += options commandline += [path] fixed_env = dict(os.environ,", "= _parse_test_headers(path) assert_emit_tags(path, etags, options=options) def get_coverage_for_file(path): etags, options = _parse_test_headers(path) del options", "TestCase(unittest.TestCase): def __init__(self, path): super().__init__('_test') self.path = os.path.relpath(path) def _test(self): _test_file(self.path, basedir=None) def", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import", "return False class TestCase(unittest.TestCase): def __init__(self, path): super().__init__('_test') self.path = os.path.relpath(path) def _test(self):", "child.poll() assert isinstance(rc, int) if rc == 0: return stdout if rc <", "(empty)'] raise SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog, options, path, queue): with open(prog, 'rt', encoding='UTF-8') as", "run_i18nspector(options, path): commandline = os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline is None: # We cheat here", "''.join( traceback.format_exception(exctp, exc, tb) ) queue.put([stdout, stderr]) sys.exit(1) raise # hi, pydiatra! else:", "options = _parse_test_headers(path) del options return (t.tag for t in etags) def get_coverage_for_function(fn):", "is enabled @tagstring(''' E: os-error No such file or directory ''') def test_os_error_no_such_file():", "import os import re import shlex import signal import subprocess as ipc import", "del dirnames for filename in filenames: if not filename.endswith(test_file_extensions): continue yield os.path.join(root, filename)", "encoding='UTF-8') as file: code = file.read() sys.argv = [prog] + list(options) + [path]", "orig_stderr) stdout = io_stdout.getvalue() stderr = io_stderr.getvalue() except SystemExit: queue.put([stdout, stderr]) raise except:", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR", "coverage = set() for filename in _get_test_filenames(): for tag in get_coverage_for_file(filename): coverage.add(tag) for", "tagstring(s): def update(x): x.tagstring = s return x return update # ---------------------------------------- class", "as tmpdir: path = os.path.join(tmpdir, 'nonexistent.po') expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) @tagstring('''", "files (the “Software”), to deal # in the Software without restriction, including without", "open(path + '.gen', encoding='UTF-8', errors='ignore') # pylint: disable=consider-using-with except FileNotFoundError: pass else: with", "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies", "for chunk in self._split(s) ) self._regexp = re.compile('^{}$'.format(regexp)) def __eq__(self, other): if isinstance(other,", "= list(etags) stdout = run_i18nspector(options, path) expected_failure = os.path.basename(path).startswith('xfail-') if stdout != etags:", "= io.StringIO() gvars = dict( __file__=prog, ) (sys.stdout, sys.stderr) = (io_stdout, io_stderr) try:", "= io_stdout.getvalue() stderr = io_stderr.getvalue() except SystemExit: queue.put([stdout, stderr]) raise except: # pylint:", "''.join( '.*' if chunk == self._ellipsis else re.escape(chunk) for chunk in self._split(s) )", "above copyright notice and this permission notice shall be included in # all", "import io import multiprocessing as mp import os import re import shlex import", "line in enumerate(file): orig_line = line if comments_only: if n == 0 and", "test_file(): for filename in _get_test_filenames(): path = os.path.relpath(filename, start=here) yield _test_file, path test_file.redundant", "gvars = dict( __file__=prog, ) (sys.stdout, sys.stderr) = (io_stdout, io_stderr) try: try: exec(code,", "def queue_get(queue, process): ''' Remove and return an item from the queue. Block", "AssertionError('unexpected success') class TestFileSyntaxError(Exception): pass def _parse_test_header_file(file, path, *, comments_only): etags = []", "assert_emit_tags(path, expected) # ---------------------------------------- def get_coverage(): coverage = set() for filename in _get_test_filenames():", "message += ['stdout:'] message += ['| ' + s for s in stdout]", "encoding='UTF-8') # pylint: disable=consider-using-with except FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path,", "__init__(self, code, path, rest): self._s = s = '{code}: {path}: {rest}'.format( code=code, path=path,", "directory ''') def test_os_error_no_such_file(): with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'nonexistent.po') expected", "pass def wantFile(self, path): if path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here), '')): return True def loadTestsFromFile(self,", "__str__(self): return self.path class SubprocessError(Exception): pass def queue_get(queue, process): ''' Remove and return", "is hereby granted, free of charge, to any person obtaining a copy #", "and associated documentation files (the “Software”), to deal # in the Software without", "persons to whom the Software is # furnished to do so, subject to", "in data.items(): yield n, name _signal_names = dict(_get_signal_names()) def get_signal_name(n): try: return _signal_names[n]", "etags = list(etags) stdout = run_i18nspector(options, path) expected_failure = os.path.basename(path).startswith('xfail-') if stdout !=", "return _parse_test_header_file(file, path, comments_only=True) def _test_file(path, basedir=here): if basedir is not None: path", "globals()[inspect.stack()[1][0].f_code.co_name] # ---------------------------------------- _parse_etag = re.compile(r'([A-Z]): (([\\w-]+).*)').match def parse_etag(contents, path): match = _parse_etag(contents)", "Copyright © 2012-2021 <NAME> <<EMAIL>> # # Permission is hereby granted, free of", "conditions: # # The above copyright notice and this permission notice shall be", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "if path.startswith(os.path.join(os.path.abspath(here), '')): return True def loadTestsFromFile(self, path): if self.wantFile(path): yield TestCase(path) def", "yield os.path.join(root, filename) def test_file(): for filename in _get_test_filenames(): path = os.path.relpath(filename, start=here)", "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "if stdout != etags: if expected_failure: raise nose.SkipTest('expected failure') str_etags = [str(x) for", "Python modules, and use multiprocessing to # “emulate” the command execution. import lib.cli", "OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "str_etags = [str(x) for x in etags] message = ['Tags differ:', ''] diff", "s.decode('UTF-8').splitlines() for s in child.communicate() ) rc = child.poll() assert isinstance(rc, int) if", "etags) def get_coverage_for_function(fn): for etag in etags_from_tagstring(fn, ''): yield etag.tag def _get_test_filenames(): for", "_get_signal_names(): data = dict( (name, getattr(signal, name)) for name in dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name)", "['stdout:'] message += ['| ' + s for s in stdout] + ['']", "s for s in stdout] + [''] else: message += ['stdout: (empty)'] if", "[] for n, line in enumerate(file): orig_line = line if comments_only: if n", "this(): ''' Return function that called this function. (Hopefully!) ''' return globals()[inspect.stack()[1][0].f_code.co_name] #", "continue for tag in get_coverage_for_function(obj): coverage.add(tag) return coverage # vim:ts=4 sts=4 sw=4 et", "until the process terminates. ''' while True: try: return queue.get(timeout=1) # This semi-active", "to permit persons to whom the Software is # furnished to do so,", "ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "if getattr(func, 'redundant', False): return False class TestCase(unittest.TestCase): def __init__(self, path): super().__init__('_test') self.path", "os.path.join(root, filename) def test_file(): for filename in _get_test_filenames(): path = os.path.relpath(filename, start=here) yield", "from the queue. Block until the process terminates. ''' while True: try: return", "+= shlex.split(line) else: etag = parse_etag(line, path) if etag is None: if comments_only:", "pyflakes happy prog = os.path.join(here, os.pardir, os.pardir, 'i18nspector') commandline = [sys.executable, prog] queue", "line.startswith('#!'): continue if line.startswith('# '): line = line[2:] else: break if line.startswith('--'): options", "substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”,", "in self._split(s) ) self._regexp = re.compile('^{}$'.format(regexp)) def __eq__(self, other): if isinstance(other, str): return", "and use multiprocessing to # “emulate” the command execution. import lib.cli # pylint:", "self._s def __repr__(self): return repr(self._s) # ---------------------------------------- def _get_signal_names(): data = dict( (name,", "notice and this permission notice shall be included in # all copies or", "sys.exit(0) def assert_emit_tags(path, etags, *, options=()): etags = list(etags) stdout = run_i18nspector(options, path)", "of charge, to any person obtaining a copy # of this software and", "''') def test_os_error_no_such_file(): with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'nonexistent.po') expected =", "= shlex.split(commandline) commandline += options commandline += [path] fixed_env = dict(os.environ, PYTHONIOENCODING='UTF-8') with", "True # not needed if the plugin is enabled @tagstring(''' E: os-error No", "if expected_failure: raise nose.SkipTest('expected failure') str_etags = [str(x) for x in etags] message", "prog = os.path.join(here, os.pardir, os.pardir, 'i18nspector') commandline = [sys.executable, prog] queue = mp.Queue()", "test must not be run as root') with tools.temporary_directory() as tmpdir: path =", "[str(x) for x in etags] message = ['Tags differ:', ''] diff = list(", "needed Python modules, and use multiprocessing to # “emulate” the command execution. import", "0: message = ['command was interrupted by signal {sig}'.format(sig=get_signal_name(-rc))] # pylint: disable=invalid-unary-operand-type else:", "name = 'po-plugin' enabled = True def options(self, parser, env): pass def wantFile(self,", "*, comments_only): etags = [] options = [] for n, line in enumerate(file):", "( s.decode('UTF-8').splitlines() for s in child.communicate() ) rc = child.poll() assert isinstance(rc, int)", "and this permission notice shall be included in # all copies or substantial", "multiprocessing as mp import os import re import shlex import signal import subprocess", "for s in child.communicate() ) rc = child.poll() assert isinstance(rc, int) if rc", "be any # obvious better way. except mp.queues.Empty: if process.exitcode is None: continue", "the needed Python modules, and use multiprocessing to # “emulate” the command execution.", "so, subject to the following conditions: # # The above copyright notice and", "in _get_test_filenames(): for tag in get_coverage_for_file(filename): coverage.add(tag) for objname, obj in globals().items(): if", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION", "sys.stderr code = compile(code, prog, 'exec') io_stdout = io.StringIO() io_stderr = io.StringIO() gvars", "''] diff = list( difflib.unified_diff(str_etags, stdout, n=9999) ) message += diff[3:] raise AssertionError('\\n'.join(message))", "class ETag(): _ellipsis = '<...>' _split = re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self, code, path, rest):", "else: with file: return _parse_test_header_file(file, path, comments_only=False) # <path>.gen: try: file = open(path", "options = [] etags, options = _parse_test_headers(path) assert_emit_tags(path, etags, options=options) def get_coverage_for_file(path): etags,", "etag in etags_from_tagstring(fn, ''): yield etag.tag def _get_test_filenames(): for root, dirnames, filenames in", "def tagstring(s): def update(x): x.tagstring = s return x return update # ----------------------------------------", "try: docstring = obj.tagstring except AttributeError: return for line in docstring.splitlines(): line =", "---------------------------------------- def _get_signal_names(): data = dict( (name, getattr(signal, name)) for name in dir(signal)", "yield TestCase(path) def wantFunction(self, func): if getattr(func, 'redundant', False): return False class TestCase(unittest.TestCase):", "ugly, but there doesn't seem be any # obvious better way. except mp.queues.Empty:", "child.start() [stdout, stderr] = ( s.splitlines() for s in queue_get(queue, child) ) child.join()", "message += diff[3:] raise AssertionError('\\n'.join(message)) elif expected_failure: raise AssertionError('unexpected success') class TestFileSyntaxError(Exception): pass", "<path>: with open(path, 'rt', encoding='UTF-8', errors='ignore') as file: return _parse_test_header_file(file, path, comments_only=True) def", "Permission denied ''') def test_os_error_permission_denied(): if os.getuid() == 0: raise nose.SkipTest('this test must", ") self._regexp = re.compile('^{}$'.format(regexp)) def __eq__(self, other): if isinstance(other, str): return self._regexp.match(other) else:", "basedir=None) def __str__(self): return self.path class SubprocessError(Exception): pass def queue_get(queue, process): ''' Remove", "n == 0 and line.startswith('#!'): continue if line.startswith('# '): line = line[2:] else:", "except SystemExit: queue.put([stdout, stderr]) raise except: # pylint: disable=bare-except exctp, exc, tb =", "= os.path.join(tmpdir, 'nonexistent.po') expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) @tagstring(''' E: os-error Permission", "= set() for filename in _get_test_filenames(): for tag in get_coverage_for_file(filename): coverage.add(tag) for objname,", "True: try: return queue.get(timeout=1) # This semi-active waiting is ugly, but there doesn't", "disable=bare-except exctp, exc, tb = sys.exc_info() stderr += ''.join( traceback.format_exception(exctp, exc, tb) )", "except KeyError: return str(n) # ---------------------------------------- test_file_extensions = ('.mo', '.po', '.pot', '.pop') #", "_get_test_filenames(): path = os.path.relpath(filename, start=here) yield _test_file, path test_file.redundant = True # not", "commandline += [path] fixed_env = dict(os.environ, PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env) as", "called this function. (Hopefully!) ''' return globals()[inspect.stack()[1][0].f_code.co_name] # ---------------------------------------- _parse_etag = re.compile(r'([A-Z]): (([\\w-]+).*)').match", "_parse_test_header_file(file, path, comments_only=False) # <path>.gen: try: file = open(path + '.gen', encoding='UTF-8', errors='ignore')", "re import shlex import signal import subprocess as ipc import sys import traceback", "os.pardir, os.pardir, 'i18nspector') commandline = [sys.executable, prog] queue = mp.Queue() child = mp.Process(", "line.startswith('# '): line = line[2:] else: break if line.startswith('--'): options += shlex.split(line) else:", "way. except mp.queues.Empty: if process.exitcode is None: continue else: raise def run_i18nspector(options, path):", "= os.path.basename(path).startswith('xfail-') if stdout != etags: if expected_failure: raise nose.SkipTest('expected failure') str_etags =", "stdout] + [''] else: message += ['stdout: (empty)'] if stderr: message += ['stderr:']", "+= [etag] return etags, options def _parse_test_headers(path): # <path>.tags: try: file = open(path", "to the following conditions: # # The above copyright notice and this permission", "included in # all copies or substantial portions of the Software. # #", "such file or directory ''') def test_os_error_no_such_file(): with tools.temporary_directory() as tmpdir: path =", "else re.escape(chunk) for chunk in self._split(s) ) self._regexp = re.compile('^{}$'.format(regexp)) def __eq__(self, other):", "pylint: disable=bare-except exctp, exc, tb = sys.exc_info() stderr += ''.join( traceback.format_exception(exctp, exc, tb)", "_test_file, path test_file.redundant = True # not needed if the plugin is enabled", "yield n, name _signal_names = dict(_get_signal_names()) def get_signal_name(n): try: return _signal_names[n] except KeyError:", "dirnames, filenames in os.walk(here): del dirnames for filename in filenames: if not filename.endswith(test_file_extensions):", "line = line[2:] else: break if line.startswith('--'): options += shlex.split(line) else: etag =", "'.tags', encoding='UTF-8') # pylint: disable=consider-using-with except FileNotFoundError: pass else: with file: return _parse_test_header_file(file,", "[] etags, options = _parse_test_headers(path) assert_emit_tags(path, etags, options=options) def get_coverage_for_file(path): etags, options =", "''): yield etag.tag def _get_test_filenames(): for root, dirnames, filenames in os.walk(here): del dirnames", "'exec') io_stdout = io.StringIO() io_stderr = io.StringIO() gvars = dict( __file__=prog, ) (sys.stdout,", "data['SIGIOT'] except KeyError: pass try: if data['SIGCHLD'] == data['SIGCLD']: del data['SIGCLD'] except KeyError:", "in etags] message = ['Tags differ:', ''] diff = list( difflib.unified_diff(str_etags, stdout, n=9999)", "code=code, path=path, rest=rest, ) self.tag = rest.split(None, 1)[0] regexp = ''.join( '.*' if", "# hi, pydiatra! else: queue.put([stdout, stderr]) sys.exit(0) def assert_emit_tags(path, etags, *, options=()): etags", "0 and line.startswith('#!'): continue if line.startswith('# '): line = line[2:] else: break if", "def test_os_error_permission_denied(): if os.getuid() == 0: raise nose.SkipTest('this test must not be run", "expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) # ---------------------------------------- def get_coverage(): coverage = set()", "'po-plugin' enabled = True def options(self, parser, env): pass def wantFile(self, path): if", "stdout if rc < 0: message = ['command was interrupted by signal {sig}'.format(sig=get_signal_name(-rc))]", "errors='ignore') # pylint: disable=consider-using-with except FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path,", "+ list(options) + [path] orig_stdout = sys.stdout orig_stderr = sys.stderr code = compile(code,", "+= ''.join( traceback.format_exception(exctp, exc, tb) ) queue.put([stdout, stderr]) sys.exit(1) raise # hi, pydiatra!", ") message += diff[3:] raise AssertionError('\\n'.join(message)) elif expected_failure: raise AssertionError('unexpected success') class TestFileSyntaxError(Exception):", "unknown-file-type class Plugin(nose.plugins.Plugin): name = 'po-plugin' enabled = True def options(self, parser, env):", ".. import tools here = os.path.dirname(__file__) # ---------------------------------------- def this(): ''' Return function", "disable=invalid-unary-operand-type else: message = ['command exited with status {rc}'.format(rc=rc)] message += [''] if", "as root') with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'denied.po') with open(path, 'wb'):", "{rest}'.format( code=code, path=path, rest=rest, ) self.tag = rest.split(None, 1)[0] regexp = ''.join( '.*'", "n, line in enumerate(file): orig_line = line if comments_only: if n == 0", "['command exited with status {rc}'.format(rc=rc)] message += [''] if stdout: message += ['stdout:']", "True def loadTestsFromFile(self, path): if self.wantFile(path): yield TestCase(path) def wantFunction(self, func): if getattr(func,", "disable=import-outside-toplevel assert lib.cli # make pyflakes happy prog = os.path.join(here, os.pardir, os.pardir, 'i18nspector')", "raise nose.SkipTest('this test must not be run as root') with tools.temporary_directory() as tmpdir:", "= os.path.relpath(filename, start=here) yield _test_file, path test_file.redundant = True # not needed if", "data['SIGABRT'] == data['SIGIOT']: del data['SIGIOT'] except KeyError: pass try: if data['SIGCHLD'] == data['SIGCLD']:", "execution. import lib.cli # pylint: disable=import-outside-toplevel assert lib.cli # make pyflakes happy prog", "message += [''] if stdout: message += ['stdout:'] message += ['| ' +", "options(self, parser, env): pass def wantFile(self, path): if path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here), '')): return", "== self._ellipsis else re.escape(chunk) for chunk in self._split(s) ) self._regexp = re.compile('^{}$'.format(regexp)) def", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #", "stdout != etags: if expected_failure: raise nose.SkipTest('expected failure') str_etags = [str(x) for x", "import signal import subprocess as ipc import sys import traceback import unittest import", "class TestFileSyntaxError(Exception): pass def _parse_test_header_file(file, path, *, comments_only): etags = [] options =", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN", "os.walk(here): del dirnames for filename in filenames: if not filename.endswith(test_file_extensions): continue yield os.path.join(root,", "test_os_error_no_such_file(): with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'nonexistent.po') expected = etags_from_tagstring(this(), path)", "expected) @tagstring(''' E: os-error Permission denied ''') def test_os_error_permission_denied(): if os.getuid() == 0:", "'nonexistent.po') expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) @tagstring(''' E: os-error Permission denied ''')", "sublicense, and/or sell # copies of the Software, and to permit persons to", "Software is # furnished to do so, subject to the following conditions: #", "ETag(): _ellipsis = '<...>' _split = re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self, code, path, rest): self._s", "_parse_test_headers(path) del options return (t.tag for t in etags) def get_coverage_for_function(fn): for etag", "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "elif expected_failure: raise AssertionError('unexpected success') class TestFileSyntaxError(Exception): pass def _parse_test_header_file(file, path, *, comments_only):", "if chunk == self._ellipsis else re.escape(chunk) for chunk in self._split(s) ) self._regexp =", "_parse_test_header_file(file, path, *, comments_only): etags = [] options = [] for n, line", "assert_emit_tags(path, etags, *, options=()): etags = list(etags) stdout = run_i18nspector(options, path) expected_failure =", "io_stderr = io.StringIO() gvars = dict( __file__=prog, ) (sys.stdout, sys.stderr) = (io_stdout, io_stderr)", "regexp = ''.join( '.*' if chunk == self._ellipsis else re.escape(chunk) for chunk in", "+ [''] else: message += ['stdout: (empty)'] if stderr: message += ['stderr:'] message", "import sys import traceback import unittest import nose import nose.plugins from .. import", "CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", ") (sys.stdout, sys.stderr) = (io_stdout, io_stderr) try: try: exec(code, gvars) # pylint: disable=exec-used", "OR OTHER DEALINGS IN THE # SOFTWARE. import difflib import inspect import io", "OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "process): ''' Remove and return an item from the queue. Block until the", "run as root') with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'denied.po') with open(path,", "command execution. import lib.cli # pylint: disable=import-outside-toplevel assert lib.cli # make pyflakes happy", "= [str(x) for x in etags] message = ['Tags differ:', ''] diff =", "queue.get(timeout=1) # This semi-active waiting is ugly, but there doesn't seem be any", "except AttributeError: return for line in docstring.splitlines(): line = line.lstrip() t = parse_etag(line,", "expected_failure: raise AssertionError('unexpected success') class TestFileSyntaxError(Exception): pass def _parse_test_header_file(file, path, *, comments_only): etags", "associated documentation files (the “Software”), to deal # in the Software without restriction,", "# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS", "match.group(2)) return t def etags_from_tagstring(obj, path): try: docstring = obj.tagstring except AttributeError: return", "_signal_names = dict(_get_signal_names()) def get_signal_name(n): try: return _signal_names[n] except KeyError: return str(n) #", "@tagstring(''' E: os-error Permission denied ''') def test_os_error_permission_denied(): if os.getuid() == 0: raise", "list(options) + [path] orig_stdout = sys.stdout orig_stderr = sys.stderr code = compile(code, prog,", "ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env) as child: stdout, stderr = ( s.decode('UTF-8').splitlines() for s", "except FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path, comments_only=True) # <path>: with", "# pylint: disable=exec-used finally: (sys.stdout, sys.stderr) = (orig_stdout, orig_stderr) stdout = io_stdout.getvalue() stderr", "# obvious better way. except mp.queues.Empty: if process.exitcode is None: continue else: raise", "io.StringIO() gvars = dict( __file__=prog, ) (sys.stdout, sys.stderr) = (io_stdout, io_stderr) try: try:", "pydiatra! else: queue.put([stdout, stderr]) sys.exit(0) def assert_emit_tags(path, etags, *, options=()): etags = list(etags)", "trigger unknown-file-type class Plugin(nose.plugins.Plugin): name = 'po-plugin' enabled = True def options(self, parser,", "message += ['stderr: (empty)'] raise SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog, options, path, queue): with open(prog,", "= '{code}: {path}: {rest}'.format( code=code, path=path, rest=rest, ) self.tag = rest.split(None, 1)[0] regexp", "'denied.po') with open(path, 'wb'): pass os.chmod(path, 0) expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected)", "pass else: with file: return _parse_test_header_file(file, path, comments_only=True) # <path>: with open(path, 'rt',", "= True # not needed if the plugin is enabled @tagstring(''' E: os-error", "else: message += ['stdout: (empty)'] if stderr: message += ['stderr:'] message += ['|", "# copies of the Software, and to permit persons to whom the Software", "enumerate(file): orig_line = line if comments_only: if n == 0 and line.startswith('#!'): continue", "return NotImplemented def __str__(self): return self._s def __repr__(self): return repr(self._s) # ---------------------------------------- def", "t def tagstring(s): def update(x): x.tagstring = s return x return update #", "DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "path, rest): self._s = s = '{code}: {path}: {rest}'.format( code=code, path=path, rest=rest, )", "for name, n in data.items(): yield n, name _signal_names = dict(_get_signal_names()) def get_signal_name(n):", "None: # We cheat here a bit, because exec(3)ing is very expensive. #", "rc = child.poll() assert isinstance(rc, int) if rc == 0: return stdout if", "def etags_from_tagstring(obj, path): try: docstring = obj.tagstring except AttributeError: return for line in", "self._split(s) ) self._regexp = re.compile('^{}$'.format(regexp)) def __eq__(self, other): if isinstance(other, str): return self._regexp.match(other)", "© 2012-2021 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge,", "def get_signal_name(n): try: return _signal_names[n] except KeyError: return str(n) # ---------------------------------------- test_file_extensions =", "load the needed Python modules, and use multiprocessing to # “emulate” the command", "args=(prog, options, path, queue) ) child.start() [stdout, stderr] = ( s.splitlines() for s", "[stdout, stderr] = ( s.splitlines() for s in queue_get(queue, child) ) child.join() rc", "def _parse_test_headers(path): # <path>.tags: try: file = open(path + '.tags', encoding='UTF-8') # pylint:", "assert_emit_tags(path, etags, options=options) def get_coverage_for_file(path): etags, options = _parse_test_headers(path) del options return (t.tag", "if commandline is None: # We cheat here a bit, because exec(3)ing is", "root, dirnames, filenames in os.walk(here): del dirnames for filename in filenames: if not", "ipc import sys import traceback import unittest import nose import nose.plugins from ..", "the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF", "by signal {sig}'.format(sig=get_signal_name(-rc))] # pylint: disable=invalid-unary-operand-type else: message = ['command exited with status", "pass def _parse_test_header_file(file, path, *, comments_only): etags = [] options = [] for", "path) expected_failure = os.path.basename(path).startswith('xfail-') if stdout != etags: if expected_failure: raise nose.SkipTest('expected failure')", "if t is not None: yield t def tagstring(s): def update(x): x.tagstring =", "this permission notice shall be included in # all copies or substantial portions", "(Hopefully!) ''' return globals()[inspect.stack()[1][0].f_code.co_name] # ---------------------------------------- _parse_etag = re.compile(r'([A-Z]): (([\\w-]+).*)').match def parse_etag(contents, path):", "return True def loadTestsFromFile(self, path): if self.wantFile(path): yield TestCase(path) def wantFunction(self, func): if", "[prog] + list(options) + [path] orig_stdout = sys.stdout orig_stderr = sys.stderr code =", "or directory ''') def test_os_error_no_such_file(): with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'nonexistent.po')", "in enumerate(file): orig_line = line if comments_only: if n == 0 and line.startswith('#!'):", "class TestCase(unittest.TestCase): def __init__(self, path): super().__init__('_test') self.path = os.path.relpath(path) def _test(self): _test_file(self.path, basedir=None)", "= open(path + '.gen', encoding='UTF-8', errors='ignore') # pylint: disable=consider-using-with except FileNotFoundError: pass else:", "NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "difflib import inspect import io import multiprocessing as mp import os import re", "Remove and return an item from the queue. Block until the process terminates.", "os.path.relpath(filename, start=here) yield _test_file, path test_file.redundant = True # not needed if the", "else: etag = parse_etag(line, path) if etag is None: if comments_only: break else:", "yield etag.tag def _get_test_filenames(): for root, dirnames, filenames in os.walk(here): del dirnames for", "shlex.split(commandline) commandline += options commandline += [path] fixed_env = dict(os.environ, PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline,", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT", "(([\\w-]+).*)').match def parse_etag(contents, path): match = _parse_etag(contents) if match is None: return t", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #", "is a special extension to trigger unknown-file-type class Plugin(nose.plugins.Plugin): name = 'po-plugin' enabled", "= ['command exited with status {rc}'.format(rc=rc)] message += [''] if stdout: message +=", "expected) # ---------------------------------------- def get_coverage(): coverage = set() for filename in _get_test_filenames(): for", "== data['SIGIOT']: del data['SIGIOT'] except KeyError: pass try: if data['SIGCHLD'] == data['SIGCLD']: del", "int) if rc == 0: return stdout if rc < 0: message =", "a copy # of this software and associated documentation files (the “Software”), to", "<path>.gen: try: file = open(path + '.gen', encoding='UTF-8', errors='ignore') # pylint: disable=consider-using-with except", "= os.path.relpath(os.path.join(basedir, path), start=os.getcwd()) options = [] etags, options = _parse_test_headers(path) assert_emit_tags(path, etags,", "t in etags) def get_coverage_for_function(fn): for etag in etags_from_tagstring(fn, ''): yield etag.tag def", "os.path.relpath(path) def _test(self): _test_file(self.path, basedir=None) def __str__(self): return self.path class SubprocessError(Exception): pass def", "# make pyflakes happy prog = os.path.join(here, os.pardir, os.pardir, 'i18nspector') commandline = [sys.executable,", "encoding='UTF-8', errors='ignore') # pylint: disable=consider-using-with except FileNotFoundError: pass else: with file: return _parse_test_header_file(file,", "commandline = shlex.split(commandline) commandline += options commandline += [path] fixed_env = dict(os.environ, PYTHONIOENCODING='UTF-8')", "and to permit persons to whom the Software is # furnished to do", "+ '.gen', encoding='UTF-8', errors='ignore') # pylint: disable=consider-using-with except FileNotFoundError: pass else: with file:", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the", "def __str__(self): return self.path class SubprocessError(Exception): pass def queue_get(queue, process): ''' Remove and", "return str(n) # ---------------------------------------- test_file_extensions = ('.mo', '.po', '.pot', '.pop') # .pop is", "s in stdout] + [''] else: message += ['stdout: (empty)'] if stderr: message", "re.compile('^{}$'.format(regexp)) def __eq__(self, other): if isinstance(other, str): return self._regexp.match(other) else: return NotImplemented def", "the following conditions: # # The above copyright notice and this permission notice", "= (orig_stdout, orig_stderr) stdout = io_stdout.getvalue() stderr = io_stderr.getvalue() except SystemExit: queue.put([stdout, stderr])", "TestFileSyntaxError(Exception): pass def _parse_test_header_file(file, path, *, comments_only): etags = [] options = []", "except FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path, comments_only=False) # <path>.gen: try:", "(sys.stdout, sys.stderr) = (orig_stdout, orig_stderr) stdout = io_stdout.getvalue() stderr = io_stderr.getvalue() except SystemExit:", "basedir=here): if basedir is not None: path = os.path.relpath(os.path.join(basedir, path), start=os.getcwd()) options =", "super().__init__('_test') self.path = os.path.relpath(path) def _test(self): _test_file(self.path, basedir=None) def __str__(self): return self.path class", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND", "''' return globals()[inspect.stack()[1][0].f_code.co_name] # ---------------------------------------- _parse_etag = re.compile(r'([A-Z]): (([\\w-]+).*)').match def parse_etag(contents, path): match", "expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) @tagstring(''' E: os-error Permission denied ''') def", "# furnished to do so, subject to the following conditions: # # The", "the Software, and to permit persons to whom the Software is # furnished", "rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #", "os.path.dirname(__file__) # ---------------------------------------- def this(): ''' Return function that called this function. (Hopefully!)", "def __eq__(self, other): if isinstance(other, str): return self._regexp.match(other) else: return NotImplemented def __str__(self):", "True def options(self, parser, env): pass def wantFile(self, path): if path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here),", "queue_get(queue, child) ) child.join() rc = child.exitcode else: commandline = shlex.split(commandline) commandline +=", "path = os.path.join(tmpdir, 'denied.po') with open(path, 'wb'): pass os.chmod(path, 0) expected = etags_from_tagstring(this(),", "“emulate” the command execution. import lib.cli # pylint: disable=import-outside-toplevel assert lib.cli # make", "etags_from_tagstring(this(), path) assert_emit_tags(path, expected) @tagstring(''' E: os-error Permission denied ''') def test_os_error_permission_denied(): if", "def wantFile(self, path): if path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here), '')): return True def loadTestsFromFile(self, path):", "path=path, rest=rest, ) self.tag = rest.split(None, 1)[0] regexp = ''.join( '.*' if chunk", "FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF", "rest.split(None, 1)[0] regexp = ''.join( '.*' if chunk == self._ellipsis else re.escape(chunk) for", "'<...>' _split = re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self, code, path, rest): self._s = s =", ") child.start() [stdout, stderr] = ( s.splitlines() for s in queue_get(queue, child) )", "path, queue): with open(prog, 'rt', encoding='UTF-8') as file: code = file.read() sys.argv =", "import traceback import unittest import nose import nose.plugins from .. import tools here", "raise TestFileSyntaxError(orig_line) etags += [etag] return etags, options def _parse_test_headers(path): # <path>.tags: try:", "s in child.communicate() ) rc = child.poll() assert isinstance(rc, int) if rc ==", "= open(path + '.tags', encoding='UTF-8') # pylint: disable=consider-using-with except FileNotFoundError: pass else: with", "< 0: message = ['command was interrupted by signal {sig}'.format(sig=get_signal_name(-rc))] # pylint: disable=invalid-unary-operand-type", "merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to", "start=os.getcwd()) options = [] etags, options = _parse_test_headers(path) assert_emit_tags(path, etags, options=options) def get_coverage_for_file(path):", "NotImplemented def __str__(self): return self._s def __repr__(self): return repr(self._s) # ---------------------------------------- def _get_signal_names():", "OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "[path] fixed_env = dict(os.environ, PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env) as child: stdout,", "(empty)'] if stderr: message += ['stderr:'] message += ['| ' + s for", "disable=consider-using-with except FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path, comments_only=False) # <path>.gen:", "# Copyright © 2012-2021 <NAME> <<EMAIL>> # # Permission is hereby granted, free", "def update(x): x.tagstring = s return x return update # ---------------------------------------- class ETag():", "ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "def loadTestsFromFile(self, path): if self.wantFile(path): yield TestCase(path) def wantFunction(self, func): if getattr(func, 'redundant',", "happy prog = os.path.join(here, os.pardir, os.pardir, 'i18nspector') commandline = [sys.executable, prog] queue =", "in stdout] + [''] else: message += ['stdout: (empty)'] if stderr: message +=", "in # all copies or substantial portions of the Software. # # THE", "success') class TestFileSyntaxError(Exception): pass def _parse_test_header_file(file, path, *, comments_only): etags = [] options", "s for s in stderr] else: message += ['stderr: (empty)'] raise SubprocessError('\\n'.join(message)) def", "to do so, subject to the following conditions: # # The above copyright", "io_stderr) try: try: exec(code, gvars) # pylint: disable=exec-used finally: (sys.stdout, sys.stderr) = (orig_stdout,", "<gh_stars>1-10 # Copyright © 2012-2021 <NAME> <<EMAIL>> # # Permission is hereby granted,", "= re.compile('^{}$'.format(regexp)) def __eq__(self, other): if isinstance(other, str): return self._regexp.match(other) else: return NotImplemented", "# ---------------------------------------- def _get_signal_names(): data = dict( (name, getattr(signal, name)) for name in", "# pylint: disable=invalid-unary-operand-type else: message = ['command exited with status {rc}'.format(rc=rc)] message +=", "diff = list( difflib.unified_diff(str_etags, stdout, n=9999) ) message += diff[3:] raise AssertionError('\\n'.join(message)) elif", "if comments_only: if n == 0 and line.startswith('#!'): continue if line.startswith('# '): line", "signal {sig}'.format(sig=get_signal_name(-rc))] # pylint: disable=invalid-unary-operand-type else: message = ['command exited with status {rc}'.format(rc=rc)]", "in etags) def get_coverage_for_function(fn): for etag in etags_from_tagstring(fn, ''): yield etag.tag def _get_test_filenames():", "difflib.unified_diff(str_etags, stdout, n=9999) ) message += diff[3:] raise AssertionError('\\n'.join(message)) elif expected_failure: raise AssertionError('unexpected", "etags, options=options) def get_coverage_for_file(path): etags, options = _parse_test_headers(path) del options return (t.tag for", "= line.lstrip() t = parse_etag(line, path) if t is not None: yield t", "etags_from_tagstring(this(), path) assert_emit_tags(path, expected) # ---------------------------------------- def get_coverage(): coverage = set() for filename", "process terminates. ''' while True: try: return queue.get(timeout=1) # This semi-active waiting is", "rest=rest, ) self.tag = rest.split(None, 1)[0] regexp = ''.join( '.*' if chunk ==", "stderr: message += ['stderr:'] message += ['| ' + s for s in", "['stderr:'] message += ['| ' + s for s in stderr] else: message", "in stderr] else: message += ['stderr: (empty)'] raise SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog, options, path,", "None: if comments_only: break else: raise TestFileSyntaxError(orig_line) etags += [etag] return etags, options", "del data['SIGIOT'] except KeyError: pass try: if data['SIGCHLD'] == data['SIGCLD']: del data['SIGCLD'] except", "+= ['| ' + s for s in stdout] + [''] else: message", "filename in filenames: if not filename.endswith(test_file_extensions): continue yield os.path.join(root, filename) def test_file(): for", "self._s = s = '{code}: {path}: {rest}'.format( code=code, path=path, rest=rest, ) self.tag =", "test_file.redundant = True # not needed if the plugin is enabled @tagstring(''' E:", "unittest import nose import nose.plugins from .. import tools here = os.path.dirname(__file__) #", "denied ''') def test_os_error_permission_denied(): if os.getuid() == 0: raise nose.SkipTest('this test must not", "item from the queue. Block until the process terminates. ''' while True: try:", "_parse_etag = re.compile(r'([A-Z]): (([\\w-]+).*)').match def parse_etag(contents, path): match = _parse_etag(contents) if match is", "dict( __file__=prog, ) (sys.stdout, sys.stderr) = (io_stdout, io_stderr) try: try: exec(code, gvars) #", "globals().items(): if not objname.startswith('test_'): continue for tag in get_coverage_for_function(obj): coverage.add(tag) return coverage #", "try: return _signal_names[n] except KeyError: return str(n) # ---------------------------------------- test_file_extensions = ('.mo', '.po',", "etags_from_tagstring(fn, ''): yield etag.tag def _get_test_filenames(): for root, dirnames, filenames in os.walk(here): del", "shlex import signal import subprocess as ipc import sys import traceback import unittest", "data['SIGIOT']: del data['SIGIOT'] except KeyError: pass try: if data['SIGCHLD'] == data['SIGCLD']: del data['SIGCLD']", "copy # of this software and associated documentation files (the “Software”), to deal", "set() for filename in _get_test_filenames(): for tag in get_coverage_for_file(filename): coverage.add(tag) for objname, obj", "loadTestsFromFile(self, path): if self.wantFile(path): yield TestCase(path) def wantFunction(self, func): if getattr(func, 'redundant', False):", "an item from the queue. Block until the process terminates. ''' while True:", "import re import shlex import signal import subprocess as ipc import sys import", "whom the Software is # furnished to do so, subject to the following", "mp.queues.Empty: if process.exitcode is None: continue else: raise def run_i18nspector(options, path): commandline =", "rc == 0: return stdout if rc < 0: message = ['command was", "IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH", "re.escape(chunk) for chunk in self._split(s) ) self._regexp = re.compile('^{}$'.format(regexp)) def __eq__(self, other): if", "repr(self._s) # ---------------------------------------- def _get_signal_names(): data = dict( (name, getattr(signal, name)) for name", "def options(self, parser, env): pass def wantFile(self, path): if path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here), '')):", "['| ' + s for s in stderr] else: message += ['stderr: (empty)']", "options commandline += [path] fixed_env = dict(os.environ, PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env)", "tb) ) queue.put([stdout, stderr]) sys.exit(1) raise # hi, pydiatra! else: queue.put([stdout, stderr]) sys.exit(0)", "None: path = os.path.relpath(os.path.join(basedir, path), start=os.getcwd()) options = [] etags, options = _parse_test_headers(path)", "' + s for s in stdout] + [''] else: message += ['stdout:", "assert_emit_tags(path, expected) @tagstring(''' E: os-error Permission denied ''') def test_os_error_permission_denied(): if os.getuid() ==", "__init__(self, path): super().__init__('_test') self.path = os.path.relpath(path) def _test(self): _test_file(self.path, basedir=None) def __str__(self): return", "free of charge, to any person obtaining a copy # of this software", "obtaining a copy # of this software and associated documentation files (the “Software”),", "+ s for s in stderr] else: message += ['stderr: (empty)'] raise SubprocessError('\\n'.join(message))", "path) assert_emit_tags(path, expected) # ---------------------------------------- def get_coverage(): coverage = set() for filename in", "SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog, options, path, queue): with open(prog, 'rt', encoding='UTF-8') as file: code", "parse_etag(line, path) if etag is None: if comments_only: break else: raise TestFileSyntaxError(orig_line) etags", "data.items(): yield n, name _signal_names = dict(_get_signal_names()) def get_signal_name(n): try: return _signal_names[n] except", "s in stderr] else: message += ['stderr: (empty)'] raise SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog, options,", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT", "options += shlex.split(line) else: etag = parse_etag(line, path) if etag is None: if", "for n, line in enumerate(file): orig_line = line if comments_only: if n ==", "copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software,", "path): try: docstring = obj.tagstring except AttributeError: return for line in docstring.splitlines(): line", "comments_only: break else: raise TestFileSyntaxError(orig_line) etags += [etag] return etags, options def _parse_test_headers(path):", "get_coverage_for_file(path): etags, options = _parse_test_headers(path) del options return (t.tag for t in etags)", "get_coverage_for_file(filename): coverage.add(tag) for objname, obj in globals().items(): if not objname.startswith('test_'): continue for tag", "_parse_test_headers(path) assert_emit_tags(path, etags, options=options) def get_coverage_for_file(path): etags, options = _parse_test_headers(path) del options return", "1)[0] regexp = ''.join( '.*' if chunk == self._ellipsis else re.escape(chunk) for chunk", "= os.path.relpath(path) def _test(self): _test_file(self.path, basedir=None) def __str__(self): return self.path class SubprocessError(Exception): pass", "without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense,", "here = os.path.dirname(__file__) # ---------------------------------------- def this(): ''' Return function that called this", "try: exec(code, gvars) # pylint: disable=exec-used finally: (sys.stdout, sys.stderr) = (orig_stdout, orig_stderr) stdout", "code = compile(code, prog, 'exec') io_stdout = io.StringIO() io_stderr = io.StringIO() gvars =", "is # furnished to do so, subject to the following conditions: # #", "path, comments_only=False) # <path>.gen: try: file = open(path + '.gen', encoding='UTF-8', errors='ignore') #", "os.getuid() == 0: raise nose.SkipTest('this test must not be run as root') with", "_test(self): _test_file(self.path, basedir=None) def __str__(self): return self.path class SubprocessError(Exception): pass def queue_get(queue, process):", "or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS", "x.tagstring = s return x return update # ---------------------------------------- class ETag(): _ellipsis =", "tmpdir: path = os.path.join(tmpdir, 'nonexistent.po') expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) @tagstring(''' E:", "''' while True: try: return queue.get(timeout=1) # This semi-active waiting is ugly, but", "nose.SkipTest('this test must not be run as root') with tools.temporary_directory() as tmpdir: path", "commandline = os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline is None: # We cheat here a bit,", "raise except: # pylint: disable=bare-except exctp, exc, tb = sys.exc_info() stderr += ''.join(", "'i18nspector') commandline = [sys.executable, prog] queue = mp.Queue() child = mp.Process( target=_mp_run_i18nspector, args=(prog,", "# <path>.gen: try: file = open(path + '.gen', encoding='UTF-8', errors='ignore') # pylint: disable=consider-using-with", "0: raise nose.SkipTest('this test must not be run as root') with tools.temporary_directory() as", "pass os.chmod(path, 0) expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) # ---------------------------------------- def get_coverage():", "to deal # in the Software without restriction, including without limitation the rights", "not None: yield t def tagstring(s): def update(x): x.tagstring = s return x", "# pylint: disable=bare-except exctp, exc, tb = sys.exc_info() stderr += ''.join( traceback.format_exception(exctp, exc,", "to any person obtaining a copy # of this software and associated documentation", "t = ETag(match.group(1), path, match.group(2)) return t def etags_from_tagstring(obj, path): try: docstring =", "etags = [] options = [] for n, line in enumerate(file): orig_line =", "assert isinstance(rc, int) if rc == 0: return stdout if rc < 0:", "<path>.tags: try: file = open(path + '.tags', encoding='UTF-8') # pylint: disable=consider-using-with except FileNotFoundError:", "re.compile('^SIG[A-Z0-9]*$').match(name) ) try: if data['SIGABRT'] == data['SIGIOT']: del data['SIGIOT'] except KeyError: pass try:", "comments_only=True) def _test_file(path, basedir=here): if basedir is not None: path = os.path.relpath(os.path.join(basedir, path),", "path.startswith(os.path.join(os.path.abspath(here), '')): return True def loadTestsFromFile(self, path): if self.wantFile(path): yield TestCase(path) def wantFunction(self,", "= '<...>' _split = re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self, code, path, rest): self._s = s", "with open(path, 'rt', encoding='UTF-8', errors='ignore') as file: return _parse_test_header_file(file, path, comments_only=True) def _test_file(path,", "there doesn't seem be any # obvious better way. except mp.queues.Empty: if process.exitcode", "PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING", "orig_line = line if comments_only: if n == 0 and line.startswith('#!'): continue if", "not filename.endswith(test_file_extensions): continue yield os.path.join(root, filename) def test_file(): for filename in _get_test_filenames(): path", "permission notice shall be included in # all copies or substantial portions of", "def wantFunction(self, func): if getattr(func, 'redundant', False): return False class TestCase(unittest.TestCase): def __init__(self,", "nose import nose.plugins from .. import tools here = os.path.dirname(__file__) # ---------------------------------------- def", "OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #", "path) if etag is None: if comments_only: break else: raise TestFileSyntaxError(orig_line) etags +=", "stdout, stderr = ( s.decode('UTF-8').splitlines() for s in child.communicate() ) rc = child.poll()", "else: break if line.startswith('--'): options += shlex.split(line) else: etag = parse_etag(line, path) if", "= ( s.decode('UTF-8').splitlines() for s in child.communicate() ) rc = child.poll() assert isinstance(rc,", "portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT", "SystemExit: queue.put([stdout, stderr]) raise except: # pylint: disable=bare-except exctp, exc, tb = sys.exc_info()", "this software and associated documentation files (the “Software”), to deal # in the", "mp.Process( target=_mp_run_i18nspector, args=(prog, options, path, queue) ) child.start() [stdout, stderr] = ( s.splitlines()", "use multiprocessing to # “emulate” the command execution. import lib.cli # pylint: disable=import-outside-toplevel", "sys.stdout orig_stderr = sys.stderr code = compile(code, prog, 'exec') io_stdout = io.StringIO() io_stderr", "in get_coverage_for_file(filename): coverage.add(tag) for objname, obj in globals().items(): if not objname.startswith('test_'): continue for", "THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "self.path class SubprocessError(Exception): pass def queue_get(queue, process): ''' Remove and return an item", "wantFunction(self, func): if getattr(func, 'redundant', False): return False class TestCase(unittest.TestCase): def __init__(self, path):", "{rc}'.format(rc=rc)] message += [''] if stdout: message += ['stdout:'] message += ['| '", "= mp.Queue() child = mp.Process( target=_mp_run_i18nspector, args=(prog, options, path, queue) ) child.start() [stdout,", "in queue_get(queue, child) ) child.join() rc = child.exitcode else: commandline = shlex.split(commandline) commandline", "'.pop') # .pop is a special extension to trigger unknown-file-type class Plugin(nose.plugins.Plugin): name", "dirnames for filename in filenames: if not filename.endswith(test_file_extensions): continue yield os.path.join(root, filename) def", "THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import difflib import inspect", "*, options=()): etags = list(etags) stdout = run_i18nspector(options, path) expected_failure = os.path.basename(path).startswith('xfail-') if", "here a bit, because exec(3)ing is very expensive. # Let's load the needed", "stderr] = ( s.splitlines() for s in queue_get(queue, child) ) child.join() rc =", "OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE", "= ETag(match.group(1), path, match.group(2)) return t def etags_from_tagstring(obj, path): try: docstring = obj.tagstring", "for filename in _get_test_filenames(): for tag in get_coverage_for_file(filename): coverage.add(tag) for objname, obj in", "orig_stdout = sys.stdout orig_stderr = sys.stderr code = compile(code, prog, 'exec') io_stdout =", "if line.startswith('--'): options += shlex.split(line) else: etag = parse_etag(line, path) if etag is", "+= options commandline += [path] fixed_env = dict(os.environ, PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #", "SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "return repr(self._s) # ---------------------------------------- def _get_signal_names(): data = dict( (name, getattr(signal, name)) for", "= run_i18nspector(options, path) expected_failure = os.path.basename(path).startswith('xfail-') if stdout != etags: if expected_failure: raise", "[] options = [] for n, line in enumerate(file): orig_line = line if", "for s in stdout] + [''] else: message += ['stdout: (empty)'] if stderr:", "data = dict( (name, getattr(signal, name)) for name in dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name) )", "# ---------------------------------------- class ETag(): _ellipsis = '<...>' _split = re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self, code,", "re.compile(r'([A-Z]): (([\\w-]+).*)').match def parse_etag(contents, path): match = _parse_etag(contents) if match is None: return", "USE OR OTHER DEALINGS IN THE # SOFTWARE. import difflib import inspect import", "get_signal_name(n): try: return _signal_names[n] except KeyError: return str(n) # ---------------------------------------- test_file_extensions = ('.mo',", "try: return queue.get(timeout=1) # This semi-active waiting is ugly, but there doesn't seem", "commandline is None: # We cheat here a bit, because exec(3)ing is very", "assert lib.cli # make pyflakes happy prog = os.path.join(here, os.pardir, os.pardir, 'i18nspector') commandline", "the command execution. import lib.cli # pylint: disable=import-outside-toplevel assert lib.cli # make pyflakes", "child.communicate() ) rc = child.poll() assert isinstance(rc, int) if rc == 0: return", "+= ['stdout:'] message += ['| ' + s for s in stdout] +", "[''] if stdout: message += ['stdout:'] message += ['| ' + s for", "os.chmod(path, 0) expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) # ---------------------------------------- def get_coverage(): coverage", "Software, and to permit persons to whom the Software is # furnished to", "queue.put([stdout, stderr]) raise except: # pylint: disable=bare-except exctp, exc, tb = sys.exc_info() stderr", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import difflib", "line = line.lstrip() t = parse_etag(line, path) if t is not None: yield", "return etags, options def _parse_test_headers(path): # <path>.tags: try: file = open(path + '.tags',", "raise nose.SkipTest('expected failure') str_etags = [str(x) for x in etags] message = ['Tags", "signal import subprocess as ipc import sys import traceback import unittest import nose", "errors='ignore') as file: return _parse_test_header_file(file, path, comments_only=True) def _test_file(path, basedir=here): if basedir is", "io_stderr.getvalue() except SystemExit: queue.put([stdout, stderr]) raise except: # pylint: disable=bare-except exctp, exc, tb", "basedir is not None: path = os.path.relpath(os.path.join(basedir, path), start=os.getcwd()) options = [] etags,", "'wb'): pass os.chmod(path, 0) expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) # ---------------------------------------- def", "sys.exc_info() stderr += ''.join( traceback.format_exception(exctp, exc, tb) ) queue.put([stdout, stderr]) sys.exit(1) raise #", "getattr(signal, name)) for name in dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name) ) try: if data['SIGABRT'] ==", "fixed_env = dict(os.environ, PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env) as child: stdout, stderr", "# We cheat here a bit, because exec(3)ing is very expensive. # Let's", "[path] orig_stdout = sys.stdout orig_stderr = sys.stderr code = compile(code, prog, 'exec') io_stdout", "path) if t is not None: yield t def tagstring(s): def update(x): x.tagstring", "= sys.stderr code = compile(code, prog, 'exec') io_stdout = io.StringIO() io_stderr = io.StringIO()", "is None: # We cheat here a bit, because exec(3)ing is very expensive.", "IN THE # SOFTWARE. import difflib import inspect import io import multiprocessing as", "in dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name) ) try: if data['SIGABRT'] == data['SIGIOT']: del data['SIGIOT'] except", "data['SIGCHLD'] == data['SIGCLD']: del data['SIGCLD'] except KeyError: pass for name, n in data.items():", "# of this software and associated documentation files (the “Software”), to deal #", "OTHER DEALINGS IN THE # SOFTWARE. import difflib import inspect import io import", "+= ['stderr:'] message += ['| ' + s for s in stderr] else:", "line in docstring.splitlines(): line = line.lstrip() t = parse_etag(line, path) if t is", "shall be included in # all copies or substantial portions of the Software.", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,", "KeyError: return str(n) # ---------------------------------------- test_file_extensions = ('.mo', '.po', '.pot', '.pop') # .pop", "name _signal_names = dict(_get_signal_names()) def get_signal_name(n): try: return _signal_names[n] except KeyError: return str(n)", "but there doesn't seem be any # obvious better way. except mp.queues.Empty: if", "child = mp.Process( target=_mp_run_i18nspector, args=(prog, options, path, queue) ) child.start() [stdout, stderr] =", "lib.cli # pylint: disable=import-outside-toplevel assert lib.cli # make pyflakes happy prog = os.path.join(here,", "= re.compile(r'([A-Z]): (([\\w-]+).*)').match def parse_etag(contents, path): match = _parse_etag(contents) if match is None:", "granted, free of charge, to any person obtaining a copy # of this", "enabled = True def options(self, parser, env): pass def wantFile(self, path): if path.endswith(test_file_extensions):", "except: # pylint: disable=bare-except exctp, exc, tb = sys.exc_info() stderr += ''.join( traceback.format_exception(exctp,", "('.mo', '.po', '.pot', '.pop') # .pop is a special extension to trigger unknown-file-type", "path): commandline = os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline is None: # We cheat here a", "io_stdout.getvalue() stderr = io_stderr.getvalue() except SystemExit: queue.put([stdout, stderr]) raise except: # pylint: disable=bare-except", "options return (t.tag for t in etags) def get_coverage_for_function(fn): for etag in etags_from_tagstring(fn,", "return update # ---------------------------------------- class ETag(): _ellipsis = '<...>' _split = re.compile('({})'.format(re.escape(_ellipsis))).split def", "None: return t = ETag(match.group(1), path, match.group(2)) return t def etags_from_tagstring(obj, path): try:", "return t def etags_from_tagstring(obj, path): try: docstring = obj.tagstring except AttributeError: return for", "TestCase(path) def wantFunction(self, func): if getattr(func, 'redundant', False): return False class TestCase(unittest.TestCase): def", ") self.tag = rest.split(None, 1)[0] regexp = ''.join( '.*' if chunk == self._ellipsis", "for filename in _get_test_filenames(): path = os.path.relpath(filename, start=here) yield _test_file, path test_file.redundant =", "if process.exitcode is None: continue else: raise def run_i18nspector(options, path): commandline = os.environ.get('I18NSPECTOR_COMMANDLINE')", "tag in get_coverage_for_file(filename): coverage.add(tag) for objname, obj in globals().items(): if not objname.startswith('test_'): continue", "+= ['stdout: (empty)'] if stderr: message += ['stderr:'] message += ['| ' +", "prog, 'exec') io_stdout = io.StringIO() io_stderr = io.StringIO() gvars = dict( __file__=prog, )", "if data['SIGCHLD'] == data['SIGCLD']: del data['SIGCLD'] except KeyError: pass for name, n in", "furnished to do so, subject to the following conditions: # # The above", "import lib.cli # pylint: disable=import-outside-toplevel assert lib.cli # make pyflakes happy prog =", "modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and", "ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "from .. import tools here = os.path.dirname(__file__) # ---------------------------------------- def this(): ''' Return", "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "is None: if comments_only: break else: raise TestFileSyntaxError(orig_line) etags += [etag] return etags,", "in filenames: if not filename.endswith(test_file_extensions): continue yield os.path.join(root, filename) def test_file(): for filename", "# Permission is hereby granted, free of charge, to any person obtaining a", "E: os-error Permission denied ''') def test_os_error_permission_denied(): if os.getuid() == 0: raise nose.SkipTest('this", "# This semi-active waiting is ugly, but there doesn't seem be any #", "OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import difflib import", "not objname.startswith('test_'): continue for tag in get_coverage_for_function(obj): coverage.add(tag) return coverage # vim:ts=4 sts=4", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF", "self._ellipsis else re.escape(chunk) for chunk in self._split(s) ) self._regexp = re.compile('^{}$'.format(regexp)) def __eq__(self,", "def __init__(self, code, path, rest): self._s = s = '{code}: {path}: {rest}'.format( code=code,", "as ipc import sys import traceback import unittest import nose import nose.plugins from", "= [sys.executable, prog] queue = mp.Queue() child = mp.Process( target=_mp_run_i18nspector, args=(prog, options, path,", "as file: return _parse_test_header_file(file, path, comments_only=True) def _test_file(path, basedir=here): if basedir is not", "t def etags_from_tagstring(obj, path): try: docstring = obj.tagstring except AttributeError: return for line", "n in data.items(): yield n, name _signal_names = dict(_get_signal_names()) def get_signal_name(n): try: return", "publish, distribute, sublicense, and/or sell # copies of the Software, and to permit", "continue yield os.path.join(root, filename) def test_file(): for filename in _get_test_filenames(): path = os.path.relpath(filename,", "_test_file(path, basedir=here): if basedir is not None: path = os.path.relpath(os.path.join(basedir, path), start=os.getcwd()) options", "etag.tag def _get_test_filenames(): for root, dirnames, filenames in os.walk(here): del dirnames for filename", "else: raise def run_i18nspector(options, path): commandline = os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline is None: #", "+= ['| ' + s for s in stderr] else: message += ['stderr:", "as tmpdir: path = os.path.join(tmpdir, 'denied.po') with open(path, 'wb'): pass os.chmod(path, 0) expected", "for s in stderr] else: message += ['stderr: (empty)'] raise SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog,", "else: raise TestFileSyntaxError(orig_line) etags += [etag] return etags, options def _parse_test_headers(path): # <path>.tags:", "def test_os_error_no_such_file(): with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'nonexistent.po') expected = etags_from_tagstring(this(),", "= [] for n, line in enumerate(file): orig_line = line if comments_only: if", "the process terminates. ''' while True: try: return queue.get(timeout=1) # This semi-active waiting", "import shlex import signal import subprocess as ipc import sys import traceback import", "etags, options = _parse_test_headers(path) assert_emit_tags(path, etags, options=options) def get_coverage_for_file(path): etags, options = _parse_test_headers(path)", "options def _parse_test_headers(path): # <path>.tags: try: file = open(path + '.tags', encoding='UTF-8') #", "be included in # all copies or substantial portions of the Software. #", "file: return _parse_test_header_file(file, path, comments_only=True) # <path>: with open(path, 'rt', encoding='UTF-8', errors='ignore') as", "is not None: yield t def tagstring(s): def update(x): x.tagstring = s return", "FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path, comments_only=False) # <path>.gen: try: file", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION", "(t.tag for t in etags) def get_coverage_for_function(fn): for etag in etags_from_tagstring(fn, ''): yield", "child) ) child.join() rc = child.exitcode else: commandline = shlex.split(commandline) commandline += options", "without restriction, including without limitation the rights # to use, copy, modify, merge,", "= _parse_test_headers(path) del options return (t.tag for t in etags) def get_coverage_for_function(fn): for", "except mp.queues.Empty: if process.exitcode is None: continue else: raise def run_i18nspector(options, path): commandline", "rest): self._s = s = '{code}: {path}: {rest}'.format( code=code, path=path, rest=rest, ) self.tag", "(name, getattr(signal, name)) for name in dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name) ) try: if data['SIGABRT']", "prog] queue = mp.Queue() child = mp.Process( target=_mp_run_i18nspector, args=(prog, options, path, queue) )", "stderr = ( s.decode('UTF-8').splitlines() for s in child.communicate() ) rc = child.poll() assert", "def __str__(self): return self._s def __repr__(self): return repr(self._s) # ---------------------------------------- def _get_signal_names(): data", "coverage.add(tag) for objname, obj in globals().items(): if not objname.startswith('test_'): continue for tag in", "def get_coverage(): coverage = set() for filename in _get_test_filenames(): for tag in get_coverage_for_file(filename):", "import unittest import nose import nose.plugins from .. import tools here = os.path.dirname(__file__)", "in the Software without restriction, including without limitation the rights # to use,", "(the “Software”), to deal # in the Software without restriction, including without limitation", "class SubprocessError(Exception): pass def queue_get(queue, process): ''' Remove and return an item from", "function that called this function. (Hopefully!) ''' return globals()[inspect.stack()[1][0].f_code.co_name] # ---------------------------------------- _parse_etag =", "self.wantFile(path): yield TestCase(path) def wantFunction(self, func): if getattr(func, 'redundant', False): return False class", "['stdout: (empty)'] if stderr: message += ['stderr:'] message += ['| ' + s", "with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'nonexistent.po') expected = etags_from_tagstring(this(), path) assert_emit_tags(path,", "tmpdir: path = os.path.join(tmpdir, 'denied.po') with open(path, 'wb'): pass os.chmod(path, 0) expected =", "== data['SIGCLD']: del data['SIGCLD'] except KeyError: pass for name, n in data.items(): yield", "stderr]) sys.exit(0) def assert_emit_tags(path, etags, *, options=()): etags = list(etags) stdout = run_i18nspector(options,", "queue.put([stdout, stderr]) sys.exit(1) raise # hi, pydiatra! else: queue.put([stdout, stderr]) sys.exit(0) def assert_emit_tags(path,", "# ---------------------------------------- def get_coverage(): coverage = set() for filename in _get_test_filenames(): for tag", "for filename in filenames: if not filename.endswith(test_file_extensions): continue yield os.path.join(root, filename) def test_file():", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS", "env): pass def wantFile(self, path): if path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here), '')): return True def", "n, name _signal_names = dict(_get_signal_names()) def get_signal_name(n): try: return _signal_names[n] except KeyError: return", "bit, because exec(3)ing is very expensive. # Let's load the needed Python modules,", "for etag in etags_from_tagstring(fn, ''): yield etag.tag def _get_test_filenames(): for root, dirnames, filenames", "copies of the Software, and to permit persons to whom the Software is", "list( difflib.unified_diff(str_etags, stdout, n=9999) ) message += diff[3:] raise AssertionError('\\n'.join(message)) elif expected_failure: raise", "lib.cli # make pyflakes happy prog = os.path.join(here, os.pardir, os.pardir, 'i18nspector') commandline =", "message += ['stderr:'] message += ['| ' + s for s in stderr]", "path, queue) ) child.start() [stdout, stderr] = ( s.splitlines() for s in queue_get(queue,", "for tag in get_coverage_for_file(filename): coverage.add(tag) for objname, obj in globals().items(): if not objname.startswith('test_'):", "queue.put([stdout, stderr]) sys.exit(0) def assert_emit_tags(path, etags, *, options=()): etags = list(etags) stdout =", "rc < 0: message = ['command was interrupted by signal {sig}'.format(sig=get_signal_name(-rc))] # pylint:", "sys.argv = [prog] + list(options) + [path] orig_stdout = sys.stdout orig_stderr = sys.stderr", "raise def run_i18nspector(options, path): commandline = os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline is None: # We", "list(etags) stdout = run_i18nspector(options, path) expected_failure = os.path.basename(path).startswith('xfail-') if stdout != etags: if", "TestFileSyntaxError(orig_line) etags += [etag] return etags, options def _parse_test_headers(path): # <path>.tags: try: file", "“Software”), to deal # in the Software without restriction, including without limitation the", "path test_file.redundant = True # not needed if the plugin is enabled @tagstring('''", "= parse_etag(line, path) if etag is None: if comments_only: break else: raise TestFileSyntaxError(orig_line)", "'.gen', encoding='UTF-8', errors='ignore') # pylint: disable=consider-using-with except FileNotFoundError: pass else: with file: return", "except KeyError: pass try: if data['SIGCHLD'] == data['SIGCLD']: del data['SIGCLD'] except KeyError: pass", "if rc == 0: return stdout if rc < 0: message = ['command", "comments_only): etags = [] options = [] for n, line in enumerate(file): orig_line", "os.path.join(tmpdir, 'nonexistent.po') expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) @tagstring(''' E: os-error Permission denied", "= dict( __file__=prog, ) (sys.stdout, sys.stderr) = (io_stdout, io_stderr) try: try: exec(code, gvars)", "test_file_extensions = ('.mo', '.po', '.pot', '.pop') # .pop is a special extension to", "if stdout: message += ['stdout:'] message += ['| ' + s for s", "# <path>.tags: try: file = open(path + '.tags', encoding='UTF-8') # pylint: disable=consider-using-with except", "exc, tb) ) queue.put([stdout, stderr]) sys.exit(1) raise # hi, pydiatra! else: queue.put([stdout, stderr])", "{path}: {rest}'.format( code=code, path=path, rest=rest, ) self.tag = rest.split(None, 1)[0] regexp = ''.join(", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR", "return self._s def __repr__(self): return repr(self._s) # ---------------------------------------- def _get_signal_names(): data = dict(", "path): if path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here), '')): return True def loadTestsFromFile(self, path): if self.wantFile(path):", "'redundant', False): return False class TestCase(unittest.TestCase): def __init__(self, path): super().__init__('_test') self.path = os.path.relpath(path)", "func): if getattr(func, 'redundant', False): return False class TestCase(unittest.TestCase): def __init__(self, path): super().__init__('_test')", "other): if isinstance(other, str): return self._regexp.match(other) else: return NotImplemented def __str__(self): return self._s", "def __repr__(self): return repr(self._s) # ---------------------------------------- def _get_signal_names(): data = dict( (name, getattr(signal,", "['command was interrupted by signal {sig}'.format(sig=get_signal_name(-rc))] # pylint: disable=invalid-unary-operand-type else: message = ['command", "traceback import unittest import nose import nose.plugins from .. import tools here =", "= io_stderr.getvalue() except SystemExit: queue.put([stdout, stderr]) raise except: # pylint: disable=bare-except exctp, exc,", "for x in etags] message = ['Tags differ:', ''] diff = list( difflib.unified_diff(str_etags,", "# Let's load the needed Python modules, and use multiprocessing to # “emulate”", "tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'nonexistent.po') expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected)", "must not be run as root') with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir,", "+= [''] if stdout: message += ['stdout:'] message += ['| ' + s", "in _get_test_filenames(): path = os.path.relpath(filename, start=here) yield _test_file, path test_file.redundant = True #", "import inspect import io import multiprocessing as mp import os import re import", "to trigger unknown-file-type class Plugin(nose.plugins.Plugin): name = 'po-plugin' enabled = True def options(self,", "= True def options(self, parser, env): pass def wantFile(self, path): if path.endswith(test_file_extensions): if", "No such file or directory ''') def test_os_error_no_such_file(): with tools.temporary_directory() as tmpdir: path", "be run as root') with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'denied.po') with", "if rc < 0: message = ['command was interrupted by signal {sig}'.format(sig=get_signal_name(-rc))] #", "= os.path.join(tmpdir, 'denied.po') with open(path, 'wb'): pass os.chmod(path, 0) expected = etags_from_tagstring(this(), path)", "return for line in docstring.splitlines(): line = line.lstrip() t = parse_etag(line, path) if", "disable=exec-used finally: (sys.stdout, sys.stderr) = (orig_stdout, orig_stderr) stdout = io_stdout.getvalue() stderr = io_stderr.getvalue()", "x return update # ---------------------------------------- class ETag(): _ellipsis = '<...>' _split = re.compile('({})'.format(re.escape(_ellipsis))).split", "KeyError: pass for name, n in data.items(): yield n, name _signal_names = dict(_get_signal_names())", "options=options) def get_coverage_for_file(path): etags, options = _parse_test_headers(path) del options return (t.tag for t", "mp.Queue() child = mp.Process( target=_mp_run_i18nspector, args=(prog, options, path, queue) ) child.start() [stdout, stderr]", "@tagstring(''' E: os-error No such file or directory ''') def test_os_error_no_such_file(): with tools.temporary_directory()", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE", "except KeyError: pass for name, n in data.items(): yield n, name _signal_names =", "= (io_stdout, io_stderr) try: try: exec(code, gvars) # pylint: disable=exec-used finally: (sys.stdout, sys.stderr)", "filename) def test_file(): for filename in _get_test_filenames(): path = os.path.relpath(filename, start=here) yield _test_file,", "= parse_etag(line, path) if t is not None: yield t def tagstring(s): def", "pass def queue_get(queue, process): ''' Remove and return an item from the queue.", "MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "a special extension to trigger unknown-file-type class Plugin(nose.plugins.Plugin): name = 'po-plugin' enabled =", "# ---------------------------------------- test_file_extensions = ('.mo', '.po', '.pot', '.pop') # .pop is a special", "tools here = os.path.dirname(__file__) # ---------------------------------------- def this(): ''' Return function that called", "['Tags differ:', ''] diff = list( difflib.unified_diff(str_etags, stdout, n=9999) ) message += diff[3:]", "as mp import os import re import shlex import signal import subprocess as", "return x return update # ---------------------------------------- class ETag(): _ellipsis = '<...>' _split =", "in globals().items(): if not objname.startswith('test_'): continue for tag in get_coverage_for_function(obj): coverage.add(tag) return coverage", "os.pardir, 'i18nspector') commandline = [sys.executable, prog] queue = mp.Queue() child = mp.Process( target=_mp_run_i18nspector,", "self.tag = rest.split(None, 1)[0] regexp = ''.join( '.*' if chunk == self._ellipsis else", "and/or sell # copies of the Software, and to permit persons to whom", "_ellipsis = '<...>' _split = re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self, code, path, rest): self._s =", "# SOFTWARE. import difflib import inspect import io import multiprocessing as mp import", "any # obvious better way. except mp.queues.Empty: if process.exitcode is None: continue else:", "child: stdout, stderr = ( s.decode('UTF-8').splitlines() for s in child.communicate() ) rc =", "stdout = io_stdout.getvalue() stderr = io_stderr.getvalue() except SystemExit: queue.put([stdout, stderr]) raise except: #", "= line if comments_only: if n == 0 and line.startswith('#!'): continue if line.startswith('#", "re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self, code, path, rest): self._s = s = '{code}: {path}: {rest}'.format(", "_parse_test_header_file(file, path, comments_only=True) def _test_file(path, basedir=here): if basedir is not None: path =", "= s return x return update # ---------------------------------------- class ETag(): _ellipsis = '<...>'", "del options return (t.tag for t in etags) def get_coverage_for_function(fn): for etag in", "etags += [etag] return etags, options def _parse_test_headers(path): # <path>.tags: try: file =", "commandline += options commandline += [path] fixed_env = dict(os.environ, PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline, stdout=ipc.PIPE,", "if line.startswith('# '): line = line[2:] else: break if line.startswith('--'): options += shlex.split(line)", "= etags_from_tagstring(this(), path) assert_emit_tags(path, expected) # ---------------------------------------- def get_coverage(): coverage = set() for", "options=()): etags = list(etags) stdout = run_i18nspector(options, path) expected_failure = os.path.basename(path).startswith('xfail-') if stdout", "# in the Software without restriction, including without limitation the rights # to", "path), start=os.getcwd()) options = [] etags, options = _parse_test_headers(path) assert_emit_tags(path, etags, options=options) def", "try: if data['SIGABRT'] == data['SIGIOT']: del data['SIGIOT'] except KeyError: pass try: if data['SIGCHLD']", "exctp, exc, tb = sys.exc_info() stderr += ''.join( traceback.format_exception(exctp, exc, tb) ) queue.put([stdout,", "expected_failure = os.path.basename(path).startswith('xfail-') if stdout != etags: if expected_failure: raise nose.SkipTest('expected failure') str_etags", "if data['SIGABRT'] == data['SIGIOT']: del data['SIGIOT'] except KeyError: pass try: if data['SIGCHLD'] ==", "AssertionError('\\n'.join(message)) elif expected_failure: raise AssertionError('unexpected success') class TestFileSyntaxError(Exception): pass def _parse_test_header_file(file, path, *,", "= [prog] + list(options) + [path] orig_stdout = sys.stdout orig_stderr = sys.stderr code", "# .pop is a special extension to trigger unknown-file-type class Plugin(nose.plugins.Plugin): name =", "continue else: raise def run_i18nspector(options, path): commandline = os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline is None:", "“AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT", "return _parse_test_header_file(file, path, comments_only=True) # <path>: with open(path, 'rt', encoding='UTF-8', errors='ignore') as file:", "if the plugin is enabled @tagstring(''' E: os-error No such file or directory", "to # “emulate” the command execution. import lib.cli # pylint: disable=import-outside-toplevel assert lib.cli", "not None: path = os.path.relpath(os.path.join(basedir, path), start=os.getcwd()) options = [] etags, options =", "TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE", "filename in _get_test_filenames(): for tag in get_coverage_for_file(filename): coverage.add(tag) for objname, obj in globals().items():", "(io_stdout, io_stderr) try: try: exec(code, gvars) # pylint: disable=exec-used finally: (sys.stdout, sys.stderr) =", "def _get_test_filenames(): for root, dirnames, filenames in os.walk(here): del dirnames for filename in", "= line[2:] else: break if line.startswith('--'): options += shlex.split(line) else: etag = parse_etag(line,", "exec(code, gvars) # pylint: disable=exec-used finally: (sys.stdout, sys.stderr) = (orig_stdout, orig_stderr) stdout =", "!= etags: if expected_failure: raise nose.SkipTest('expected failure') str_etags = [str(x) for x in", "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS", "nose.plugins from .. import tools here = os.path.dirname(__file__) # ---------------------------------------- def this(): '''", "str(n) # ---------------------------------------- test_file_extensions = ('.mo', '.po', '.pot', '.pop') # .pop is a", "finally: (sys.stdout, sys.stderr) = (orig_stdout, orig_stderr) stdout = io_stdout.getvalue() stderr = io_stderr.getvalue() except", "terminates. ''' while True: try: return queue.get(timeout=1) # This semi-active waiting is ugly,", "filename in _get_test_filenames(): path = os.path.relpath(filename, start=here) yield _test_file, path test_file.redundant = True", "__repr__(self): return repr(self._s) # ---------------------------------------- def _get_signal_names(): data = dict( (name, getattr(signal, name))", "def get_coverage_for_file(path): etags, options = _parse_test_headers(path) del options return (t.tag for t in", "file: return _parse_test_header_file(file, path, comments_only=True) def _test_file(path, basedir=here): if basedir is not None:", "compile(code, prog, 'exec') io_stdout = io.StringIO() io_stderr = io.StringIO() gvars = dict( __file__=prog,", "as child: stdout, stderr = ( s.decode('UTF-8').splitlines() for s in child.communicate() ) rc", "docstring = obj.tagstring except AttributeError: return for line in docstring.splitlines(): line = line.lstrip()", "try: file = open(path + '.tags', encoding='UTF-8') # pylint: disable=consider-using-with except FileNotFoundError: pass", "[etag] return etags, options def _parse_test_headers(path): # <path>.tags: try: file = open(path +", "None: continue else: raise def run_i18nspector(options, path): commandline = os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline is", "with ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env) as child: stdout, stderr = ( s.decode('UTF-8').splitlines() for", "documentation files (the “Software”), to deal # in the Software without restriction, including", "open(prog, 'rt', encoding='UTF-8') as file: code = file.read() sys.argv = [prog] + list(options)", "for root, dirnames, filenames in os.walk(here): del dirnames for filename in filenames: if", "any person obtaining a copy # of this software and associated documentation files", "break else: raise TestFileSyntaxError(orig_line) etags += [etag] return etags, options def _parse_test_headers(path): #", "def __init__(self, path): super().__init__('_test') self.path = os.path.relpath(path) def _test(self): _test_file(self.path, basedir=None) def __str__(self):", "# # The above copyright notice and this permission notice shall be included", "update(x): x.tagstring = s return x return update # ---------------------------------------- class ETag(): _ellipsis", "path): super().__init__('_test') self.path = os.path.relpath(path) def _test(self): _test_file(self.path, basedir=None) def __str__(self): return self.path", "# # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,", "os import re import shlex import signal import subprocess as ipc import sys", "failure') str_etags = [str(x) for x in etags] message = ['Tags differ:', '']", "if basedir is not None: path = os.path.relpath(os.path.join(basedir, path), start=os.getcwd()) options = []", "None: yield t def tagstring(s): def update(x): x.tagstring = s return x return", "stderr] else: message += ['stderr: (empty)'] raise SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog, options, path, queue):", "interrupted by signal {sig}'.format(sig=get_signal_name(-rc))] # pylint: disable=invalid-unary-operand-type else: message = ['command exited with", "== 0: raise nose.SkipTest('this test must not be run as root') with tools.temporary_directory()", "in os.walk(here): del dirnames for filename in filenames: if not filename.endswith(test_file_extensions): continue yield", "['| ' + s for s in stdout] + [''] else: message +=", "raise SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog, options, path, queue): with open(prog, 'rt', encoding='UTF-8') as file:", "KeyError: pass try: if data['SIGCHLD'] == data['SIGCLD']: del data['SIGCLD'] except KeyError: pass for", "copyright notice and this permission notice shall be included in # all copies", "subprocess as ipc import sys import traceback import unittest import nose import nose.plugins", "with status {rc}'.format(rc=rc)] message += [''] if stdout: message += ['stdout:'] message +=", "return an item from the queue. Block until the process terminates. ''' while", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE", "os.path.join(here, os.pardir, os.pardir, 'i18nspector') commandline = [sys.executable, prog] queue = mp.Queue() child =", "path = os.path.relpath(filename, start=here) yield _test_file, path test_file.redundant = True # not needed", "deal # in the Software without restriction, including without limitation the rights #", "if etag is None: if comments_only: break else: raise TestFileSyntaxError(orig_line) etags += [etag]", "2012-2021 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to", "self.path = os.path.relpath(path) def _test(self): _test_file(self.path, basedir=None) def __str__(self): return self.path class SubprocessError(Exception):", "data['SIGCLD']: del data['SIGCLD'] except KeyError: pass for name, n in data.items(): yield n,", "while True: try: return queue.get(timeout=1) # This semi-active waiting is ugly, but there", "This semi-active waiting is ugly, but there doesn't seem be any # obvious", "disable=consider-using-with except FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path, comments_only=True) # <path>:", "etags: if expected_failure: raise nose.SkipTest('expected failure') str_etags = [str(x) for x in etags]", "[''] else: message += ['stdout: (empty)'] if stderr: message += ['stderr:'] message +=", "of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY", "= child.exitcode else: commandline = shlex.split(commandline) commandline += options commandline += [path] fixed_env", ") child.join() rc = child.exitcode else: commandline = shlex.split(commandline) commandline += options commandline", "os-error Permission denied ''') def test_os_error_permission_denied(): if os.getuid() == 0: raise nose.SkipTest('this test", "try: try: exec(code, gvars) # pylint: disable=exec-used finally: (sys.stdout, sys.stderr) = (orig_stdout, orig_stderr)", "+= ['stderr: (empty)'] raise SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog, options, path, queue): with open(prog, 'rt',", "= obj.tagstring except AttributeError: return for line in docstring.splitlines(): line = line.lstrip() t", "_get_test_filenames(): for root, dirnames, filenames in os.walk(here): del dirnames for filename in filenames:", "line if comments_only: if n == 0 and line.startswith('#!'): continue if line.startswith('# '):", "objname.startswith('test_'): continue for tag in get_coverage_for_function(obj): coverage.add(tag) return coverage # vim:ts=4 sts=4 sw=4", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #", "else: with file: return _parse_test_header_file(file, path, comments_only=True) # <path>: with open(path, 'rt', encoding='UTF-8',", "path, *, comments_only): etags = [] options = [] for n, line in", "IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "because exec(3)ing is very expensive. # Let's load the needed Python modules, and", "inspect import io import multiprocessing as mp import os import re import shlex", "in docstring.splitlines(): line = line.lstrip() t = parse_etag(line, path) if t is not", "stderr]) sys.exit(1) raise # hi, pydiatra! else: queue.put([stdout, stderr]) sys.exit(0) def assert_emit_tags(path, etags,", ") try: if data['SIGABRT'] == data['SIGIOT']: del data['SIGIOT'] except KeyError: pass try: if", "distribute, sublicense, and/or sell # copies of the Software, and to permit persons", "SOFTWARE. import difflib import inspect import io import multiprocessing as mp import os", "etags] message = ['Tags differ:', ''] diff = list( difflib.unified_diff(str_etags, stdout, n=9999) )", "obj in globals().items(): if not objname.startswith('test_'): continue for tag in get_coverage_for_function(obj): coverage.add(tag) return", "+= diff[3:] raise AssertionError('\\n'.join(message)) elif expected_failure: raise AssertionError('unexpected success') class TestFileSyntaxError(Exception): pass def", "return _parse_test_header_file(file, path, comments_only=False) # <path>.gen: try: file = open(path + '.gen', encoding='UTF-8',", "charge, to any person obtaining a copy # of this software and associated", "is very expensive. # Let's load the needed Python modules, and use multiprocessing", "if isinstance(other, str): return self._regexp.match(other) else: return NotImplemented def __str__(self): return self._s def", "{sig}'.format(sig=get_signal_name(-rc))] # pylint: disable=invalid-unary-operand-type else: message = ['command exited with status {rc}'.format(rc=rc)] message", "IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,", "docstring.splitlines(): line = line.lstrip() t = parse_etag(line, path) if t is not None:", "<<EMAIL>> # # Permission is hereby granted, free of charge, to any person", "WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "options, path, queue) ) child.start() [stdout, stderr] = ( s.splitlines() for s in", "child.join() rc = child.exitcode else: commandline = shlex.split(commandline) commandline += options commandline +=", "' + s for s in stderr] else: message += ['stderr: (empty)'] raise", "chunk == self._ellipsis else re.escape(chunk) for chunk in self._split(s) ) self._regexp = re.compile('^{}$'.format(regexp))", "obj.tagstring except AttributeError: return for line in docstring.splitlines(): line = line.lstrip() t =", "queue. Block until the process terminates. ''' while True: try: return queue.get(timeout=1) #", "file = open(path + '.gen', encoding='UTF-8', errors='ignore') # pylint: disable=consider-using-with except FileNotFoundError: pass", "WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO", "get_coverage(): coverage = set() for filename in _get_test_filenames(): for tag in get_coverage_for_file(filename): coverage.add(tag)", "'): line = line[2:] else: break if line.startswith('--'): options += shlex.split(line) else: etag", "data['SIGCLD'] except KeyError: pass for name, n in data.items(): yield n, name _signal_names", "= os.path.dirname(__file__) # ---------------------------------------- def this(): ''' Return function that called this function.", "if re.compile('^SIG[A-Z0-9]*$').match(name) ) try: if data['SIGABRT'] == data['SIGIOT']: del data['SIGIOT'] except KeyError: pass", "pylint: disable=import-outside-toplevel assert lib.cli # make pyflakes happy prog = os.path.join(here, os.pardir, os.pardir,", "s in queue_get(queue, child) ) child.join() rc = child.exitcode else: commandline = shlex.split(commandline)", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED", "KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "= [] options = [] for n, line in enumerate(file): orig_line = line", "<NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any", "to whom the Software is # furnished to do so, subject to the", "limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or", "dict(_get_signal_names()) def get_signal_name(n): try: return _signal_names[n] except KeyError: return str(n) # ---------------------------------------- test_file_extensions", "# ---------------------------------------- def this(): ''' Return function that called this function. (Hopefully!) '''", "def assert_emit_tags(path, etags, *, options=()): etags = list(etags) stdout = run_i18nspector(options, path) expected_failure", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER", "wantFile(self, path): if path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here), '')): return True def loadTestsFromFile(self, path): if", "def _test(self): _test_file(self.path, basedir=None) def __str__(self): return self.path class SubprocessError(Exception): pass def queue_get(queue,", "= sys.stdout orig_stderr = sys.stderr code = compile(code, prog, 'exec') io_stdout = io.StringIO()", "file or directory ''') def test_os_error_no_such_file(): with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir,", "this function. (Hopefully!) ''' return globals()[inspect.stack()[1][0].f_code.co_name] # ---------------------------------------- _parse_etag = re.compile(r'([A-Z]): (([\\w-]+).*)').match def", "Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY", "= ['Tags differ:', ''] diff = list( difflib.unified_diff(str_etags, stdout, n=9999) ) message +=", "shlex.split(line) else: etag = parse_etag(line, path) if etag is None: if comments_only: break", "file.read() sys.argv = [prog] + list(options) + [path] orig_stdout = sys.stdout orig_stderr =", "code = file.read() sys.argv = [prog] + list(options) + [path] orig_stdout = sys.stdout", "import nose.plugins from .. import tools here = os.path.dirname(__file__) # ---------------------------------------- def this():", "def parse_etag(contents, path): match = _parse_etag(contents) if match is None: return t =", "= 'po-plugin' enabled = True def options(self, parser, env): pass def wantFile(self, path):", "pylint: disable=invalid-unary-operand-type else: message = ['command exited with status {rc}'.format(rc=rc)] message += ['']", "'.*' if chunk == self._ellipsis else re.escape(chunk) for chunk in self._split(s) ) self._regexp", "path): if self.wantFile(path): yield TestCase(path) def wantFunction(self, func): if getattr(func, 'redundant', False): return", "is None: continue else: raise def run_i18nspector(options, path): commandline = os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline", "+= [path] fixed_env = dict(os.environ, PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env) as child:", "Plugin(nose.plugins.Plugin): name = 'po-plugin' enabled = True def options(self, parser, env): pass def", "os.path.join(tmpdir, 'denied.po') with open(path, 'wb'): pass os.chmod(path, 0) expected = etags_from_tagstring(this(), path) assert_emit_tags(path,", "copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED", "---------------------------------------- def get_coverage(): coverage = set() for filename in _get_test_filenames(): for tag in", "_parse_test_header_file(file, path, comments_only=True) # <path>: with open(path, 'rt', encoding='UTF-8', errors='ignore') as file: return", "with open(path, 'wb'): pass os.chmod(path, 0) expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) #", "message = ['command exited with status {rc}'.format(rc=rc)] message += [''] if stdout: message", "getattr(func, 'redundant', False): return False class TestCase(unittest.TestCase): def __init__(self, path): super().__init__('_test') self.path =", "traceback.format_exception(exctp, exc, tb) ) queue.put([stdout, stderr]) sys.exit(1) raise # hi, pydiatra! else: queue.put([stdout,", "mp import os import re import shlex import signal import subprocess as ipc", "filenames in os.walk(here): del dirnames for filename in filenames: if not filename.endswith(test_file_extensions): continue", "os.path.relpath(os.path.join(basedir, path), start=os.getcwd()) options = [] etags, options = _parse_test_headers(path) assert_emit_tags(path, etags, options=options)", "path, comments_only=True) # <path>: with open(path, 'rt', encoding='UTF-8', errors='ignore') as file: return _parse_test_header_file(file,", "with file: return _parse_test_header_file(file, path, comments_only=False) # <path>.gen: try: file = open(path +", "for line in docstring.splitlines(): line = line.lstrip() t = parse_etag(line, path) if t", "do so, subject to the following conditions: # # The above copyright notice", "io.StringIO() io_stderr = io.StringIO() gvars = dict( __file__=prog, ) (sys.stdout, sys.stderr) = (io_stdout,", "options, path, queue): with open(prog, 'rt', encoding='UTF-8') as file: code = file.read() sys.argv", "make pyflakes happy prog = os.path.join(here, os.pardir, os.pardir, 'i18nspector') commandline = [sys.executable, prog]", "t = parse_etag(line, path) if t is not None: yield t def tagstring(s):", "code, path, rest): self._s = s = '{code}: {path}: {rest}'.format( code=code, path=path, rest=rest,", "= ('.mo', '.po', '.pot', '.pop') # .pop is a special extension to trigger", "AttributeError: return for line in docstring.splitlines(): line = line.lstrip() t = parse_etag(line, path)", "os-error No such file or directory ''') def test_os_error_no_such_file(): with tools.temporary_directory() as tmpdir:", "stderr=ipc.PIPE, env=fixed_env) as child: stdout, stderr = ( s.decode('UTF-8').splitlines() for s in child.communicate()", "'{code}: {path}: {rest}'.format( code=code, path=path, rest=rest, ) self.tag = rest.split(None, 1)[0] regexp =", "__file__=prog, ) (sys.stdout, sys.stderr) = (io_stdout, io_stderr) try: try: exec(code, gvars) # pylint:", "THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "import difflib import inspect import io import multiprocessing as mp import os import", "options = _parse_test_headers(path) assert_emit_tags(path, etags, options=options) def get_coverage_for_file(path): etags, options = _parse_test_headers(path) del", "isinstance(other, str): return self._regexp.match(other) else: return NotImplemented def __str__(self): return self._s def __repr__(self):", "comments_only=False) # <path>.gen: try: file = open(path + '.gen', encoding='UTF-8', errors='ignore') # pylint:", "with open(prog, 'rt', encoding='UTF-8') as file: code = file.read() sys.argv = [prog] +", "run_i18nspector(options, path) expected_failure = os.path.basename(path).startswith('xfail-') if stdout != etags: if expected_failure: raise nose.SkipTest('expected", "os.path.basename(path).startswith('xfail-') if stdout != etags: if expected_failure: raise nose.SkipTest('expected failure') str_etags = [str(x)", "and line.startswith('#!'): continue if line.startswith('# '): line = line[2:] else: break if line.startswith('--'):", "class Plugin(nose.plugins.Plugin): name = 'po-plugin' enabled = True def options(self, parser, env): pass", "permit persons to whom the Software is # furnished to do so, subject", "= compile(code, prog, 'exec') io_stdout = io.StringIO() io_stderr = io.StringIO() gvars = dict(", "file: code = file.read() sys.argv = [prog] + list(options) + [path] orig_stdout =", "# pylint: disable=consider-using-with except FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path, comments_only=False)", "return _signal_names[n] except KeyError: return str(n) # ---------------------------------------- test_file_extensions = ('.mo', '.po', '.pot',", "filename.endswith(test_file_extensions): continue yield os.path.join(root, filename) def test_file(): for filename in _get_test_filenames(): path =", "Permission is hereby granted, free of charge, to any person obtaining a copy", "path) assert_emit_tags(path, expected) @tagstring(''' E: os-error Permission denied ''') def test_os_error_permission_denied(): if os.getuid()", "modules, and use multiprocessing to # “emulate” the command execution. import lib.cli #", "exc, tb = sys.exc_info() stderr += ''.join( traceback.format_exception(exctp, exc, tb) ) queue.put([stdout, stderr])", "EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "Software without restriction, including without limitation the rights # to use, copy, modify,", "is None: return t = ETag(match.group(1), path, match.group(2)) return t def etags_from_tagstring(obj, path):", "return stdout if rc < 0: message = ['command was interrupted by signal", "Block until the process terminates. ''' while True: try: return queue.get(timeout=1) # This", "Let's load the needed Python modules, and use multiprocessing to # “emulate” the", "stderr]) raise except: # pylint: disable=bare-except exctp, exc, tb = sys.exc_info() stderr +=", "FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path, comments_only=True) # <path>: with open(path,", "= list( difflib.unified_diff(str_etags, stdout, n=9999) ) message += diff[3:] raise AssertionError('\\n'.join(message)) elif expected_failure:", "'rt', encoding='UTF-8', errors='ignore') as file: return _parse_test_header_file(file, path, comments_only=True) def _test_file(path, basedir=here): if", "= dict(os.environ, PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env) as child: stdout, stderr =", "test_os_error_permission_denied(): if os.getuid() == 0: raise nose.SkipTest('this test must not be run as", "t is not None: yield t def tagstring(s): def update(x): x.tagstring = s", "queue = mp.Queue() child = mp.Process( target=_mp_run_i18nspector, args=(prog, options, path, queue) ) child.start()", "exited with status {rc}'.format(rc=rc)] message += [''] if stdout: message += ['stdout:'] message", "with file: return _parse_test_header_file(file, path, comments_only=True) # <path>: with open(path, 'rt', encoding='UTF-8', errors='ignore')", "# not needed if the plugin is enabled @tagstring(''' E: os-error No such", "line.lstrip() t = parse_etag(line, path) if t is not None: yield t def", "message += ['| ' + s for s in stderr] else: message +=", "def _test_file(path, basedir=here): if basedir is not None: path = os.path.relpath(os.path.join(basedir, path), start=os.getcwd())", ") queue.put([stdout, stderr]) sys.exit(1) raise # hi, pydiatra! else: queue.put([stdout, stderr]) sys.exit(0) def", "# The above copyright notice and this permission notice shall be included in", "return t = ETag(match.group(1), path, match.group(2)) return t def etags_from_tagstring(obj, path): try: docstring", "= child.poll() assert isinstance(rc, int) if rc == 0: return stdout if rc", "if stderr: message += ['stderr:'] message += ['| ' + s for s", "n=9999) ) message += diff[3:] raise AssertionError('\\n'.join(message)) elif expected_failure: raise AssertionError('unexpected success') class", "OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "if not filename.endswith(test_file_extensions): continue yield os.path.join(root, filename) def test_file(): for filename in _get_test_filenames():", "commandline = [sys.executable, prog] queue = mp.Queue() child = mp.Process( target=_mp_run_i18nspector, args=(prog, options,", "of this software and associated documentation files (the “Software”), to deal # in", "SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #", "sell # copies of the Software, and to permit persons to whom the", "parser, env): pass def wantFile(self, path): if path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here), '')): return True", "very expensive. # Let's load the needed Python modules, and use multiprocessing to", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.", "---------------------------------------- test_file_extensions = ('.mo', '.po', '.pot', '.pop') # .pop is a special extension", "message += ['stdout: (empty)'] if stderr: message += ['stderr:'] message += ['| '", "etags, options def _parse_test_headers(path): # <path>.tags: try: file = open(path + '.tags', encoding='UTF-8')", "+ '.tags', encoding='UTF-8') # pylint: disable=consider-using-with except FileNotFoundError: pass else: with file: return", "path, comments_only=True) def _test_file(path, basedir=here): if basedir is not None: path = os.path.relpath(os.path.join(basedir,", "def test_file(): for filename in _get_test_filenames(): path = os.path.relpath(filename, start=here) yield _test_file, path", "''') def test_os_error_permission_denied(): if os.getuid() == 0: raise nose.SkipTest('this test must not be", "return self.path class SubprocessError(Exception): pass def queue_get(queue, process): ''' Remove and return an", "queue): with open(prog, 'rt', encoding='UTF-8') as file: code = file.read() sys.argv = [prog]", "yield t def tagstring(s): def update(x): x.tagstring = s return x return update", "expensive. # Let's load the needed Python modules, and use multiprocessing to #", "stderr += ''.join( traceback.format_exception(exctp, exc, tb) ) queue.put([stdout, stderr]) sys.exit(1) raise # hi,", "parse_etag(line, path) if t is not None: yield t def tagstring(s): def update(x):", "# all copies or substantial portions of the Software. # # THE SOFTWARE", "SubprocessError(Exception): pass def queue_get(queue, process): ''' Remove and return an item from the", "'rt', encoding='UTF-8') as file: code = file.read() sys.argv = [prog] + list(options) +", "self._regexp = re.compile('^{}$'.format(regexp)) def __eq__(self, other): if isinstance(other, str): return self._regexp.match(other) else: return", "update # ---------------------------------------- class ETag(): _ellipsis = '<...>' _split = re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self,", "del data['SIGCLD'] except KeyError: pass for name, n in data.items(): yield n, name", "= _parse_etag(contents) if match is None: return t = ETag(match.group(1), path, match.group(2)) return", "stdout: message += ['stdout:'] message += ['| ' + s for s in", "raise # hi, pydiatra! else: queue.put([stdout, stderr]) sys.exit(0) def assert_emit_tags(path, etags, *, options=()):", "message += ['| ' + s for s in stdout] + [''] else:", "objname, obj in globals().items(): if not objname.startswith('test_'): continue for tag in get_coverage_for_function(obj): coverage.add(tag)", "= s = '{code}: {path}: {rest}'.format( code=code, path=path, rest=rest, ) self.tag = rest.split(None,", "restriction, including without limitation the rights # to use, copy, modify, merge, publish,", "obvious better way. except mp.queues.Empty: if process.exitcode is None: continue else: raise def", "s = '{code}: {path}: {rest}'.format( code=code, path=path, rest=rest, ) self.tag = rest.split(None, 1)[0]", "that called this function. (Hopefully!) ''' return globals()[inspect.stack()[1][0].f_code.co_name] # ---------------------------------------- _parse_etag = re.compile(r'([A-Z]):", "_signal_names[n] except KeyError: return str(n) # ---------------------------------------- test_file_extensions = ('.mo', '.po', '.pot', '.pop')", "'')): return True def loadTestsFromFile(self, path): if self.wantFile(path): yield TestCase(path) def wantFunction(self, func):", "dict(os.environ, PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env) as child: stdout, stderr = (", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS", "= sys.exc_info() stderr += ''.join( traceback.format_exception(exctp, exc, tb) ) queue.put([stdout, stderr]) sys.exit(1) raise", "enabled @tagstring(''' E: os-error No such file or directory ''') def test_os_error_no_such_file(): with", "pylint: disable=consider-using-with except FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path, comments_only=True) #", "sys import traceback import unittest import nose import nose.plugins from .. import tools", "# # Permission is hereby granted, free of charge, to any person obtaining", "all copies or substantial portions of the Software. # # THE SOFTWARE IS", "False class TestCase(unittest.TestCase): def __init__(self, path): super().__init__('_test') self.path = os.path.relpath(path) def _test(self): _test_file(self.path,", "needed if the plugin is enabled @tagstring(''' E: os-error No such file or", "stdout, n=9999) ) message += diff[3:] raise AssertionError('\\n'.join(message)) elif expected_failure: raise AssertionError('unexpected success')", "file = open(path + '.tags', encoding='UTF-8') # pylint: disable=consider-using-with except FileNotFoundError: pass else:", "dict( (name, getattr(signal, name)) for name in dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name) ) try: if", "root') with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'denied.po') with open(path, 'wb'): pass", "self._regexp.match(other) else: return NotImplemented def __str__(self): return self._s def __repr__(self): return repr(self._s) #", "s return x return update # ---------------------------------------- class ETag(): _ellipsis = '<...>' _split", "etag = parse_etag(line, path) if etag is None: if comments_only: break else: raise", "= dict(_get_signal_names()) def get_signal_name(n): try: return _signal_names[n] except KeyError: return str(n) # ----------------------------------------", "parse_etag(contents, path): match = _parse_etag(contents) if match is None: return t = ETag(match.group(1),", "sys.stderr) = (io_stdout, io_stderr) try: try: exec(code, gvars) # pylint: disable=exec-used finally: (sys.stdout,", "PYTHONIOENCODING='UTF-8') with ipc.Popen(commandline, stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env) as child: stdout, stderr = ( s.decode('UTF-8').splitlines()", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR", "is ugly, but there doesn't seem be any # obvious better way. except", "rc = child.exitcode else: commandline = shlex.split(commandline) commandline += options commandline += [path]", "function. (Hopefully!) ''' return globals()[inspect.stack()[1][0].f_code.co_name] # ---------------------------------------- _parse_etag = re.compile(r'([A-Z]): (([\\w-]+).*)').match def parse_etag(contents,", "is not None: path = os.path.relpath(os.path.join(basedir, path), start=os.getcwd()) options = [] etags, options", "path, match.group(2)) return t def etags_from_tagstring(obj, path): try: docstring = obj.tagstring except AttributeError:", "tb = sys.exc_info() stderr += ''.join( traceback.format_exception(exctp, exc, tb) ) queue.put([stdout, stderr]) sys.exit(1)", "= os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline is None: # We cheat here a bit, because", "if match is None: return t = ETag(match.group(1), path, match.group(2)) return t def", "else: return NotImplemented def __str__(self): return self._s def __repr__(self): return repr(self._s) # ----------------------------------------", "options = [] for n, line in enumerate(file): orig_line = line if comments_only:", "expected_failure: raise nose.SkipTest('expected failure') str_etags = [str(x) for x in etags] message =", "in child.communicate() ) rc = child.poll() assert isinstance(rc, int) if rc == 0:", "FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "raise AssertionError('unexpected success') class TestFileSyntaxError(Exception): pass def _parse_test_header_file(file, path, *, comments_only): etags =", "_parse_test_headers(path): # <path>.tags: try: file = open(path + '.tags', encoding='UTF-8') # pylint: disable=consider-using-with", "return self._regexp.match(other) else: return NotImplemented def __str__(self): return self._s def __repr__(self): return repr(self._s)", "for name in dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name) ) try: if data['SIGABRT'] == data['SIGIOT']: del", "def run_i18nspector(options, path): commandline = os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline is None: # We cheat", "os.environ.get('I18NSPECTOR_COMMANDLINE') if commandline is None: # We cheat here a bit, because exec(3)ing", "str): return self._regexp.match(other) else: return NotImplemented def __str__(self): return self._s def __repr__(self): return", "gvars) # pylint: disable=exec-used finally: (sys.stdout, sys.stderr) = (orig_stdout, orig_stderr) stdout = io_stdout.getvalue()", "= os.path.join(here, os.pardir, os.pardir, 'i18nspector') commandline = [sys.executable, prog] queue = mp.Queue() child", "path.endswith(test_file_extensions): if path.startswith(os.path.join(os.path.abspath(here), '')): return True def loadTestsFromFile(self, path): if self.wantFile(path): yield TestCase(path)", ") rc = child.poll() assert isinstance(rc, int) if rc == 0: return stdout", "the plugin is enabled @tagstring(''' E: os-error No such file or directory ''')", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "We cheat here a bit, because exec(3)ing is very expensive. # Let's load", "sys.stderr) = (orig_stdout, orig_stderr) stdout = io_stdout.getvalue() stderr = io_stderr.getvalue() except SystemExit: queue.put([stdout,", "== 0 and line.startswith('#!'): continue if line.startswith('# '): line = line[2:] else: break", "path = os.path.join(tmpdir, 'nonexistent.po') expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) @tagstring(''' E: os-error", "import tools here = os.path.dirname(__file__) # ---------------------------------------- def this(): ''' Return function that", "chunk in self._split(s) ) self._regexp = re.compile('^{}$'.format(regexp)) def __eq__(self, other): if isinstance(other, str):", "pass for name, n in data.items(): yield n, name _signal_names = dict(_get_signal_names()) def", "= ['command was interrupted by signal {sig}'.format(sig=get_signal_name(-rc))] # pylint: disable=invalid-unary-operand-type else: message =", "the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "s.splitlines() for s in queue_get(queue, child) ) child.join() rc = child.exitcode else: commandline", "doesn't seem be any # obvious better way. except mp.queues.Empty: if process.exitcode is", "name, n in data.items(): yield n, name _signal_names = dict(_get_signal_names()) def get_signal_name(n): try:", "process.exitcode is None: continue else: raise def run_i18nspector(options, path): commandline = os.environ.get('I18NSPECTOR_COMMANDLINE') if", "better way. except mp.queues.Empty: if process.exitcode is None: continue else: raise def run_i18nspector(options,", "else: message = ['command exited with status {rc}'.format(rc=rc)] message += [''] if stdout:", "following conditions: # # The above copyright notice and this permission notice shall", "etags, *, options=()): etags = list(etags) stdout = run_i18nspector(options, path) expected_failure = os.path.basename(path).startswith('xfail-')", "of the Software, and to permit persons to whom the Software is #", "not be run as root') with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'denied.po')", "stdout = run_i18nspector(options, path) expected_failure = os.path.basename(path).startswith('xfail-') if stdout != etags: if expected_failure:", "line.startswith('--'): options += shlex.split(line) else: etag = parse_etag(line, path) if etag is None:", "cheat here a bit, because exec(3)ing is very expensive. # Let's load the", "= mp.Process( target=_mp_run_i18nspector, args=(prog, options, path, queue) ) child.start() [stdout, stderr] = (", "as file: code = file.read() sys.argv = [prog] + list(options) + [path] orig_stdout", "E: os-error No such file or directory ''') def test_os_error_no_such_file(): with tools.temporary_directory() as", "etags_from_tagstring(obj, path): try: docstring = obj.tagstring except AttributeError: return for line in docstring.splitlines():", "_split = re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self, code, path, rest): self._s = s = '{code}:", "name in dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name) ) try: if data['SIGABRT'] == data['SIGIOT']: del data['SIGIOT']", "match is None: return t = ETag(match.group(1), path, match.group(2)) return t def etags_from_tagstring(obj,", "message = ['Tags differ:', ''] diff = list( difflib.unified_diff(str_etags, stdout, n=9999) ) message", "0) expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) # ---------------------------------------- def get_coverage(): coverage =", "''' Remove and return an item from the queue. Block until the process", "+ [path] orig_stdout = sys.stdout orig_stderr = sys.stderr code = compile(code, prog, 'exec')", "path = os.path.relpath(os.path.join(basedir, path), start=os.getcwd()) options = [] etags, options = _parse_test_headers(path) assert_emit_tags(path,", "The above copyright notice and this permission notice shall be included in #", "nose.SkipTest('expected failure') str_etags = [str(x) for x in etags] message = ['Tags differ:',", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR", "import subprocess as ipc import sys import traceback import unittest import nose import", "---------------------------------------- def this(): ''' Return function that called this function. (Hopefully!) ''' return", "multiprocessing to # “emulate” the command execution. import lib.cli # pylint: disable=import-outside-toplevel assert", "target=_mp_run_i18nspector, args=(prog, options, path, queue) ) child.start() [stdout, stderr] = ( s.splitlines() for", "match = _parse_etag(contents) if match is None: return t = ETag(match.group(1), path, match.group(2))", "encoding='UTF-8', errors='ignore') as file: return _parse_test_header_file(file, path, comments_only=True) def _test_file(path, basedir=here): if basedir", "orig_stderr = sys.stderr code = compile(code, prog, 'exec') io_stdout = io.StringIO() io_stderr =", "= dict( (name, getattr(signal, name)) for name in dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name) ) try:", "status {rc}'.format(rc=rc)] message += [''] if stdout: message += ['stdout:'] message += ['|", "else: message += ['stderr: (empty)'] raise SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog, options, path, queue): with", "plugin is enabled @tagstring(''' E: os-error No such file or directory ''') def", "software and associated documentation files (the “Software”), to deal # in the Software", "if self.wantFile(path): yield TestCase(path) def wantFunction(self, func): if getattr(func, 'redundant', False): return False", "''' Return function that called this function. (Hopefully!) ''' return globals()[inspect.stack()[1][0].f_code.co_name] # ----------------------------------------", "= [] etags, options = _parse_test_headers(path) assert_emit_tags(path, etags, options=options) def get_coverage_for_file(path): etags, options", "open(path, 'wb'): pass os.chmod(path, 0) expected = etags_from_tagstring(this(), path) assert_emit_tags(path, expected) # ----------------------------------------", "(orig_stdout, orig_stderr) stdout = io_stdout.getvalue() stderr = io_stderr.getvalue() except SystemExit: queue.put([stdout, stderr]) raise", "# pylint: disable=consider-using-with except FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path, comments_only=True)", "if comments_only: break else: raise TestFileSyntaxError(orig_line) etags += [etag] return etags, options def", "= rest.split(None, 1)[0] regexp = ''.join( '.*' if chunk == self._ellipsis else re.escape(chunk)", "False): return False class TestCase(unittest.TestCase): def __init__(self, path): super().__init__('_test') self.path = os.path.relpath(path) def", "in etags_from_tagstring(fn, ''): yield etag.tag def _get_test_filenames(): for root, dirnames, filenames in os.walk(here):", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "path): match = _parse_etag(contents) if match is None: return t = ETag(match.group(1), path,", "exec(3)ing is very expensive. # Let's load the needed Python modules, and use", "stdout=ipc.PIPE, stderr=ipc.PIPE, env=fixed_env) as child: stdout, stderr = ( s.decode('UTF-8').splitlines() for s in", "# “emulate” the command execution. import lib.cli # pylint: disable=import-outside-toplevel assert lib.cli #", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN", "file: return _parse_test_header_file(file, path, comments_only=False) # <path>.gen: try: file = open(path + '.gen',", ".pop is a special extension to trigger unknown-file-type class Plugin(nose.plugins.Plugin): name = 'po-plugin'", "including without limitation the rights # to use, copy, modify, merge, publish, distribute,", "def _get_signal_names(): data = dict( (name, getattr(signal, name)) for name in dir(signal) if", "pass try: if data['SIGCHLD'] == data['SIGCLD']: del data['SIGCLD'] except KeyError: pass for name,", "env=fixed_env) as child: stdout, stderr = ( s.decode('UTF-8').splitlines() for s in child.communicate() )", "pylint: disable=consider-using-with except FileNotFoundError: pass else: with file: return _parse_test_header_file(file, path, comments_only=False) #", "# <path>: with open(path, 'rt', encoding='UTF-8', errors='ignore') as file: return _parse_test_header_file(file, path, comments_only=True)", "tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'denied.po') with open(path, 'wb'): pass os.chmod(path, 0)", "get_coverage_for_function(fn): for etag in etags_from_tagstring(fn, ''): yield etag.tag def _get_test_filenames(): for root, dirnames,", "THE # SOFTWARE. import difflib import inspect import io import multiprocessing as mp", "---------------------------------------- _parse_etag = re.compile(r'([A-Z]): (([\\w-]+).*)').match def parse_etag(contents, path): match = _parse_etag(contents) if match", "_test_file(self.path, basedir=None) def __str__(self): return self.path class SubprocessError(Exception): pass def queue_get(queue, process): '''", "return globals()[inspect.stack()[1][0].f_code.co_name] # ---------------------------------------- _parse_etag = re.compile(r'([A-Z]): (([\\w-]+).*)').match def parse_etag(contents, path): match =", "DEALINGS IN THE # SOFTWARE. import difflib import inspect import io import multiprocessing", "try: if data['SIGCHLD'] == data['SIGCLD']: del data['SIGCLD'] except KeyError: pass for name, n", "queue_get(queue, process): ''' Remove and return an item from the queue. Block until", "continue if line.startswith('# '): line = line[2:] else: break if line.startswith('--'): options +=", "= etags_from_tagstring(this(), path) assert_emit_tags(path, expected) @tagstring(''' E: os-error Permission denied ''') def test_os_error_permission_denied():", "['stderr: (empty)'] raise SubprocessError('\\n'.join(message)) def _mp_run_i18nspector(prog, options, path, queue): with open(prog, 'rt', encoding='UTF-8')", "pass else: with file: return _parse_test_header_file(file, path, comments_only=False) # <path>.gen: try: file =", "comments_only: if n == 0 and line.startswith('#!'): continue if line.startswith('# '): line =", "raise AssertionError('\\n'.join(message)) elif expected_failure: raise AssertionError('unexpected success') class TestFileSyntaxError(Exception): pass def _parse_test_header_file(file, path,", "if n == 0 and line.startswith('#!'): continue if line.startswith('# '): line = line[2:]", "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "queue) ) child.start() [stdout, stderr] = ( s.splitlines() for s in queue_get(queue, child)", "open(path + '.tags', encoding='UTF-8') # pylint: disable=consider-using-with except FileNotFoundError: pass else: with file:", "_get_test_filenames(): for tag in get_coverage_for_file(filename): coverage.add(tag) for objname, obj in globals().items(): if not", "[sys.executable, prog] queue = mp.Queue() child = mp.Process( target=_mp_run_i18nspector, args=(prog, options, path, queue)", "def _mp_run_i18nspector(prog, options, path, queue): with open(prog, 'rt', encoding='UTF-8') as file: code =", "# pylint: disable=import-outside-toplevel assert lib.cli # make pyflakes happy prog = os.path.join(here, os.pardir,", "+ s for s in stdout] + [''] else: message += ['stdout: (empty)']", "pylint: disable=exec-used finally: (sys.stdout, sys.stderr) = (orig_stdout, orig_stderr) stdout = io_stdout.getvalue() stderr =", "__eq__(self, other): if isinstance(other, str): return self._regexp.match(other) else: return NotImplemented def __str__(self): return", "---------------------------------------- class ETag(): _ellipsis = '<...>' _split = re.compile('({})'.format(re.escape(_ellipsis))).split def __init__(self, code, path,", "hereby granted, free of charge, to any person obtaining a copy # of", "= ''.join( '.*' if chunk == self._ellipsis else re.escape(chunk) for chunk in self._split(s)", "else: queue.put([stdout, stderr]) sys.exit(0) def assert_emit_tags(path, etags, *, options=()): etags = list(etags) stdout", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "comments_only=True) # <path>: with open(path, 'rt', encoding='UTF-8', errors='ignore') as file: return _parse_test_header_file(file, path,", "# ---------------------------------------- _parse_etag = re.compile(r'([A-Z]): (([\\w-]+).*)').match def parse_etag(contents, path): match = _parse_etag(contents) if", "open(path, 'rt', encoding='UTF-8', errors='ignore') as file: return _parse_test_header_file(file, path, comments_only=True) def _test_file(path, basedir=here):", "_parse_etag(contents) if match is None: return t = ETag(match.group(1), path, match.group(2)) return t", "= io.StringIO() io_stderr = io.StringIO() gvars = dict( __file__=prog, ) (sys.stdout, sys.stderr) =", "line[2:] else: break if line.startswith('--'): options += shlex.split(line) else: etag = parse_etag(line, path)", "etags, options = _parse_test_headers(path) del options return (t.tag for t in etags) def", "message = ['command was interrupted by signal {sig}'.format(sig=get_signal_name(-rc))] # pylint: disable=invalid-unary-operand-type else: message", "= ( s.splitlines() for s in queue_get(queue, child) ) child.join() rc = child.exitcode", "child.exitcode else: commandline = shlex.split(commandline) commandline += options commandline += [path] fixed_env =", "waiting is ugly, but there doesn't seem be any # obvious better way.", "differ:', ''] diff = list( difflib.unified_diff(str_etags, stdout, n=9999) ) message += diff[3:] raise", "( s.splitlines() for s in queue_get(queue, child) ) child.join() rc = child.exitcode else:", "Return function that called this function. (Hopefully!) ''' return globals()[inspect.stack()[1][0].f_code.co_name] # ---------------------------------------- _parse_etag", "seem be any # obvious better way. except mp.queues.Empty: if process.exitcode is None:", "notice shall be included in # all copies or substantial portions of the", "with tools.temporary_directory() as tmpdir: path = os.path.join(tmpdir, 'denied.po') with open(path, 'wb'): pass os.chmod(path,", "and return an item from the queue. Block until the process terminates. '''", "io_stdout = io.StringIO() io_stderr = io.StringIO() gvars = dict( __file__=prog, ) (sys.stdout, sys.stderr)", "x in etags] message = ['Tags differ:', ''] diff = list( difflib.unified_diff(str_etags, stdout,", "import nose import nose.plugins from .. import tools here = os.path.dirname(__file__) # ----------------------------------------", "was interrupted by signal {sig}'.format(sig=get_signal_name(-rc))] # pylint: disable=invalid-unary-operand-type else: message = ['command exited", "_mp_run_i18nspector(prog, options, path, queue): with open(prog, 'rt', encoding='UTF-8') as file: code = file.read()", "(sys.stdout, sys.stderr) = (io_stdout, io_stderr) try: try: exec(code, gvars) # pylint: disable=exec-used finally:", "io import multiprocessing as mp import os import re import shlex import signal", "NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "__str__(self): return self._s def __repr__(self): return repr(self._s) # ---------------------------------------- def _get_signal_names(): data =", "stderr = io_stderr.getvalue() except SystemExit: queue.put([stdout, stderr]) raise except: # pylint: disable=bare-except exctp,", "for objname, obj in globals().items(): if not objname.startswith('test_'): continue for tag in get_coverage_for_function(obj):", "if not objname.startswith('test_'): continue for tag in get_coverage_for_function(obj): coverage.add(tag) return coverage # vim:ts=4", "a bit, because exec(3)ing is very expensive. # Let's load the needed Python", "for s in queue_get(queue, child) ) child.join() rc = child.exitcode else: commandline =", "not needed if the plugin is enabled @tagstring(''' E: os-error No such file", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of", "the queue. Block until the process terminates. ''' while True: try: return queue.get(timeout=1)", "isinstance(rc, int) if rc == 0: return stdout if rc < 0: message", "the Software is # furnished to do so, subject to the following conditions:", "subject to the following conditions: # # The above copyright notice and this", "import multiprocessing as mp import os import re import shlex import signal import", "name)) for name in dir(signal) if re.compile('^SIG[A-Z0-9]*$').match(name) ) try: if data['SIGABRT'] == data['SIGIOT']:", "0: return stdout if rc < 0: message = ['command was interrupted by" ]
[ "return f\"{key}{' '.join(args)}{bcolors.ENDC}\" def okblue(self, *args): return self._end(bcolors.OKBLUE, *args) def warn(self, *args): return", "MinyConsole: def _end(self, key, *args): return f\"{key}{' '.join(args)}{bcolors.ENDC}\" def okblue(self, *args): return self._end(bcolors.OKBLUE,", "_end(self, key, *args): return f\"{key}{' '.join(args)}{bcolors.ENDC}\" def okblue(self, *args): return self._end(bcolors.OKBLUE, *args) def", "*args) def bold(self, *args): return self._end(bcolors.BOLD, *args) def underline(self, *args): return self._end(bcolors.UNDERLINE, *args)", "= \"\\033[91m\" ENDC = \"\\033[0m\" BOLD = \"\\033[1m\" UNDERLINE = \"\\033[4m\" class MinyConsole:", "return self._end(bcolors.OKGREEN, *args) def fail(self, *args): return self._end(bcolors.FAIL, *args) def bold(self, *args): return", "\"\\033[92m\" WARNING = \"\\033[93m\" FAIL = \"\\033[91m\" ENDC = \"\\033[0m\" BOLD = \"\\033[1m\"", "\"\\033[1m\" UNDERLINE = \"\\033[4m\" class MinyConsole: def _end(self, key, *args): return f\"{key}{' '.join(args)}{bcolors.ENDC}\"", "\"\\033[94m\" OKGREEN = \"\\033[92m\" WARNING = \"\\033[93m\" FAIL = \"\\033[91m\" ENDC = \"\\033[0m\"", "ENDC = \"\\033[0m\" BOLD = \"\\033[1m\" UNDERLINE = \"\\033[4m\" class MinyConsole: def _end(self,", "bcolors: HEADER = \"\\033[95m\" OKBLUE = \"\\033[94m\" OKGREEN = \"\\033[92m\" WARNING = \"\\033[93m\"", "= \"\\033[92m\" WARNING = \"\\033[93m\" FAIL = \"\\033[91m\" ENDC = \"\\033[0m\" BOLD =", "HEADER = \"\\033[95m\" OKBLUE = \"\\033[94m\" OKGREEN = \"\\033[92m\" WARNING = \"\\033[93m\" FAIL", "def okgreen(self, *args): return self._end(bcolors.OKGREEN, *args) def fail(self, *args): return self._end(bcolors.FAIL, *args) def", "*args) def fail(self, *args): return self._end(bcolors.FAIL, *args) def bold(self, *args): return self._end(bcolors.BOLD, *args)", "f\"{key}{' '.join(args)}{bcolors.ENDC}\" def okblue(self, *args): return self._end(bcolors.OKBLUE, *args) def warn(self, *args): return self._end(bcolors.WARNING,", "UNDERLINE = \"\\033[4m\" class MinyConsole: def _end(self, key, *args): return f\"{key}{' '.join(args)}{bcolors.ENDC}\" def", "WARNING = \"\\033[93m\" FAIL = \"\\033[91m\" ENDC = \"\\033[0m\" BOLD = \"\\033[1m\" UNDERLINE", "return self._end(bcolors.FAIL, *args) def bold(self, *args): return self._end(bcolors.BOLD, *args) def underline(self, *args): return", "fail(self, *args): return self._end(bcolors.FAIL, *args) def bold(self, *args): return self._end(bcolors.BOLD, *args) def underline(self,", "\"\\033[95m\" OKBLUE = \"\\033[94m\" OKGREEN = \"\\033[92m\" WARNING = \"\\033[93m\" FAIL = \"\\033[91m\"", "def okblue(self, *args): return self._end(bcolors.OKBLUE, *args) def warn(self, *args): return self._end(bcolors.WARNING, *args) def", "\"\\033[91m\" ENDC = \"\\033[0m\" BOLD = \"\\033[1m\" UNDERLINE = \"\\033[4m\" class MinyConsole: def", "\"\\033[0m\" BOLD = \"\\033[1m\" UNDERLINE = \"\\033[4m\" class MinyConsole: def _end(self, key, *args):", "okgreen(self, *args): return self._end(bcolors.OKGREEN, *args) def fail(self, *args): return self._end(bcolors.FAIL, *args) def bold(self,", "def fail(self, *args): return self._end(bcolors.FAIL, *args) def bold(self, *args): return self._end(bcolors.BOLD, *args) def", "FAIL = \"\\033[91m\" ENDC = \"\\033[0m\" BOLD = \"\\033[1m\" UNDERLINE = \"\\033[4m\" class", "*args): return self._end(bcolors.OKBLUE, *args) def warn(self, *args): return self._end(bcolors.WARNING, *args) def okgreen(self, *args):", "= \"\\033[93m\" FAIL = \"\\033[91m\" ENDC = \"\\033[0m\" BOLD = \"\\033[1m\" UNDERLINE =", "self._end(bcolors.FAIL, *args) def bold(self, *args): return self._end(bcolors.BOLD, *args) def underline(self, *args): return self._end(bcolors.UNDERLINE,", "*args): return f\"{key}{' '.join(args)}{bcolors.ENDC}\" def okblue(self, *args): return self._end(bcolors.OKBLUE, *args) def warn(self, *args):", "= \"\\033[94m\" OKGREEN = \"\\033[92m\" WARNING = \"\\033[93m\" FAIL = \"\\033[91m\" ENDC =", "self._end(bcolors.OKBLUE, *args) def warn(self, *args): return self._end(bcolors.WARNING, *args) def okgreen(self, *args): return self._end(bcolors.OKGREEN,", "def _end(self, key, *args): return f\"{key}{' '.join(args)}{bcolors.ENDC}\" def okblue(self, *args): return self._end(bcolors.OKBLUE, *args)", "*args): return self._end(bcolors.WARNING, *args) def okgreen(self, *args): return self._end(bcolors.OKGREEN, *args) def fail(self, *args):", "okblue(self, *args): return self._end(bcolors.OKBLUE, *args) def warn(self, *args): return self._end(bcolors.WARNING, *args) def okgreen(self,", "class bcolors: HEADER = \"\\033[95m\" OKBLUE = \"\\033[94m\" OKGREEN = \"\\033[92m\" WARNING =", "self._end(bcolors.WARNING, *args) def okgreen(self, *args): return self._end(bcolors.OKGREEN, *args) def fail(self, *args): return self._end(bcolors.FAIL,", "warn(self, *args): return self._end(bcolors.WARNING, *args) def okgreen(self, *args): return self._end(bcolors.OKGREEN, *args) def fail(self,", "def warn(self, *args): return self._end(bcolors.WARNING, *args) def okgreen(self, *args): return self._end(bcolors.OKGREEN, *args) def", "= \"\\033[95m\" OKBLUE = \"\\033[94m\" OKGREEN = \"\\033[92m\" WARNING = \"\\033[93m\" FAIL =", "= \"\\033[1m\" UNDERLINE = \"\\033[4m\" class MinyConsole: def _end(self, key, *args): return f\"{key}{'", "return self._end(bcolors.WARNING, *args) def okgreen(self, *args): return self._end(bcolors.OKGREEN, *args) def fail(self, *args): return", "OKBLUE = \"\\033[94m\" OKGREEN = \"\\033[92m\" WARNING = \"\\033[93m\" FAIL = \"\\033[91m\" ENDC", "*args) def okgreen(self, *args): return self._end(bcolors.OKGREEN, *args) def fail(self, *args): return self._end(bcolors.FAIL, *args)", "BOLD = \"\\033[1m\" UNDERLINE = \"\\033[4m\" class MinyConsole: def _end(self, key, *args): return", "key, *args): return f\"{key}{' '.join(args)}{bcolors.ENDC}\" def okblue(self, *args): return self._end(bcolors.OKBLUE, *args) def warn(self,", "class MinyConsole: def _end(self, key, *args): return f\"{key}{' '.join(args)}{bcolors.ENDC}\" def okblue(self, *args): return", "= \"\\033[4m\" class MinyConsole: def _end(self, key, *args): return f\"{key}{' '.join(args)}{bcolors.ENDC}\" def okblue(self,", "'.join(args)}{bcolors.ENDC}\" def okblue(self, *args): return self._end(bcolors.OKBLUE, *args) def warn(self, *args): return self._end(bcolors.WARNING, *args)", "\"\\033[4m\" class MinyConsole: def _end(self, key, *args): return f\"{key}{' '.join(args)}{bcolors.ENDC}\" def okblue(self, *args):", "self._end(bcolors.OKGREEN, *args) def fail(self, *args): return self._end(bcolors.FAIL, *args) def bold(self, *args): return self._end(bcolors.BOLD,", "return self._end(bcolors.OKBLUE, *args) def warn(self, *args): return self._end(bcolors.WARNING, *args) def okgreen(self, *args): return", "*args): return self._end(bcolors.FAIL, *args) def bold(self, *args): return self._end(bcolors.BOLD, *args) def underline(self, *args):", "*args) def warn(self, *args): return self._end(bcolors.WARNING, *args) def okgreen(self, *args): return self._end(bcolors.OKGREEN, *args)", "<gh_stars>0 class bcolors: HEADER = \"\\033[95m\" OKBLUE = \"\\033[94m\" OKGREEN = \"\\033[92m\" WARNING", "OKGREEN = \"\\033[92m\" WARNING = \"\\033[93m\" FAIL = \"\\033[91m\" ENDC = \"\\033[0m\" BOLD", "= \"\\033[0m\" BOLD = \"\\033[1m\" UNDERLINE = \"\\033[4m\" class MinyConsole: def _end(self, key,", "*args): return self._end(bcolors.OKGREEN, *args) def fail(self, *args): return self._end(bcolors.FAIL, *args) def bold(self, *args):", "\"\\033[93m\" FAIL = \"\\033[91m\" ENDC = \"\\033[0m\" BOLD = \"\\033[1m\" UNDERLINE = \"\\033[4m\"" ]
[ "if not matcher.match(bn_pat, expr): return expr matched_exprs = matcher.matched_exprs if conv_pat_0 in matched_exprs:", "is used {} times and its name will be reset to {}.{}\".format( mnode.qualname,", "matcher.match(pattern, expr) if res: break if not res: return expr return func(expr) def", ".pattern import ExprPattern, any_node, is_const, is_op, is_var from .utils import get_const_value, register_obj logger", "import get_const_value, register_obj logger = get_logger(__name__) @register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass): \"\"\"Fold adjacent const add", "expr return func(expr) def _fold_helper(self, expr: Expr, op_c: Callable, op_t: Callable): const_0 =", "= self.get_const_value(expr) # todo: support more shape if isinstance(const_0, Tensor) and const_0._tuple_shape not", "x = x + 1 x = 2 + x x = x", "isinstance(const_1, Tensor) and const_1._tuple_shape not in [(1,), tuple()]: return expr inp_node = expr.inputs[0].expr.inputs[0]", "self._fold_helper(expr, operator.mul, F.pow) def get_const_value(self, expr: Expr): if is_call_function(expr, F.neg): return -1 if", "1: self.used_name[mnode.qualname] += 1 attr_name = \"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning( \"{} is used {}", "running_var, weight, bias bn_inps = ( conv_pat_0 | conv_pat_1, is_const(), is_const(), is_const(), is_const(),", "in [F.neg, operator.mul]: for op_1 in [F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)] = self.fold_mul def", "attr_name ) ) conv_module = mnode.owner weight, bias = conv_module.weight, conv_module.bias mean, var,", ".utils import get_const_value, register_obj logger = get_logger(__name__) @register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass): \"\"\"Fold adjacent const", "shape if isinstance(const_0, Tensor) and const_0._tuple_shape not in [(1,), tuple()]: return expr const_1", "get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps = named_args[\"eps\"]", "from ...logger import get_logger from ...tensor import Parameter, Tensor from ...utils.bn_fusion import fold_weight_bias", "get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps = named_args[\"eps\"] return mean, var, gamma, beta, eps else: bn_module", "bn_module.running_var gamma = bn_module.weight beta = bn_module.bias eps = bn_module.eps return mean, var,", "operator from collections import defaultdict from typing import Any, Callable, List from ...", "op_0(x, is_const()) | op_0(x, \"*\") pattern = op_1(pattern, is_const()) | op_1(pattern, \"*\") return", "beta, mean, var, eps) named_args[\"weight\"] = weight named_args[\"bias\"] = bias graph = conv.top_graph", "software distributed under the License is distributed on an # \"AS IS\" BASIS,", "def fold_mul(self, expr): return self._fold_helper(expr, operator.mul, operator.mul) def fold_pow(self, expr): return self._fold_helper(expr, operator.mul,", "self.pattern_dict = {} for op, func in zip([operator.add, F.pow], [self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op, op)]", "op_1)] = self.fold_mul def run_transform(self, expr: Expr): matcher = PatternMatcher() for pattern, func", "beta, mean, var, eps) new_conv = M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation,", "= fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) new_conv = M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels,", "expr: Expr, op_c: Callable, op_t: Callable): const_0 = self.get_const_value(expr) # todo: support more", "fold_pow(self, expr): return self._fold_helper(expr, operator.mul, F.pow) def get_const_value(self, expr: Expr): if is_call_function(expr, F.neg):", "bias = fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) named_args[\"weight\"] = weight named_args[\"bias\"]", "attr_name) with graph.insert_exprs(mnode.expr): out_node = get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name", "out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def get_bn_params(self, bn: Expr): if is_call_function(bn):", "under the Apache License, Version 2.0 (the \"License\") # # Copyright (c) 2014-2021", "graph.replace_node({expr.outputs[0]: out_node}) graph.compile() return out_node.expr def fold_add(self, expr: Expr): return self._fold_helper(expr, operator.add, operator.add)", "not in [operator.add, operator.mul]: op_1 = is_op(op_1) pattern = op_0(x, is_const()) | op_0(x,", "\" return value value = expr.const_val[0][-1] return value @register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass): r\"\"\"Fuse BN", "x = x * 0.25 will be changed to .. code-block:: x =", "op_0 in [F.neg, operator.mul]: for op_1 in [F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)] = self.fold_mul", "used {} times and its name will be reset to {}.{}\".format( mnode.qualname, len(mnode.users),", "matched_exprs[bn_pat]) def fold_convm_bn(self, conv: Expr, bn: Expr): mnode, inp_node = conv.inputs[:2] self_node =", "bias graph = conv.top_graph with graph.insert_exprs(): out_node = F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name", "None, \" \" return value value = expr.const_val[0][-1] return value @register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass):", "= bn_module.running_var gamma = bn_module.weight beta = bn_module.bias eps = bn_module.eps return mean,", "2 + x x = x * 4 x = x * 0.25", "[\"AttrToConstant\"] run_once = True def __init__(self): super().__init__() self.used_name = defaultdict(int) def run_transform(self, expr:", "matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else: return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def fold_convm_bn(self, conv: Expr, bn:", "graph.qualname, attr_name ) ) conv_module = mnode.owner weight, bias = conv_module.weight, conv_module.bias mean,", "weight = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean, var, gamma, beta, eps", "const_0._tuple_shape not in [(1,), tuple()]: return expr const_1 = self.get_const_value(expr.inputs[0].expr) if isinstance(const_1, Tensor)", "= False def __init__(self,): super().__init__() def _make_pattern(op_0, op_1) -> ExprPattern: x = is_var().check_users(False)", "= ( (bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps)) | bn_pat_0 ) matcher = PatternMatcher()", "= matcher.matched_exprs if conv_pat_0 in matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else: return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat])", "value is not None, \" \" return value value = expr.const_val[0][-1] return value", "bias, gamma, beta, mean, var, eps) named_args[\"weight\"] = weight named_args[\"bias\"] = bias graph", "op_0 = is_op(op_0) if op_1 not in [operator.add, operator.mul]: op_1 = is_op(op_1) pattern", "def run_transform(self, expr: Expr): conv_pat_0 = is_op(M.Conv2d) conv_pat_1 = is_op(F.conv2d) bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0", "pattern = op_0(x, is_const()) | op_0(x, \"*\") pattern = op_1(pattern, is_const()) | op_1(pattern,", "Callable, op_t: Callable): const_0 = self.get_const_value(expr) # todo: support more shape if isinstance(const_0,", "var, gamma, beta, eps = self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias, gamma, beta,", "import Expr, is_call_function from ..utils import assign_attr, get_subattr from .matcher import PatternMatcher from", "= self.get_const_value(expr.inputs[0].expr) if isinstance(const_1, Tensor) and const_1._tuple_shape not in [(1,), tuple()]: return expr", "out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias is not None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name,", "M from ...logger import get_logger from ...tensor import Parameter, Tensor from ...utils.bn_fusion import", "3 \"\"\" name = \"FuseAddMul\" required_pass = [\"NormElemWise\"] run_once = False def __init__(self,):", "\"\"\"Fold adjacent const add or mul binary operations. For example, the following code", "[operator.add, operator.mul]: op_0 = is_op(op_0) if op_1 not in [operator.add, operator.mul]: op_1 =", "..utils import assign_attr, get_subattr from .matcher import PatternMatcher from .pass_base import BackwardPass, register_pass", "= self.fold_mul def run_transform(self, expr: Expr): matcher = PatternMatcher() for pattern, func in", "attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def fold_convf_bn(self, conv: Expr,", "[operator.add] ): graph.replace_node({expr.outputs[0]: inp_node}) graph.compile() return expr with expr.top_graph.insert_exprs(): out_node = op_t(inp_node, const)", "( const == 0 and op_t in [operator.add] ): graph.replace_node({expr.outputs[0]: inp_node}) graph.compile() return", "operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)] = self.fold_mul def run_transform(self, expr: Expr): matcher = PatternMatcher() for", "const = op_c(const_0, const_1) graph = expr.top_graph if (const == 1 and op_t", "graph = expr.top_graph if (const == 1 and op_t in [operator.pow, operator.mul]) or", "for op_0 in [F.neg, operator.mul]: for op_1 in [F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)] =", "= 2 + x x = x * 4 x = x *", "return out_node.expr def fold_add(self, expr: Expr): return self._fold_helper(expr, operator.add, operator.add) def fold_mul(self, expr):", "or agreed to in writing, # software distributed under the License is distributed", "| op_0(x, \"*\") pattern = op_1(pattern, is_const()) | op_1(pattern, \"*\") return pattern self.pattern_dict", "= [\"AttrToConstant\"] run_once = True def __init__(self): super().__init__() self.used_name = defaultdict(int) def run_transform(self,", "named_args[\"running_var\"]) gamma = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps = named_args[\"eps\"] return", "Expr): matcher = PatternMatcher() for pattern, func in self.pattern_dict.items(): res = matcher.match(pattern, expr)", ".matcher import PatternMatcher from .pass_base import BackwardPass, register_pass from .pattern import ExprPattern, any_node,", "in [(1,), tuple()]: return expr const_1 = self.get_const_value(expr.inputs[0].expr) if isinstance(const_1, Tensor) and const_1._tuple_shape", "op_t(inp_node, const) graph.replace_node({expr.outputs[0]: out_node}) graph.compile() return out_node.expr def fold_add(self, expr: Expr): return self._fold_helper(expr,", "= self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) new_conv", "if op_1 not in [operator.add, operator.mul]: op_1 = is_op(op_1) pattern = op_0(x, is_const())", "conv_pat_1 = is_op(F.conv2d) bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1) bn_pat_1 = is_op(F.batch_norm) # inp,", "out_node = op_t(inp_node, const) graph.replace_node({expr.outputs[0]: out_node}) graph.compile() return out_node.expr def fold_add(self, expr: Expr):", "bn_pat = ( (bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps)) | bn_pat_0 ) matcher =", "zip([operator.add, F.pow], [self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op, op)] = func for op_0 in [F.neg, operator.mul]:", "weight, bias = fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) new_conv = M.Conv2d(", "new_conv = M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias is not", "\"\"\" name = \"FuseAddMul\" required_pass = [\"NormElemWise\"] run_once = False def __init__(self,): super().__init__()", "Tensor) and const_1._tuple_shape not in [(1,), tuple()]: return expr inp_node = expr.inputs[0].expr.inputs[0] const", "def fold_pow(self, expr): return self._fold_helper(expr, operator.mul, F.pow) def get_const_value(self, expr: Expr): if is_call_function(expr,", "op_1 = is_op(op_1) pattern = op_0(x, is_const()) | op_0(x, \"*\") pattern = op_1(pattern,", "= bn_module.weight beta = bn_module.bias eps = bn_module.eps return mean, var, gamma, beta,", "| (bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps)) | bn_pat_0 ) matcher = PatternMatcher() if not matcher.match(bn_pat,", "register_pass from .pattern import ExprPattern, any_node, is_const, is_op, is_var from .utils import get_const_value,", "x = x * 4 x = x * 0.25 will be changed", "pattern = op_1(pattern, is_const()) | op_1(pattern, \"*\") return pattern self.pattern_dict = {} for", "conv2d.\"\"\" name = \"FuseConvBn\" required_pass = [\"AttrToConstant\"] run_once = True def __init__(self): super().__init__()", "mnode, inp_node = conv.inputs[:2] self_node = mnode.expr.inputs[0] attr_name = conv.inputs[0].expr.name graph = conv.top_graph", "F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def get_bn_params(self, bn: Expr):", "(bn_pat_1(*bn_inps)) | bn_pat_0 ) matcher = PatternMatcher() if not matcher.match(bn_pat, expr): return expr", "= \"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning( \"{} is used {} times and its name will", "defaultdict(int) def run_transform(self, expr: Expr): conv_pat_0 = is_op(M.Conv2d) conv_pat_1 = is_op(F.conv2d) bn_pat_0 =", "= conv_module.training assign_attr(new_conv, self_node.owner, attr_name) with graph.insert_exprs(mnode.expr): out_node = get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node})", "return self._fold_helper(expr, operator.add, operator.add) def fold_mul(self, expr): return self._fold_helper(expr, operator.mul, operator.mul) def fold_pow(self,", "self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) new_conv =", "= get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps = named_args[\"eps\"] return mean, var,", "= conv.outputs[0].name return out_node.expr def fold_convf_bn(self, conv: Expr, bn: Expr): named_args = conv.named_args", "Expr): if is_call_function(bn): named_args = bn.named_args mean = get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"] ) var", "is_var().check_users(False) if op_0 not in [operator.add, operator.mul]: op_0 = is_op(op_0) if op_1 not", "matched_exprs = matcher.matched_exprs if conv_pat_0 in matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else: return self.fold_convf_bn(matched_exprs[conv_pat_1],", "binary operations. For example, the following code .. code-block:: x = x +", "Expr): conv_pat_0 = is_op(M.Conv2d) conv_pat_1 = is_op(F.conv2d) bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1) bn_pat_1", "bn_module.running_mean var = bn_module.running_var gamma = bn_module.weight beta = bn_module.bias eps = bn_module.eps", "import ExprPattern, any_node, is_const, is_op, is_var from .utils import get_const_value, register_obj logger =", "operator.mul]: op_0 = is_op(op_0) if op_1 not in [operator.add, operator.mul]: op_1 = is_op(op_1)", "return expr with expr.top_graph.insert_exprs(): out_node = op_t(inp_node, const) graph.replace_node({expr.outputs[0]: out_node}) graph.compile() return out_node.expr", "\"*\") pattern = op_1(pattern, is_const()) | op_1(pattern, \"*\") return pattern self.pattern_dict = {}", "for op_1 in [F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)] = self.fold_mul def run_transform(self, expr: Expr):", "matched_exprs[bn_pat]) else: return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def fold_convm_bn(self, conv: Expr, bn: Expr): mnode, inp_node", "beta, eps = self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias, gamma, beta, mean, var,", "logger.warning( \"{} is used {} times and its name will be reset to", "graph.insert_exprs(): out_node = F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def", "conv_module.weight, conv_module.bias mean, var, gamma, beta, eps = self.get_bn_params(bn) weight, bias = fold_weight_bias(weight,", "matcher = PatternMatcher() for pattern, func in self.pattern_dict.items(): res = matcher.match(pattern, expr) if", "new_conv.training = conv_module.training assign_attr(new_conv, self_node.owner, attr_name) with graph.insert_exprs(mnode.expr): out_node = get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]:", "operations. For example, the following code .. code-block:: x = x + 1", "under the License is distributed on an # \"AS IS\" BASIS, WITHOUT ARRANTIES", "weight named_args[\"bias\"] = bias graph = conv.top_graph with graph.insert_exprs(): out_node = F.conv2d(**named_args) graph.replace_node({bn.outputs[0]:", "running_mean, running_var, weight, bias bn_inps = ( conv_pat_0 | conv_pat_1, is_const(), is_const(), is_const(),", "conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name, ) new_conv.weight = Parameter(weight) new_conv.bias = Parameter(bias) new_conv.training = conv_module.training", "op)] = func for op_0 in [F.neg, operator.mul]: for op_1 in [F.neg, operator.mul]:", "in [F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)] = self.fold_mul def run_transform(self, expr: Expr): matcher =", "else: return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def fold_convm_bn(self, conv: Expr, bn: Expr): mnode, inp_node =", "conv_pat_1, is_const(), is_const(), is_const(), is_const(), ) bn_pat = ( (bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4])) |", "bias = conv_module.weight, conv_module.bias mean, var, gamma, beta, eps = self.get_bn_params(bn) weight, bias", "get_const_value(self, expr: Expr): if is_call_function(expr, F.neg): return -1 if len(expr.inputs) == 2: value", "res = matcher.match(pattern, expr) if res: break if not res: return expr return", "Expr, bn: Expr): named_args = conv.named_args weight = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias = get_const_value(named_args[\"bias\"],", "is Licensed under the Apache License, Version 2.0 (the \"License\") # # Copyright", "ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import operator from", "const_1._tuple_shape not in [(1,), tuple()]: return expr inp_node = expr.inputs[0].expr.inputs[0] const = op_c(const_0,", "= True def __init__(self): super().__init__() self.used_name = defaultdict(int) def run_transform(self, expr: Expr): conv_pat_0", "fold_mul(self, expr): return self._fold_helper(expr, operator.mul, operator.mul) def fold_pow(self, expr): return self._fold_helper(expr, operator.mul, F.pow)", "{} times and its name will be reset to {}.{}\".format( mnode.qualname, len(mnode.users), graph.qualname,", "operator.mul, operator.mul) def fold_pow(self, expr): return self._fold_helper(expr, operator.mul, F.pow) def get_const_value(self, expr: Expr):", "as M from ...logger import get_logger from ...tensor import Parameter, Tensor from ...utils.bn_fusion", "and its name will be reset to {}.{}\".format( mnode.qualname, len(mnode.users), graph.qualname, attr_name )", "named_args[\"running_mean\"] ) var = get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta = get_const_value(named_args[\"bias\"],", "x + 1 x = 2 + x x = x * 4", "# Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required", "__init__(self,): super().__init__() def _make_pattern(op_0, op_1) -> ExprPattern: x = is_var().check_users(False) if op_0 not", "const add or mul binary operations. For example, the following code .. code-block::", "either express or implied. import operator from collections import defaultdict from typing import", "run_transform(self, expr: Expr): conv_pat_0 = is_op(M.Conv2d) conv_pat_1 = is_op(F.conv2d) bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0 |", "= is_var().check_users(False) if op_0 not in [operator.add, operator.mul]: op_0 = is_op(op_0) if op_1", "= Parameter(bias) new_conv.training = conv_module.training assign_attr(new_conv, self_node.owner, attr_name) with graph.insert_exprs(mnode.expr): out_node = get_subattr(self_node,", "value = get_const_value(expr.inputs[1].expr, None) assert value is not None, \" \" return value", "is not None, \" \" return value value = expr.const_val[0][-1] return value @register_pass(\"FuseConvBn\")", "(const == 1 and op_t in [operator.pow, operator.mul]) or ( const == 0", "return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else: return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def fold_convm_bn(self, conv: Expr, bn: Expr):", "conv_pat_0 | conv_pat_1, is_const(), is_const(), is_const(), is_const(), ) bn_pat = ( (bn_pat_1(*bn_inps[:3])) |", "conv_pat_0 in matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else: return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def fold_convm_bn(self, conv:", "_fold_helper(self, expr: Expr, op_c: Callable, op_t: Callable): const_0 = self.get_const_value(expr) # todo: support", "from collections import defaultdict from typing import Any, Callable, List from ... import", "pattern self.pattern_dict = {} for op, func in zip([operator.add, F.pow], [self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op,", "class FuseConvBn(BackwardPass): r\"\"\"Fuse BN layers into conv2d.\"\"\" name = \"FuseConvBn\" required_pass = [\"AttrToConstant\"]", "tuple()]: return expr inp_node = expr.inputs[0].expr.inputs[0] const = op_c(const_0, const_1) graph = expr.top_graph", "fold_add(self, expr: Expr): return self._fold_helper(expr, operator.add, operator.add) def fold_mul(self, expr): return self._fold_helper(expr, operator.mul,", "= [\"NormElemWise\"] run_once = False def __init__(self,): super().__init__() def _make_pattern(op_0, op_1) -> ExprPattern:", "not None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name, ) new_conv.weight = Parameter(weight) new_conv.bias = Parameter(bias) new_conv.training", "def get_bn_params(self, bn: Expr): if is_call_function(bn): named_args = bn.named_args mean = get_const_value( named_args[\"running_mean\"],", "if isinstance(const_1, Tensor) and const_1._tuple_shape not in [(1,), tuple()]: return expr inp_node =", "op_1 not in [operator.add, operator.mul]: op_1 = is_op(op_1) pattern = op_0(x, is_const()) |", "(the \"License\") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. #", "graph.replace_node({expr.outputs[0]: inp_node}) graph.compile() return expr with expr.top_graph.insert_exprs(): out_node = op_t(inp_node, const) graph.replace_node({expr.outputs[0]: out_node})", "= get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"] ) var = get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma = get_const_value(named_args[\"weight\"], named_args[\"weight\"])", "distributed on an # \"AS IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY", "expr matched_exprs = matcher.matched_exprs if conv_pat_0 in matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else: return", "graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def fold_convf_bn(self, conv: Expr, bn:", "self_node.owner, attr_name) with graph.insert_exprs(mnode.expr): out_node = get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name =", "BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import", "operator.mul, F.pow) def get_const_value(self, expr: Expr): if is_call_function(expr, F.neg): return -1 if len(expr.inputs)", "name will be reset to {}.{}\".format( mnode.qualname, len(mnode.users), graph.qualname, attr_name ) ) conv_module", "value value = expr.const_val[0][-1] return value @register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass): r\"\"\"Fuse BN layers into", "@register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass): r\"\"\"Fuse BN layers into conv2d.\"\"\" name = \"FuseConvBn\" required_pass =", "PatternMatcher() if not matcher.match(bn_pat, expr): return expr matched_exprs = matcher.matched_exprs if conv_pat_0 in", "if res: break if not res: return expr return func(expr) def _fold_helper(self, expr:", "expr: Expr): conv_pat_0 = is_op(M.Conv2d) conv_pat_1 = is_op(F.conv2d) bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1)", "= is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1) bn_pat_1 = is_op(F.batch_norm) # inp, running_mean, running_var, weight, bias", "in matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else: return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def fold_convm_bn(self, conv: Expr,", "> 1: self.used_name[mnode.qualname] += 1 attr_name = \"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning( \"{} is used", "eps) named_args[\"weight\"] = weight named_args[\"bias\"] = bias graph = conv.top_graph with graph.insert_exprs(): out_node", "collections import defaultdict from typing import Any, Callable, List from ... import functional", "add or mul binary operations. For example, the following code .. code-block:: x", "from ... import functional as F from ... import module as M from", "is_const()) | op_1(pattern, \"*\") return pattern self.pattern_dict = {} for op, func in", "| conv_pat_1, is_const(), is_const(), is_const(), is_const(), ) bn_pat = ( (bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4]))", "[F.neg, operator.mul]: for op_1 in [F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)] = self.fold_mul def run_transform(self,", "super().__init__() self.used_name = defaultdict(int) def run_transform(self, expr: Expr): conv_pat_0 = is_op(M.Conv2d) conv_pat_1 =", "expr): return expr matched_exprs = matcher.matched_exprs if conv_pat_0 in matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat])", "the License is distributed on an # \"AS IS\" BASIS, WITHOUT ARRANTIES OR", "self_node = mnode.expr.inputs[0] attr_name = conv.inputs[0].expr.name graph = conv.top_graph if len(mnode.users) > 1:", "+= 1 attr_name = \"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning( \"{} is used {} times and", "break if not res: return expr return func(expr) def _fold_helper(self, expr: Expr, op_c:", "self.used_name = defaultdict(int) def run_transform(self, expr: Expr): conv_pat_0 = is_op(M.Conv2d) conv_pat_1 = is_op(F.conv2d)", "get_bn_params(self, bn: Expr): if is_call_function(bn): named_args = bn.named_args mean = get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"]", "return func(expr) def _fold_helper(self, expr: Expr, op_c: Callable, op_t: Callable): const_0 = self.get_const_value(expr)", "op_c(const_0, const_1) graph = expr.top_graph if (const == 1 and op_t in [operator.pow,", "= op_1(pattern, is_const()) | op_1(pattern, \"*\") return pattern self.pattern_dict = {} for op,", "bias bn_inps = ( conv_pat_0 | conv_pat_1, is_const(), is_const(), is_const(), is_const(), ) bn_pat", "1 x = 2 + x x = x * 4 x =", "= bias graph = conv.top_graph with graph.insert_exprs(): out_node = F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node}) graph.compile()", "fold_convm_bn(self, conv: Expr, bn: Expr): mnode, inp_node = conv.inputs[:2] self_node = mnode.expr.inputs[0] attr_name", "bn: Expr): named_args = conv.named_args weight = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias = get_const_value(named_args[\"bias\"], named_args[\"bias\"])", "expr): return self._fold_helper(expr, operator.mul, F.pow) def get_const_value(self, expr: Expr): if is_call_function(expr, F.neg): return", "{} for op, func in zip([operator.add, F.pow], [self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op, op)] = func", "self.fold_mul def run_transform(self, expr: Expr): matcher = PatternMatcher() for pattern, func in self.pattern_dict.items():", "All rights reserved. # # Unless required by applicable law or agreed to", "BackwardPass, register_pass from .pattern import ExprPattern, any_node, is_const, is_op, is_var from .utils import", "= x * 4 x = x * 0.25 will be changed to", "out_node = F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def get_bn_params(self,", "is_op(op_0) if op_1 not in [operator.add, operator.mul]: op_1 = is_op(op_1) pattern = op_0(x,", "eps else: bn_module = bn.inputs[0].owner mean = bn_module.running_mean var = bn_module.running_var gamma =", "for op, func in zip([operator.add, F.pow], [self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op, op)] = func for", "= func for op_0 in [F.neg, operator.mul]: for op_1 in [F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0,", "is_call_function(expr, F.neg): return -1 if len(expr.inputs) == 2: value = get_const_value(expr.inputs[1].expr, None) assert", "): graph.replace_node({expr.outputs[0]: inp_node}) graph.compile() return expr with expr.top_graph.insert_exprs(): out_node = op_t(inp_node, const) graph.replace_node({expr.outputs[0]:", "= defaultdict(int) def run_transform(self, expr: Expr): conv_pat_0 = is_op(M.Conv2d) conv_pat_1 = is_op(F.conv2d) bn_pat_0", "reset to {}.{}\".format( mnode.qualname, len(mnode.users), graph.qualname, attr_name ) ) conv_module = mnode.owner weight,", "distributed under the License is distributed on an # \"AS IS\" BASIS, WITHOUT", "x * 4 x = x * 0.25 will be changed to ..", "bias = fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) new_conv = M.Conv2d( in_channels=conv_module.in_channels,", "= get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps =", "= get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps = named_args[\"eps\"] return mean, var, gamma, beta, eps else:", "eps = named_args[\"eps\"] return mean, var, gamma, beta, eps else: bn_module = bn.inputs[0].owner", "def _fold_helper(self, expr: Expr, op_c: Callable, op_t: Callable): const_0 = self.get_const_value(expr) # todo:", "== 2: value = get_const_value(expr.inputs[1].expr, None) assert value is not None, \" \"", "is_op, is_var from .utils import get_const_value, register_obj logger = get_logger(__name__) @register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass):", "return expr const_1 = self.get_const_value(expr.inputs[0].expr) if isinstance(const_1, Tensor) and const_1._tuple_shape not in [(1,),", "if len(expr.inputs) == 2: value = get_const_value(expr.inputs[1].expr, None) assert value is not None,", "expr with expr.top_graph.insert_exprs(): out_node = op_t(inp_node, const) graph.replace_node({expr.outputs[0]: out_node}) graph.compile() return out_node.expr def", "Tensor) and const_0._tuple_shape not in [(1,), tuple()]: return expr const_1 = self.get_const_value(expr.inputs[0].expr) if", "is_op(M.Conv2d) conv_pat_1 = is_op(F.conv2d) bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1) bn_pat_1 = is_op(F.batch_norm) #", "to {}.{}\".format( mnode.qualname, len(mnode.users), graph.qualname, attr_name ) ) conv_module = mnode.owner weight, bias", "var, eps) named_args[\"weight\"] = weight named_args[\"bias\"] = bias graph = conv.top_graph with graph.insert_exprs():", "return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def fold_convm_bn(self, conv: Expr, bn: Expr): mnode, inp_node = conv.inputs[:2]", "if op_0 not in [operator.add, operator.mul]: op_0 = is_op(op_0) if op_1 not in", "def get_const_value(self, expr: Expr): if is_call_function(expr, F.neg): return -1 if len(expr.inputs) == 2:", "const == 0 and op_t in [operator.add] ): graph.replace_node({expr.outputs[0]: inp_node}) graph.compile() return expr", "= bn.inputs[0].owner mean = bn_module.running_mean var = bn_module.running_var gamma = bn_module.weight beta =", "value @register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass): r\"\"\"Fuse BN layers into conv2d.\"\"\" name = \"FuseConvBn\" required_pass", "Expr): named_args = conv.named_args weight = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean,", "out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def fold_convf_bn(self, conv: Expr, bn: Expr):", "self.get_const_value(expr) # todo: support more shape if isinstance(const_0, Tensor) and const_0._tuple_shape not in", "Unless required by applicable law or agreed to in writing, # software distributed", "op_t: Callable): const_0 = self.get_const_value(expr) # todo: support more shape if isinstance(const_0, Tensor)", "bn_inps = ( conv_pat_0 | conv_pat_1, is_const(), is_const(), is_const(), is_const(), ) bn_pat =", "mean, var, eps) new_conv = M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups,", "Expr, is_call_function from ..utils import assign_attr, get_subattr from .matcher import PatternMatcher from .pass_base", "# MegEngine is Licensed under the Apache License, Version 2.0 (the \"License\") #", "License is distributed on an # \"AS IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS", "[F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)] = self.fold_mul def run_transform(self, expr: Expr): matcher = PatternMatcher()", "-1 if len(expr.inputs) == 2: value = get_const_value(expr.inputs[1].expr, None) assert value is not", ") new_conv.weight = Parameter(weight) new_conv.bias = Parameter(bias) new_conv.training = conv_module.training assign_attr(new_conv, self_node.owner, attr_name)", "= fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) named_args[\"weight\"] = weight named_args[\"bias\"] =", "return expr inp_node = expr.inputs[0].expr.inputs[0] const = op_c(const_0, const_1) graph = expr.top_graph if", "| op_1(pattern, \"*\") return pattern self.pattern_dict = {} for op, func in zip([operator.add,", "| bn_pat_0 ) matcher = PatternMatcher() if not matcher.match(bn_pat, expr): return expr matched_exprs", "fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) new_conv = M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size,", "# # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless", "self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def fold_convm_bn(self, conv: Expr, bn: Expr): mnode, inp_node = conv.inputs[:2] self_node", "+ x x = x * 4 x = x * 0.25 will", "const_1) graph = expr.top_graph if (const == 1 and op_t in [operator.pow, operator.mul])", "return self._fold_helper(expr, operator.mul, F.pow) def get_const_value(self, expr: Expr): if is_call_function(expr, F.neg): return -1", "* 0.25 will be changed to .. code-block:: x = x + 3", "op, func in zip([operator.add, F.pow], [self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op, op)] = func for op_0", "example, the following code .. code-block:: x = x + 1 x =", "if not res: return expr return func(expr) def _fold_helper(self, expr: Expr, op_c: Callable,", "return expr matched_exprs = matcher.matched_exprs if conv_pat_0 in matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else:", "from ..expr import Expr, is_call_function from ..utils import assign_attr, get_subattr from .matcher import", "0.25 will be changed to .. code-block:: x = x + 3 \"\"\"", "op_0 not in [operator.add, operator.mul]: op_0 = is_op(op_0) if op_1 not in [operator.add,", "self.pattern_dict[_make_pattern(op, op)] = func for op_0 in [F.neg, operator.mul]: for op_1 in [F.neg,", "expr const_1 = self.get_const_value(expr.inputs[0].expr) if isinstance(const_1, Tensor) and const_1._tuple_shape not in [(1,), tuple()]:", "return self._fold_helper(expr, operator.mul, operator.mul) def fold_pow(self, expr): return self._fold_helper(expr, operator.mul, F.pow) def get_const_value(self,", "import Any, Callable, List from ... import functional as F from ... import", "assign_attr, get_subattr from .matcher import PatternMatcher from .pass_base import BackwardPass, register_pass from .pattern", "[\"NormElemWise\"] run_once = False def __init__(self,): super().__init__() def _make_pattern(op_0, op_1) -> ExprPattern: x", "(bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps)) | bn_pat_0 ) matcher = PatternMatcher() if not", ".. code-block:: x = x + 1 x = 2 + x x", "self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else: return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def fold_convm_bn(self, conv: Expr, bn: Expr): mnode,", "== 0 and op_t in [operator.add] ): graph.replace_node({expr.outputs[0]: inp_node}) graph.compile() return expr with", "\"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning( \"{} is used {} times and its name will be", "..expr import Expr, is_call_function from ..utils import assign_attr, get_subattr from .matcher import PatternMatcher", "bias, gamma, beta, mean, var, eps) new_conv = M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride,", "and op_t in [operator.add] ): graph.replace_node({expr.outputs[0]: inp_node}) graph.compile() return expr with expr.top_graph.insert_exprs(): out_node", "eps) new_conv = M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias is", "layers into conv2d.\"\"\" name = \"FuseConvBn\" required_pass = [\"AttrToConstant\"] run_once = True def", "graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def get_bn_params(self, bn: Expr): if", "matcher.match(bn_pat, expr): return expr matched_exprs = matcher.matched_exprs if conv_pat_0 in matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0],", "run_transform(self, expr: Expr): matcher = PatternMatcher() for pattern, func in self.pattern_dict.items(): res =", "op_1(pattern, \"*\") return pattern self.pattern_dict = {} for op, func in zip([operator.add, F.pow],", "is_const(), ) bn_pat = ( (bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps)) | bn_pat_0 )", "self._fold_helper(expr, operator.mul, operator.mul) def fold_pow(self, expr): return self._fold_helper(expr, operator.mul, F.pow) def get_const_value(self, expr:", "... import module as M from ...logger import get_logger from ...tensor import Parameter,", "operator.mul) def fold_pow(self, expr): return self._fold_helper(expr, operator.mul, F.pow) def get_const_value(self, expr: Expr): if", "bias=conv_module.bias is not None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name, ) new_conv.weight = Parameter(weight) new_conv.bias =", "conv_pat_0 = is_op(M.Conv2d) conv_pat_1 = is_op(F.conv2d) bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1) bn_pat_1 =", "len(mnode.users), graph.qualname, attr_name ) ) conv_module = mnode.owner weight, bias = conv_module.weight, conv_module.bias", "beta = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps = named_args[\"eps\"] return mean, var, gamma, beta, eps", "not None, \" \" return value value = expr.const_val[0][-1] return value @register_pass(\"FuseConvBn\") class", "Parameter(weight) new_conv.bias = Parameter(bias) new_conv.training = conv_module.training assign_attr(new_conv, self_node.owner, attr_name) with graph.insert_exprs(mnode.expr): out_node", "conv.inputs[:2] self_node = mnode.expr.inputs[0] attr_name = conv.inputs[0].expr.name graph = conv.top_graph if len(mnode.users) >", ".. code-block:: x = x + 3 \"\"\" name = \"FuseAddMul\" required_pass =", "and const_0._tuple_shape not in [(1,), tuple()]: return expr const_1 = self.get_const_value(expr.inputs[0].expr) if isinstance(const_1,", "not matcher.match(bn_pat, expr): return expr matched_exprs = matcher.matched_exprs if conv_pat_0 in matched_exprs: return", "res: return expr return func(expr) def _fold_helper(self, expr: Expr, op_c: Callable, op_t: Callable):", "func(expr) def _fold_helper(self, expr: Expr, op_c: Callable, op_t: Callable): const_0 = self.get_const_value(expr) #", "[(1,), tuple()]: return expr const_1 = self.get_const_value(expr.inputs[0].expr) if isinstance(const_1, Tensor) and const_1._tuple_shape not", "Callable): const_0 = self.get_const_value(expr) # todo: support more shape if isinstance(const_0, Tensor) and", "Any, Callable, List from ... import functional as F from ... import module", "= is_op(op_1) pattern = op_0(x, is_const()) | op_0(x, \"*\") pattern = op_1(pattern, is_const())", "the Apache License, Version 2.0 (the \"License\") # # Copyright (c) 2014-2021 Megvii", "Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by", "\"FuseAddMul\" required_pass = [\"NormElemWise\"] run_once = False def __init__(self,): super().__init__() def _make_pattern(op_0, op_1)", "conv_pat_1) bn_pat_1 = is_op(F.batch_norm) # inp, running_mean, running_var, weight, bias bn_inps = (", "weight, bias = fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) named_args[\"weight\"] = weight", "import defaultdict from typing import Any, Callable, List from ... import functional as", "named_args[\"weight\"]) beta = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps = named_args[\"eps\"] return mean, var, gamma, beta,", "graph.insert_exprs(mnode.expr): out_node = get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr", "beta, eps else: bn_module = bn.inputs[0].owner mean = bn_module.running_mean var = bn_module.running_var gamma", "code .. code-block:: x = x + 1 x = 2 + x", "def fold_convm_bn(self, conv: Expr, bn: Expr): mnode, inp_node = conv.inputs[:2] self_node = mnode.expr.inputs[0]", "( (bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps)) | bn_pat_0 ) matcher = PatternMatcher() if", "expr: Expr): if is_call_function(expr, F.neg): return -1 if len(expr.inputs) == 2: value =", "or implied. import operator from collections import defaultdict from typing import Any, Callable,", "gamma, beta, mean, var, eps) named_args[\"weight\"] = weight named_args[\"bias\"] = bias graph =", "name=conv_module.name, ) new_conv.weight = Parameter(weight) new_conv.bias = Parameter(bias) new_conv.training = conv_module.training assign_attr(new_conv, self_node.owner,", "fold_convf_bn(self, conv: Expr, bn: Expr): named_args = conv.named_args weight = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias", "graph = conv.top_graph if len(mnode.users) > 1: self.used_name[mnode.qualname] += 1 attr_name = \"{}_{}\".format(attr_name,", "get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def fold_convf_bn(self, conv:", "# \"AS IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express", "func in zip([operator.add, F.pow], [self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op, op)] = func for op_0 in", "0 and op_t in [operator.add] ): graph.replace_node({expr.outputs[0]: inp_node}) graph.compile() return expr with expr.top_graph.insert_exprs():", "any_node, is_const, is_op, is_var from .utils import get_const_value, register_obj logger = get_logger(__name__) @register_pass(\"FuseAddMul\")", "into conv2d.\"\"\" name = \"FuseConvBn\" required_pass = [\"AttrToConstant\"] run_once = True def __init__(self):", "= conv.named_args weight = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean, var, gamma,", "else: bn_module = bn.inputs[0].owner mean = bn_module.running_mean var = bn_module.running_var gamma = bn_module.weight", "in [operator.add, operator.mul]: op_0 = is_op(op_0) if op_1 not in [operator.add, operator.mul]: op_1", "bn_pat_1 = is_op(F.batch_norm) # inp, running_mean, running_var, weight, bias bn_inps = ( conv_pat_0", "self.get_const_value(expr.inputs[0].expr) if isinstance(const_1, Tensor) and const_1._tuple_shape not in [(1,), tuple()]: return expr inp_node", "_make_pattern(op_0, op_1) -> ExprPattern: x = is_var().check_users(False) if op_0 not in [operator.add, operator.mul]:", "return -1 if len(expr.inputs) == 2: value = get_const_value(expr.inputs[1].expr, None) assert value is", "Expr): mnode, inp_node = conv.inputs[:2] self_node = mnode.expr.inputs[0] attr_name = conv.inputs[0].expr.name graph =", "if conv_pat_0 in matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else: return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def fold_convm_bn(self,", "self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) named_args[\"weight\"] =", "mean = get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"] ) var = get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma = get_const_value(named_args[\"weight\"],", "1 and op_t in [operator.pow, operator.mul]) or ( const == 0 and op_t", "is_call_function(bn): named_args = bn.named_args mean = get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"] ) var = get_const_value(named_args[\"running_var\"],", "op_t in [operator.pow, operator.mul]) or ( const == 0 and op_t in [operator.add]", "F.pow], [self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op, op)] = func for op_0 in [F.neg, operator.mul]: for", "CONDITIONS OF ANY KIND, either express or implied. import operator from collections import", "weight, bias bn_inps = ( conv_pat_0 | conv_pat_1, is_const(), is_const(), is_const(), is_const(), )", "bn: Expr): mnode, inp_node = conv.inputs[:2] self_node = mnode.expr.inputs[0] attr_name = conv.inputs[0].expr.name graph", "self.pattern_dict[_make_pattern(op_0, op_1)] = self.fold_mul def run_transform(self, expr: Expr): matcher = PatternMatcher() for pattern,", "is not None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name, ) new_conv.weight = Parameter(weight) new_conv.bias = Parameter(bias)", "code-block:: x = x + 1 x = 2 + x x =", "(c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable", "compute_mode=conv_module.compute_mode, name=conv_module.name, ) new_conv.weight = Parameter(weight) new_conv.bias = Parameter(bias) new_conv.training = conv_module.training assign_attr(new_conv,", "expr.top_graph if (const == 1 and op_t in [operator.pow, operator.mul]) or ( const", "graph.compile() return out_node.expr def fold_add(self, expr: Expr): return self._fold_helper(expr, operator.add, operator.add) def fold_mul(self,", "= ( conv_pat_0 | conv_pat_1, is_const(), is_const(), is_const(), is_const(), ) bn_pat = (", "Expr): if is_call_function(expr, F.neg): return -1 if len(expr.inputs) == 2: value = get_const_value(expr.inputs[1].expr,", "<reponame>Olalaye/MegEngine # MegEngine is Licensed under the Apache License, Version 2.0 (the \"License\")", "Tensor from ...utils.bn_fusion import fold_weight_bias from ..expr import Expr, is_call_function from ..utils import", "self.used_name[mnode.qualname] += 1 attr_name = \"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning( \"{} is used {} times", "...logger import get_logger from ...tensor import Parameter, Tensor from ...utils.bn_fusion import fold_weight_bias from", "[(1,), tuple()]: return expr inp_node = expr.inputs[0].expr.inputs[0] const = op_c(const_0, const_1) graph =", "named_args[\"eps\"] return mean, var, gamma, beta, eps else: bn_module = bn.inputs[0].owner mean =", "| (bn_pat_1(*bn_inps)) | bn_pat_0 ) matcher = PatternMatcher() if not matcher.match(bn_pat, expr): return", "# # Unless required by applicable law or agreed to in writing, #", "conv_module.bias mean, var, gamma, beta, eps = self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias,", "r\"\"\"Fuse BN layers into conv2d.\"\"\" name = \"FuseConvBn\" required_pass = [\"AttrToConstant\"] run_once =", "run_once = False def __init__(self,): super().__init__() def _make_pattern(op_0, op_1) -> ExprPattern: x =", "operator.mul]: for op_1 in [F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)] = self.fold_mul def run_transform(self, expr:", "...utils.bn_fusion import fold_weight_bias from ..expr import Expr, is_call_function from ..utils import assign_attr, get_subattr", "PatternMatcher() for pattern, func in self.pattern_dict.items(): res = matcher.match(pattern, expr) if res: break", "mnode.qualname, len(mnode.users), graph.qualname, attr_name ) ) conv_module = mnode.owner weight, bias = conv_module.weight,", "None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name, ) new_conv.weight = Parameter(weight) new_conv.bias = Parameter(bias) new_conv.training =", "mean, var, gamma, beta, eps else: bn_module = bn.inputs[0].owner mean = bn_module.running_mean var", ") var = get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta = get_const_value(named_args[\"bias\"], named_args[\"bias\"])", "const) graph.replace_node({expr.outputs[0]: out_node}) graph.compile() return out_node.expr def fold_add(self, expr: Expr): return self._fold_helper(expr, operator.add,", "import fold_weight_bias from ..expr import Expr, is_call_function from ..utils import assign_attr, get_subattr from", "self.pattern_dict.items(): res = matcher.match(pattern, expr) if res: break if not res: return expr", "named_args = conv.named_args weight = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean, var,", "get_logger from ...tensor import Parameter, Tensor from ...utils.bn_fusion import fold_weight_bias from ..expr import", "F.neg): return -1 if len(expr.inputs) == 2: value = get_const_value(expr.inputs[1].expr, None) assert value", "out_node.name = conv.outputs[0].name return out_node.expr def get_bn_params(self, bn: Expr): if is_call_function(bn): named_args =", "For example, the following code .. code-block:: x = x + 1 x", "out_node.expr def fold_add(self, expr: Expr): return self._fold_helper(expr, operator.add, operator.add) def fold_mul(self, expr): return", "= PatternMatcher() if not matcher.match(bn_pat, expr): return expr matched_exprs = matcher.matched_exprs if conv_pat_0", "support more shape if isinstance(const_0, Tensor) and const_0._tuple_shape not in [(1,), tuple()]: return", "expr inp_node = expr.inputs[0].expr.inputs[0] const = op_c(const_0, const_1) graph = expr.top_graph if (const", "in [operator.pow, operator.mul]) or ( const == 0 and op_t in [operator.add] ):", "= conv.outputs[0].name return out_node.expr def get_bn_params(self, bn: Expr): if is_call_function(bn): named_args = bn.named_args", "gamma = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps = named_args[\"eps\"] return mean,", "with graph.insert_exprs(): out_node = F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr", "conv.outputs[0].name return out_node.expr def fold_convf_bn(self, conv: Expr, bn: Expr): named_args = conv.named_args weight", "if is_call_function(bn): named_args = bn.named_args mean = get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"] ) var =", "[operator.add, operator.mul]: op_1 = is_op(op_1) pattern = op_0(x, is_const()) | op_0(x, \"*\") pattern", "= F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def get_bn_params(self, bn:", "operator.mul]: op_1 = is_op(op_1) pattern = op_0(x, is_const()) | op_0(x, \"*\") pattern =", "[operator.pow, operator.mul]) or ( const == 0 and op_t in [operator.add] ): graph.replace_node({expr.outputs[0]:", "def __init__(self,): super().__init__() def _make_pattern(op_0, op_1) -> ExprPattern: x = is_var().check_users(False) if op_0", "Expr, op_c: Callable, op_t: Callable): const_0 = self.get_const_value(expr) # todo: support more shape", ".pass_base import BackwardPass, register_pass from .pattern import ExprPattern, any_node, is_const, is_op, is_var from", "with graph.insert_exprs(mnode.expr): out_node = get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return", "get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps = named_args[\"eps\"] return mean, var, gamma,", "expr): return self._fold_helper(expr, operator.mul, operator.mul) def fold_pow(self, expr): return self._fold_helper(expr, operator.mul, F.pow) def", "2.0 (the \"License\") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.", "following code .. code-block:: x = x + 1 x = 2 +", "is_const, is_op, is_var from .utils import get_const_value, register_obj logger = get_logger(__name__) @register_pass(\"FuseAddMul\") class", "const_1 = self.get_const_value(expr.inputs[0].expr) if isinstance(const_1, Tensor) and const_1._tuple_shape not in [(1,), tuple()]: return", "\"License\") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # #", "matcher.matched_exprs if conv_pat_0 in matched_exprs: return self.fold_convm_bn(matched_exprs[conv_pat_0], matched_exprs[bn_pat]) else: return self.fold_convf_bn(matched_exprs[conv_pat_1], matched_exprs[bn_pat]) def", "var, eps) new_conv = M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias", "= is_op(F.batch_norm) # inp, running_mean, running_var, weight, bias bn_inps = ( conv_pat_0 |", "mnode.owner weight, bias = conv_module.weight, conv_module.bias mean, var, gamma, beta, eps = self.get_bn_params(bn)", "return out_node.expr def fold_convf_bn(self, conv: Expr, bn: Expr): named_args = conv.named_args weight =", "get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean, var, gamma, beta, eps = self.get_bn_params(bn)", "conv.top_graph if len(mnode.users) > 1: self.used_name[mnode.qualname] += 1 attr_name = \"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning(", "pattern, func in self.pattern_dict.items(): res = matcher.match(pattern, expr) if res: break if not", "named_args[\"weight\"]) bias = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean, var, gamma, beta, eps = self.get_bn_params(bn) weight,", "new_conv.bias = Parameter(bias) new_conv.training = conv_module.training assign_attr(new_conv, self_node.owner, attr_name) with graph.insert_exprs(mnode.expr): out_node =", "name = \"FuseAddMul\" required_pass = [\"NormElemWise\"] run_once = False def __init__(self,): super().__init__() def", "import PatternMatcher from .pass_base import BackwardPass, register_pass from .pattern import ExprPattern, any_node, is_const,", "IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "Version 2.0 (the \"License\") # # Copyright (c) 2014-2021 Megvii Inc. All rights", "typing import Any, Callable, List from ... import functional as F from ...", "bn: Expr): if is_call_function(bn): named_args = bn.named_args mean = get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"] )", "new_conv.weight = Parameter(weight) new_conv.bias = Parameter(bias) new_conv.training = conv_module.training assign_attr(new_conv, self_node.owner, attr_name) with", "run_once = True def __init__(self): super().__init__() self.used_name = defaultdict(int) def run_transform(self, expr: Expr):", "changed to .. code-block:: x = x + 3 \"\"\" name = \"FuseAddMul\"", "from .pattern import ExprPattern, any_node, is_const, is_op, is_var from .utils import get_const_value, register_obj", "is_var from .utils import get_const_value, register_obj logger = get_logger(__name__) @register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass): \"\"\"Fold", "conv: Expr, bn: Expr): named_args = conv.named_args weight = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias =", "expr) if res: break if not res: return expr return func(expr) def _fold_helper(self,", "x + 3 \"\"\" name = \"FuseAddMul\" required_pass = [\"NormElemWise\"] run_once = False", "conv.top_graph with graph.insert_exprs(): out_node = F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return", "or ( const == 0 and op_t in [operator.add] ): graph.replace_node({expr.outputs[0]: inp_node}) graph.compile()", "= get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def fold_convf_bn(self,", "-> ExprPattern: x = is_var().check_users(False) if op_0 not in [operator.add, operator.mul]: op_0 =", "weight, bias = conv_module.weight, conv_module.bias mean, var, gamma, beta, eps = self.get_bn_params(bn) weight,", "graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def get_bn_params(self, bn: Expr): if is_call_function(bn): named_args", "False def __init__(self,): super().__init__() def _make_pattern(op_0, op_1) -> ExprPattern: x = is_var().check_users(False) if", "op_t in [operator.add] ): graph.replace_node({expr.outputs[0]: inp_node}) graph.compile() return expr with expr.top_graph.insert_exprs(): out_node =", "bn_module = bn.inputs[0].owner mean = bn_module.running_mean var = bn_module.running_var gamma = bn_module.weight beta", "= mnode.expr.inputs[0] attr_name = conv.inputs[0].expr.name graph = conv.top_graph if len(mnode.users) > 1: self.used_name[mnode.qualname]", "self.fold_pow],): self.pattern_dict[_make_pattern(op, op)] = func for op_0 in [F.neg, operator.mul]: for op_1 in", "def _make_pattern(op_0, op_1) -> ExprPattern: x = is_var().check_users(False) if op_0 not in [operator.add,", "OF ANY KIND, either express or implied. import operator from collections import defaultdict", "expr: Expr): return self._fold_helper(expr, operator.add, operator.add) def fold_mul(self, expr): return self._fold_helper(expr, operator.mul, operator.mul)", "get_const_value(expr.inputs[1].expr, None) assert value is not None, \" \" return value value =", "from typing import Any, Callable, List from ... import functional as F from", "func in self.pattern_dict.items(): res = matcher.match(pattern, expr) if res: break if not res:", "get_logger(__name__) @register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass): \"\"\"Fold adjacent const add or mul binary operations. For", "= op_c(const_0, const_1) graph = expr.top_graph if (const == 1 and op_t in", "gamma, beta, mean, var, eps) new_conv = M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding,", "@register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass): \"\"\"Fold adjacent const add or mul binary operations. For example,", "= get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean, var, gamma, beta, eps = self.get_bn_params(bn) weight, bias =", "fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) named_args[\"weight\"] = weight named_args[\"bias\"] = bias", "is distributed on an # \"AS IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF", "not in [operator.add, operator.mul]: op_0 = is_op(op_0) if op_1 not in [operator.add, operator.mul]:", "1 attr_name = \"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning( \"{} is used {} times and its", "None) assert value is not None, \" \" return value value = expr.const_val[0][-1]", "writing, # software distributed under the License is distributed on an # \"AS", "F.pow) def get_const_value(self, expr: Expr): if is_call_function(expr, F.neg): return -1 if len(expr.inputs) ==", "register_obj logger = get_logger(__name__) @register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass): \"\"\"Fold adjacent const add or mul", "from ...utils.bn_fusion import fold_weight_bias from ..expr import Expr, is_call_function from ..utils import assign_attr,", "from .utils import get_const_value, register_obj logger = get_logger(__name__) @register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass): \"\"\"Fold adjacent", "res: break if not res: return expr return func(expr) def _fold_helper(self, expr: Expr,", "self.used_name[mnode.qualname]) logger.warning( \"{} is used {} times and its name will be reset", "WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import operator", "ExprPattern: x = is_var().check_users(False) if op_0 not in [operator.add, operator.mul]: op_0 = is_op(op_0)", "= conv_module.weight, conv_module.bias mean, var, gamma, beta, eps = self.get_bn_params(bn) weight, bias =", "if isinstance(const_0, Tensor) and const_0._tuple_shape not in [(1,), tuple()]: return expr const_1 =", "get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean, var, gamma, beta, eps = self.get_bn_params(bn) weight, bias = fold_weight_bias(weight,", "from .pass_base import BackwardPass, register_pass from .pattern import ExprPattern, any_node, is_const, is_op, is_var", "isinstance(const_0, Tensor) and const_0._tuple_shape not in [(1,), tuple()]: return expr const_1 = self.get_const_value(expr.inputs[0].expr)", "be reset to {}.{}\".format( mnode.qualname, len(mnode.users), graph.qualname, attr_name ) ) conv_module = mnode.owner", "tuple()]: return expr const_1 = self.get_const_value(expr.inputs[0].expr) if isinstance(const_1, Tensor) and const_1._tuple_shape not in", "implied. import operator from collections import defaultdict from typing import Any, Callable, List", "= bn_module.running_mean var = bn_module.running_var gamma = bn_module.weight beta = bn_module.bias eps =", "will be reset to {}.{}\".format( mnode.qualname, len(mnode.users), graph.qualname, attr_name ) ) conv_module =", "in [(1,), tuple()]: return expr inp_node = expr.inputs[0].expr.inputs[0] const = op_c(const_0, const_1) graph", "x = x + 3 \"\"\" name = \"FuseAddMul\" required_pass = [\"NormElemWise\"] run_once", "if (const == 1 and op_t in [operator.pow, operator.mul]) or ( const ==", "\"AS IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or", "import Parameter, Tensor from ...utils.bn_fusion import fold_weight_bias from ..expr import Expr, is_call_function from", "in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias is not None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode,", "bias = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean, var, gamma, beta, eps = self.get_bn_params(bn) weight, bias", "assign_attr(new_conv, self_node.owner, attr_name) with graph.insert_exprs(mnode.expr): out_node = get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name", "mean = bn_module.running_mean var = bn_module.running_var gamma = bn_module.weight beta = bn_module.bias eps", "mul binary operations. For example, the following code .. code-block:: x = x", "= expr.const_val[0][-1] return value @register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass): r\"\"\"Fuse BN layers into conv2d.\"\"\" name", "Licensed under the Apache License, Version 2.0 (the \"License\") # # Copyright (c)", "in [operator.add, operator.mul]: op_1 = is_op(op_1) pattern = op_0(x, is_const()) | op_0(x, \"*\")", "bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1) bn_pat_1 = is_op(F.batch_norm) # inp, running_mean, running_var, weight,", "conv.inputs[0].expr.name graph = conv.top_graph if len(mnode.users) > 1: self.used_name[mnode.qualname] += 1 attr_name =", "named_args[\"bias\"]) eps = named_args[\"eps\"] return mean, var, gamma, beta, eps else: bn_module =", "= weight named_args[\"bias\"] = bias graph = conv.top_graph with graph.insert_exprs(): out_node = F.conv2d(**named_args)", "x = is_var().check_users(False) if op_0 not in [operator.add, operator.mul]: op_0 = is_op(op_0) if", "conv_module.training assign_attr(new_conv, self_node.owner, attr_name) with graph.insert_exprs(mnode.expr): out_node = get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node}) graph.compile()", "is_const(), is_const(), is_const(), ) bn_pat = ( (bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps)) |", "return pattern self.pattern_dict = {} for op, func in zip([operator.add, F.pow], [self.fold_add, self.fold_pow],):", "(bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps)) | bn_pat_0 ) matcher = PatternMatcher() if not matcher.match(bn_pat, expr):", "from .matcher import PatternMatcher from .pass_base import BackwardPass, register_pass from .pattern import ExprPattern,", "= conv.top_graph if len(mnode.users) > 1: self.used_name[mnode.qualname] += 1 attr_name = \"{}_{}\".format(attr_name, self.used_name[mnode.qualname])", "= M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias is not None,", "the following code .. code-block:: x = x + 1 x = 2", "required_pass = [\"NormElemWise\"] run_once = False def __init__(self,): super().__init__() def _make_pattern(op_0, op_1) ->", "dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias is not None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name, ) new_conv.weight = Parameter(weight)", "Inc. All rights reserved. # # Unless required by applicable law or agreed", "...tensor import Parameter, Tensor from ...utils.bn_fusion import fold_weight_bias from ..expr import Expr, is_call_function", "= is_op(F.conv2d) bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1) bn_pat_1 = is_op(F.batch_norm) # inp, running_mean,", "[self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op, op)] = func for op_0 in [F.neg, operator.mul]: for op_1", "ExprPattern, any_node, is_const, is_op, is_var from .utils import get_const_value, register_obj logger = get_logger(__name__)", "operator.add, operator.add) def fold_mul(self, expr): return self._fold_helper(expr, operator.mul, operator.mul) def fold_pow(self, expr): return", "is_const(), is_const(), is_const(), is_const(), ) bn_pat = ( (bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps))", "defaultdict from typing import Any, Callable, List from ... import functional as F", "= mnode.owner weight, bias = conv_module.weight, conv_module.bias mean, var, gamma, beta, eps =", "== 1 and op_t in [operator.pow, operator.mul]) or ( const == 0 and", "attr_name = \"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning( \"{} is used {} times and its name", "x = 2 + x x = x * 4 x = x", "its name will be reset to {}.{}\".format( mnode.qualname, len(mnode.users), graph.qualname, attr_name ) )", ") bn_pat = ( (bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps)) | bn_pat_0 ) matcher", "= get_logger(__name__) @register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass): \"\"\"Fold adjacent const add or mul binary operations.", "= expr.top_graph if (const == 1 and op_t in [operator.pow, operator.mul]) or (", ") ) conv_module = mnode.owner weight, bias = conv_module.weight, conv_module.bias mean, var, gamma,", "logger = get_logger(__name__) @register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass): \"\"\"Fold adjacent const add or mul binary", "in self.pattern_dict.items(): res = matcher.match(pattern, expr) if res: break if not res: return", "fold_weight_bias from ..expr import Expr, is_call_function from ..utils import assign_attr, get_subattr from .matcher", "module as M from ...logger import get_logger from ...tensor import Parameter, Tensor from", "op_1 in [F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)] = self.fold_mul def run_transform(self, expr: Expr): matcher", ") matcher = PatternMatcher() if not matcher.match(bn_pat, expr): return expr matched_exprs = matcher.matched_exprs", "on an # \"AS IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND,", "= named_args[\"eps\"] return mean, var, gamma, beta, eps else: bn_module = bn.inputs[0].owner mean", "( conv_pat_0 | conv_pat_1, is_const(), is_const(), is_const(), is_const(), ) bn_pat = ( (bn_pat_1(*bn_inps[:3]))", "Callable, List from ... import functional as F from ... import module as", "is_op(op_1) pattern = op_0(x, is_const()) | op_0(x, \"*\") pattern = op_1(pattern, is_const()) |", "= op_t(inp_node, const) graph.replace_node({expr.outputs[0]: out_node}) graph.compile() return out_node.expr def fold_add(self, expr: Expr): return", "| conv_pat_1) bn_pat_1 = is_op(F.batch_norm) # inp, running_mean, running_var, weight, bias bn_inps =", "self._fold_helper(expr, operator.add, operator.add) def fold_mul(self, expr): return self._fold_helper(expr, operator.mul, operator.mul) def fold_pow(self, expr):", "out_node.expr def fold_convf_bn(self, conv: Expr, bn: Expr): named_args = conv.named_args weight = get_const_value(named_args[\"weight\"],", "law or agreed to in writing, # software distributed under the License is", "Apache License, Version 2.0 (the \"License\") # # Copyright (c) 2014-2021 Megvii Inc.", "BN layers into conv2d.\"\"\" name = \"FuseConvBn\" required_pass = [\"AttrToConstant\"] run_once = True", "from ... import module as M from ...logger import get_logger from ...tensor import", "conv_module = mnode.owner weight, bias = conv_module.weight, conv_module.bias mean, var, gamma, beta, eps", "get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"] ) var = get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta", "# software distributed under the License is distributed on an # \"AS IS\"", "is_op(F.conv2d) bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1) bn_pat_1 = is_op(F.batch_norm) # inp, running_mean, running_var,", "get_subattr from .matcher import PatternMatcher from .pass_base import BackwardPass, register_pass from .pattern import", "and const_1._tuple_shape not in [(1,), tuple()]: return expr inp_node = expr.inputs[0].expr.inputs[0] const =", ") conv_module = mnode.owner weight, bias = conv_module.weight, conv_module.bias mean, var, gamma, beta,", "\"{} is used {} times and its name will be reset to {}.{}\".format(", "get_const_value, register_obj logger = get_logger(__name__) @register_pass(\"FuseAddMul\") class FuseAddMul(BackwardPass): \"\"\"Fold adjacent const add or", "if is_call_function(expr, F.neg): return -1 if len(expr.inputs) == 2: value = get_const_value(expr.inputs[1].expr, None)", "out_node = get_subattr(self_node, attr_name)(inp_node) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def", "expr.top_graph.insert_exprs(): out_node = op_t(inp_node, const) graph.replace_node({expr.outputs[0]: out_node}) graph.compile() return out_node.expr def fold_add(self, expr:", "code-block:: x = x + 3 \"\"\" name = \"FuseAddMul\" required_pass = [\"NormElemWise\"]", "= self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias, gamma, beta, mean, var, eps) named_args[\"weight\"]", "Parameter(bias) new_conv.training = conv_module.training assign_attr(new_conv, self_node.owner, attr_name) with graph.insert_exprs(mnode.expr): out_node = get_subattr(self_node, attr_name)(inp_node)", "graph = conv.top_graph with graph.insert_exprs(): out_node = F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name =", "... import functional as F from ... import module as M from ...logger", "is_call_function from ..utils import assign_attr, get_subattr from .matcher import PatternMatcher from .pass_base import", "will be changed to .. code-block:: x = x + 3 \"\"\" name", "\"FuseConvBn\" required_pass = [\"AttrToConstant\"] run_once = True def __init__(self): super().__init__() self.used_name = defaultdict(int)", "bn.named_args mean = get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"] ) var = get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma =", "and op_t in [operator.pow, operator.mul]) or ( const == 0 and op_t in", "not in [(1,), tuple()]: return expr inp_node = expr.inputs[0].expr.inputs[0] const = op_c(const_0, const_1)", "# Unless required by applicable law or agreed to in writing, # software", "in [operator.add] ): graph.replace_node({expr.outputs[0]: inp_node}) graph.compile() return expr with expr.top_graph.insert_exprs(): out_node = op_t(inp_node,", "or mul binary operations. For example, the following code .. code-block:: x =", "op_c: Callable, op_t: Callable): const_0 = self.get_const_value(expr) # todo: support more shape if", "is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1) bn_pat_1 = is_op(F.batch_norm) # inp, running_mean, running_var, weight, bias bn_inps", "functional as F from ... import module as M from ...logger import get_logger", "named_args[\"bias\"]) mean, var, gamma, beta, eps = self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias,", "import functional as F from ... import module as M from ...logger import", "from ..utils import assign_attr, get_subattr from .matcher import PatternMatcher from .pass_base import BackwardPass,", "to in writing, # software distributed under the License is distributed on an", "def run_transform(self, expr: Expr): matcher = PatternMatcher() for pattern, func in self.pattern_dict.items(): res", "License, Version 2.0 (the \"License\") # # Copyright (c) 2014-2021 Megvii Inc. All", "be changed to .. code-block:: x = x + 3 \"\"\" name =", "2: value = get_const_value(expr.inputs[1].expr, None) assert value is not None, \" \" return", "\" \" return value value = expr.const_val[0][-1] return value @register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass): r\"\"\"Fuse", "agreed to in writing, # software distributed under the License is distributed on", "= x + 1 x = 2 + x x = x *", "= is_op(M.Conv2d) conv_pat_1 = is_op(F.conv2d) bn_pat_0 = is_op(M.BatchNorm2d)(conv_pat_0 | conv_pat_1) bn_pat_1 = is_op(F.batch_norm)", "out_node.name = conv.outputs[0].name return out_node.expr def fold_convf_bn(self, conv: Expr, bn: Expr): named_args =", "import operator from collections import defaultdict from typing import Any, Callable, List from", "Parameter, Tensor from ...utils.bn_fusion import fold_weight_bias from ..expr import Expr, is_call_function from ..utils", "M.Conv2d( in_channels=conv_module.in_channels, out_channels=conv_module.out_channels, kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias is not None, conv_mode=conv_module.conv_mode,", "is_op(F.batch_norm) # inp, running_mean, running_var, weight, bias bn_inps = ( conv_pat_0 | conv_pat_1,", "inp_node}) graph.compile() return expr with expr.top_graph.insert_exprs(): out_node = op_t(inp_node, const) graph.replace_node({expr.outputs[0]: out_node}) graph.compile()", "rights reserved. # # Unless required by applicable law or agreed to in", "inp_node = expr.inputs[0].expr.inputs[0] const = op_c(const_0, const_1) graph = expr.top_graph if (const ==", "MegEngine is Licensed under the Apache License, Version 2.0 (the \"License\") # #", "assert value is not None, \" \" return value value = expr.const_val[0][-1] return", "* 4 x = x * 0.25 will be changed to .. code-block::", "op_1(pattern, is_const()) | op_1(pattern, \"*\") return pattern self.pattern_dict = {} for op, func", "var, gamma, beta, eps else: bn_module = bn.inputs[0].owner mean = bn_module.running_mean var =", "def fold_add(self, expr: Expr): return self._fold_helper(expr, operator.add, operator.add) def fold_mul(self, expr): return self._fold_helper(expr,", "return value value = expr.const_val[0][-1] return value @register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass): r\"\"\"Fuse BN layers", "= \"FuseConvBn\" required_pass = [\"AttrToConstant\"] run_once = True def __init__(self): super().__init__() self.used_name =", "attr_name = conv.inputs[0].expr.name graph = conv.top_graph if len(mnode.users) > 1: self.used_name[mnode.qualname] += 1", "kernel_size=conv_module.kernel_size, stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias is not None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name, )", "+ 3 \"\"\" name = \"FuseAddMul\" required_pass = [\"NormElemWise\"] run_once = False def", "return value @register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass): r\"\"\"Fuse BN layers into conv2d.\"\"\" name = \"FuseConvBn\"", "= conv.inputs[:2] self_node = mnode.expr.inputs[0] attr_name = conv.inputs[0].expr.name graph = conv.top_graph if len(mnode.users)", "out_node.expr def get_bn_params(self, bn: Expr): if is_call_function(bn): named_args = bn.named_args mean = get_const_value(", "var = bn_module.running_var gamma = bn_module.weight beta = bn_module.bias eps = bn_module.eps return", "required_pass = [\"AttrToConstant\"] run_once = True def __init__(self): super().__init__() self.used_name = defaultdict(int) def", "op_0(x, \"*\") pattern = op_1(pattern, is_const()) | op_1(pattern, \"*\") return pattern self.pattern_dict =", "conv.outputs[0].name return out_node.expr def get_bn_params(self, bn: Expr): if is_call_function(bn): named_args = bn.named_args mean", "List from ... import functional as F from ... import module as M", "OR CONDITIONS OF ANY KIND, either express or implied. import operator from collections", "matcher = PatternMatcher() if not matcher.match(bn_pat, expr): return expr matched_exprs = matcher.matched_exprs if", "FuseConvBn(BackwardPass): r\"\"\"Fuse BN layers into conv2d.\"\"\" name = \"FuseConvBn\" required_pass = [\"AttrToConstant\"] run_once", "inp_node = conv.inputs[:2] self_node = mnode.expr.inputs[0] attr_name = conv.inputs[0].expr.name graph = conv.top_graph if", "+ 1 x = 2 + x x = x * 4 x", "conv.named_args weight = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean, var, gamma, beta,", "expr.const_val[0][-1] return value @register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass): r\"\"\"Fuse BN layers into conv2d.\"\"\" name =", "named_args[\"weight\"] = weight named_args[\"bias\"] = bias graph = conv.top_graph with graph.insert_exprs(): out_node =", "FuseAddMul(BackwardPass): \"\"\"Fold adjacent const add or mul binary operations. For example, the following", "bn.inputs[0].owner mean = bn_module.running_mean var = bn_module.running_var gamma = bn_module.weight beta = bn_module.bias", "to .. code-block:: x = x + 3 \"\"\" name = \"FuseAddMul\" required_pass", "len(mnode.users) > 1: self.used_name[mnode.qualname] += 1 attr_name = \"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning( \"{} is", "named_args = bn.named_args mean = get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"] ) var = get_const_value(named_args[\"running_var\"], named_args[\"running_var\"])", "times and its name will be reset to {}.{}\".format( mnode.qualname, len(mnode.users), graph.qualname, attr_name", "express or implied. import operator from collections import defaultdict from typing import Any,", "from ...tensor import Parameter, Tensor from ...utils.bn_fusion import fold_weight_bias from ..expr import Expr,", "PatternMatcher from .pass_base import BackwardPass, register_pass from .pattern import ExprPattern, any_node, is_const, is_op,", "= PatternMatcher() for pattern, func in self.pattern_dict.items(): res = matcher.match(pattern, expr) if res:", "named_args[\"running_mean\"], named_args[\"running_mean\"] ) var = get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta =", "padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias is not None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name, ) new_conv.weight =", "True def __init__(self): super().__init__() self.used_name = defaultdict(int) def run_transform(self, expr: Expr): conv_pat_0 =", "class FuseAddMul(BackwardPass): \"\"\"Fold adjacent const add or mul binary operations. For example, the", "operator.mul]) or ( const == 0 and op_t in [operator.add] ): graph.replace_node({expr.outputs[0]: inp_node})", "for pattern, func in self.pattern_dict.items(): res = matcher.match(pattern, expr) if res: break if", "import assign_attr, get_subattr from .matcher import PatternMatcher from .pass_base import BackwardPass, register_pass from", "graph.compile() return expr with expr.top_graph.insert_exprs(): out_node = op_t(inp_node, const) graph.replace_node({expr.outputs[0]: out_node}) graph.compile() return", "= op_0(x, is_const()) | op_0(x, \"*\") pattern = op_1(pattern, is_const()) | op_1(pattern, \"*\")", "len(expr.inputs) == 2: value = get_const_value(expr.inputs[1].expr, None) assert value is not None, \"", "bn_module.weight beta = bn_module.bias eps = bn_module.eps return mean, var, gamma, beta, eps", "with expr.top_graph.insert_exprs(): out_node = op_t(inp_node, const) graph.replace_node({expr.outputs[0]: out_node}) graph.compile() return out_node.expr def fold_add(self,", "return expr return func(expr) def _fold_helper(self, expr: Expr, op_c: Callable, op_t: Callable): const_0", "in writing, # software distributed under the License is distributed on an #", "= bn.named_args mean = get_const_value( named_args[\"running_mean\"], named_args[\"running_mean\"] ) var = get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma", "import module as M from ...logger import get_logger from ...tensor import Parameter, Tensor", "bn_pat_0 ) matcher = PatternMatcher() if not matcher.match(bn_pat, expr): return expr matched_exprs =", "eps = self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias, gamma, beta, mean, var, eps)", "Expr, bn: Expr): mnode, inp_node = conv.inputs[:2] self_node = mnode.expr.inputs[0] attr_name = conv.inputs[0].expr.name", "expr.inputs[0].expr.inputs[0] const = op_c(const_0, const_1) graph = expr.top_graph if (const == 1 and", "= conv.inputs[0].expr.name graph = conv.top_graph if len(mnode.users) > 1: self.used_name[mnode.qualname] += 1 attr_name", "mnode.expr.inputs[0] attr_name = conv.inputs[0].expr.name graph = conv.top_graph if len(mnode.users) > 1: self.used_name[mnode.qualname] +=", "out_node}) graph.compile() return out_node.expr def fold_add(self, expr: Expr): return self._fold_helper(expr, operator.add, operator.add) def", "return out_node.expr def get_bn_params(self, bn: Expr): if is_call_function(bn): named_args = bn.named_args mean =", "todo: support more shape if isinstance(const_0, Tensor) and const_0._tuple_shape not in [(1,), tuple()]:", "an # \"AS IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either", "value = expr.const_val[0][-1] return value @register_pass(\"FuseConvBn\") class FuseConvBn(BackwardPass): r\"\"\"Fuse BN layers into conv2d.\"\"\"", "= Parameter(weight) new_conv.bias = Parameter(bias) new_conv.training = conv_module.training assign_attr(new_conv, self_node.owner, attr_name) with graph.insert_exprs(mnode.expr):", "def __init__(self): super().__init__() self.used_name = defaultdict(int) def run_transform(self, expr: Expr): conv_pat_0 = is_op(M.Conv2d)", "more shape if isinstance(const_0, Tensor) and const_0._tuple_shape not in [(1,), tuple()]: return expr", "stride=conv_module.stride, padding=conv_module.padding, dilation=conv_module.dilation, groups=conv_module.groups, bias=conv_module.bias is not None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name, ) new_conv.weight", "# todo: support more shape if isinstance(const_0, Tensor) and const_0._tuple_shape not in [(1,),", "x x = x * 4 x = x * 0.25 will be", "= is_op(op_0) if op_1 not in [operator.add, operator.mul]: op_1 = is_op(op_1) pattern =", "2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law", "gamma, beta, eps = self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias, gamma, beta, mean,", "= get_const_value(named_args[\"weight\"], named_args[\"weight\"]) bias = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) mean, var, gamma, beta, eps =", "= get_const_value(expr.inputs[1].expr, None) assert value is not None, \" \" return value value", "{}.{}\".format( mnode.qualname, len(mnode.users), graph.qualname, attr_name ) ) conv_module = mnode.owner weight, bias =", "named_args[\"bias\"] = bias graph = conv.top_graph with graph.insert_exprs(): out_node = F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node})", "mean, var, eps) named_args[\"weight\"] = weight named_args[\"bias\"] = bias graph = conv.top_graph with", "super().__init__() def _make_pattern(op_0, op_1) -> ExprPattern: x = is_var().check_users(False) if op_0 not in", "F from ... import module as M from ...logger import get_logger from ...tensor", "not in [(1,), tuple()]: return expr const_1 = self.get_const_value(expr.inputs[0].expr) if isinstance(const_1, Tensor) and", "Megvii Inc. All rights reserved. # # Unless required by applicable law or", "= x * 0.25 will be changed to .. code-block:: x = x", "ANY KIND, either express or implied. import operator from collections import defaultdict from", "\"*\") return pattern self.pattern_dict = {} for op, func in zip([operator.add, F.pow], [self.fold_add,", "import get_logger from ...tensor import Parameter, Tensor from ...utils.bn_fusion import fold_weight_bias from ..expr", "not res: return expr return func(expr) def _fold_helper(self, expr: Expr, op_c: Callable, op_t:", "operator.add) def fold_mul(self, expr): return self._fold_helper(expr, operator.mul, operator.mul) def fold_pow(self, expr): return self._fold_helper(expr,", "# inp, running_mean, running_var, weight, bias bn_inps = ( conv_pat_0 | conv_pat_1, is_const(),", "conv: Expr, bn: Expr): mnode, inp_node = conv.inputs[:2] self_node = mnode.expr.inputs[0] attr_name =", "in zip([operator.add, F.pow], [self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op, op)] = func for op_0 in [F.neg,", "x * 0.25 will be changed to .. code-block:: x = x +", "= {} for op, func in zip([operator.add, F.pow], [self.fold_add, self.fold_pow],): self.pattern_dict[_make_pattern(op, op)] =", "required by applicable law or agreed to in writing, # software distributed under", "mean, var, gamma, beta, eps = self.get_bn_params(bn) weight, bias = fold_weight_bias(weight, bias, gamma,", "graph.compile() out_node.name = conv.outputs[0].name return out_node.expr def fold_convf_bn(self, conv: Expr, bn: Expr): named_args", "KIND, either express or implied. import operator from collections import defaultdict from typing", "= \"FuseAddMul\" required_pass = [\"NormElemWise\"] run_once = False def __init__(self,): super().__init__() def _make_pattern(op_0,", "func for op_0 in [F.neg, operator.mul]: for op_1 in [F.neg, operator.mul]: self.pattern_dict[_make_pattern(op_0, op_1)]", "4 x = x * 0.25 will be changed to .. code-block:: x", "reserved. # # Unless required by applicable law or agreed to in writing,", "def fold_convf_bn(self, conv: Expr, bn: Expr): named_args = conv.named_args weight = get_const_value(named_args[\"weight\"], named_args[\"weight\"])", "gamma = bn_module.weight beta = bn_module.bias eps = bn_module.eps return mean, var, gamma,", "as F from ... import module as M from ...logger import get_logger from", "op_1) -> ExprPattern: x = is_var().check_users(False) if op_0 not in [operator.add, operator.mul]: op_0", "groups=conv_module.groups, bias=conv_module.bias is not None, conv_mode=conv_module.conv_mode, compute_mode=conv_module.compute_mode, name=conv_module.name, ) new_conv.weight = Parameter(weight) new_conv.bias", "by applicable law or agreed to in writing, # software distributed under the", "__init__(self): super().__init__() self.used_name = defaultdict(int) def run_transform(self, expr: Expr): conv_pat_0 = is_op(M.Conv2d) conv_pat_1", "is_const(), is_const(), ) bn_pat = ( (bn_pat_1(*bn_inps[:3])) | (bn_pat_1(*bn_inps[:4])) | (bn_pat_1(*bn_inps)) | bn_pat_0", "import BackwardPass, register_pass from .pattern import ExprPattern, any_node, is_const, is_op, is_var from .utils", "= x + 3 \"\"\" name = \"FuseAddMul\" required_pass = [\"NormElemWise\"] run_once =", "= expr.inputs[0].expr.inputs[0] const = op_c(const_0, const_1) graph = expr.top_graph if (const == 1", "Expr): return self._fold_helper(expr, operator.add, operator.add) def fold_mul(self, expr): return self._fold_helper(expr, operator.mul, operator.mul) def", "if len(mnode.users) > 1: self.used_name[mnode.qualname] += 1 attr_name = \"{}_{}\".format(attr_name, self.used_name[mnode.qualname]) logger.warning( \"{}", "applicable law or agreed to in writing, # software distributed under the License", "inp, running_mean, running_var, weight, bias bn_inps = ( conv_pat_0 | conv_pat_1, is_const(), is_const(),", "var = get_const_value(named_args[\"running_var\"], named_args[\"running_var\"]) gamma = get_const_value(named_args[\"weight\"], named_args[\"weight\"]) beta = get_const_value(named_args[\"bias\"], named_args[\"bias\"]) eps", "name = \"FuseConvBn\" required_pass = [\"AttrToConstant\"] run_once = True def __init__(self): super().__init__() self.used_name", "= conv.top_graph with graph.insert_exprs(): out_node = F.conv2d(**named_args) graph.replace_node({bn.outputs[0]: out_node}) graph.compile() out_node.name = conv.outputs[0].name", "gamma, beta, eps else: bn_module = bn.inputs[0].owner mean = bn_module.running_mean var = bn_module.running_var", "const_0 = self.get_const_value(expr) # todo: support more shape if isinstance(const_0, Tensor) and const_0._tuple_shape", "expr: Expr): matcher = PatternMatcher() for pattern, func in self.pattern_dict.items(): res = matcher.match(pattern,", "= matcher.match(pattern, expr) if res: break if not res: return expr return func(expr)", "return mean, var, gamma, beta, eps else: bn_module = bn.inputs[0].owner mean = bn_module.running_mean", "adjacent const add or mul binary operations. For example, the following code ..", "is_const()) | op_0(x, \"*\") pattern = op_1(pattern, is_const()) | op_1(pattern, \"*\") return pattern" ]
[ "= True for row in xrange (len (self.checks)): self.checks[row] = value # Implementation", "value = True for row in xrange (len (self.checks)): self.checks[row] = value #", "= log self.activity_name = activity_name @property def entries (self): return self.log.get_entries (self.activity_name) @property", "self.entries[row] if col == 0: return fmt (entry.start_time) elif col == 1: return", "= [ ## gtk.gdk.Color (*mpl_colors[i % n_color]) for i in xrange (n)] cm", "def on_iter_children (self, parent): return 0 # TODO: is this right? def on_iter_has_child", "= value # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns", "path): if self.n_rows: return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value", "n)[:3] for i in xrange (n)] self.alphas = [ int (.8 * 65535)", "elif index == 1: return str elif index == 2: return gtk.gdk.Pixbuf def", "def on_get_value (self, row, col): def fmt (t): return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format ( t.year,", "(self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 2 def on_get_column_type (self, index): return", "return (rowref,) def on_get_value (self, row, col): if len (self.log.timing_activities) == 0: return", "= gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16) color = self.colors[row] color_str =", "(self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3 def on_get_column_type (self, index): if", "/ n)[:3]) for i in xrange (n)] self.color_tuples = [ cm (i /", "(0.75, 0.0, 0.75), ## (0.75, 0.75, 0.0), ## (0.0, 0.0, 0.0), ## (0.0,", "== 0: return None activity = sorted (self.activities)[row] if col == 0: return", "gtk.gdk.Color (*cm (i / n)[:3]) for i in xrange (n)] self.color_tuples = [", "this right? def on_iter_has_child (self, rowref): return False def on_iter_n_children (self, rowref): if", "len (self.entries): return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self,", "color = self.colors[row] color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map (int, (color.red / 256, color.green", "Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 2", "else: return rowref + 1 def on_iter_children (self, parent): return 0 # TODO:", "self.activity_name = activity_name @property def entries (self): return self.log.get_entries (self.activity_name) @property def n_rows", "= self.colors[row] color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map (int, (color.red / 256, color.green /", "row, col): if len (self.log.timing_activities) == 0: return None activity = sorted (self.log.timing_activities)[row]", "## (0.0, 0.5, 0.0), ## (1.0, 0.0, 0.0), ## (0.0, 0.75, 0.75), ##", "= [ gtk.gdk.Color (*cm (i / n)[:3]) for i in xrange (n)] self.color_tuples", "pb.fill (int (color_str, 16)) return pb def on_iter_next (self, rowref): if rowref ==", "if len (self.log.timing_activities) == 0: return None activity = sorted (self.log.timing_activities)[row] if col", "in self.activities] n = len (self.activities) ##mpl_colors = [ ## (0.0, 0.0, 1.0),", "len (self.checks): value = False else: value = True for row in xrange", "*map (int, (color.red / 256, color.green / 256, color.blue / 256, self.alphas[row] /", "elif index == 2: return gtk.gdk.Pixbuf def on_get_iter (self, path): if self.n_rows: return", "def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3 def on_get_column_type (self,", "(self): return len (self.log.timing_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY", "= [ False for activity in self.activities] n = len (self.activities) ##mpl_colors =", "Activity's in a Log.\"\"\" def __init__ (self, activities): gtk.GenericTreeModel.__init__ (self) self.activities = sorted", "col == 0: return activity.name elif col == 1: return activity.unit else: return", "(self.entries): return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self, row,", "def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 1 def on_get_column_type (self,", "def on_get_column_type (self, index): if index == 0: return bool elif index ==", "on_get_column_type (self, index): return str def on_get_iter (self, path): if len (self.log.timing_activities): return", "def toggle_all (self): if np.sum (self.checks) == len (self.checks): value = False else:", "= int (path) self.checks[row] = not self.checks[row] def toggle_all (self): if np.sum (self.checks)", "if col == 0: return str (entry.date) elif col == 1: return str", "gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3 def on_get_column_type (self, index): return str def", "return str elif index == 2: return gtk.gdk.Pixbuf def on_get_iter (self, path): if", "in xrange (n)] self.alphas = [ int (.8 * 65535) for activity in", "len (self.log.timing_activities) == 0: return None activity = sorted (self.log.timing_activities)[row] if col ==", "(self.log.timing_activities) == 0: return None activity = sorted (self.log.timing_activities)[row] if col == 0:", "toggle def toggle (self, path): row = int (path) self.checks[row] = not self.checks[row]", "if index == 0: return bool elif index == 1: return str elif", "(color.red / 256, color.green / 256, color.blue / 256, self.alphas[row] / 256))) pb.fill", "{3:02d}:{4:02d}'.format ( t.year, t.month, t.day, t.hour, t.minute) if self.n_rows == 0: return None", "2: return str (entry.note) else: return None def on_iter_next (self, rowref): if rowref", "activities): gtk.GenericTreeModel.__init__ (self) self.activities = sorted (activities) self.checks = [ False for activity", "(self, row, col): if len (self.log.timing_activities) == 0: return None activity = sorted", "(self.activities) ##mpl_colors = [ ## (0.0, 0.0, 1.0), ## (0.0, 0.5, 0.0), ##", "0.0), ## (1.0, 0.0, 0.0), ## (0.0, 0.75, 0.75), ## (0.75, 0.0, 0.75),", "self.colors[row] color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map (int, (color.red / 256, color.green / 256,", "return None class TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingActivity's in a Log.\"\"\" def", "a Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log = log self.activity_name", "cm = plt.get_cmap ('rainbow') self.colors = [ gtk.gdk.Color (*cm (i / n)[:3]) for", "on_get_column_type (self, index): return str def on_get_iter (self, path): if len (self.log.counting_activities): return", "def on_iter_next (self, rowref): if rowref == self.n_rows - 1 or self.n_rows ==", "## (1.0, 0.0, 0.0), ## (0.0, 0.75, 0.75), ## (0.75, 0.0, 0.75), ##", "def on_get_path (self, rowref): return (rowref,) def on_get_value (self, row, col): if self.n_rows", "i in xrange (n)] cm = plt.get_cmap ('rainbow') self.colors = [ gtk.gdk.Color (*cm", "color.blue / 256, self.alphas[row] / 256))) pb.fill (int (color_str, 16)) return pb def", "return None activity = sorted (self.log.timing_activities)[row] if col == 0: return activity.name else:", "on_get_path (self, rowref): return (rowref,) def on_get_value (self, row, col): if len (self.log.counting_activities)", "(n)] self.color_tuples = [ cm (i / n)[:3] for i in xrange (n)]", "in xrange (len (self.checks)): self.checks[row] = value # Implementation of gtk.GenericTreeModel def on_get_flags", "on_get_iter (self, path): if self.n_rows: return path[0] def on_get_path (self, rowref): return (rowref,)", "0: return None activity = sorted (self.log.timing_activities)[row] if col == 0: return activity.name", "(rowref,) def on_get_value (self, row, col): if self.n_rows == 0: return None entry", "int (path) self.checks[row] = not self.checks[row] def toggle_all (self): if np.sum (self.checks) ==", "0.0, 0.75), ## (0.75, 0.75, 0.0), ## (0.0, 0.0, 0.0), ## (0.0, 0.0,", "def on_iter_has_child (self, rowref): return False def on_iter_n_children (self, rowref): if rowref: return", "TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingActivity's in a Log.\"\"\" def __init__ (self, log):", "return self.n_rows def on_iter_nth_child (self, parent, n): if parent: return None elif n", "(0.0, 0.0, 0.0), ## (0.0, 0.0, 1.0) ] ##n_color = len (mpl_colors) ##self.colors", "0: return str (entry.date) elif col == 1: return str (entry.n) elif col", "if np.sum (self.checks) == len (self.checks): value = False else: value = True", "'{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format ( t.year, t.month, t.day, t.hour, t.minute) if self.n_rows == 0: return", "log @property def n_rows (self): return len (self.log.timing_activities) # Implementation of gtk.GenericTreeModel def", "def on_get_column_type (self, index): return str def on_get_iter (self, path): if len (self.log.counting_activities):", "(self): return 3 def on_get_column_type (self, index): if index == 0: return bool", "if rowref: return 0 else: return self.n_rows def on_iter_nth_child (self, parent, n): if", "self.n_rows - 1 or self.n_rows == 0: return None else: return rowref +", "return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3 def on_get_column_type (self, index): if index", "256, self.alphas[row] / 256))) pb.fill (int (color_str, 16)) return pb def on_iter_next (self,", "(t): return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format ( t.year, t.month, t.day, t.hour, t.minute) if self.n_rows ==", "import numpy as np import matplotlib.pyplot as plt class CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel", "for activity in self.activities] @property def n_rows (self): return len (self.activities) # toggle", "return None class TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingEntry's in a Log.\"\"\" def", "1.0) ] ##n_color = len (mpl_colors) ##self.colors = [ ## gtk.gdk.Color (*mpl_colors[i %", "/ n)[:3] for i in xrange (n)] self.alphas = [ int (.8 *", "(self) self.log = log @property def n_rows (self): return len (self.log.counting_activities) # Implementation", "on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3 def on_get_column_type (self, index):", "65535) for activity in self.activities] @property def n_rows (self): return len (self.activities) #", "## (0.75, 0.0, 0.75), ## (0.75, 0.75, 0.0), ## (0.0, 0.0, 0.0), ##", "(self): return len (self.log.counting_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY", "n_color]) for i in xrange (n)] cm = plt.get_cmap ('rainbow') self.colors = [", "xrange (n)] cm = plt.get_cmap ('rainbow') self.colors = [ gtk.gdk.Color (*cm (i /", "0.75, 0.75), ## (0.75, 0.0, 0.75), ## (0.75, 0.75, 0.0), ## (0.0, 0.0,", "index): if index == 0: return bool elif index == 1: return str", "return len (self.log.timing_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def", "1 def on_iter_children (self, parent): return 0 # TODO: is this right? def", "== 1: return fmt (entry.end_time) elif col == 2: return str (entry.note) else:", "toggle_all (self): if np.sum (self.checks) == len (self.checks): value = False else: value", "(self, index): return str def on_get_iter (self, path): if len (self.entries): return path[0]", "activity = sorted (self.log.timing_activities)[row] if col == 0: return activity.name else: return None", "== 1: return str elif index == 2: return gtk.gdk.Pixbuf def on_get_iter (self,", "gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 1 def on_get_column_type (self, index): return str def", "0: return None entry = self.entries[row] if col == 0: return str (entry.date)", "0: return fmt (entry.start_time) elif col == 1: return fmt (entry.end_time) elif col", "if col == 0: return activity.name else: return None def on_iter_next (self, rowref):", "== 0: return None entry = self.entries[row] if col == 0: return str", "(self.log.timing_activities)[row] if col == 0: return activity.name else: return None def on_iter_next (self,", "len (self.activities) ##mpl_colors = [ ## (0.0, 0.0, 1.0), ## (0.0, 0.5, 0.0),", "== 3: return str (entry.note) else: return None def on_iter_next (self, rowref): if", "rowref): if rowref == self.n_rows - 1 or self.n_rows == 0: return None", "= len (mpl_colors) ##self.colors = [ ## gtk.gdk.Color (*mpl_colors[i % n_color]) for i", "None def on_iter_parent (self, child): return None class TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for", "(i / n)[:3]) for i in xrange (n)] self.color_tuples = [ cm (i", "rowref): return (rowref,) def on_get_value (self, row, col): if len (self.log.counting_activities) == 0:", "def on_get_iter (self, path): if len (self.entries): return path[0] def on_get_path (self, rowref):", "self.log.get_entries (self.activity_name) @property def n_rows (self): return len (self.entries) # Implementation of gtk.GenericTreeModel", "def on_get_n_columns (self): return 3 def on_get_column_type (self, index): return str def on_get_iter", "def entries (self): return self.log.get_entries (self.activity_name) @property def n_rows (self): return len (self.entries)", "rowref): return False def on_iter_n_children (self, rowref): if rowref: return 0 else: return", "[ False for activity in self.activities] n = len (self.activities) ##mpl_colors = [", "0: return None activity = sorted (self.activities)[row] if col == 0: return self.checks[row]", "(self, child): return None class TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingActivity's in a", "numpy as np import matplotlib.pyplot as plt class CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for", "self.alphas[row] / 256))) pb.fill (int (color_str, 16)) return pb def on_iter_next (self, rowref):", "return 0 # TODO: is this right? def on_iter_has_child (self, rowref): return False", "or self.n_rows == 0: return None else: return rowref + 1 def on_iter_children", "else: return None def on_iter_parent (self, child): return None class TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk", "t.month, t.day, t.hour, t.minute) if self.n_rows == 0: return None entry = self.entries[row]", "##self.colors = [ ## gtk.gdk.Color (*mpl_colors[i % n_color]) for i in xrange (n)]", "log): gtk.GenericTreeModel.__init__ (self) self.log = log @property def n_rows (self): return len (self.log.timing_activities)", "on_get_path (self, rowref): return (rowref,) def on_get_value (self, row, col): if self.n_rows ==", "plt.get_cmap ('rainbow') self.colors = [ gtk.gdk.Color (*cm (i / n)[:3]) for i in", "index == 0: return bool elif index == 1: return str elif index", "if self.n_rows: return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self,", "return len (self.entries) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def", "return None class CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingEntry's in a Log.\"\"\" def", "(self, row, col): if self.n_rows == 0: return None entry = self.entries[row] if", "np import matplotlib.pyplot as plt class CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingActivity's in", "return pb def on_iter_next (self, rowref): if rowref == self.n_rows - 1 or", "(0.0, 0.75, 0.75), ## (0.75, 0.0, 0.75), ## (0.75, 0.75, 0.0), ## (0.0,", "def n_rows (self): return len (self.activities) # toggle def toggle (self, path): row", "in xrange (n)] self.color_tuples = [ cm (i / n)[:3] for i in", "row, col): if self.n_rows == 0: return None activity = sorted (self.activities)[row] if", "== 0: return activity.name else: return None def on_iter_next (self, rowref): if rowref", "n else: return None def on_iter_parent (self, child): return None class ActivityDrawModel (gtk.GenericTreeModel):", "return self.checks[row] elif col == 1: return activity.name else: pb = gtk.gdk.Pixbuf (", "CountingEntry's in a Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log =", "str def on_get_iter (self, path): if len (self.entries): return path[0] def on_get_path (self,", "index): return str def on_get_iter (self, path): if len (self.log.counting_activities): return path[0] def", "on_get_n_columns (self): return 2 def on_get_column_type (self, index): return str def on_get_iter (self,", "in self.activities] @property def n_rows (self): return len (self.activities) # toggle def toggle", "(self.log.counting_activities) == 0: return None activity = sorted (self.log.counting_activities)[row] if col == 0:", "0: return None else: return rowref + 1 def on_iter_children (self, parent): return", "== 1: return activity.name else: pb = gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB, True, 8, 16,", "col == 0: return str (entry.date) elif col == 1: return str (entry.n)", "debug import * import numpy as np import matplotlib.pyplot as plt class CountingActivitiesModel", "return None activity = sorted (self.activities)[row] if col == 0: return self.checks[row] elif", "value = False else: value = True for row in xrange (len (self.checks)):", "(self.log.counting_activities): return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self, row,", "rowref): if rowref: return 0 else: return self.n_rows def on_iter_nth_child (self, parent, n):", "color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map (int, (color.red / 256, color.green / 256, color.blue", "TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingEntry's in a Log.\"\"\" def __init__ (self, log,", "# Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return", "## gtk.gdk.Color (*mpl_colors[i % n_color]) for i in xrange (n)] cm = plt.get_cmap", "False for activity in self.activities] n = len (self.activities) ##mpl_colors = [ ##", "log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log = log self.activity_name = activity_name @property def entries", "None activity = sorted (self.log.timing_activities)[row] if col == 0: return activity.name else: return", "row = int (path) self.checks[row] = not self.checks[row] def toggle_all (self): if np.sum", "1: return fmt (entry.end_time) elif col == 2: return str (entry.note) else: return", "for drawing Activity's in a Log.\"\"\" def __init__ (self, activities): gtk.GenericTreeModel.__init__ (self) self.activities", "self.activities] n = len (self.activities) ##mpl_colors = [ ## (0.0, 0.0, 1.0), ##", "def on_get_path (self, rowref): return (rowref,) def on_get_value (self, row, col): if len", "gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 1 def on_get_column_type", "1: return str elif index == 2: return gtk.gdk.Pixbuf def on_get_iter (self, path):", "(self, activities): gtk.GenericTreeModel.__init__ (self) self.activities = sorted (activities) self.checks = [ False for", "(entry.n) elif col == 2: return str (entry.error) elif col == 3: return", "256, color.blue / 256, self.alphas[row] / 256))) pb.fill (int (color_str, 16)) return pb", "(self, row, col): if len (self.log.counting_activities) == 0: return None activity = sorted", "def on_iter_parent (self, child): return None class CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingEntry's", "return str def on_get_iter (self, path): if len (self.log.counting_activities): return path[0] def on_get_path", "col == 1: return activity.name else: pb = gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB, True, 8,", "if col == 0: return fmt (entry.start_time) elif col == 1: return fmt", "import * import numpy as np import matplotlib.pyplot as plt class CountingActivitiesModel (gtk.GenericTreeModel):", "return bool elif index == 1: return str elif index == 2: return", "Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log = log @property def n_rows", "activity.name elif col == 1: return activity.unit else: return None def on_iter_next (self,", "\"\"\"Gtk TreeModel for drawing Activity's in a Log.\"\"\" def __init__ (self, activities): gtk.GenericTreeModel.__init__", "[ ## (0.0, 0.0, 1.0), ## (0.0, 0.5, 0.0), ## (1.0, 0.0, 0.0),", "rowref): return (rowref,) def on_get_value (self, row, col): if len (self.log.timing_activities) == 0:", "self.activities = sorted (activities) self.checks = [ False for activity in self.activities] n", "child): return None class TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingEntry's in a Log.\"\"\"", "= [ cm (i / n)[:3] for i in xrange (n)] self.alphas =", "n_rows (self): return len (self.activities) # toggle def toggle (self, path): row =", "def on_iter_parent (self, child): return None class TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingActivity's", "activity = sorted (self.activities)[row] if col == 0: return self.checks[row] elif col ==", "0.75), ## (0.75, 0.75, 0.0), ## (0.0, 0.0, 0.0), ## (0.0, 0.0, 1.0)", "on_get_n_columns (self): return 3 def on_get_column_type (self, index): if index == 0: return", "def on_get_value (self, row, col): if self.n_rows == 0: return None entry =", "* import numpy as np import matplotlib.pyplot as plt class CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk", "if rowref == self.n_rows - 1 or self.n_rows == 0: return None else:", "n_rows (self): return len (self.log.timing_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return", "## (0.75, 0.75, 0.0), ## (0.0, 0.0, 0.0), ## (0.0, 0.0, 1.0) ]", "def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log = log self.activity_name = activity_name", "None class ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for drawing Activity's in a Log.\"\"\" def", "return activity.name else: pb = gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16) color", "self.alphas = [ int (.8 * 65535) for activity in self.activities] @property def", "\"\"\"Gtk TreeModel for CountingActivity's in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self)", "is this right? def on_iter_has_child (self, rowref): return False def on_iter_n_children (self, rowref):", "(n)] self.alphas = [ int (.8 * 65535) for activity in self.activities] @property", "CountingActivity's in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log = log", "(self.activities)[row] if col == 0: return self.checks[row] elif col == 1: return activity.name", "n)[:3]) for i in xrange (n)] self.color_tuples = [ cm (i / n)[:3]", "if self.n_rows == 0: return None entry = self.entries[row] if col == 0:", "False else: value = True for row in xrange (len (self.checks)): self.checks[row] =", "(self, path): if len (self.log.timing_activities): return path[0] def on_get_path (self, rowref): return (rowref,)", "str (entry.n) elif col == 2: return str (entry.error) elif col == 3:", "(self, child): return None class CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingEntry's in a", "(self.checks)): self.checks[row] = value # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY", "return None def on_iter_next (self, rowref): if rowref == self.n_rows - 1 or", "(self, rowref): return (rowref,) def on_get_value (self, row, col): if len (self.log.counting_activities) ==", "__future__ import division import gtk from debug import * import numpy as np", "(*mpl_colors[i % n_color]) for i in xrange (n)] cm = plt.get_cmap ('rainbow') self.colors", "self.n_rows: return n else: return None def on_iter_parent (self, child): return None class", "return fmt (entry.end_time) elif col == 2: return str (entry.note) else: return None", "3: return str (entry.note) else: return None def on_iter_next (self, rowref): if rowref", "(n)] cm = plt.get_cmap ('rainbow') self.colors = [ gtk.gdk.Color (*cm (i / n)[:3])", "plt class CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingActivity's in a Log.\"\"\" def __init__", "None activity = sorted (self.log.counting_activities)[row] if col == 0: return activity.name elif col", "fmt (entry.start_time) elif col == 1: return fmt (entry.end_time) elif col == 2:", "0: return activity.name elif col == 1: return activity.unit else: return None def", "col == 0: return fmt (entry.start_time) elif col == 1: return fmt (entry.end_time)", "0: return bool elif index == 1: return str elif index == 2:", "(rowref,) def on_get_value (self, row, col): def fmt (t): return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format (", "def on_iter_parent (self, child): return None class ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for drawing", "return None class ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for drawing Activity's in a Log.\"\"\"", "for CountingEntry's in a Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log", "None class TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingEntry's in a Log.\"\"\" def __init__", "0.75), ## (0.75, 0.0, 0.75), ## (0.75, 0.75, 0.0), ## (0.0, 0.0, 0.0),", "in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log = log @property", "(self, path): if len (self.log.counting_activities): return path[0] def on_get_path (self, rowref): return (rowref,)", "self.n_rows def on_iter_nth_child (self, parent, n): if parent: return None elif n <", "self.log = log @property def n_rows (self): return len (self.log.timing_activities) # Implementation of", "for i in xrange (n)] self.alphas = [ int (.8 * 65535) for", "def __init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log = log @property def n_rows (self):", "col == 0: return activity.name else: return None def on_iter_next (self, rowref): if", "drawing Activity's in a Log.\"\"\" def __init__ (self, activities): gtk.GenericTreeModel.__init__ (self) self.activities =", "= self.entries[row] if col == 0: return fmt (entry.start_time) elif col == 1:", "return None entry = self.entries[row] if col == 0: return str (entry.date) elif", "(self): return 3 def on_get_column_type (self, index): return str def on_get_iter (self, path):", "None def on_iter_parent (self, child): return None class TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for", "len (self.activities) # toggle def toggle (self, path): row = int (path) self.checks[row]", "gtk.GenericTreeModel.__init__ (self) self.log = log self.activity_name = activity_name @property def entries (self): return", "# toggle def toggle (self, path): row = int (path) self.checks[row] = not", "path): if len (self.entries): return path[0] def on_get_path (self, rowref): return (rowref,) def", "= log @property def n_rows (self): return len (self.log.counting_activities) # Implementation of gtk.GenericTreeModel", "== 2: return gtk.gdk.Pixbuf def on_get_iter (self, path): if self.n_rows: return path[0] def", "(self.entries) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self):", "1 def on_get_column_type (self, index): return str def on_get_iter (self, path): if len", "return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 1 def on_get_column_type (self, index): return str", "(gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingEntry's in a Log.\"\"\" def __init__ (self, log, activity_name):", "(self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3 def on_get_column_type (self, index): return", "(self, child): return None class TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingEntry's in a", "def on_get_iter (self, path): if len (self.log.timing_activities): return path[0] def on_get_path (self, rowref):", "n = len (self.activities) ##mpl_colors = [ ## (0.0, 0.0, 1.0), ## (0.0,", "(gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingEntry's in a Log.\"\"\" def __init__ (self, log, activity_name):", "on_get_value (self, row, col): if len (self.log.counting_activities) == 0: return None activity =", "self.n_rows: return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self, row,", "xrange (n)] self.color_tuples = [ cm (i / n)[:3] for i in xrange", "sorted (self.log.timing_activities)[row] if col == 0: return activity.name else: return None def on_iter_next", "gtk from debug import * import numpy as np import matplotlib.pyplot as plt", "0.0, 0.0), ## (0.0, 0.75, 0.75), ## (0.75, 0.0, 0.75), ## (0.75, 0.75,", "def on_get_n_columns (self): return 2 def on_get_column_type (self, index): return str def on_get_iter", "(0.0, 0.5, 0.0), ## (1.0, 0.0, 0.0), ## (0.0, 0.75, 0.75), ## (0.75,", "row, col): if self.n_rows == 0: return None entry = self.entries[row] if col", "(gtk.GenericTreeModel): \"\"\"Gtk TreeModel for drawing Activity's in a Log.\"\"\" def __init__ (self, activities):", "child): return None class CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingEntry's in a Log.\"\"\"", "if len (self.log.timing_activities): return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value", "TreeModel for CountingEntry's in a Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self)", "return 3 def on_get_column_type (self, index): return str def on_get_iter (self, path): if", "(self.log.counting_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self):", "on_get_value (self, row, col): if self.n_rows == 0: return None entry = self.entries[row]", "not self.checks[row] def toggle_all (self): if np.sum (self.checks) == len (self.checks): value =", "entry = self.entries[row] if col == 0: return fmt (entry.start_time) elif col ==", "return None def on_iter_parent (self, child): return None class TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel", "col): if len (self.log.counting_activities) == 0: return None activity = sorted (self.log.counting_activities)[row] if", "= log @property def n_rows (self): return len (self.log.timing_activities) # Implementation of gtk.GenericTreeModel", "color.green / 256, color.blue / 256, self.alphas[row] / 256))) pb.fill (int (color_str, 16))", "for TimingEntry's in a Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log", "else: return None def on_iter_parent (self, child): return None class ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk", "= [ int (.8 * 65535) for activity in self.activities] @property def n_rows", "len (mpl_colors) ##self.colors = [ ## gtk.gdk.Color (*mpl_colors[i % n_color]) for i in", "1: return activity.unit else: return None def on_iter_next (self, rowref): if rowref ==", "as plt class CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingActivity's in a Log.\"\"\" def", "on_iter_next (self, rowref): if rowref == self.n_rows - 1 or self.n_rows == 0:", "def on_get_iter (self, path): if len (self.log.counting_activities): return path[0] def on_get_path (self, rowref):", "class ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for drawing Activity's in a Log.\"\"\" def __init__", "self.activities] @property def n_rows (self): return len (self.activities) # toggle def toggle (self,", "gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16) color = self.colors[row] color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format", "/ 256))) pb.fill (int (color_str, 16)) return pb def on_iter_next (self, rowref): if", "0: return None entry = self.entries[row] if col == 0: return fmt (entry.start_time)", "TreeModel for TimingActivity's in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log", "return 2 def on_get_column_type (self, index): return str def on_get_iter (self, path): if", "2: return gtk.gdk.Pixbuf def on_get_iter (self, path): if self.n_rows: return path[0] def on_get_path", "from debug import * import numpy as np import matplotlib.pyplot as plt class", "return 0 else: return self.n_rows def on_iter_nth_child (self, parent, n): if parent: return", "class TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingActivity's in a Log.\"\"\" def __init__ (self,", "(self, rowref): return (rowref,) def on_get_value (self, row, col): if self.n_rows == 0:", "== self.n_rows - 1 or self.n_rows == 0: return None else: return rowref", "self.checks[row] = not self.checks[row] def toggle_all (self): if np.sum (self.checks) == len (self.checks):", "str def on_get_iter (self, path): if len (self.log.counting_activities): return path[0] def on_get_path (self,", "(rowref,) def on_get_value (self, row, col): if len (self.log.counting_activities) == 0: return None", "i in xrange (n)] self.alphas = [ int (.8 * 65535) for activity", "(self): return 1 def on_get_column_type (self, index): return str def on_get_iter (self, path):", "def toggle (self, path): row = int (path) self.checks[row] = not self.checks[row] def", "def on_get_path (self, rowref): return (rowref,) def on_get_value (self, row, col): def fmt", "cm (i / n)[:3] for i in xrange (n)] self.alphas = [ int", "activity_name): gtk.GenericTreeModel.__init__ (self) self.log = log self.activity_name = activity_name @property def entries (self):", "= not self.checks[row] def toggle_all (self): if np.sum (self.checks) == len (self.checks): value", "(entry.end_time) elif col == 2: return str (entry.note) else: return None def on_iter_next", "value # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self):", "def on_get_n_columns (self): return 1 def on_get_column_type (self, index): return str def on_get_iter", "##mpl_colors = [ ## (0.0, 0.0, 1.0), ## (0.0, 0.5, 0.0), ## (1.0,", "on_iter_children (self, parent): return 0 # TODO: is this right? def on_iter_has_child (self,", "self.checks[row] = value # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def", "n): if parent: return None elif n < self.n_rows: return n else: return", "on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 1 def on_get_column_type (self, index):", "None entry = self.entries[row] if col == 0: return fmt (entry.start_time) elif col", "gtk.gdk.Color (*mpl_colors[i % n_color]) for i in xrange (n)] cm = plt.get_cmap ('rainbow')", "col): if self.n_rows == 0: return None activity = sorted (self.activities)[row] if col", "(gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingActivity's in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__", "pb = gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16) color = self.colors[row] color_str", "col == 0: return self.checks[row] elif col == 1: return activity.name else: pb", "return 3 def on_get_column_type (self, index): if index == 0: return bool elif", "TODO: is this right? def on_iter_has_child (self, rowref): return False def on_iter_n_children (self,", "(self) self.log = log @property def n_rows (self): return len (self.log.timing_activities) # Implementation", "t.year, t.month, t.day, t.hour, t.minute) if self.n_rows == 0: return None entry =", "else: return self.n_rows def on_iter_nth_child (self, parent, n): if parent: return None elif", "(1.0, 0.0, 0.0), ## (0.0, 0.75, 0.75), ## (0.75, 0.0, 0.75), ## (0.75,", "parent): return 0 # TODO: is this right? def on_iter_has_child (self, rowref): return", "(self, row, col): if self.n_rows == 0: return None activity = sorted (self.activities)[row]", "activity.unit else: return None def on_iter_next (self, rowref): if rowref == self.n_rows -", "a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log = log @property def", "Log.\"\"\" def __init__ (self, activities): gtk.GenericTreeModel.__init__ (self) self.activities = sorted (activities) self.checks =", "sorted (self.activities)[row] if col == 0: return self.checks[row] elif col == 1: return", "i in xrange (n)] self.color_tuples = [ cm (i / n)[:3] for i", "import division import gtk from debug import * import numpy as np import", "return None else: return rowref + 1 def on_iter_children (self, parent): return 0", "(self, rowref): if rowref == self.n_rows - 1 or self.n_rows == 0: return", "@property def entries (self): return self.log.get_entries (self.activity_name) @property def n_rows (self): return len", "elif n < self.n_rows: return n else: return None def on_iter_parent (self, child):", "of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 1 def", "(i / n)[:3] for i in xrange (n)] self.alphas = [ int (.8", "(int, (color.red / 256, color.green / 256, color.blue / 256, self.alphas[row] / 256)))", "activity = sorted (self.log.counting_activities)[row] if col == 0: return activity.name elif col ==", "def fmt (t): return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format ( t.year, t.month, t.day, t.hour, t.minute) if", "activity_name @property def entries (self): return self.log.get_entries (self.activity_name) @property def n_rows (self): return", "(self.checks) == len (self.checks): value = False else: value = True for row", "n else: return None def on_iter_parent (self, child): return None class TimingActivitiesModel (gtk.GenericTreeModel):", "return None def on_iter_parent (self, child): return None class CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel", "== 0: return None activity = sorted (self.log.timing_activities)[row] if col == 0: return", "## (0.0, 0.0, 1.0) ] ##n_color = len (mpl_colors) ##self.colors = [ ##", "pb def on_iter_next (self, rowref): if rowref == self.n_rows - 1 or self.n_rows", "= [ ## (0.0, 0.0, 1.0), ## (0.0, 0.5, 0.0), ## (1.0, 0.0,", "col): if len (self.log.timing_activities) == 0: return None activity = sorted (self.log.timing_activities)[row] if", "( gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16) color = self.colors[row] color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format (", "child): return None class TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingActivity's in a Log.\"\"\"", "/ 256, color.blue / 256, self.alphas[row] / 256))) pb.fill (int (color_str, 16)) return", "as np import matplotlib.pyplot as plt class CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingActivity's", "(self.log.timing_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self):", "elif col == 2: return str (entry.note) else: return None def on_iter_next (self,", "xrange (len (self.checks)): self.checks[row] = value # Implementation of gtk.GenericTreeModel def on_get_flags (self):", "on_iter_parent (self, child): return None class CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingEntry's in", "def n_rows (self): return len (self.log.timing_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self):", "rowref == self.n_rows - 1 or self.n_rows == 0: return None else: return", "else: return None def on_iter_next (self, rowref): if rowref == self.n_rows - 1", "class CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingActivity's in a Log.\"\"\" def __init__ (self,", "else: return None def on_iter_parent (self, child): return None class CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk", "return activity.name else: return None def on_iter_next (self, rowref): if rowref == self.n_rows", "Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3", "right? def on_iter_has_child (self, rowref): return False def on_iter_n_children (self, rowref): if rowref:", "/ 256, self.alphas[row] / 256))) pb.fill (int (color_str, 16)) return pb def on_iter_next", "return n else: return None def on_iter_parent (self, child): return None class ActivityDrawModel", "def on_get_column_type (self, index): return str def on_get_iter (self, path): if len (self.entries):", "def on_iter_n_children (self, rowref): if rowref: return 0 else: return self.n_rows def on_iter_nth_child", "( *map (int, (color.red / 256, color.green / 256, color.blue / 256, self.alphas[row]", "if parent: return None elif n < self.n_rows: return n else: return None", "gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 2 def on_get_column_type", "None entry = self.entries[row] if col == 0: return str (entry.date) elif col", "\"\"\"Gtk TreeModel for TimingEntry's in a Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__", "True for row in xrange (len (self.checks)): self.checks[row] = value # Implementation of", "3 def on_get_column_type (self, index): if index == 0: return bool elif index", "2: return str (entry.error) elif col == 3: return str (entry.note) else: return", "(.8 * 65535) for activity in self.activities] @property def n_rows (self): return len", "treemodels.py from __future__ import division import gtk from debug import * import numpy", "0 # TODO: is this right? def on_iter_has_child (self, rowref): return False def", "on_iter_parent (self, child): return None class ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for drawing Activity's", "gtk.GenericTreeModel.__init__ (self) self.log = log @property def n_rows (self): return len (self.log.counting_activities) #", "for TimingActivity's in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log =", "@property def n_rows (self): return len (self.entries) # Implementation of gtk.GenericTreeModel def on_get_flags", "on_get_value (self, row, col): if self.n_rows == 0: return None activity = sorted", "if col == 0: return self.checks[row] elif col == 1: return activity.name else:", "path): if len (self.log.timing_activities): return path[0] def on_get_path (self, rowref): return (rowref,) def", "if self.n_rows == 0: return None activity = sorted (self.activities)[row] if col ==", "TreeModel for CountingActivity's in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log", "= sorted (activities) self.checks = [ False for activity in self.activities] n =", "0.0, 0.0), ## (0.0, 0.0, 1.0) ] ##n_color = len (mpl_colors) ##self.colors =", "1.0), ## (0.0, 0.5, 0.0), ## (1.0, 0.0, 0.0), ## (0.0, 0.75, 0.75),", "entry = self.entries[row] if col == 0: return str (entry.date) elif col ==", "(path) self.checks[row] = not self.checks[row] def toggle_all (self): if np.sum (self.checks) == len", "3 def on_get_column_type (self, index): return str def on_get_iter (self, path): if len", "def on_iter_nth_child (self, parent, n): if parent: return None elif n < self.n_rows:", "== 1: return str (entry.n) elif col == 2: return str (entry.error) elif", "str elif index == 2: return gtk.gdk.Pixbuf def on_get_iter (self, path): if self.n_rows:", "(self.activity_name) @property def n_rows (self): return len (self.entries) # Implementation of gtk.GenericTreeModel def", "0.0, 1.0), ## (0.0, 0.5, 0.0), ## (1.0, 0.0, 0.0), ## (0.0, 0.75,", "return rowref + 1 def on_iter_children (self, parent): return 0 # TODO: is", "on_get_column_type (self, index): if index == 0: return bool elif index == 1:", "n < self.n_rows: return n else: return None def on_iter_parent (self, child): return", "n else: return None def on_iter_parent (self, child): return None class TimingEntriesModel (gtk.GenericTreeModel):", "for activity in self.activities] n = len (self.activities) ##mpl_colors = [ ## (0.0,", "matplotlib.pyplot as plt class CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingActivity's in a Log.\"\"\"", "## (0.0, 0.0, 0.0), ## (0.0, 0.0, 1.0) ] ##n_color = len (mpl_colors)", "0.0, 1.0) ] ##n_color = len (mpl_colors) ##self.colors = [ ## gtk.gdk.Color (*mpl_colors[i", "path): row = int (path) self.checks[row] = not self.checks[row] def toggle_all (self): if", "row, col): def fmt (t): return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format ( t.year, t.month, t.day, t.hour,", "else: value = True for row in xrange (len (self.checks)): self.checks[row] = value", "return None activity = sorted (self.log.counting_activities)[row] if col == 0: return activity.name elif", "elif col == 1: return str (entry.n) elif col == 2: return str", "return str (entry.error) elif col == 3: return str (entry.note) else: return None", "(entry.error) elif col == 3: return str (entry.note) else: return None def on_iter_next", "len (self.log.counting_activities) == 0: return None activity = sorted (self.log.counting_activities)[row] if col ==", "self.log = log self.activity_name = activity_name @property def entries (self): return self.log.get_entries (self.activity_name)", "on_iter_nth_child (self, parent, n): if parent: return None elif n < self.n_rows: return", "return str (entry.note) else: return None def on_iter_next (self, rowref): if rowref ==", "(self): return len (self.activities) # toggle def toggle (self, path): row = int", "return str (entry.date) elif col == 1: return str (entry.n) elif col ==", "== 0: return None entry = self.entries[row] if col == 0: return fmt", "n_rows (self): return len (self.log.counting_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return", "2 def on_get_column_type (self, index): return str def on_get_iter (self, path): if len", "activity in self.activities] @property def n_rows (self): return len (self.activities) # toggle def", "bool elif index == 1: return str elif index == 2: return gtk.gdk.Pixbuf", "(self): return len (self.entries) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY", "gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 2 def on_get_column_type (self, index): return str def", "self.n_rows == 0: return None entry = self.entries[row] if col == 0: return", "rowref: return 0 else: return self.n_rows def on_iter_nth_child (self, parent, n): if parent:", "256))) pb.fill (int (color_str, 16)) return pb def on_iter_next (self, rowref): if rowref", "col == 2: return str (entry.note) else: return None def on_iter_next (self, rowref):", "def n_rows (self): return len (self.log.counting_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self):", "on_iter_parent (self, child): return None class TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingActivity's in", "None else: return rowref + 1 def on_iter_children (self, parent): return 0 #", "fmt (entry.end_time) elif col == 2: return str (entry.note) else: return None def", "rowref + 1 def on_iter_children (self, parent): return 0 # TODO: is this", "self.n_rows == 0: return None else: return rowref + 1 def on_iter_children (self,", "def on_get_iter (self, path): if self.n_rows: return path[0] def on_get_path (self, rowref): return", "\"\"\"Gtk TreeModel for CountingEntry's in a Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__", "(0.0, 0.0, 1.0) ] ##n_color = len (mpl_colors) ##self.colors = [ ## gtk.gdk.Color", "(int (color_str, 16)) return pb def on_iter_next (self, rowref): if rowref == self.n_rows", "len (self.log.timing_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns", "division import gtk from debug import * import numpy as np import matplotlib.pyplot", "(self, rowref): return (rowref,) def on_get_value (self, row, col): if len (self.log.timing_activities) ==", "gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16) color = self.colors[row] color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map", "(self, index): return str def on_get_iter (self, path): if len (self.log.timing_activities): return path[0]", "(*cm (i / n)[:3]) for i in xrange (n)] self.color_tuples = [ cm", "(self.log.counting_activities)[row] if col == 0: return activity.name elif col == 1: return activity.unit", "def on_get_column_type (self, index): return str def on_get_iter (self, path): if len (self.log.timing_activities):", "return False def on_iter_n_children (self, rowref): if rowref: return 0 else: return self.n_rows", "on_get_iter (self, path): if len (self.entries): return path[0] def on_get_path (self, rowref): return", "for row in xrange (len (self.checks)): self.checks[row] = value # Implementation of gtk.GenericTreeModel", "- 1 or self.n_rows == 0: return None else: return rowref + 1", "self.color_tuples = [ cm (i / n)[:3] for i in xrange (n)] self.alphas", "a Log.\"\"\" def __init__ (self, activities): gtk.GenericTreeModel.__init__ (self) self.activities = sorted (activities) self.checks", "(self.checks): value = False else: value = True for row in xrange (len", "(self, rowref): return (rowref,) def on_get_value (self, row, col): def fmt (t): return", "(self) self.activities = sorted (activities) self.checks = [ False for activity in self.activities]", "0.0), ## (0.0, 0.0, 1.0) ] ##n_color = len (mpl_colors) ##self.colors = [", "0: return activity.name else: return None def on_iter_next (self, rowref): if rowref ==", "col == 1: return activity.unit else: return None def on_iter_next (self, rowref): if", "= '{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map (int, (color.red / 256, color.green / 256, color.blue /", "(entry.note) else: return None def on_iter_next (self, rowref): if rowref == self.n_rows -", "(self): return 2 def on_get_column_type (self, index): return str def on_get_iter (self, path):", "of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3 def", "gtk.GenericTreeModel.__init__ (self) self.activities = sorted (activities) self.checks = [ False for activity in", "return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 2 def on_get_column_type (self, index): return str", "(self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 1 def on_get_column_type (self, index): return", "on_iter_n_children (self, rowref): if rowref: return 0 else: return self.n_rows def on_iter_nth_child (self,", "path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self, row, col): def", "col == 1: return str (entry.n) elif col == 2: return str (entry.error)", "in xrange (n)] cm = plt.get_cmap ('rainbow') self.colors = [ gtk.gdk.Color (*cm (i", "on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 2 def on_get_column_type (self, index):", "(0.0, 0.0, 1.0), ## (0.0, 0.5, 0.0), ## (1.0, 0.0, 0.0), ## (0.0,", "rowref): return (rowref,) def on_get_value (self, row, col): if self.n_rows == 0: return", "return str def on_get_iter (self, path): if len (self.log.timing_activities): return path[0] def on_get_path", "from __future__ import division import gtk from debug import * import numpy as", "return None def on_iter_parent (self, child): return None class TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel", "return str (entry.n) elif col == 2: return str (entry.error) elif col ==", "% n_color]) for i in xrange (n)] cm = plt.get_cmap ('rainbow') self.colors =", "TimingEntry's in a Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log =", "(self, rowref): return False def on_iter_n_children (self, rowref): if rowref: return 0 else:", "activity.name else: return None def on_iter_next (self, rowref): if rowref == self.n_rows -", "(self) self.log = log self.activity_name = activity_name @property def entries (self): return self.log.get_entries", "return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3 def on_get_column_type (self, index): return str", "import matplotlib.pyplot as plt class CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingActivity's in a", "col == 1: return fmt (entry.end_time) elif col == 2: return str (entry.note)", "(mpl_colors) ##self.colors = [ ## gtk.gdk.Color (*mpl_colors[i % n_color]) for i in xrange", "activity.name else: pb = gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16) color =", "path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self, row, col): if", "TreeModel for drawing Activity's in a Log.\"\"\" def __init__ (self, activities): gtk.GenericTreeModel.__init__ (self)", "if len (self.entries): return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value", "index): return str def on_get_iter (self, path): if len (self.entries): return path[0] def", "= sorted (self.log.counting_activities)[row] if col == 0: return activity.name elif col == 1:", "== 0: return self.checks[row] elif col == 1: return activity.name else: pb =", "Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 1", "== 2: return str (entry.error) elif col == 3: return str (entry.note) else:", "= plt.get_cmap ('rainbow') self.colors = [ gtk.gdk.Color (*cm (i / n)[:3]) for i", "256, color.green / 256, color.blue / 256, self.alphas[row] / 256))) pb.fill (int (color_str,", "activity in self.activities] n = len (self.activities) ##mpl_colors = [ ## (0.0, 0.0,", "return n else: return None def on_iter_parent (self, child): return None class TimingEntriesModel", "(self): if np.sum (self.checks) == len (self.checks): value = False else: value =", "fmt (t): return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format ( t.year, t.month, t.day, t.hour, t.minute) if self.n_rows", "None def on_iter_parent (self, child): return None class ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for", "def on_iter_parent (self, child): return None class TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingEntry's", "self.checks[row] elif col == 1: return activity.name else: pb = gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB,", "gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3 def on_get_column_type (self, index): if index ==", "= self.entries[row] if col == 0: return str (entry.date) elif col == 1:", "return (rowref,) def on_get_value (self, row, col): def fmt (t): return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format", "== 1: return activity.unit else: return None def on_iter_next (self, rowref): if rowref", "def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 2 def on_get_column_type (self,", "0.75, 0.0), ## (0.0, 0.0, 0.0), ## (0.0, 0.0, 1.0) ] ##n_color =", "== 0: return None else: return rowref + 1 def on_iter_children (self, parent):", "return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format ( t.year, t.month, t.day, t.hour, t.minute) if self.n_rows == 0:", "def on_get_value (self, row, col): if len (self.log.counting_activities) == 0: return None activity", "0.0), ## (0.0, 0.0, 0.0), ## (0.0, 0.0, 1.0) ] ##n_color = len", "= sorted (self.activities)[row] if col == 0: return self.checks[row] elif col == 1:", "'{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map (int, (color.red / 256, color.green / 256, color.blue / 256,", "on_get_iter (self, path): if len (self.log.counting_activities): return path[0] def on_get_path (self, rowref): return", "n_rows (self): return len (self.entries) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return", "import gtk from debug import * import numpy as np import matplotlib.pyplot as", "== 0: return bool elif index == 1: return str elif index ==", "(self, path): if self.n_rows: return path[0] def on_get_path (self, rowref): return (rowref,) def", "self.n_rows == 0: return None activity = sorted (self.activities)[row] if col == 0:", "##n_color = len (mpl_colors) ##self.colors = [ ## gtk.gdk.Color (*mpl_colors[i % n_color]) for", "__init__ (self, activities): gtk.GenericTreeModel.__init__ (self) self.activities = sorted (activities) self.checks = [ False", "CountingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingActivity's in a Log.\"\"\" def __init__ (self, log):", "(self, rowref): if rowref: return 0 else: return self.n_rows def on_iter_nth_child (self, parent,", "(rowref,) def on_get_value (self, row, col): if len (self.log.timing_activities) == 0: return None", "row in xrange (len (self.checks)): self.checks[row] = value # Implementation of gtk.GenericTreeModel def", "TreeModel for TimingEntry's in a Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self)", "child): return None class ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for drawing Activity's in a", "index == 1: return str elif index == 2: return gtk.gdk.Pixbuf def on_get_iter", "16) color = self.colors[row] color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map (int, (color.red / 256,", "< self.n_rows: return n else: return None def on_iter_parent (self, child): return None", "elif col == 3: return str (entry.note) else: return None def on_iter_next (self,", "(entry.start_time) elif col == 1: return fmt (entry.end_time) elif col == 2: return", "len (self.log.counting_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns", "on_get_n_columns (self): return 1 def on_get_column_type (self, index): return str def on_get_iter (self,", "col): if self.n_rows == 0: return None entry = self.entries[row] if col ==", "self.colors = [ gtk.gdk.Color (*cm (i / n)[:3]) for i in xrange (n)]", "(self, path): if len (self.entries): return path[0] def on_get_path (self, rowref): return (rowref,)", "int (.8 * 65535) for activity in self.activities] @property def n_rows (self): return", "in a Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log = log", "on_get_value (self, row, col): if len (self.log.timing_activities) == 0: return None activity =", "on_get_value (self, row, col): def fmt (t): return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format ( t.year, t.month,", "+ 1 def on_iter_children (self, parent): return 0 # TODO: is this right?", "(0.75, 0.75, 0.0), ## (0.0, 0.0, 0.0), ## (0.0, 0.0, 1.0) ] ##n_color", "self.checks[row] def toggle_all (self): if np.sum (self.checks) == len (self.checks): value = False", "def on_get_value (self, row, col): if len (self.log.timing_activities) == 0: return None activity", "ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for drawing Activity's in a Log.\"\"\" def __init__ (self,", "col == 3: return str (entry.note) else: return None def on_iter_next (self, rowref):", "None elif n < self.n_rows: return n else: return None def on_iter_parent (self,", "# treemodels.py from __future__ import division import gtk from debug import * import", "Log.\"\"\" def __init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log = log self.activity_name =", "True, 8, 16, 16) color = self.colors[row] color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map (int,", "return None def on_iter_parent (self, child): return None class ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel", "(entry.date) elif col == 1: return str (entry.n) elif col == 2: return", "(self, index): return str def on_get_iter (self, path): if len (self.log.counting_activities): return path[0]", "== 0: return str (entry.date) elif col == 1: return str (entry.n) elif", "elif col == 2: return str (entry.error) elif col == 3: return str", "on_iter_has_child (self, rowref): return False def on_iter_n_children (self, rowref): if rowref: return 0", "@property def n_rows (self): return len (self.activities) # toggle def toggle (self, path):", "return activity.unit else: return None def on_iter_next (self, rowref): if rowref == self.n_rows", "## (0.0, 0.75, 0.75), ## (0.75, 0.0, 0.75), ## (0.75, 0.75, 0.0), ##", "if len (self.log.counting_activities): return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value", "return n else: return None def on_iter_parent (self, child): return None class CountingEntriesModel", "xrange (n)] self.alphas = [ int (.8 * 65535) for activity in self.activities]", "self.checks = [ False for activity in self.activities] n = len (self.activities) ##mpl_colors", "[ cm (i / n)[:3] for i in xrange (n)] self.alphas = [", "return len (self.activities) # toggle def toggle (self, path): row = int (path)", "8, 16, 16) color = self.colors[row] color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map (int, (color.red", "return len (self.log.counting_activities) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def", "__init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log = log @property def n_rows (self): return", "None def on_iter_parent (self, child): return None class CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for", "return activity.name elif col == 1: return activity.unit else: return None def on_iter_next", "= False else: value = True for row in xrange (len (self.checks)): self.checks[row]", "(rowref,) def on_get_value (self, row, col): if self.n_rows == 0: return None activity", "for i in xrange (n)] self.color_tuples = [ cm (i / n)[:3] for", "None class CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingEntry's in a Log.\"\"\" def __init__", "if len (self.log.counting_activities) == 0: return None activity = sorted (self.log.counting_activities)[row] if col", "parent: return None elif n < self.n_rows: return n else: return None def", "on_get_path (self, rowref): return (rowref,) def on_get_value (self, row, col): def fmt (t):", "in a Log.\"\"\" def __init__ (self, activities): gtk.GenericTreeModel.__init__ (self) self.activities = sorted (activities)", "t.day, t.hour, t.minute) if self.n_rows == 0: return None entry = self.entries[row] if", "str (entry.note) else: return None def on_iter_next (self, rowref): if rowref == self.n_rows", "None class TimingActivitiesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingActivity's in a Log.\"\"\" def __init__", "__init__ (self, log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log = log self.activity_name = activity_name @property", "str (entry.error) elif col == 3: return str (entry.note) else: return None def", "('rainbow') self.colors = [ gtk.gdk.Color (*cm (i / n)[:3]) for i in xrange", "16)) return pb def on_iter_next (self, rowref): if rowref == self.n_rows - 1", "(self, parent, n): if parent: return None elif n < self.n_rows: return n", "str def on_get_iter (self, path): if len (self.log.timing_activities): return path[0] def on_get_path (self,", "len (self.log.timing_activities): return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self,", "== 2: return str (entry.note) else: return None def on_iter_next (self, rowref): if", "t.minute) if self.n_rows == 0: return None entry = self.entries[row] if col ==", "str (entry.date) elif col == 1: return str (entry.n) elif col == 2:", "gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 3 def on_get_column_type", "col == 2: return str (entry.error) elif col == 3: return str (entry.note)", "gtk.gdk.Pixbuf def on_get_iter (self, path): if self.n_rows: return path[0] def on_get_path (self, rowref):", "1: return activity.name else: pb = gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16)", "# TODO: is this right? def on_iter_has_child (self, rowref): return False def on_iter_n_children", "(self, index): if index == 0: return bool elif index == 1: return", "== 0: return activity.name elif col == 1: return activity.unit else: return None", "CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingEntry's in a Log.\"\"\" def __init__ (self, log,", "on_get_column_type (self, index): return str def on_get_iter (self, path): if len (self.entries): return", "== len (self.checks): value = False else: value = True for row in", "(activities) self.checks = [ False for activity in self.activities] n = len (self.activities)", "== 0: return fmt (entry.start_time) elif col == 1: return fmt (entry.end_time) elif", "elif col == 1: return activity.name else: pb = gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB, True,", "(self.log.timing_activities): return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self, row,", "@property def n_rows (self): return len (self.log.counting_activities) # Implementation of gtk.GenericTreeModel def on_get_flags", "class TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingEntry's in a Log.\"\"\" def __init__ (self,", "None activity = sorted (self.activities)[row] if col == 0: return self.checks[row] elif col", "on_get_path (self, rowref): return (rowref,) def on_get_value (self, row, col): if len (self.log.timing_activities)", "self.log = log @property def n_rows (self): return len (self.log.counting_activities) # Implementation of", "return None elif n < self.n_rows: return n else: return None def on_iter_parent", "[ int (.8 * 65535) for activity in self.activities] @property def n_rows (self):", "TimingActivity's in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log = log", "(self, log): gtk.GenericTreeModel.__init__ (self) self.log = log @property def n_rows (self): return len", "= activity_name @property def entries (self): return self.log.get_entries (self.activity_name) @property def n_rows (self):", "return None entry = self.entries[row] if col == 0: return fmt (entry.start_time) elif", "None def on_iter_next (self, rowref): if rowref == self.n_rows - 1 or self.n_rows", "index): return str def on_get_iter (self, path): if len (self.log.timing_activities): return path[0] def", "return (rowref,) def on_get_value (self, row, col): if self.n_rows == 0: return None", "for CountingActivity's in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self) self.log =", "def on_get_n_columns (self): return 3 def on_get_column_type (self, index): if index == 0:", "class CountingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for CountingEntry's in a Log.\"\"\" def __init__ (self,", "entries (self): return self.log.get_entries (self.activity_name) @property def n_rows (self): return len (self.entries) #", "= len (self.activities) ##mpl_colors = [ ## (0.0, 0.0, 1.0), ## (0.0, 0.5,", "toggle (self, path): row = int (path) self.checks[row] = not self.checks[row] def toggle_all", "False def on_iter_n_children (self, rowref): if rowref: return 0 else: return self.n_rows def", "gtk.GenericTreeModel.__init__ (self) self.log = log @property def n_rows (self): return len (self.log.timing_activities) #", "return 1 def on_get_column_type (self, index): return str def on_get_iter (self, path): if", "(self, child): return None class ActivityDrawModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for drawing Activity's in", "[ gtk.gdk.Color (*cm (i / n)[:3]) for i in xrange (n)] self.color_tuples =", "return n else: return None def on_iter_parent (self, child): return None class TimingActivitiesModel", "else: pb = gtk.gdk.Pixbuf ( gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16) color = self.colors[row]", "0 else: return self.n_rows def on_iter_nth_child (self, parent, n): if parent: return None", "on_get_iter (self, path): if len (self.log.timing_activities): return path[0] def on_get_path (self, rowref): return", "def on_get_value (self, row, col): if self.n_rows == 0: return None activity =", "len (self.log.counting_activities): return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self,", "(gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingActivity's in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__", "on_iter_parent (self, child): return None class TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk TreeModel for TimingEntry's in", "return (rowref,) def on_get_value (self, row, col): if len (self.log.counting_activities) == 0: return", "log self.activity_name = activity_name @property def entries (self): return self.log.get_entries (self.activity_name) @property def", "16, 16) color = self.colors[row] color_str = '{0:02x}{1:02x}{2:02x}{3:02x}'.format ( *map (int, (color.red /", "return gtk.gdk.Pixbuf def on_get_iter (self, path): if self.n_rows: return path[0] def on_get_path (self,", "len (self.entries) # Implementation of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns", "rowref): return (rowref,) def on_get_value (self, row, col): def fmt (t): return '{0:04d}-{1:02d}-{2:02d}", "return fmt (entry.start_time) elif col == 1: return fmt (entry.end_time) elif col ==", "if col == 0: return activity.name elif col == 1: return activity.unit else:", "## (0.0, 0.0, 1.0), ## (0.0, 0.5, 0.0), ## (1.0, 0.0, 0.0), ##", "return self.log.get_entries (self.activity_name) @property def n_rows (self): return len (self.entries) # Implementation of", "parent, n): if parent: return None elif n < self.n_rows: return n else:", "self.entries[row] if col == 0: return str (entry.date) elif col == 1: return", "\"\"\"Gtk TreeModel for TimingActivity's in a Log.\"\"\" def __init__ (self, log): gtk.GenericTreeModel.__init__ (self)", "@property def n_rows (self): return len (self.log.timing_activities) # Implementation of gtk.GenericTreeModel def on_get_flags", "(self, parent): return 0 # TODO: is this right? def on_iter_has_child (self, rowref):", "(self, row, col): def fmt (t): return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format ( t.year, t.month, t.day,", "row, col): if len (self.log.counting_activities) == 0: return None activity = sorted (self.log.counting_activities)[row]", "def __init__ (self, activities): gtk.GenericTreeModel.__init__ (self) self.activities = sorted (activities) self.checks = [", "on_get_n_columns (self): return 3 def on_get_column_type (self, index): return str def on_get_iter (self,", "(self, path): row = int (path) self.checks[row] = not self.checks[row] def toggle_all (self):", "path): if len (self.log.counting_activities): return path[0] def on_get_path (self, rowref): return (rowref,) def", "(color_str, 16)) return pb def on_iter_next (self, rowref): if rowref == self.n_rows -", "sorted (self.log.counting_activities)[row] if col == 0: return activity.name elif col == 1: return", "sorted (activities) self.checks = [ False for activity in self.activities] n = len", "n else: return None def on_iter_parent (self, child): return None class CountingEntriesModel (gtk.GenericTreeModel):", "/ 256, color.green / 256, color.blue / 256, self.alphas[row] / 256))) pb.fill (int", "t.hour, t.minute) if self.n_rows == 0: return None entry = self.entries[row] if col", "log): gtk.GenericTreeModel.__init__ (self) self.log = log @property def n_rows (self): return len (self.log.counting_activities)", "(self, log, activity_name): gtk.GenericTreeModel.__init__ (self) self.log = log self.activity_name = activity_name @property def", "0.0), ## (0.0, 0.75, 0.75), ## (0.75, 0.0, 0.75), ## (0.75, 0.75, 0.0),", "* 65535) for activity in self.activities] @property def n_rows (self): return len (self.activities)", "0: return None activity = sorted (self.log.counting_activities)[row] if col == 0: return activity.name", "elif col == 1: return activity.unit else: return None def on_iter_next (self, rowref):", "1 or self.n_rows == 0: return None else: return rowref + 1 def", "log @property def n_rows (self): return len (self.log.counting_activities) # Implementation of gtk.GenericTreeModel def", "for i in xrange (n)] cm = plt.get_cmap ('rainbow') self.colors = [ gtk.gdk.Color", "] ##n_color = len (mpl_colors) ##self.colors = [ ## gtk.gdk.Color (*mpl_colors[i % n_color])", "(self.activities) # toggle def toggle (self, path): row = int (path) self.checks[row] =", "of gtk.GenericTreeModel def on_get_flags (self): return gtk.TREE_MODEL_LIST_ONLY def on_get_n_columns (self): return 2 def", "elif col == 1: return fmt (entry.end_time) elif col == 2: return str", "index == 2: return gtk.gdk.Pixbuf def on_get_iter (self, path): if self.n_rows: return path[0]", "else: return None def on_iter_parent (self, child): return None class TimingEntriesModel (gtk.GenericTreeModel): \"\"\"Gtk", "return path[0] def on_get_path (self, rowref): return (rowref,) def on_get_value (self, row, col):", "def n_rows (self): return len (self.entries) # Implementation of gtk.GenericTreeModel def on_get_flags (self):", "0: return self.checks[row] elif col == 1: return activity.name else: pb = gtk.gdk.Pixbuf", "1: return str (entry.n) elif col == 2: return str (entry.error) elif col", "= sorted (self.log.timing_activities)[row] if col == 0: return activity.name else: return None def", "== 0: return None activity = sorted (self.log.counting_activities)[row] if col == 0: return", "(self): return self.log.get_entries (self.activity_name) @property def n_rows (self): return len (self.entries) # Implementation", "return str def on_get_iter (self, path): if len (self.entries): return path[0] def on_get_path", "(len (self.checks)): self.checks[row] = value # Implementation of gtk.GenericTreeModel def on_get_flags (self): return", "col): def fmt (t): return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}'.format ( t.year, t.month, t.day, t.hour, t.minute)", "np.sum (self.checks) == len (self.checks): value = False else: value = True for", "( t.year, t.month, t.day, t.hour, t.minute) if self.n_rows == 0: return None entry", "[ ## gtk.gdk.Color (*mpl_colors[i % n_color]) for i in xrange (n)] cm =", "0.5, 0.0), ## (1.0, 0.0, 0.0), ## (0.0, 0.75, 0.75), ## (0.75, 0.0," ]
[ "(c) 2019 Microsoft Corporation # Distributed under the MIT software license import sys", "Copyright (c) 2019 Microsoft Corporation # Distributed under the MIT software license import", "2019 Microsoft Corporation # Distributed under the MIT software license import sys from", "# Distributed under the MIT software license import sys from interpret.ext.extension_utils import load_class_extensions", "MIT software license import sys from interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension import GLASSBOX_EXTENSION_KEY,", "sys from interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension import GLASSBOX_EXTENSION_KEY, _is_valid_glassbox_explainer load_class_extensions( sys.modules[__name__], GLASSBOX_EXTENSION_KEY,", "# Copyright (c) 2019 Microsoft Corporation # Distributed under the MIT software license", "Distributed under the MIT software license import sys from interpret.ext.extension_utils import load_class_extensions from", "interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension import GLASSBOX_EXTENSION_KEY, _is_valid_glassbox_explainer load_class_extensions( sys.modules[__name__], GLASSBOX_EXTENSION_KEY, _is_valid_glassbox_explainer )", "Microsoft Corporation # Distributed under the MIT software license import sys from interpret.ext.extension_utils", "<reponame>prateekiiest/interpret<gh_stars>1000+ # Copyright (c) 2019 Microsoft Corporation # Distributed under the MIT software", "under the MIT software license import sys from interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension", "the MIT software license import sys from interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension import", "Corporation # Distributed under the MIT software license import sys from interpret.ext.extension_utils import", "license import sys from interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension import GLASSBOX_EXTENSION_KEY, _is_valid_glassbox_explainer load_class_extensions(", "software license import sys from interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension import GLASSBOX_EXTENSION_KEY, _is_valid_glassbox_explainer", "from interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension import GLASSBOX_EXTENSION_KEY, _is_valid_glassbox_explainer load_class_extensions( sys.modules[__name__], GLASSBOX_EXTENSION_KEY, _is_valid_glassbox_explainer", "import sys from interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension import GLASSBOX_EXTENSION_KEY, _is_valid_glassbox_explainer load_class_extensions( sys.modules[__name__]," ]
[ "config file\", ) parser.add_argument( \"--head_cluster\", type=str, default=\"ray-head\", help=\"Name of the headnode cluster\", )", "import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from rlo import git_utils def get_environment(): print(\"Getting docker password...\")", "are valid if args.check_params: check_params(args.scenario, params) if args.enable_cli_auth: cli_auth = AzureCliAuthentication() else: cli_auth", "cluster\", ) parser.add_argument( \"--body_cluster\", type=str, default=\"ray-p40\", help=\"Name of the worker cluster\", ) parser.add_argument(", "datetime import datetime import os import subprocess import sys from tempfile import NamedTemporaryFile", "additional_args # Check arguments are valid if args.check_params: check_params(args.scenario, params) if args.enable_cli_auth: cli_auth", "), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600, # How long to wait for whole cluster", "import ReinforcementLearningEstimator, Ray from azureml.contrib.train.rl import WorkerConfiguration from azureml_util import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\"))", "use_gpu=False, cluster_coordination_timeout_seconds=3600, # How long to wait for whole cluster to start max_run_duration_seconds=40", "head_run.get_file_names() if f.endswith(\"best_episodes.kso\") ) with NamedTemporaryFile(mode=\"r\") as f: head_run.download_file(kso_file, output_file_path=f.name) content = f.read()", "it starts, or the run will fail to complete. Alternatively (recommended), you can", "for whole cluster to start max_run_duration_seconds=40 * 3600, # Allow the docker container", "body_compute = ws.compute_targets[args.body_cluster] env = get_environment() # Specify the Ray worker configuration worker_conf", "clash) ``` pip install -r test/builds/ci-requirements.txt ``` 3. Try to run `fewer_simplify_rules` scenario", "# Check arguments are valid if args.check_params: check_params(args.scenario, params) if args.enable_cli_auth: cli_auth =", "= [child_run.id for child_run in pipeline_run.get_steps()] print([id for id in child_ids if \"head\"", "run\") parser.add_argument( \"--aml_config_file\", type=str, default=\"aml_config.json\", help=\"Path to the Azure ML config file\", )", "rather than start its own (\"--address\", \"auto\"), # The command-line ray process run", "Contributor access to the resource group (knossosamlrg). You can (not recommended) temporarily elevate", "note, no GPU required, the head is expected to be only a co-ordinator.", "password env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies = True return env def check_params(scenario, params): #", "rlo.flags import make_config_for_scenario from ray_main import ray_run_arguments if not os.path.isfile(scenario): scenario = os.path.join(\"src\",", "1. Make sure you have access to the knossos Azure subscription. > az", "azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray from azureml.contrib.train.rl import WorkerConfiguration from azureml_util import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__),", "NaNs, but found the following lines:\\n\" + \"\\n\".join(lines) ) print(\"Found no NaNs!\") def", "runs the estimator, but doesn't do anything to save the outputs (PNGs or", "succeeded!\") print( \"Download from container azureml path ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note: run_id is the", "best_episodes.kso file does not contain NaNs Regression test for #1438 \"\"\" head_run =", "tempfile import NamedTemporaryFile from azureml.core import Workspace, Experiment, Environment from azureml.core.authentication import AzureCliAuthentication", "kso_file = next( f for f in head_run.get_file_names() if f.endswith(\"best_episodes.kso\") ) with NamedTemporaryFile(mode=\"r\")", "but found the following lines:\\n\" + \"\\n\".join(lines) ) print(\"Found no NaNs!\") def main():", "from container azureml path ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note: run_id is the ID of the", "locally before submission\", ) args, additional_args = parser.parse_known_args() run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params", "+ docker_tag env.docker.base_image_registry.address = \"knossos.azurecr.io\" env.docker.base_image_registry.password = password env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies =", "to run\") parser.add_argument( \"--aml_config_file\", type=str, default=\"aml_config.json\", help=\"Path to the Azure ML config file\",", "action=\"store_true\", help=\"Enable AzureCliAuthentication (for CI)\", ) parser.add_argument( \"--wait_for_completion\", action=\"store_true\", help=\"Wait for the completion", "source_directory=source_dir, compute_target=head_compute, environment=env, entry_script=\"ray_main.py\", script_params=dict( [(p, \"\") for p in params] + [", "# This tells ray_main.py to connect to an existing Ray/redis server rather than", ") args, additional_args = parser.parse_known_args() run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params = [ args.scenario,", "resource group. 2. Install dependencies (better to do it in an isolated conda", "\"Expected no NaNs, but found the following lines:\\n\" + \"\\n\".join(lines) ) print(\"Found no", "+ additional_args # Check arguments are valid if args.check_params: check_params(args.scenario, params) if args.enable_cli_auth:", "pip install -r test/builds/ci-requirements.txt ``` 3. Try to run `fewer_simplify_rules` scenario ``` python", "tells ray_main.py to connect to an existing Ray/redis server rather than start its", "server rather than start its own (\"--address\", \"auto\"), # The command-line ray process", "the host OS. shm_size=24 * 1024 * 1024 * 1024, ) # This", "in params] + [ # This tells ray_main.py to connect to an existing", "if \"NaN\" in line] raise ValueError( \"Expected no NaNs, but found the following", "when it starts, or the run will fail to complete. Alternatively (recommended), you", "Learning imports from azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray from azureml.contrib.train.rl import WorkerConfiguration from azureml_util", "group (knossosamlrg). You can (not recommended) temporarily elevate yourself to Contributor using Azure", "env.docker.base_image_registry.password = password env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies = True return env def check_params(scenario,", "for rn in run.get_children() if rn.id.endswith(\"_head\")) kso_file = next( f for f in", "rn in run.get_children() if rn.id.endswith(\"_head\")) kso_file = next( f for f in head_run.get_file_names()", "import make_config_for_scenario from ray_main import ray_run_arguments if not os.path.isfile(scenario): scenario = os.path.join(\"src\", \"scenarios\",", "from azureml.pipeline.core import PipelineRun # Azure ML Reinforcement Learning imports from azureml.contrib.train.rl import", "headnode cluster\", ) parser.add_argument( \"--body_cluster\", type=str, default=\"ray-p40\", help=\"Name of the worker cluster\", )", "with combined_source_directory() as source_dir: # This defines the head configuration - note, no", "help=\"Name of the worker cluster\", ) parser.add_argument( \"--num_workers\", type=int, default=10, help=\"Number of worker", "passed to `ray_main.py`. \"\"\" import argparse from datetime import datetime import os import", "will need to have said level of access _for_the_duration_of_the_run_ not just when it", "az account set -s Knossos You'll need to have at least Contributor access", "ray_run_arguments, cmdline=params) def check_best_episodes(run): \"\"\" Checks best_episodes.kso file does not contain NaNs Regression", "= AzureCliAuthentication() else: cli_auth = None ws = Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute = ws.compute_targets[args.head_cluster]", "next(rn for rn in run.get_children() if rn.id.endswith(\"_head\")) kso_file = next( f for f", "imports from azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray from azureml.contrib.train.rl import WorkerConfiguration from azureml_util import", "yourself to Owner using PIM, and give yourself permanent Contributor rights to the", "env.python.user_managed_dependencies = True return env def check_params(scenario, params): # import locally so that", "install ray==0.8.7; ray start --head\". (\"--redis_token\", \"<PASSWORD>\"), # Ensure workers are using GPUs", "or the run will fail to complete. Alternatively (recommended), you can temporarily elevate", "need to have at least Contributor access to the resource group (knossosamlrg). You", "head_run.download_file(kso_file, output_file_path=f.name) content = f.read() print(f\"Downloaded {kso_file} (length={len(content)})\") if \"NaN\" in content: lines", "+ [ # This tells ray_main.py to connect to an existing Ray/redis server", "that CI can run without dependencies from rlo.flags import make_config_for_scenario from ray_main import", "\"\\n\".join(lines) ) print(\"Found no NaNs!\") def main(): parser = argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str, help=\"Scenario", "default=\"ray-head\", help=\"Name of the headnode cluster\", ) parser.add_argument( \"--body_cluster\", type=str, default=\"ray-p40\", help=\"Name of", "ws.compute_targets[args.head_cluster] body_compute = ws.compute_targets[args.body_cluster] env = get_environment() # Specify the Ray worker configuration", "if args.check_params: check_params(args.scenario, params) if args.enable_cli_auth: cli_auth = AzureCliAuthentication() else: cli_auth = None", "ReinforcementLearningEstimator, Ray from azureml.contrib.train.rl import WorkerConfiguration from azureml_util import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from", ".decode(\"ASCII\") .strip() ) print(\"Docker tag\", docker_tag) env = Environment(\"my_ray_env\") # ws.register(env) - no,", "GPUs (\"--force_gpu\", \"\"), ] ), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600, # How long to", "anything to save the outputs (PNGs or events.json) experiment = Experiment(ws, args.scenario) run", "\"--body_cluster\", type=str, default=\"ray-p40\", help=\"Name of the worker cluster\", ) parser.add_argument( \"--num_workers\", type=int, default=10,", "can be seen by \"pip install ray==0.8.7; ray start --head\". (\"--redis_token\", \"<PASSWORD>\"), #", "run without dependencies from rlo.flags import make_config_for_scenario from ray_main import ray_run_arguments if not", "] + additional_args # Check arguments are valid if args.check_params: check_params(args.scenario, params) if", "outputs (PNGs or events.json) experiment = Experiment(ws, args.scenario) run = experiment.submit(config=est) print(run) print(\"Run", "ws = Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute = ws.compute_targets[args.head_cluster] body_compute = ws.compute_targets[args.body_cluster] env = get_environment()", "type=str, default=\"ray-head\", help=\"Name of the headnode cluster\", ) parser.add_argument( \"--body_cluster\", type=str, default=\"ray-p40\", help=\"Name", "import ray_run_arguments if not os.path.isfile(scenario): scenario = os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments, cmdline=params)", "This can be seen by \"pip install ray==0.8.7; ray start --head\". (\"--redis_token\", \"<PASSWORD>\"),", "_for_the_duration_of_the_run_ not just when it starts, or the run will fail to complete.", "GPU required, the head is expected to be only a co-ordinator. est =", "= None ws = Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute = ws.compute_targets[args.head_cluster] body_compute = ws.compute_targets[args.body_cluster] env", "= Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute = ws.compute_targets[args.head_cluster] body_compute = ws.compute_targets[args.body_cluster] env = get_environment() #", "(not recommended) temporarily elevate yourself to Contributor using Azure Privileged Identity Management (PIM),", "= next( f for f in head_run.get_file_names() if f.endswith(\"best_episodes.kso\") ) with NamedTemporaryFile(mode=\"r\") as", "access to the resource group (knossosamlrg). You can (not recommended) temporarily elevate yourself", "nodes\", ) parser.add_argument( \"--enable_cli_auth\", action=\"store_true\", help=\"Enable AzureCliAuthentication (for CI)\", ) parser.add_argument( \"--wait_for_completion\", action=\"store_true\",", "subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip() ) print(\"Docker tag\", docker_tag) env = Environment(\"my_ray_env\") # ws.register(env)", "Privileged Identity Management (PIM), but you will need to have said level of", "args.scenario) run = experiment.submit(config=est) print(run) print(\"Run submitted!\", run.get_portal_url()) if args.wait_for_completion: run.wait_for_completion() # Check", ") print(\"Found no NaNs!\") def main(): parser = argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str, help=\"Scenario to", "\"--head_cluster\", type=str, default=\"ray-head\", help=\"Name of the headnode cluster\", ) parser.add_argument( \"--body_cluster\", type=str, default=\"ray-p40\",", "NaN in best_episodes.kso check_best_episodes(run) print(\"Run succeeded!\") print( \"Download from container azureml path ExperimentRun/dcid.{run_id}/outputs\"", "head is expected to be only a co-ordinator. est = ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute,", "the Azure ML config file\", ) parser.add_argument( \"--head_cluster\", type=str, default=\"ray-head\", help=\"Name of the", "parser.add_argument( \"--head_cluster\", type=str, default=\"ray-head\", help=\"Name of the headnode cluster\", ) parser.add_argument( \"--body_cluster\", type=str,", "= next(rn for rn in run.get_children() if rn.id.endswith(\"_head\")) kso_file = next( f for", "(knossosamlrg). You can (not recommended) temporarily elevate yourself to Contributor using Azure Privileged", "Azure ML config file\", ) parser.add_argument( \"--head_cluster\", type=str, default=\"ray-head\", help=\"Name of the headnode", "co-ordinator. est = ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute, environment=env, entry_script=\"ray_main.py\", script_params=dict( [(p, \"\") for p", "in best_episodes.kso check_best_episodes(run) print(\"Run succeeded!\") print( \"Download from container azureml path ExperimentRun/dcid.{run_id}/outputs\" )", "process run by the AzureML RL framework seems to default to this. #", "# of the shared memory available from the host OS. shm_size=24 * 1024", "to be only a co-ordinator. est = ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute, environment=env, entry_script=\"ray_main.py\", script_params=dict(", "= WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers, use_gpu=True, environment=env, ) with combined_source_directory() as source_dir: # This", "temporarily elevate yourself to Owner using PIM, and give yourself permanent Contributor rights", "NamedTemporaryFile from azureml.core import Workspace, Experiment, Environment from azureml.core.authentication import AzureCliAuthentication from azureml.pipeline.core", "run.id) child_ids = [child_run.id for child_run in pipeline_run.get_steps()] print([id for id in child_ids", "as f: head_run.download_file(kso_file, output_file_path=f.name) content = f.read() print(f\"Downloaded {kso_file} (length={len(content)})\") if \"NaN\" in", "no, let's not env.docker.base_image = \"rlo_linux_base:\" + docker_tag env.docker.base_image_registry.address = \"knossos.azurecr.io\" env.docker.base_image_registry.password =", "the estimator, but doesn't do anything to save the outputs (PNGs or events.json)", "type=str, default=\"ray-p40\", help=\"Name of the worker cluster\", ) parser.add_argument( \"--num_workers\", type=int, default=10, help=\"Number", "git_utils def get_environment(): print(\"Getting docker password...\") password = ( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip()", "need to have said level of access _for_the_duration_of_the_run_ not just when it starts,", "not contain NaNs Regression test for #1438 \"\"\" head_run = next(rn for rn", "Specify the Ray worker configuration worker_conf = WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers, use_gpu=True, environment=env, )", "group. 2. Install dependencies (better to do it in an isolated conda environment", "seen by \"pip install ray==0.8.7; ray start --head\". (\"--redis_token\", \"<PASSWORD>\"), # Ensure workers", "# How long to wait for whole cluster to start max_run_duration_seconds=40 * 3600,", "= Experiment(ws, args.scenario) run = experiment.submit(config=est) print(run) print(\"Run submitted!\", run.get_portal_url()) if args.wait_for_completion: run.wait_for_completion()", "experiment.submit(config=est) print(run) print(\"Run submitted!\", run.get_portal_url()) if args.wait_for_completion: run.wait_for_completion() # Check no NaN in", "run will fail to complete. Alternatively (recommended), you can temporarily elevate yourself to", "if f.endswith(\"best_episodes.kso\") ) with NamedTemporaryFile(mode=\"r\") as f: head_run.download_file(kso_file, output_file_path=f.name) content = f.read() print(f\"Downloaded", "worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600, # How long to wait for whole cluster to start", "container Ray runs in to make full use # of the shared memory", "PIM, and give yourself permanent Contributor rights to the knossosaml resource group. 2.", "args.scenario, \"--run_id\", run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(), ] + additional_args # Check arguments are valid", "child_run in pipeline_run.get_steps()] print([id for id in child_ids if \"head\" in id]) if", "3600, # Allow the docker container Ray runs in to make full use", "the worker cluster\", ) parser.add_argument( \"--num_workers\", type=int, default=10, help=\"Number of worker nodes\", )", "if args.enable_cli_auth: cli_auth = AzureCliAuthentication() else: cli_auth = None ws = Workspace.from_config(args.aml_config_file, auth=cli_auth)", "run `fewer_simplify_rules` scenario ``` python scripts/azureml_ray.py fewer_simplify_rules --num_workers=2 ``` Note: any additional arguments", "because it may clash) ``` pip install -r test/builds/ci-requirements.txt ``` 3. Try to", "help=\"Path to the Azure ML config file\", ) parser.add_argument( \"--head_cluster\", type=str, default=\"ray-head\", help=\"Name", "for the completion of the run\", ) parser.add_argument( \"--no-check-params\", action=\"store_false\", dest=\"check_params\", help=\"Don't check", "Check no NaN in best_episodes.kso check_best_episodes(run) print(\"Run succeeded!\") print( \"Download from container azureml", "additional arguments will be passed to `ray_main.py`. \"\"\" import argparse from datetime import", "configuration worker_conf = WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers, use_gpu=True, environment=env, ) with combined_source_directory() as source_dir:", "sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from rlo import git_utils def get_environment(): print(\"Getting docker password...\") password =", "shared memory available from the host OS. shm_size=24 * 1024 * 1024 *", "the ID of the head step:\") pipeline_run = PipelineRun(experiment, run.id) child_ids = [child_run.id", "= ( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip() ) print(\"Docker tag\", docker_tag) env = Environment(\"my_ray_env\")", "Identity Management (PIM), but you will need to have said level of access", "fewer_simplify_rules --num_workers=2 ``` Note: any additional arguments will be passed to `ray_main.py`. \"\"\"", "Reinforcement Learning imports from azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray from azureml.contrib.train.rl import WorkerConfiguration from", "run.get_portal_url()) if args.wait_for_completion: run.wait_for_completion() # Check no NaN in best_episodes.kso check_best_episodes(run) print(\"Run succeeded!\")", "CI)\", ) parser.add_argument( \"--wait_for_completion\", action=\"store_true\", help=\"Wait for the completion of the run\", )", "\"../src\")) from rlo import git_utils def get_environment(): print(\"Getting docker password...\") password = (", "sys from tempfile import NamedTemporaryFile from azureml.core import Workspace, Experiment, Environment from azureml.core.authentication", "runs in to make full use # of the shared memory available from", "the head is expected to be only a co-ordinator. est = ReinforcementLearningEstimator( source_directory=source_dir,", "\"\"\" import argparse from datetime import datetime import os import subprocess import sys", "import NamedTemporaryFile from azureml.core import Workspace, Experiment, Environment from azureml.core.authentication import AzureCliAuthentication from", "sure you have access to the knossos Azure subscription. > az login >", "get_environment() # Specify the Ray worker configuration worker_conf = WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers, use_gpu=True,", "path ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note: run_id is the ID of the head step:\") pipeline_run", "main(): parser = argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str, help=\"Scenario to run\") parser.add_argument( \"--aml_config_file\", type=str, default=\"aml_config.json\",", "print(\"Docker tag\", docker_tag) env = Environment(\"my_ray_env\") # ws.register(env) - no, let's not env.docker.base_image", "full use # of the shared memory available from the host OS. shm_size=24", "2. Install dependencies (better to do it in an isolated conda environment because", "conda environment because it may clash) ``` pip install -r test/builds/ci-requirements.txt ``` 3.", "azureml.core import Workspace, Experiment, Environment from azureml.core.authentication import AzureCliAuthentication from azureml.pipeline.core import PipelineRun", "experiment = Experiment(ws, args.scenario) run = experiment.submit(config=est) print(run) print(\"Run submitted!\", run.get_portal_url()) if args.wait_for_completion:", "make_config_for_scenario from ray_main import ray_run_arguments if not os.path.isfile(scenario): scenario = os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\")", "the resource group (knossosamlrg). You can (not recommended) temporarily elevate yourself to Contributor", "= argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str, help=\"Scenario to run\") parser.add_argument( \"--aml_config_file\", type=str, default=\"aml_config.json\", help=\"Path to", "the outputs (PNGs or events.json) experiment = Experiment(ws, args.scenario) run = experiment.submit(config=est) print(run)", "set -s Knossos You'll need to have at least Contributor access to the", "parser = argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str, help=\"Scenario to run\") parser.add_argument( \"--aml_config_file\", type=str, default=\"aml_config.json\", help=\"Path", "parameters are valid locally before submission\", ) args, additional_args = parser.parse_known_args() run_id =", "``` Note: any additional arguments will be passed to `ray_main.py`. \"\"\" import argparse", "to complete. Alternatively (recommended), you can temporarily elevate yourself to Owner using PIM,", "docker_tag env.docker.base_image_registry.address = \"knossos.azurecr.io\" env.docker.base_image_registry.password = password env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies = True", "if not os.path.isfile(scenario): scenario = os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments, cmdline=params) def check_best_episodes(run):", "docker_tag = ( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip() ) print(\"Docker tag\", docker_tag) env =", "an isolated conda environment because it may clash) ``` pip install -r test/builds/ci-requirements.txt", "of the headnode cluster\", ) parser.add_argument( \"--body_cluster\", type=str, default=\"ray-p40\", help=\"Name of the worker", "check_best_episodes(run) print(\"Run succeeded!\") print( \"Download from container azureml path ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note: run_id", "the AzureML RL framework seems to default to this. # This can be", "auth=cli_auth) head_compute = ws.compute_targets[args.head_cluster] body_compute = ws.compute_targets[args.body_cluster] env = get_environment() # Specify the", "\"NaN\" in line] raise ValueError( \"Expected no NaNs, but found the following lines:\\n\"", "env = get_environment() # Specify the Ray worker configuration worker_conf = WorkerConfiguration( compute_target=body_compute,", "ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute, environment=env, entry_script=\"ray_main.py\", script_params=dict( [(p, \"\") for p in params] +", "to default to this. # This can be seen by \"pip install ray==0.8.7;", "= password env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies = True return env def check_params(scenario, params):", "1024 * 1024 * 1024, ) # This runs the estimator, but doesn't", "default to this. # This can be seen by \"pip install ray==0.8.7; ray", "from azureml.contrib.train.rl import WorkerConfiguration from azureml_util import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from rlo import", "contain NaNs Regression test for #1438 \"\"\" head_run = next(rn for rn in", "print(\"Run succeeded!\") print( \"Download from container azureml path ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note: run_id is", "import WorkerConfiguration from azureml_util import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from rlo import git_utils def", "is expected to be only a co-ordinator. est = ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute, environment=env,", "= \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies = True return env def check_params(scenario, params): # import locally", "Try to run `fewer_simplify_rules` scenario ``` python scripts/azureml_ray.py fewer_simplify_rules --num_workers=2 ``` Note: any", "expected to be only a co-ordinator. est = ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute, environment=env, entry_script=\"ray_main.py\",", "but doesn't do anything to save the outputs (PNGs or events.json) experiment =", "of the worker cluster\", ) parser.add_argument( \"--num_workers\", type=int, default=10, help=\"Number of worker nodes\",", "in content: lines = [line for line in content.split(\"\\n\") if \"NaN\" in line]", "than start its own (\"--address\", \"auto\"), # The command-line ray process run by", "type=int, default=10, help=\"Number of worker nodes\", ) parser.add_argument( \"--enable_cli_auth\", action=\"store_true\", help=\"Enable AzureCliAuthentication (for", "azureml.core.authentication import AzureCliAuthentication from azureml.pipeline.core import PipelineRun # Azure ML Reinforcement Learning imports", "ID of the head step:\") pipeline_run = PipelineRun(experiment, run.id) child_ids = [child_run.id for", "and give yourself permanent Contributor rights to the knossosaml resource group. 2. Install", "Regression test for #1438 \"\"\" head_run = next(rn for rn in run.get_children() if", "rights to the knossosaml resource group. 2. Install dependencies (better to do it", "yourself to Contributor using Azure Privileged Identity Management (PIM), but you will need", "to an existing Ray/redis server rather than start its own (\"--address\", \"auto\"), #", "# ws.register(env) - no, let's not env.docker.base_image = \"rlo_linux_base:\" + docker_tag env.docker.base_image_registry.address =", "Checks best_episodes.kso file does not contain NaNs Regression test for #1438 \"\"\" head_run", "Ray/redis server rather than start its own (\"--address\", \"auto\"), # The command-line ray", "shm_size=24 * 1024 * 1024 * 1024, ) # This runs the estimator,", "parser.add_argument( \"--body_cluster\", type=str, default=\"ray-p40\", help=\"Name of the worker cluster\", ) parser.add_argument( \"--num_workers\", type=int,", "lines = [line for line in content.split(\"\\n\") if \"NaN\" in line] raise ValueError(", "in pipeline_run.get_steps()] print([id for id in child_ids if \"head\" in id]) if __name__", "instructions: 1. Make sure you have access to the knossos Azure subscription. >", "print(\"Note: run_id is the ID of the head step:\") pipeline_run = PipelineRun(experiment, run.id)", "environment because it may clash) ``` pip install -r test/builds/ci-requirements.txt ``` 3. Try", "you will need to have said level of access _for_the_duration_of_the_run_ not just when", "arguments will be passed to `ray_main.py`. \"\"\" import argparse from datetime import datetime", "as source_dir: # This defines the head configuration - note, no GPU required,", "= \"knossos.azurecr.io\" env.docker.base_image_registry.password = password env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies = True return env", "WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers, use_gpu=True, environment=env, ) with combined_source_directory() as source_dir: # This defines", "ray==0.8.7; ray start --head\". (\"--redis_token\", \"<PASSWORD>\"), # Ensure workers are using GPUs (\"--force_gpu\",", "least Contributor access to the resource group (knossosamlrg). You can (not recommended) temporarily", "rn.id.endswith(\"_head\")) kso_file = next( f for f in head_run.get_file_names() if f.endswith(\"best_episodes.kso\") ) with", "--head\". (\"--redis_token\", \"<PASSWORD>\"), # Ensure workers are using GPUs (\"--force_gpu\", \"\"), ] ),", "\"\"\" head_run = next(rn for rn in run.get_children() if rn.id.endswith(\"_head\")) kso_file = next(", "Experiment, Environment from azureml.core.authentication import AzureCliAuthentication from azureml.pipeline.core import PipelineRun # Azure ML", "default=10, help=\"Number of worker nodes\", ) parser.add_argument( \"--enable_cli_auth\", action=\"store_true\", help=\"Enable AzureCliAuthentication (for CI)\",", "login > az account set -s Knossos You'll need to have at least", ") parser.add_argument( \"--body_cluster\", type=str, default=\"ray-p40\", help=\"Name of the worker cluster\", ) parser.add_argument( \"--num_workers\",", "(PNGs or events.json) experiment = Experiment(ws, args.scenario) run = experiment.submit(config=est) print(run) print(\"Run submitted!\",", "args.wait_for_completion: run.wait_for_completion() # Check no NaN in best_episodes.kso check_best_episodes(run) print(\"Run succeeded!\") print( \"Download", "to the Azure ML config file\", ) parser.add_argument( \"--head_cluster\", type=str, default=\"ray-head\", help=\"Name of", "run.wait_for_completion() # Check no NaN in best_episodes.kso check_best_episodes(run) print(\"Run succeeded!\") print( \"Download from", "-r test/builds/ci-requirements.txt ``` 3. Try to run `fewer_simplify_rules` scenario ``` python scripts/azureml_ray.py fewer_simplify_rules", "this. # This can be seen by \"pip install ray==0.8.7; ray start --head\".", "from datetime import datetime import os import subprocess import sys from tempfile import", "the parameters are valid locally before submission\", ) args, additional_args = parser.parse_known_args() run_id", "azureml.pipeline.core import PipelineRun # Azure ML Reinforcement Learning imports from azureml.contrib.train.rl import ReinforcementLearningEstimator,", ") # This runs the estimator, but doesn't do anything to save the", "recommended) temporarily elevate yourself to Contributor using Azure Privileged Identity Management (PIM), but", "of the shared memory available from the host OS. shm_size=24 * 1024 *", "default=\"aml_config.json\", help=\"Path to the Azure ML config file\", ) parser.add_argument( \"--head_cluster\", type=str, default=\"ray-head\",", "( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip() ) print(\"Docker tag\", docker_tag) env = Environment(\"my_ray_env\") #", "submitted!\", run.get_portal_url()) if args.wait_for_completion: run.wait_for_completion() # Check no NaN in best_episodes.kso check_best_episodes(run) print(\"Run", "password = ( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip() ) docker_tag = ( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"])", "yourself permanent Contributor rights to the knossosaml resource group. 2. Install dependencies (better", "type=str, default=\"aml_config.json\", help=\"Path to the Azure ML config file\", ) parser.add_argument( \"--head_cluster\", type=str,", "Alternatively (recommended), you can temporarily elevate yourself to Owner using PIM, and give", "run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params = [ args.scenario, \"--run_id\", run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(), ]", "def check_params(scenario, params): # import locally so that CI can run without dependencies", "knossosaml resource group. 2. Install dependencies (better to do it in an isolated", "from tempfile import NamedTemporaryFile from azureml.core import Workspace, Experiment, Environment from azureml.core.authentication import", "file\", ) parser.add_argument( \"--head_cluster\", type=str, default=\"ray-head\", help=\"Name of the headnode cluster\", ) parser.add_argument(", "compute_target=body_compute, node_count=args.num_workers, use_gpu=True, environment=env, ) with combined_source_directory() as source_dir: # This defines the", "Ray runs in to make full use # of the shared memory available", "This runs the estimator, but doesn't do anything to save the outputs (PNGs", "events.json) experiment = Experiment(ws, args.scenario) run = experiment.submit(config=est) print(run) print(\"Run submitted!\", run.get_portal_url()) if", "from azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray from azureml.contrib.train.rl import WorkerConfiguration from azureml_util import combined_source_directory", "\"\"), ] ), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600, # How long to wait for", "\"--num_workers\", type=int, default=10, help=\"Number of worker nodes\", ) parser.add_argument( \"--enable_cli_auth\", action=\"store_true\", help=\"Enable AzureCliAuthentication", "parser.add_argument( \"--wait_for_completion\", action=\"store_true\", help=\"Wait for the completion of the run\", ) parser.add_argument( \"--no-check-params\",", "head_run = next(rn for rn in run.get_children() if rn.id.endswith(\"_head\")) kso_file = next( f", "* 1024 * 1024 * 1024, ) # This runs the estimator, but", "args.scenario) params = [ args.scenario, \"--run_id\", run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(), ] + additional_args #", "password...\") password = ( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip() ) docker_tag = ( subprocess.check_output([\"bash\",", "Ray from azureml.contrib.train.rl import WorkerConfiguration from azureml_util import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from rlo", "doesn't do anything to save the outputs (PNGs or events.json) experiment = Experiment(ws,", "[line for line in content.split(\"\\n\") if \"NaN\" in line] raise ValueError( \"Expected no", "docker password...\") password = ( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip() ) docker_tag = (", "start --head\". (\"--redis_token\", \"<PASSWORD>\"), # Ensure workers are using GPUs (\"--force_gpu\", \"\"), ]", "connect to an existing Ray/redis server rather than start its own (\"--address\", \"auto\"),", "compute_target=head_compute, environment=env, entry_script=\"ray_main.py\", script_params=dict( [(p, \"\") for p in params] + [ #", "import datetime import os import subprocess import sys from tempfile import NamedTemporaryFile from", "rlo import git_utils def get_environment(): print(\"Getting docker password...\") password = ( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"])", "using Azure Privileged Identity Management (PIM), but you will need to have said", "defines the head configuration - note, no GPU required, the head is expected", "args, additional_args = parser.parse_known_args() run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params = [ args.scenario, \"--run_id\",", "cli_auth = AzureCliAuthentication() else: cli_auth = None ws = Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute =", "AzureCliAuthentication() else: cli_auth = None ws = Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute = ws.compute_targets[args.head_cluster] body_compute", "from the host OS. shm_size=24 * 1024 * 1024 * 1024, ) #", "import Workspace, Experiment, Environment from azureml.core.authentication import AzureCliAuthentication from azureml.pipeline.core import PipelineRun #", "the docker container Ray runs in to make full use # of the", "have access to the knossos Azure subscription. > az login > az account", "dest=\"check_params\", help=\"Don't check if the parameters are valid locally before submission\", ) args,", "ray_main.py to connect to an existing Ray/redis server rather than start its own", "no NaNs!\") def main(): parser = argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str, help=\"Scenario to run\") parser.add_argument(", "content.split(\"\\n\") if \"NaN\" in line] raise ValueError( \"Expected no NaNs, but found the", "at least Contributor access to the resource group (knossosamlrg). You can (not recommended)", "content = f.read() print(f\"Downloaded {kso_file} (length={len(content)})\") if \"NaN\" in content: lines = [line", "to do it in an isolated conda environment because it may clash) ```", "so that CI can run without dependencies from rlo.flags import make_config_for_scenario from ray_main", ".strip() ) docker_tag = ( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip() ) print(\"Docker tag\", docker_tag)", "This tells ray_main.py to connect to an existing Ray/redis server rather than start", "\"--aml_config_file\", type=str, default=\"aml_config.json\", help=\"Path to the Azure ML config file\", ) parser.add_argument( \"--head_cluster\",", "( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip() ) docker_tag = ( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip()", "help=\"Wait for the completion of the run\", ) parser.add_argument( \"--no-check-params\", action=\"store_false\", dest=\"check_params\", help=\"Don't", "env def check_params(scenario, params): # import locally so that CI can run without", "Knossos You'll need to have at least Contributor access to the resource group", "arguments are valid if args.check_params: check_params(args.scenario, params) if args.enable_cli_auth: cli_auth = AzureCliAuthentication() else:", "\"rlo_linux_base:\" + docker_tag env.docker.base_image_registry.address = \"knossos.azurecr.io\" env.docker.base_image_registry.password = password env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies", "scenario = os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments, cmdline=params) def check_best_episodes(run): \"\"\" Checks best_episodes.kso", "make_config_for_scenario(scenario, ray_run_arguments, cmdline=params) def check_best_episodes(run): \"\"\" Checks best_episodes.kso file does not contain NaNs", "``` 3. Try to run `fewer_simplify_rules` scenario ``` python scripts/azureml_ray.py fewer_simplify_rules --num_workers=2 ```", "by \"pip install ray==0.8.7; ray start --head\". (\"--redis_token\", \"<PASSWORD>\"), # Ensure workers are", "ws.register(env) - no, let's not env.docker.base_image = \"rlo_linux_base:\" + docker_tag env.docker.base_image_registry.address = \"knossos.azurecr.io\"", "= ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute, environment=env, entry_script=\"ray_main.py\", script_params=dict( [(p, \"\") for p in params]", "have said level of access _for_the_duration_of_the_run_ not just when it starts, or the", "may clash) ``` pip install -r test/builds/ci-requirements.txt ``` 3. Try to run `fewer_simplify_rules`", "next( f for f in head_run.get_file_names() if f.endswith(\"best_episodes.kso\") ) with NamedTemporaryFile(mode=\"r\") as f:", "isolated conda environment because it may clash) ``` pip install -r test/builds/ci-requirements.txt ```", "of the run\", ) parser.add_argument( \"--no-check-params\", action=\"store_false\", dest=\"check_params\", help=\"Don't check if the parameters", "the head step:\") pipeline_run = PipelineRun(experiment, run.id) child_ids = [child_run.id for child_run in", "step:\") pipeline_run = PipelineRun(experiment, run.id) child_ids = [child_run.id for child_run in pipeline_run.get_steps()] print([id", "argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str, help=\"Scenario to run\") parser.add_argument( \"--aml_config_file\", type=str, default=\"aml_config.json\", help=\"Path to the", "\"--gitlog\", git_utils.get_git_revision_short_hash(), ] + additional_args # Check arguments are valid if args.check_params: check_params(args.scenario,", "(PIM), but you will need to have said level of access _for_the_duration_of_the_run_ not", "best_episodes.kso check_best_episodes(run) print(\"Run succeeded!\") print( \"Download from container azureml path ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note:", "lines:\\n\" + \"\\n\".join(lines) ) print(\"Found no NaNs!\") def main(): parser = argparse.ArgumentParser() parser.add_argument(\"scenario\",", "- note, no GPU required, the head is expected to be only a", "host OS. shm_size=24 * 1024 * 1024 * 1024, ) # This runs", "before submission\", ) args, additional_args = parser.parse_known_args() run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params =", "# This runs the estimator, but doesn't do anything to save the outputs", "the shared memory available from the host OS. shm_size=24 * 1024 * 1024", "import git_utils def get_environment(): print(\"Getting docker password...\") password = ( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\")", "permanent Contributor rights to the knossosaml resource group. 2. Install dependencies (better to", "start instructions: 1. Make sure you have access to the knossos Azure subscription.", "(length={len(content)})\") if \"NaN\" in content: lines = [line for line in content.split(\"\\n\") if", "\"\") for p in params] + [ # This tells ray_main.py to connect", "locally so that CI can run without dependencies from rlo.flags import make_config_for_scenario from", "long to wait for whole cluster to start max_run_duration_seconds=40 * 3600, # Allow", "python scripts/azureml_ray.py fewer_simplify_rules --num_workers=2 ``` Note: any additional arguments will be passed to", "in line] raise ValueError( \"Expected no NaNs, but found the following lines:\\n\" +", "with NamedTemporaryFile(mode=\"r\") as f: head_run.download_file(kso_file, output_file_path=f.name) content = f.read() print(f\"Downloaded {kso_file} (length={len(content)})\") if", "\"NaN\" in content: lines = [line for line in content.split(\"\\n\") if \"NaN\" in", "params = [ args.scenario, \"--run_id\", run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(), ] + additional_args # Check", "be only a co-ordinator. est = ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute, environment=env, entry_script=\"ray_main.py\", script_params=dict( [(p,", "account set -s Knossos You'll need to have at least Contributor access to", "# This defines the head configuration - note, no GPU required, the head", "Environment from azureml.core.authentication import AzureCliAuthentication from azureml.pipeline.core import PipelineRun # Azure ML Reinforcement", "pipeline_run = PipelineRun(experiment, run.id) child_ids = [child_run.id for child_run in pipeline_run.get_steps()] print([id for", "get_environment(): print(\"Getting docker password...\") password = ( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip() ) docker_tag", "run\", ) parser.add_argument( \"--no-check-params\", action=\"store_false\", dest=\"check_params\", help=\"Don't check if the parameters are valid", "cluster\", ) parser.add_argument( \"--num_workers\", type=int, default=10, help=\"Number of worker nodes\", ) parser.add_argument( \"--enable_cli_auth\",", "print(\"Run submitted!\", run.get_portal_url()) if args.wait_for_completion: run.wait_for_completion() # Check no NaN in best_episodes.kso check_best_episodes(run)", "check_params(scenario, params): # import locally so that CI can run without dependencies from", "run.get_children() if rn.id.endswith(\"_head\")) kso_file = next( f for f in head_run.get_file_names() if f.endswith(\"best_episodes.kso\")", "is the ID of the head step:\") pipeline_run = PipelineRun(experiment, run.id) child_ids =", "valid if args.check_params: check_params(args.scenario, params) if args.enable_cli_auth: cli_auth = AzureCliAuthentication() else: cli_auth =", "(recommended), you can temporarily elevate yourself to Owner using PIM, and give yourself", "by the AzureML RL framework seems to default to this. # This can", "# Azure ML Reinforcement Learning imports from azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray from azureml.contrib.train.rl", "the following lines:\\n\" + \"\\n\".join(lines) ) print(\"Found no NaNs!\") def main(): parser =", "to save the outputs (PNGs or events.json) experiment = Experiment(ws, args.scenario) run =", "subscription. > az login > az account set -s Knossos You'll need to", "env.docker.base_image = \"rlo_linux_base:\" + docker_tag env.docker.base_image_registry.address = \"knossos.azurecr.io\" env.docker.base_image_registry.password = password env.docker.base_image_registry.username =", "`fewer_simplify_rules` scenario ``` python scripts/azureml_ray.py fewer_simplify_rules --num_workers=2 ``` Note: any additional arguments will", "print([id for id in child_ids if \"head\" in id]) if __name__ == \"__main__\":", "\"--no-check-params\", action=\"store_false\", dest=\"check_params\", help=\"Don't check if the parameters are valid locally before submission\",", "cluster to start max_run_duration_seconds=40 * 3600, # Allow the docker container Ray runs", "valid locally before submission\", ) args, additional_args = parser.parse_known_args() run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario)", "# This can be seen by \"pip install ray==0.8.7; ray start --head\". (\"--redis_token\",", "scenario ``` python scripts/azureml_ray.py fewer_simplify_rules --num_workers=2 ``` Note: any additional arguments will be", "dependencies from rlo.flags import make_config_for_scenario from ray_main import ray_run_arguments if not os.path.isfile(scenario): scenario", "env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies = True return env def check_params(scenario, params): # import", "to start max_run_duration_seconds=40 * 3600, # Allow the docker container Ray runs in", "print(f\"Downloaded {kso_file} (length={len(content)})\") if \"NaN\" in content: lines = [line for line in", "elevate yourself to Contributor using Azure Privileged Identity Management (PIM), but you will", "using PIM, and give yourself permanent Contributor rights to the knossosaml resource group.", "subprocess import sys from tempfile import NamedTemporaryFile from azureml.core import Workspace, Experiment, Environment", "PipelineRun(experiment, run.id) child_ids = [child_run.id for child_run in pipeline_run.get_steps()] print([id for id in", "params) if args.enable_cli_auth: cli_auth = AzureCliAuthentication() else: cli_auth = None ws = Workspace.from_config(args.aml_config_file,", "scripts/azureml_ray.py fewer_simplify_rules --num_workers=2 ``` Note: any additional arguments will be passed to `ray_main.py`.", "help=\"Scenario to run\") parser.add_argument( \"--aml_config_file\", type=str, default=\"aml_config.json\", help=\"Path to the Azure ML config", "level of access _for_the_duration_of_the_run_ not just when it starts, or the run will", "can (not recommended) temporarily elevate yourself to Contributor using Azure Privileged Identity Management", "docker_tag) env = Environment(\"my_ray_env\") # ws.register(env) - no, let's not env.docker.base_image = \"rlo_linux_base:\"", "WorkerConfiguration from azureml_util import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from rlo import git_utils def get_environment():", "Environment(\"my_ray_env\") # ws.register(env) - no, let's not env.docker.base_image = \"rlo_linux_base:\" + docker_tag env.docker.base_image_registry.address", "give yourself permanent Contributor rights to the knossosaml resource group. 2. Install dependencies", "azureml_util import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from rlo import git_utils def get_environment(): print(\"Getting docker", "from azureml_util import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from rlo import git_utils def get_environment(): print(\"Getting", "[(p, \"\") for p in params] + [ # This tells ray_main.py to", "worker configuration worker_conf = WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers, use_gpu=True, environment=env, ) with combined_source_directory() as", "Allow the docker container Ray runs in to make full use # of", "= \"rlo_linux_base:\" + docker_tag env.docker.base_image_registry.address = \"knossos.azurecr.io\" env.docker.base_image_registry.password = password env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\"", "\"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments, cmdline=params) def check_best_episodes(run): \"\"\" Checks best_episodes.kso file does not", ") parser.add_argument( \"--no-check-params\", action=\"store_false\", dest=\"check_params\", help=\"Don't check if the parameters are valid locally", "check if the parameters are valid locally before submission\", ) args, additional_args =", "for child_run in pipeline_run.get_steps()] print([id for id in child_ids if \"head\" in id])", "you have access to the knossos Azure subscription. > az login > az", "elevate yourself to Owner using PIM, and give yourself permanent Contributor rights to", "parser.add_argument(\"scenario\", type=str, help=\"Scenario to run\") parser.add_argument( \"--aml_config_file\", type=str, default=\"aml_config.json\", help=\"Path to the Azure", "\"<PASSWORD>\"), # Ensure workers are using GPUs (\"--force_gpu\", \"\"), ] ), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf,", "line] raise ValueError( \"Expected no NaNs, but found the following lines:\\n\" + \"\\n\".join(lines)", "configuration - note, no GPU required, the head is expected to be only", "cmdline=params) def check_best_episodes(run): \"\"\" Checks best_episodes.kso file does not contain NaNs Regression test", "its own (\"--address\", \"auto\"), # The command-line ray process run by the AzureML", "\"Download from container azureml path ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note: run_id is the ID of", "container azureml path ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note: run_id is the ID of the head", "ValueError( \"Expected no NaNs, but found the following lines:\\n\" + \"\\n\".join(lines) ) print(\"Found", "parser.add_argument( \"--num_workers\", type=int, default=10, help=\"Number of worker nodes\", ) parser.add_argument( \"--enable_cli_auth\", action=\"store_true\", help=\"Enable", ") parser.add_argument( \"--enable_cli_auth\", action=\"store_true\", help=\"Enable AzureCliAuthentication (for CI)\", ) parser.add_argument( \"--wait_for_completion\", action=\"store_true\", help=\"Wait", "to `ray_main.py`. \"\"\" import argparse from datetime import datetime import os import subprocess", "AzureML RL framework seems to default to this. # This can be seen", "from rlo import git_utils def get_environment(): print(\"Getting docker password...\") password = ( subprocess.check_output([\"bash\",", "env = Environment(\"my_ray_env\") # ws.register(env) - no, let's not env.docker.base_image = \"rlo_linux_base:\" +", "NaNs!\") def main(): parser = argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str, help=\"Scenario to run\") parser.add_argument( \"--aml_config_file\",", "said level of access _for_the_duration_of_the_run_ not just when it starts, or the run", "default=\"ray-p40\", help=\"Name of the worker cluster\", ) parser.add_argument( \"--num_workers\", type=int, default=10, help=\"Number of", "an existing Ray/redis server rather than start its own (\"--address\", \"auto\"), # The", "dependencies (better to do it in an isolated conda environment because it may", "RL framework seems to default to this. # This can be seen by", ".strip() ) print(\"Docker tag\", docker_tag) env = Environment(\"my_ray_env\") # ws.register(env) - no, let's", "args.check_params: check_params(args.scenario, params) if args.enable_cli_auth: cli_auth = AzureCliAuthentication() else: cli_auth = None ws", "env.docker.base_image_registry.address = \"knossos.azurecr.io\" env.docker.base_image_registry.password = password env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies = True return", "just when it starts, or the run will fail to complete. Alternatively (recommended),", "import sys from tempfile import NamedTemporaryFile from azureml.core import Workspace, Experiment, Environment from", "check_best_episodes(run): \"\"\" Checks best_episodes.kso file does not contain NaNs Regression test for #1438", "raise ValueError( \"Expected no NaNs, but found the following lines:\\n\" + \"\\n\".join(lines) )", "cluster_coordination_timeout_seconds=3600, # How long to wait for whole cluster to start max_run_duration_seconds=40 *", "it in an isolated conda environment because it may clash) ``` pip install", "NaNs Regression test for #1438 \"\"\" head_run = next(rn for rn in run.get_children()", "knossos Azure subscription. > az login > az account set -s Knossos You'll", "for #1438 \"\"\" head_run = next(rn for rn in run.get_children() if rn.id.endswith(\"_head\")) kso_file", ") print(\"Note: run_id is the ID of the head step:\") pipeline_run = PipelineRun(experiment,", "azureml path ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note: run_id is the ID of the head step:\")", "run_id is the ID of the head step:\") pipeline_run = PipelineRun(experiment, run.id) child_ids", "start its own (\"--address\", \"auto\"), # The command-line ray process run by the", "Ensure workers are using GPUs (\"--force_gpu\", \"\"), ] ), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600,", "to have said level of access _for_the_duration_of_the_run_ not just when it starts, or", "# The command-line ray process run by the AzureML RL framework seems to", "ray start --head\". (\"--redis_token\", \"<PASSWORD>\"), # Ensure workers are using GPUs (\"--force_gpu\", \"\"),", "#1438 \"\"\" head_run = next(rn for rn in run.get_children() if rn.id.endswith(\"_head\")) kso_file =", "content: lines = [line for line in content.split(\"\\n\") if \"NaN\" in line] raise", "complete. Alternatively (recommended), you can temporarily elevate yourself to Owner using PIM, and", "None ws = Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute = ws.compute_targets[args.head_cluster] body_compute = ws.compute_targets[args.body_cluster] env =", "# Ensure workers are using GPUs (\"--force_gpu\", \"\"), ] ), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False,", "are using GPUs (\"--force_gpu\", \"\"), ] ), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600, # How", "save the outputs (PNGs or events.json) experiment = Experiment(ws, args.scenario) run = experiment.submit(config=est)", "for f in head_run.get_file_names() if f.endswith(\"best_episodes.kso\") ) with NamedTemporaryFile(mode=\"r\") as f: head_run.download_file(kso_file, output_file_path=f.name)", "AzureCliAuthentication from azureml.pipeline.core import PipelineRun # Azure ML Reinforcement Learning imports from azureml.contrib.train.rl", "node_count=args.num_workers, use_gpu=True, environment=env, ) with combined_source_directory() as source_dir: # This defines the head", "for line in content.split(\"\\n\") if \"NaN\" in line] raise ValueError( \"Expected no NaNs,", "run = experiment.submit(config=est) print(run) print(\"Run submitted!\", run.get_portal_url()) if args.wait_for_completion: run.wait_for_completion() # Check no", "script_params=dict( [(p, \"\") for p in params] + [ # This tells ray_main.py", "to the knossos Azure subscription. > az login > az account set -s", "head_compute = ws.compute_targets[args.head_cluster] body_compute = ws.compute_targets[args.body_cluster] env = get_environment() # Specify the Ray", "be seen by \"pip install ray==0.8.7; ray start --head\". (\"--redis_token\", \"<PASSWORD>\"), # Ensure", "`ray_main.py`. \"\"\" import argparse from datetime import datetime import os import subprocess import", "whole cluster to start max_run_duration_seconds=40 * 3600, # Allow the docker container Ray", "access to the knossos Azure subscription. > az login > az account set", "Make sure you have access to the knossos Azure subscription. > az login", "ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note: run_id is the ID of the head step:\") pipeline_run =", "use # of the shared memory available from the host OS. shm_size=24 *", "f in head_run.get_file_names() if f.endswith(\"best_episodes.kso\") ) with NamedTemporaryFile(mode=\"r\") as f: head_run.download_file(kso_file, output_file_path=f.name) content", "ML config file\", ) parser.add_argument( \"--head_cluster\", type=str, default=\"ray-head\", help=\"Name of the headnode cluster\",", "not just when it starts, or the run will fail to complete. Alternatively", "found the following lines:\\n\" + \"\\n\".join(lines) ) print(\"Found no NaNs!\") def main(): parser", "+ \"\\n\".join(lines) ) print(\"Found no NaNs!\") def main(): parser = argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str,", "f.read() print(f\"Downloaded {kso_file} (length={len(content)})\") if \"NaN\" in content: lines = [line for line", "child_ids = [child_run.id for child_run in pipeline_run.get_steps()] print([id for id in child_ids if", "# Specify the Ray worker configuration worker_conf = WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers, use_gpu=True, environment=env,", "any additional arguments will be passed to `ray_main.py`. \"\"\" import argparse from datetime", "\"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies = True return env def check_params(scenario, params): # import locally so", "seems to default to this. # This can be seen by \"pip install", "\"knossos.azurecr.io\" env.docker.base_image_registry.password = password env.docker.base_image_registry.username = \"00000000-0000-0000-0000-000000000000\" env.python.user_managed_dependencies = True return env def", "worker cluster\", ) parser.add_argument( \"--num_workers\", type=int, default=10, help=\"Number of worker nodes\", ) parser.add_argument(", "source_dir: # This defines the head configuration - note, no GPU required, the", "using GPUs (\"--force_gpu\", \"\"), ] ), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600, # How long", "worker nodes\", ) parser.add_argument( \"--enable_cli_auth\", action=\"store_true\", help=\"Enable AzureCliAuthentication (for CI)\", ) parser.add_argument( \"--wait_for_completion\",", "environment=env, ) with combined_source_directory() as source_dir: # This defines the head configuration -", "This defines the head configuration - note, no GPU required, the head is", "combined_source_directory() as source_dir: # This defines the head configuration - note, no GPU", "{kso_file} (length={len(content)})\") if \"NaN\" in content: lines = [line for line in content.split(\"\\n\")", "Ray worker configuration worker_conf = WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers, use_gpu=True, environment=env, ) with combined_source_directory()", "to connect to an existing Ray/redis server rather than start its own (\"--address\",", "if \"NaN\" in content: lines = [line for line in content.split(\"\\n\") if \"NaN\"", "own (\"--address\", \"auto\"), # The command-line ray process run by the AzureML RL", "of the head step:\") pipeline_run = PipelineRun(experiment, run.id) child_ids = [child_run.id for child_run", "Azure subscription. > az login > az account set -s Knossos You'll need", "Workspace, Experiment, Environment from azureml.core.authentication import AzureCliAuthentication from azureml.pipeline.core import PipelineRun # Azure", "no NaNs, but found the following lines:\\n\" + \"\\n\".join(lines) ) print(\"Found no NaNs!\")", "entry_script=\"ray_main.py\", script_params=dict( [(p, \"\") for p in params] + [ # This tells", "= Environment(\"my_ray_env\") # ws.register(env) - no, let's not env.docker.base_image = \"rlo_linux_base:\" + docker_tag", "to this. # This can be seen by \"pip install ray==0.8.7; ray start", "make full use # of the shared memory available from the host OS.", "The command-line ray process run by the AzureML RL framework seems to default", "params): # import locally so that CI can run without dependencies from rlo.flags", "following lines:\\n\" + \"\\n\".join(lines) ) print(\"Found no NaNs!\") def main(): parser = argparse.ArgumentParser()", "action=\"store_true\", help=\"Wait for the completion of the run\", ) parser.add_argument( \"--no-check-params\", action=\"store_false\", dest=\"check_params\",", "> az login > az account set -s Knossos You'll need to have", "docker container Ray runs in to make full use # of the shared", "import AzureCliAuthentication from azureml.pipeline.core import PipelineRun # Azure ML Reinforcement Learning imports from", "access _for_the_duration_of_the_run_ not just when it starts, or the run will fail to", "import locally so that CI can run without dependencies from rlo.flags import make_config_for_scenario", "parser.add_argument( \"--enable_cli_auth\", action=\"store_true\", help=\"Enable AzureCliAuthentication (for CI)\", ) parser.add_argument( \"--wait_for_completion\", action=\"store_true\", help=\"Wait for", "head configuration - note, no GPU required, the head is expected to be", "1024 * 1024, ) # This runs the estimator, but doesn't do anything", "import PipelineRun # Azure ML Reinforcement Learning imports from azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray", "use_gpu=True, environment=env, ) with combined_source_directory() as source_dir: # This defines the head configuration", "datetime import os import subprocess import sys from tempfile import NamedTemporaryFile from azureml.core", "action=\"store_false\", dest=\"check_params\", help=\"Don't check if the parameters are valid locally before submission\", )", "* 3600, # Allow the docker container Ray runs in to make full", "\"--wait_for_completion\", action=\"store_true\", help=\"Wait for the completion of the run\", ) parser.add_argument( \"--no-check-params\", action=\"store_false\",", "test for #1438 \"\"\" head_run = next(rn for rn in run.get_children() if rn.id.endswith(\"_head\"))", "for id in child_ids if \"head\" in id]) if __name__ == \"__main__\": main()", "] ), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600, # How long to wait for whole", "else: cli_auth = None ws = Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute = ws.compute_targets[args.head_cluster] body_compute =", "git_utils.get_git_revision_short_hash(), ] + additional_args # Check arguments are valid if args.check_params: check_params(args.scenario, params)", "be passed to `ray_main.py`. \"\"\" import argparse from datetime import datetime import os", "without dependencies from rlo.flags import make_config_for_scenario from ray_main import ray_run_arguments if not os.path.isfile(scenario):", "in head_run.get_file_names() if f.endswith(\"best_episodes.kso\") ) with NamedTemporaryFile(mode=\"r\") as f: head_run.download_file(kso_file, output_file_path=f.name) content =", "p in params] + [ # This tells ray_main.py to connect to an", "if rn.id.endswith(\"_head\")) kso_file = next( f for f in head_run.get_file_names() if f.endswith(\"best_episodes.kso\") )", "> az account set -s Knossos You'll need to have at least Contributor", "help=\"Don't check if the parameters are valid locally before submission\", ) args, additional_args", "fail to complete. Alternatively (recommended), you can temporarily elevate yourself to Owner using", "parser.add_argument( \"--no-check-params\", action=\"store_false\", dest=\"check_params\", help=\"Don't check if the parameters are valid locally before", "max_run_duration_seconds=40 * 3600, # Allow the docker container Ray runs in to make", "the knossos Azure subscription. > az login > az account set -s Knossos", "environment=env, entry_script=\"ray_main.py\", script_params=dict( [(p, \"\") for p in params] + [ # This", "you can temporarily elevate yourself to Owner using PIM, and give yourself permanent", "os import subprocess import sys from tempfile import NamedTemporaryFile from azureml.core import Workspace,", "= \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params = [ args.scenario, \"--run_id\", run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(), ] +", "will be passed to `ray_main.py`. \"\"\" import argparse from datetime import datetime import", "Check arguments are valid if args.check_params: check_params(args.scenario, params) if args.enable_cli_auth: cli_auth = AzureCliAuthentication()", "to Owner using PIM, and give yourself permanent Contributor rights to the knossosaml", ") docker_tag = ( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip() ) print(\"Docker tag\", docker_tag) env", "Management (PIM), but you will need to have said level of access _for_the_duration_of_the_run_", "\"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params = [ args.scenario, \"--run_id\", run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(), ] + additional_args", "f.endswith(\"best_episodes.kso\") ) with NamedTemporaryFile(mode=\"r\") as f: head_run.download_file(kso_file, output_file_path=f.name) content = f.read() print(f\"Downloaded {kso_file}", "= PipelineRun(experiment, run.id) child_ids = [child_run.id for child_run in pipeline_run.get_steps()] print([id for id", "head step:\") pipeline_run = PipelineRun(experiment, run.id) child_ids = [child_run.id for child_run in pipeline_run.get_steps()]", "Experiment(ws, args.scenario) run = experiment.submit(config=est) print(run) print(\"Run submitted!\", run.get_portal_url()) if args.wait_for_completion: run.wait_for_completion() #", "= f.read() print(f\"Downloaded {kso_file} (length={len(content)})\") if \"NaN\" in content: lines = [line for", "a co-ordinator. est = ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute, environment=env, entry_script=\"ray_main.py\", script_params=dict( [(p, \"\") for", "f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments, cmdline=params) def check_best_episodes(run): \"\"\" Checks best_episodes.kso file does not contain", "(\"--redis_token\", \"<PASSWORD>\"), # Ensure workers are using GPUs (\"--force_gpu\", \"\"), ] ), rl_framework=Ray(version=\"0.8.3\"),", "start max_run_duration_seconds=40 * 3600, # Allow the docker container Ray runs in to", "(better to do it in an isolated conda environment because it may clash)", "from azureml.core.authentication import AzureCliAuthentication from azureml.pipeline.core import PipelineRun # Azure ML Reinforcement Learning", "it may clash) ``` pip install -r test/builds/ci-requirements.txt ``` 3. Try to run", "cli_auth = None ws = Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute = ws.compute_targets[args.head_cluster] body_compute = ws.compute_targets[args.body_cluster]", "parser.add_argument( \"--aml_config_file\", type=str, default=\"aml_config.json\", help=\"Path to the Azure ML config file\", ) parser.add_argument(", "line in content.split(\"\\n\") if \"NaN\" in line] raise ValueError( \"Expected no NaNs, but", "ML Reinforcement Learning imports from azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray from azureml.contrib.train.rl import WorkerConfiguration", "\"pip install ray==0.8.7; ray start --head\". (\"--redis_token\", \"<PASSWORD>\"), # Ensure workers are using", "NamedTemporaryFile(mode=\"r\") as f: head_run.download_file(kso_file, output_file_path=f.name) content = f.read() print(f\"Downloaded {kso_file} (length={len(content)})\") if \"NaN\"", "pipeline_run.get_steps()] print([id for id in child_ids if \"head\" in id]) if __name__ ==", "to the resource group (knossosamlrg). You can (not recommended) temporarily elevate yourself to", "\"--run_id\", run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(), ] + additional_args # Check arguments are valid if", "print( \"Download from container azureml path ExperimentRun/dcid.{run_id}/outputs\" ) print(\"Note: run_id is the ID", "in to make full use # of the shared memory available from the", "submission\", ) args, additional_args = parser.parse_known_args() run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params = [", "= get_environment() # Specify the Ray worker configuration worker_conf = WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers,", "run by the AzureML RL framework seems to default to this. # This", "to Contributor using Azure Privileged Identity Management (PIM), but you will need to", "(\"--address\", \"auto\"), # The command-line ray process run by the AzureML RL framework", "# Check no NaN in best_episodes.kso check_best_episodes(run) print(\"Run succeeded!\") print( \"Download from container", "additional_args = parser.parse_known_args() run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params = [ args.scenario, \"--run_id\", run_id,", "args.enable_cli_auth: cli_auth = AzureCliAuthentication() else: cli_auth = None ws = Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute", "tag\", docker_tag) env = Environment(\"my_ray_env\") # ws.register(env) - no, let's not env.docker.base_image =", "ray_main import ray_run_arguments if not os.path.isfile(scenario): scenario = os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments,", "have at least Contributor access to the resource group (knossosamlrg). You can (not", "the headnode cluster\", ) parser.add_argument( \"--body_cluster\", type=str, default=\"ray-p40\", help=\"Name of the worker cluster\",", ") parser.add_argument( \"--head_cluster\", type=str, default=\"ray-head\", help=\"Name of the headnode cluster\", ) parser.add_argument( \"--body_cluster\",", "or events.json) experiment = Experiment(ws, args.scenario) run = experiment.submit(config=est) print(run) print(\"Run submitted!\", run.get_portal_url())", "only a co-ordinator. est = ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute, environment=env, entry_script=\"ray_main.py\", script_params=dict( [(p, \"\")", "import argparse from datetime import datetime import os import subprocess import sys from", "- no, let's not env.docker.base_image = \"rlo_linux_base:\" + docker_tag env.docker.base_image_registry.address = \"knossos.azurecr.io\" env.docker.base_image_registry.password", "print(\"Getting docker password...\") password = ( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip() ) docker_tag =", "You'll need to have at least Contributor access to the resource group (knossosamlrg).", "install -r test/builds/ci-requirements.txt ``` 3. Try to run `fewer_simplify_rules` scenario ``` python scripts/azureml_ray.py", "ws.compute_targets[args.body_cluster] env = get_environment() # Specify the Ray worker configuration worker_conf = WorkerConfiguration(", "worker_conf = WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers, use_gpu=True, environment=env, ) with combined_source_directory() as source_dir: #", "az login > az account set -s Knossos You'll need to have at", "to wait for whole cluster to start max_run_duration_seconds=40 * 3600, # Allow the", "but you will need to have said level of access _for_the_duration_of_the_run_ not just", "= True return env def check_params(scenario, params): # import locally so that CI", "run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(), ] + additional_args # Check arguments are valid if args.check_params:", "framework seems to default to this. # This can be seen by \"pip", "return env def check_params(scenario, params): # import locally so that CI can run", "OS. shm_size=24 * 1024 * 1024 * 1024, ) # This runs the", "in an isolated conda environment because it may clash) ``` pip install -r", "memory available from the host OS. shm_size=24 * 1024 * 1024 * 1024,", "\"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip() ) print(\"Docker tag\", docker_tag) env = Environment(\"my_ray_env\") # ws.register(env) -", ") with combined_source_directory() as source_dir: # This defines the head configuration - note,", "AzureCliAuthentication (for CI)\", ) parser.add_argument( \"--wait_for_completion\", action=\"store_true\", help=\"Wait for the completion of the", "are valid locally before submission\", ) args, additional_args = parser.parse_known_args() run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"),", "from ray_main import ray_run_arguments if not os.path.isfile(scenario): scenario = os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario,", "How long to wait for whole cluster to start max_run_duration_seconds=40 * 3600, #", "required, the head is expected to be only a co-ordinator. est = ReinforcementLearningEstimator(", "not env.docker.base_image = \"rlo_linux_base:\" + docker_tag env.docker.base_image_registry.address = \"knossos.azurecr.io\" env.docker.base_image_registry.password = password env.docker.base_image_registry.username", "wait for whole cluster to start max_run_duration_seconds=40 * 3600, # Allow the docker", "Azure Privileged Identity Management (PIM), but you will need to have said level", "does not contain NaNs Regression test for #1438 \"\"\" head_run = next(rn for", "est = ReinforcementLearningEstimator( source_directory=source_dir, compute_target=head_compute, environment=env, entry_script=\"ray_main.py\", script_params=dict( [(p, \"\") for p in", ") print(\"Docker tag\", docker_tag) env = Environment(\"my_ray_env\") # ws.register(env) - no, let's not", "do it in an isolated conda environment because it may clash) ``` pip", "do anything to save the outputs (PNGs or events.json) experiment = Experiment(ws, args.scenario)", "can run without dependencies from rlo.flags import make_config_for_scenario from ray_main import ray_run_arguments if", "= ws.compute_targets[args.head_cluster] body_compute = ws.compute_targets[args.body_cluster] env = get_environment() # Specify the Ray worker", "params] + [ # This tells ray_main.py to connect to an existing Ray/redis", "\"\"\" Quick start instructions: 1. Make sure you have access to the knossos", "estimator, but doesn't do anything to save the outputs (PNGs or events.json) experiment", "temporarily elevate yourself to Contributor using Azure Privileged Identity Management (PIM), but you", "Contributor using Azure Privileged Identity Management (PIM), but you will need to have", "os.path.isfile(scenario): scenario = os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments, cmdline=params) def check_best_episodes(run): \"\"\" Checks", "[ args.scenario, \"--run_id\", run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(), ] + additional_args # Check arguments are", "not os.path.isfile(scenario): scenario = os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments, cmdline=params) def check_best_episodes(run): \"\"\"", "--num_workers=2 ``` Note: any additional arguments will be passed to `ray_main.py`. \"\"\" import", "= parser.parse_known_args() run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params = [ args.scenario, \"--run_id\", run_id, \"--gitlog\",", "\"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip() ) docker_tag = ( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip() ) print(\"Docker", "1024, ) # This runs the estimator, but doesn't do anything to save", "def get_environment(): print(\"Getting docker password...\") password = ( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip() )", "* 1024 * 1024, ) # This runs the estimator, but doesn't do", "= [line for line in content.split(\"\\n\") if \"NaN\" in line] raise ValueError( \"Expected", "(\"--force_gpu\", \"\"), ] ), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600, # How long to wait", "Quick start instructions: 1. Make sure you have access to the knossos Azure", "to run `fewer_simplify_rules` scenario ``` python scripts/azureml_ray.py fewer_simplify_rules --num_workers=2 ``` Note: any additional", "will fail to complete. Alternatively (recommended), you can temporarily elevate yourself to Owner", ") parser.add_argument( \"--num_workers\", type=int, default=10, help=\"Number of worker nodes\", ) parser.add_argument( \"--enable_cli_auth\", action=\"store_true\",", "-s Knossos You'll need to have at least Contributor access to the resource", "completion of the run\", ) parser.add_argument( \"--no-check-params\", action=\"store_false\", dest=\"check_params\", help=\"Don't check if the", "the head configuration - note, no GPU required, the head is expected to", "to have at least Contributor access to the resource group (knossosamlrg). You can", "import os import subprocess import sys from tempfile import NamedTemporaryFile from azureml.core import", "to make full use # of the shared memory available from the host", ") parser.add_argument( \"--wait_for_completion\", action=\"store_true\", help=\"Wait for the completion of the run\", ) parser.add_argument(", "Azure ML Reinforcement Learning imports from azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray from azureml.contrib.train.rl import", "``` python scripts/azureml_ray.py fewer_simplify_rules --num_workers=2 ``` Note: any additional arguments will be passed", "True return env def check_params(scenario, params): # import locally so that CI can", "the run will fail to complete. Alternatively (recommended), you can temporarily elevate yourself", "help=\"Name of the headnode cluster\", ) parser.add_argument( \"--body_cluster\", type=str, default=\"ray-p40\", help=\"Name of the", "parser.parse_known_args() run_id = \"{}_{}\".format(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), args.scenario) params = [ args.scenario, \"--run_id\", run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(),", "the Ray worker configuration worker_conf = WorkerConfiguration( compute_target=body_compute, node_count=args.num_workers, use_gpu=True, environment=env, ) with", "to the knossosaml resource group. 2. Install dependencies (better to do it in", "command-line ray process run by the AzureML RL framework seems to default to", "# import locally so that CI can run without dependencies from rlo.flags import", "let's not env.docker.base_image = \"rlo_linux_base:\" + docker_tag env.docker.base_image_registry.address = \"knossos.azurecr.io\" env.docker.base_image_registry.password = password", "existing Ray/redis server rather than start its own (\"--address\", \"auto\"), # The command-line", "subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip() ) docker_tag = ( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip() )", "Note: any additional arguments will be passed to `ray_main.py`. \"\"\" import argparse from", "from azureml.core import Workspace, Experiment, Environment from azureml.core.authentication import AzureCliAuthentication from azureml.pipeline.core import", "combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from rlo import git_utils def get_environment(): print(\"Getting docker password...\") password", "# Allow the docker container Ray runs in to make full use #", "from rlo.flags import make_config_for_scenario from ray_main import ray_run_arguments if not os.path.isfile(scenario): scenario =", "type=str, help=\"Scenario to run\") parser.add_argument( \"--aml_config_file\", type=str, default=\"aml_config.json\", help=\"Path to the Azure ML", "help=\"Enable AzureCliAuthentication (for CI)\", ) parser.add_argument( \"--wait_for_completion\", action=\"store_true\", help=\"Wait for the completion of", "\"--enable_cli_auth\", action=\"store_true\", help=\"Enable AzureCliAuthentication (for CI)\", ) parser.add_argument( \"--wait_for_completion\", action=\"store_true\", help=\"Wait for the", ".decode(\"ASCII\") .strip() ) docker_tag = ( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\") .strip() ) print(\"Docker tag\",", "the run\", ) parser.add_argument( \"--no-check-params\", action=\"store_false\", dest=\"check_params\", help=\"Don't check if the parameters are", "(for CI)\", ) parser.add_argument( \"--wait_for_completion\", action=\"store_true\", help=\"Wait for the completion of the run\",", "\"auto\"), # The command-line ray process run by the AzureML RL framework seems", "file does not contain NaNs Regression test for #1438 \"\"\" head_run = next(rn", "f: head_run.download_file(kso_file, output_file_path=f.name) content = f.read() print(f\"Downloaded {kso_file} (length={len(content)})\") if \"NaN\" in content:", "= experiment.submit(config=est) print(run) print(\"Run submitted!\", run.get_portal_url()) if args.wait_for_completion: run.wait_for_completion() # Check no NaN", "argparse from datetime import datetime import os import subprocess import sys from tempfile", "print(run) print(\"Run submitted!\", run.get_portal_url()) if args.wait_for_completion: run.wait_for_completion() # Check no NaN in best_episodes.kso", "no NaN in best_episodes.kso check_best_episodes(run) print(\"Run succeeded!\") print( \"Download from container azureml path", "in content.split(\"\\n\") if \"NaN\" in line] raise ValueError( \"Expected no NaNs, but found", "if args.wait_for_completion: run.wait_for_completion() # Check no NaN in best_episodes.kso check_best_episodes(run) print(\"Run succeeded!\") print(", "test/builds/ci-requirements.txt ``` 3. Try to run `fewer_simplify_rules` scenario ``` python scripts/azureml_ray.py fewer_simplify_rules --num_workers=2", "def main(): parser = argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str, help=\"Scenario to run\") parser.add_argument( \"--aml_config_file\", type=str,", "= ( subprocess.check_output([\"bash\", \"./test/builds/docker_password.sh\"]) .decode(\"ASCII\") .strip() ) docker_tag = ( subprocess.check_output([\"bash\", \"./test/builds/docker_tag.sh\"]) .decode(\"ASCII\")", "Workspace.from_config(args.aml_config_file, auth=cli_auth) head_compute = ws.compute_targets[args.head_cluster] body_compute = ws.compute_targets[args.body_cluster] env = get_environment() # Specify", "can temporarily elevate yourself to Owner using PIM, and give yourself permanent Contributor", "workers are using GPUs (\"--force_gpu\", \"\"), ] ), rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600, #", "[child_run.id for child_run in pipeline_run.get_steps()] print([id for id in child_ids if \"head\" in", "starts, or the run will fail to complete. Alternatively (recommended), you can temporarily", "resource group (knossosamlrg). You can (not recommended) temporarily elevate yourself to Contributor using", "Contributor rights to the knossosaml resource group. 2. Install dependencies (better to do", "PipelineRun # Azure ML Reinforcement Learning imports from azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray from", "os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments, cmdline=params) def check_best_episodes(run): \"\"\" Checks best_episodes.kso file does", "available from the host OS. shm_size=24 * 1024 * 1024 * 1024, )", "import subprocess import sys from tempfile import NamedTemporaryFile from azureml.core import Workspace, Experiment,", "output_file_path=f.name) content = f.read() print(f\"Downloaded {kso_file} (length={len(content)})\") if \"NaN\" in content: lines =", "``` pip install -r test/builds/ci-requirements.txt ``` 3. Try to run `fewer_simplify_rules` scenario ```", "print(\"Found no NaNs!\") def main(): parser = argparse.ArgumentParser() parser.add_argument(\"scenario\", type=str, help=\"Scenario to run\")", "rl_framework=Ray(version=\"0.8.3\"), worker_configuration=worker_conf, use_gpu=False, cluster_coordination_timeout_seconds=3600, # How long to wait for whole cluster to", "of access _for_the_duration_of_the_run_ not just when it starts, or the run will fail", "if the parameters are valid locally before submission\", ) args, additional_args = parser.parse_known_args()", ") with NamedTemporaryFile(mode=\"r\") as f: head_run.download_file(kso_file, output_file_path=f.name) content = f.read() print(f\"Downloaded {kso_file} (length={len(content)})\")", "* 1024, ) # This runs the estimator, but doesn't do anything to", "the knossosaml resource group. 2. Install dependencies (better to do it in an", "ray process run by the AzureML RL framework seems to default to this.", "CI can run without dependencies from rlo.flags import make_config_for_scenario from ray_main import ray_run_arguments", "Install dependencies (better to do it in an isolated conda environment because it", "= [ args.scenario, \"--run_id\", run_id, \"--gitlog\", git_utils.get_git_revision_short_hash(), ] + additional_args # Check arguments", "Owner using PIM, and give yourself permanent Contributor rights to the knossosaml resource", "= ws.compute_targets[args.body_cluster] env = get_environment() # Specify the Ray worker configuration worker_conf =", "def check_best_episodes(run): \"\"\" Checks best_episodes.kso file does not contain NaNs Regression test for", "check_params(args.scenario, params) if args.enable_cli_auth: cli_auth = AzureCliAuthentication() else: cli_auth = None ws =", "= os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments, cmdline=params) def check_best_episodes(run): \"\"\" Checks best_episodes.kso file", "\"\"\" Checks best_episodes.kso file does not contain NaNs Regression test for #1438 \"\"\"", "[ # This tells ray_main.py to connect to an existing Ray/redis server rather", "f for f in head_run.get_file_names() if f.endswith(\"best_episodes.kso\") ) with NamedTemporaryFile(mode=\"r\") as f: head_run.download_file(kso_file,", "<reponame>tomjaguarpaw/knossos-ksc \"\"\" Quick start instructions: 1. Make sure you have access to the", "in run.get_children() if rn.id.endswith(\"_head\")) kso_file = next( f for f in head_run.get_file_names() if", "of worker nodes\", ) parser.add_argument( \"--enable_cli_auth\", action=\"store_true\", help=\"Enable AzureCliAuthentication (for CI)\", ) parser.add_argument(", "the completion of the run\", ) parser.add_argument( \"--no-check-params\", action=\"store_false\", dest=\"check_params\", help=\"Don't check if", "help=\"Number of worker nodes\", ) parser.add_argument( \"--enable_cli_auth\", action=\"store_true\", help=\"Enable AzureCliAuthentication (for CI)\", )", "azureml.contrib.train.rl import WorkerConfiguration from azureml_util import combined_source_directory sys.path.append(os.path.join(os.path.dirname(__file__), \"../src\")) from rlo import git_utils", "for p in params] + [ # This tells ray_main.py to connect to", "3. Try to run `fewer_simplify_rules` scenario ``` python scripts/azureml_ray.py fewer_simplify_rules --num_workers=2 ``` Note:", "no GPU required, the head is expected to be only a co-ordinator. est", "You can (not recommended) temporarily elevate yourself to Contributor using Azure Privileged Identity", "ray_run_arguments if not os.path.isfile(scenario): scenario = os.path.join(\"src\", \"scenarios\", f\"{scenario}.json\") make_config_for_scenario(scenario, ray_run_arguments, cmdline=params) def" ]
[ "DeleteTestGridProject = Action(\"DeleteTestGridProject\") DeleteUpload = Action(\"DeleteUpload\") DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\") GetAccountSettings = Action(\"GetAccountSettings\") GetDevice", "Action(\"GetDevicePoolCompatibility\") GetInstanceProfile = Action(\"GetInstanceProfile\") GetJob = Action(\"GetJob\") GetNetworkProfile = Action(\"GetNetworkProfile\") GetOfferingStatus = Action(\"GetOfferingStatus\")", "DeleteDevicePool = Action(\"DeleteDevicePool\") DeleteInstanceProfile = Action(\"DeleteInstanceProfile\") DeleteNetworkProfile = Action(\"DeleteNetworkProfile\") DeleteProject = Action(\"DeleteProject\") DeleteRemoteAccessSession", "\"AWS Device Farm\" prefix = \"devicefarm\" class Action(BaseAction): def __init__(self, action: str =", "GetProject = Action(\"GetProject\") GetRemoteAccessSession = Action(\"GetRemoteAccessSession\") GetRun = Action(\"GetRun\") GetSuite = Action(\"GetSuite\") GetTest", "= Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\") ListArtifacts = Action(\"ListArtifacts\") ListDeviceInstances = Action(\"ListDeviceInstances\") ListDevicePools =", "import Action as BaseAction from .aws import BaseARN service_name = \"AWS Device Farm\"", "Action(\"ListOfferingTransactions\") ListOfferings = Action(\"ListOfferings\") ListProjects = Action(\"ListProjects\") ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\") ListRuns = Action(\"ListRuns\")", "prefix = \"devicefarm\" class Action(BaseAction): def __init__(self, action: str = None) -> None:", "= Action(\"StopJob\") StopRemoteAccessSession = Action(\"StopRemoteAccessSession\") StopRun = Action(\"StopRun\") TagResource = Action(\"TagResource\") UntagResource =", ") CreateDevicePool = Action(\"CreateDevicePool\") CreateInstanceProfile = Action(\"CreateInstanceProfile\") CreateNetworkProfile = Action(\"CreateNetworkProfile\") CreateProject = Action(\"CreateProject\")", "CreateDevicePool = Action(\"CreateDevicePool\") CreateInstanceProfile = Action(\"CreateInstanceProfile\") CreateNetworkProfile = Action(\"CreateNetworkProfile\") CreateProject = Action(\"CreateProject\") CreateRemoteAccessSession", "Action(\"CreateNetworkProfile\") CreateProject = Action(\"CreateProject\") CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\") CreateTestGridProject = Action(\"CreateTestGridProject\") CreateTestGridUrl = Action(\"CreateTestGridUrl\")", "GetAccountSettings = Action(\"GetAccountSettings\") GetDevice = Action(\"GetDevice\") GetDeviceInstance = Action(\"GetDeviceInstance\") GetDevicePool = Action(\"GetDevicePool\") GetDevicePoolCompatibility", "Action(\"GetProject\") GetRemoteAccessSession = Action(\"GetRemoteAccessSession\") GetRun = Action(\"GetRun\") GetSuite = Action(\"GetSuite\") GetTest = Action(\"GetTest\")", "CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\") CreateTestGridProject = Action(\"CreateTestGridProject\") CreateTestGridUrl = Action(\"CreateTestGridUrl\") CreateUpload = Action(\"CreateUpload\") CreateVPCEConfiguration", "= Action(\"DeleteVPCEConfiguration\") GetAccountSettings = Action(\"GetAccountSettings\") GetDevice = Action(\"GetDevice\") GetDeviceInstance = Action(\"GetDeviceInstance\") GetDevicePool =", "DeleteProject = Action(\"DeleteProject\") DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\") DeleteRun = Action(\"DeleteRun\") DeleteTestGridProject = Action(\"DeleteTestGridProject\") DeleteUpload", "Action(\"GetDevicePool\") GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\") GetInstanceProfile = Action(\"GetInstanceProfile\") GetJob = Action(\"GetJob\") GetNetworkProfile = Action(\"GetNetworkProfile\")", "<NAME> <<EMAIL>> # All rights reserved. # # See LICENSE file for full", "ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\") ListRuns = Action(\"ListRuns\") ListSamples = Action(\"ListSamples\") ListSuites = Action(\"ListSuites\") ListTagsForResource", "account=account ) CreateDevicePool = Action(\"CreateDevicePool\") CreateInstanceProfile = Action(\"CreateInstanceProfile\") CreateNetworkProfile = Action(\"CreateNetworkProfile\") CreateProject =", "__init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self,", "= \"\") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateDevicePool = Action(\"CreateDevicePool\")", "Action as BaseAction from .aws import BaseARN service_name = \"AWS Device Farm\" prefix", "DeleteRun = Action(\"DeleteRun\") DeleteTestGridProject = Action(\"DeleteTestGridProject\") DeleteUpload = Action(\"DeleteUpload\") DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\") GetAccountSettings", "GetOfferingStatus = Action(\"GetOfferingStatus\") GetProject = Action(\"GetProject\") GetRemoteAccessSession = Action(\"GetRemoteAccessSession\") GetRun = Action(\"GetRun\") GetSuite", "Action(\"GetRun\") GetSuite = Action(\"GetSuite\") GetTest = Action(\"GetTest\") GetTestGridProject = Action(\"GetTestGridProject\") GetTestGridSession = Action(\"GetTestGridSession\")", "Action(\"ListSamples\") ListSuites = Action(\"ListSuites\") ListTagsForResource = Action(\"ListTagsForResource\") ListTestGridProjects = Action(\"ListTestGridProjects\") ListTestGridSessionActions = Action(\"ListTestGridSessionActions\")", "# All rights reserved. # # See LICENSE file for full license. from", "Action(\"StopJob\") StopRemoteAccessSession = Action(\"StopRemoteAccessSession\") StopRun = Action(\"StopRun\") TagResource = Action(\"TagResource\") UntagResource = Action(\"UntagResource\")", "= Action(\"ListOfferingTransactions\") ListOfferings = Action(\"ListOfferings\") ListProjects = Action(\"ListProjects\") ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\") ListRuns =", "= Action(\"GetAccountSettings\") GetDevice = Action(\"GetDevice\") GetDeviceInstance = Action(\"GetDeviceInstance\") GetDevicePool = Action(\"GetDevicePool\") GetDevicePoolCompatibility =", "= \"\", account: str = \"\") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account", "= Action(\"GetDevicePoolCompatibility\") GetInstanceProfile = Action(\"GetInstanceProfile\") GetJob = Action(\"GetJob\") GetNetworkProfile = Action(\"GetNetworkProfile\") GetOfferingStatus =", "= Action(\"ListTestGridProjects\") ListTestGridSessionActions = Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions = Action(\"ListTestGridSessions\") ListTests =", "Action(\"DeleteRemoteAccessSession\") DeleteRun = Action(\"DeleteRun\") DeleteTestGridProject = Action(\"DeleteTestGridProject\") DeleteUpload = Action(\"DeleteUpload\") DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\")", "Action(\"GetTestGridProject\") GetTestGridSession = Action(\"GetTestGridSession\") GetUpload = Action(\"GetUpload\") GetVPCEConfiguration = Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\")", "# # See LICENSE file for full license. from .aws import Action as", "Action(\"ListProjects\") ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\") ListRuns = Action(\"ListRuns\") ListSamples = Action(\"ListSamples\") ListSuites = Action(\"ListSuites\")", "= Action(\"ListTestGridSessions\") ListTests = Action(\"ListTests\") ListUniqueProblems = Action(\"ListUniqueProblems\") ListUploads = Action(\"ListUploads\") ListVPCEConfigurations =", "= Action(\"ListDeviceInstances\") ListDevicePools = Action(\"ListDevicePools\") ListDevices = Action(\"ListDevices\") ListInstanceProfiles = Action(\"ListInstanceProfiles\") ListJobs =", "Action(\"UpdateInstanceProfile\") UpdateNetworkProfile = Action(\"UpdateNetworkProfile\") UpdateProject = Action(\"UpdateProject\") UpdateTestGridProject = Action(\"UpdateTestGridProject\") UpdateUpload = Action(\"UpdateUpload\")", "Action(\"ListDeviceInstances\") ListDevicePools = Action(\"ListDevicePools\") ListDevices = Action(\"ListDevices\") ListInstanceProfiles = Action(\"ListInstanceProfiles\") ListJobs = Action(\"ListJobs\")", "Action(\"InstallToRemoteAccessSession\") ListArtifacts = Action(\"ListArtifacts\") ListDeviceInstances = Action(\"ListDeviceInstances\") ListDevicePools = Action(\"ListDevicePools\") ListDevices = Action(\"ListDevices\")", "= Action(\"GetSuite\") GetTest = Action(\"GetTest\") GetTestGridProject = Action(\"GetTestGridProject\") GetTestGridSession = Action(\"GetTestGridSession\") GetUpload =", "All rights reserved. # # See LICENSE file for full license. from .aws", "= Action(\"ListProjects\") ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\") ListRuns = Action(\"ListRuns\") ListSamples = Action(\"ListSamples\") ListSuites =", "def __init__(self, resource: str = \"\", region: str = \"\", account: str =", "= Action(\"GetTest\") GetTestGridProject = Action(\"GetTestGridProject\") GetTestGridSession = Action(\"GetTestGridSession\") GetUpload = Action(\"GetUpload\") GetVPCEConfiguration =", "ListOfferingTransactions = Action(\"ListOfferingTransactions\") ListOfferings = Action(\"ListOfferings\") ListProjects = Action(\"ListProjects\") ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\") ListRuns", "GetUpload = Action(\"GetUpload\") GetVPCEConfiguration = Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\") ListArtifacts = Action(\"ListArtifacts\") ListDeviceInstances", "StopRemoteAccessSession = Action(\"StopRemoteAccessSession\") StopRun = Action(\"StopRun\") TagResource = Action(\"TagResource\") UntagResource = Action(\"UntagResource\") UpdateDeviceInstance", "= Action(\"DeleteRemoteAccessSession\") DeleteRun = Action(\"DeleteRun\") DeleteTestGridProject = Action(\"DeleteTestGridProject\") DeleteUpload = Action(\"DeleteUpload\") DeleteVPCEConfiguration =", "= Action(\"GetTestGridProject\") GetTestGridSession = Action(\"GetTestGridSession\") GetUpload = Action(\"GetUpload\") GetVPCEConfiguration = Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession =", "ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions = Action(\"ListTestGridSessions\") ListTests = Action(\"ListTests\") ListUniqueProblems = Action(\"ListUniqueProblems\") ListUploads", "GetDeviceInstance = Action(\"GetDeviceInstance\") GetDevicePool = Action(\"GetDevicePool\") GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\") GetInstanceProfile = Action(\"GetInstanceProfile\") GetJob", "= \"AWS Device Farm\" prefix = \"devicefarm\" class Action(BaseAction): def __init__(self, action: str", "Action(\"ListTests\") ListUniqueProblems = Action(\"ListUniqueProblems\") ListUploads = Action(\"ListUploads\") ListVPCEConfigurations = Action(\"ListVPCEConfigurations\") PurchaseOffering = Action(\"PurchaseOffering\")", "UntagResource = Action(\"UntagResource\") UpdateDeviceInstance = Action(\"UpdateDeviceInstance\") UpdateDevicePool = Action(\"UpdateDevicePool\") UpdateInstanceProfile = Action(\"UpdateInstanceProfile\") UpdateNetworkProfile", "DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\") GetAccountSettings = Action(\"GetAccountSettings\") GetDevice = Action(\"GetDevice\") GetDeviceInstance = Action(\"GetDeviceInstance\") GetDevicePool", "<filename>awacs/devicefarm.py # Copyright (c) 2012-2021, <NAME> <<EMAIL>> # All rights reserved. # #", "= \"devicefarm\" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix,", "Device Farm\" prefix = \"devicefarm\" class Action(BaseAction): def __init__(self, action: str = None)", "Action(\"DeleteRun\") DeleteTestGridProject = Action(\"DeleteTestGridProject\") DeleteUpload = Action(\"DeleteUpload\") DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\") GetAccountSettings = Action(\"GetAccountSettings\")", "DeleteUpload = Action(\"DeleteUpload\") DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\") GetAccountSettings = Action(\"GetAccountSettings\") GetDevice = Action(\"GetDevice\") GetDeviceInstance", "= Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions = Action(\"ListTestGridSessions\") ListTests = Action(\"ListTests\") ListUniqueProblems = Action(\"ListUniqueProblems\") ListUploads =", "Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\") ListArtifacts = Action(\"ListArtifacts\") ListDeviceInstances = Action(\"ListDeviceInstances\") ListDevicePools = Action(\"ListDevicePools\")", "Copyright (c) 2012-2021, <NAME> <<EMAIL>> # All rights reserved. # # See LICENSE", "Action(\"ListTestGridSessions\") ListTests = Action(\"ListTests\") ListUniqueProblems = Action(\"ListUniqueProblems\") ListUploads = Action(\"ListUploads\") ListVPCEConfigurations = Action(\"ListVPCEConfigurations\")", "ListJobs = Action(\"ListJobs\") ListNetworkProfiles = Action(\"ListNetworkProfiles\") ListOfferingPromotions = Action(\"ListOfferingPromotions\") ListOfferingTransactions = Action(\"ListOfferingTransactions\") ListOfferings", "GetRemoteAccessSession = Action(\"GetRemoteAccessSession\") GetRun = Action(\"GetRun\") GetSuite = Action(\"GetSuite\") GetTest = Action(\"GetTest\") GetTestGridProject", "None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = \"\",", "= Action(\"CreateNetworkProfile\") CreateProject = Action(\"CreateProject\") CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\") CreateTestGridProject = Action(\"CreateTestGridProject\") CreateTestGridUrl =", "= Action(\"GetRemoteAccessSession\") GetRun = Action(\"GetRun\") GetSuite = Action(\"GetSuite\") GetTest = Action(\"GetTest\") GetTestGridProject =", "ListTestGridProjects = Action(\"ListTestGridProjects\") ListTestGridSessionActions = Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions = Action(\"ListTestGridSessions\") ListTests", "BaseARN service_name = \"AWS Device Farm\" prefix = \"devicefarm\" class Action(BaseAction): def __init__(self,", "Action(\"GetDevice\") GetDeviceInstance = Action(\"GetDeviceInstance\") GetDevicePool = Action(\"GetDevicePool\") GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\") GetInstanceProfile = Action(\"GetInstanceProfile\")", "= Action(\"ListRuns\") ListSamples = Action(\"ListSamples\") ListSuites = Action(\"ListSuites\") ListTagsForResource = Action(\"ListTagsForResource\") ListTestGridProjects =", "str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str", "CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\") DeleteDevicePool = Action(\"DeleteDevicePool\") DeleteInstanceProfile = Action(\"DeleteInstanceProfile\") DeleteNetworkProfile = Action(\"DeleteNetworkProfile\") DeleteProject", "= Action(\"CreateInstanceProfile\") CreateNetworkProfile = Action(\"CreateNetworkProfile\") CreateProject = Action(\"CreateProject\") CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\") CreateTestGridProject =", "= Action(\"GetTestGridSession\") GetUpload = Action(\"GetUpload\") GetVPCEConfiguration = Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\") ListArtifacts =", "Action(\"UpdateDeviceInstance\") UpdateDevicePool = Action(\"UpdateDevicePool\") UpdateInstanceProfile = Action(\"UpdateInstanceProfile\") UpdateNetworkProfile = Action(\"UpdateNetworkProfile\") UpdateProject = Action(\"UpdateProject\")", "GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\") GetInstanceProfile = Action(\"GetInstanceProfile\") GetJob = Action(\"GetJob\") GetNetworkProfile = Action(\"GetNetworkProfile\") GetOfferingStatus", "= Action(\"UpdateNetworkProfile\") UpdateProject = Action(\"UpdateProject\") UpdateTestGridProject = Action(\"UpdateTestGridProject\") UpdateUpload = Action(\"UpdateUpload\") UpdateVPCEConfiguration =", "GetVPCEConfiguration = Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\") ListArtifacts = Action(\"ListArtifacts\") ListDeviceInstances = Action(\"ListDeviceInstances\") ListDevicePools", "Action(\"GetUpload\") GetVPCEConfiguration = Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\") ListArtifacts = Action(\"ListArtifacts\") ListDeviceInstances = Action(\"ListDeviceInstances\")", "= Action(\"ListNetworkProfiles\") ListOfferingPromotions = Action(\"ListOfferingPromotions\") ListOfferingTransactions = Action(\"ListOfferingTransactions\") ListOfferings = Action(\"ListOfferings\") ListProjects =", "Action(\"DeleteVPCEConfiguration\") GetAccountSettings = Action(\"GetAccountSettings\") GetDevice = Action(\"GetDevice\") GetDeviceInstance = Action(\"GetDeviceInstance\") GetDevicePool = Action(\"GetDevicePool\")", "2012-2021, <NAME> <<EMAIL>> # All rights reserved. # # See LICENSE file for", "Action(\"ListOfferingPromotions\") ListOfferingTransactions = Action(\"ListOfferingTransactions\") ListOfferings = Action(\"ListOfferings\") ListProjects = Action(\"ListProjects\") ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\")", "region: str = \"\", account: str = \"\") -> None: super().__init__( service=prefix, resource=resource,", "-> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateDevicePool = Action(\"CreateDevicePool\") CreateInstanceProfile =", "BaseAction from .aws import BaseARN service_name = \"AWS Device Farm\" prefix = \"devicefarm\"", "= Action(\"GetProject\") GetRemoteAccessSession = Action(\"GetRemoteAccessSession\") GetRun = Action(\"GetRun\") GetSuite = Action(\"GetSuite\") GetTest =", "ListDevices = Action(\"ListDevices\") ListInstanceProfiles = Action(\"ListInstanceProfiles\") ListJobs = Action(\"ListJobs\") ListNetworkProfiles = Action(\"ListNetworkProfiles\") ListOfferingPromotions", "Action(\"ListOfferings\") ListProjects = Action(\"ListProjects\") ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\") ListRuns = Action(\"ListRuns\") ListSamples = Action(\"ListSamples\")", "import BaseARN service_name = \"AWS Device Farm\" prefix = \"devicefarm\" class Action(BaseAction): def", "ListTests = Action(\"ListTests\") ListUniqueProblems = Action(\"ListUniqueProblems\") ListUploads = Action(\"ListUploads\") ListVPCEConfigurations = Action(\"ListVPCEConfigurations\") PurchaseOffering", "CreateUpload = Action(\"CreateUpload\") CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\") DeleteDevicePool = Action(\"DeleteDevicePool\") DeleteInstanceProfile = Action(\"DeleteInstanceProfile\") DeleteNetworkProfile", "= \"\", region: str = \"\", account: str = \"\") -> None: super().__init__(", "= Action(\"PurchaseOffering\") RenewOffering = Action(\"RenewOffering\") ScheduleRun = Action(\"ScheduleRun\") StopJob = Action(\"StopJob\") StopRemoteAccessSession =", "= Action(\"ListUniqueProblems\") ListUploads = Action(\"ListUploads\") ListVPCEConfigurations = Action(\"ListVPCEConfigurations\") PurchaseOffering = Action(\"PurchaseOffering\") RenewOffering =", "= Action(\"GetNetworkProfile\") GetOfferingStatus = Action(\"GetOfferingStatus\") GetProject = Action(\"GetProject\") GetRemoteAccessSession = Action(\"GetRemoteAccessSession\") GetRun =", "Action(\"GetTestGridSession\") GetUpload = Action(\"GetUpload\") GetVPCEConfiguration = Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\") ListArtifacts = Action(\"ListArtifacts\")", "GetTestGridProject = Action(\"GetTestGridProject\") GetTestGridSession = Action(\"GetTestGridSession\") GetUpload = Action(\"GetUpload\") GetVPCEConfiguration = Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession", "= Action(\"GetJob\") GetNetworkProfile = Action(\"GetNetworkProfile\") GetOfferingStatus = Action(\"GetOfferingStatus\") GetProject = Action(\"GetProject\") GetRemoteAccessSession =", "ListDeviceInstances = Action(\"ListDeviceInstances\") ListDevicePools = Action(\"ListDevicePools\") ListDevices = Action(\"ListDevices\") ListInstanceProfiles = Action(\"ListInstanceProfiles\") ListJobs", "ListNetworkProfiles = Action(\"ListNetworkProfiles\") ListOfferingPromotions = Action(\"ListOfferingPromotions\") ListOfferingTransactions = Action(\"ListOfferingTransactions\") ListOfferings = Action(\"ListOfferings\") ListProjects", "UpdateInstanceProfile = Action(\"UpdateInstanceProfile\") UpdateNetworkProfile = Action(\"UpdateNetworkProfile\") UpdateProject = Action(\"UpdateProject\") UpdateTestGridProject = Action(\"UpdateTestGridProject\") UpdateUpload", "= Action(\"StopRun\") TagResource = Action(\"TagResource\") UntagResource = Action(\"UntagResource\") UpdateDeviceInstance = Action(\"UpdateDeviceInstance\") UpdateDevicePool =", "Action(\"TagResource\") UntagResource = Action(\"UntagResource\") UpdateDeviceInstance = Action(\"UpdateDeviceInstance\") UpdateDevicePool = Action(\"UpdateDevicePool\") UpdateInstanceProfile = Action(\"UpdateInstanceProfile\")", "from .aws import BaseARN service_name = \"AWS Device Farm\" prefix = \"devicefarm\" class", "GetTestGridSession = Action(\"GetTestGridSession\") GetUpload = Action(\"GetUpload\") GetVPCEConfiguration = Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\") ListArtifacts", "ListSamples = Action(\"ListSamples\") ListSuites = Action(\"ListSuites\") ListTagsForResource = Action(\"ListTagsForResource\") ListTestGridProjects = Action(\"ListTestGridProjects\") ListTestGridSessionActions", "GetTest = Action(\"GetTest\") GetTestGridProject = Action(\"GetTestGridProject\") GetTestGridSession = Action(\"GetTestGridSession\") GetUpload = Action(\"GetUpload\") GetVPCEConfiguration", "= Action(\"CreateProject\") CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\") CreateTestGridProject = Action(\"CreateTestGridProject\") CreateTestGridUrl = Action(\"CreateTestGridUrl\") CreateUpload =", "= Action(\"DeleteTestGridProject\") DeleteUpload = Action(\"DeleteUpload\") DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\") GetAccountSettings = Action(\"GetAccountSettings\") GetDevice =", "Action(\"DeleteDevicePool\") DeleteInstanceProfile = Action(\"DeleteInstanceProfile\") DeleteNetworkProfile = Action(\"DeleteNetworkProfile\") DeleteProject = Action(\"DeleteProject\") DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\")", "super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateDevicePool = Action(\"CreateDevicePool\") CreateInstanceProfile = Action(\"CreateInstanceProfile\") CreateNetworkProfile", "CreateTestGridProject = Action(\"CreateTestGridProject\") CreateTestGridUrl = Action(\"CreateTestGridUrl\") CreateUpload = Action(\"CreateUpload\") CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\") DeleteDevicePool", "ListTagsForResource = Action(\"ListTagsForResource\") ListTestGridProjects = Action(\"ListTestGridProjects\") ListTestGridSessionActions = Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions", "ListDevicePools = Action(\"ListDevicePools\") ListDevices = Action(\"ListDevices\") ListInstanceProfiles = Action(\"ListInstanceProfiles\") ListJobs = Action(\"ListJobs\") ListNetworkProfiles", "= Action(\"ListDevicePools\") ListDevices = Action(\"ListDevices\") ListInstanceProfiles = Action(\"ListInstanceProfiles\") ListJobs = Action(\"ListJobs\") ListNetworkProfiles =", "StopRun = Action(\"StopRun\") TagResource = Action(\"TagResource\") UntagResource = Action(\"UntagResource\") UpdateDeviceInstance = Action(\"UpdateDeviceInstance\") UpdateDevicePool", "region=region, account=account ) CreateDevicePool = Action(\"CreateDevicePool\") CreateInstanceProfile = Action(\"CreateInstanceProfile\") CreateNetworkProfile = Action(\"CreateNetworkProfile\") CreateProject", "See LICENSE file for full license. from .aws import Action as BaseAction from", "= Action(\"CreateTestGridUrl\") CreateUpload = Action(\"CreateUpload\") CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\") DeleteDevicePool = Action(\"DeleteDevicePool\") DeleteInstanceProfile =", "ListOfferings = Action(\"ListOfferings\") ListProjects = Action(\"ListProjects\") ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\") ListRuns = Action(\"ListRuns\") ListSamples", "Action(\"ListDevicePools\") ListDevices = Action(\"ListDevices\") ListInstanceProfiles = Action(\"ListInstanceProfiles\") ListJobs = Action(\"ListJobs\") ListNetworkProfiles = Action(\"ListNetworkProfiles\")", "Action(\"ListRuns\") ListSamples = Action(\"ListSamples\") ListSuites = Action(\"ListSuites\") ListTagsForResource = Action(\"ListTagsForResource\") ListTestGridProjects = Action(\"ListTestGridProjects\")", "str = \"\") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateDevicePool =", "= Action(\"CreateDevicePool\") CreateInstanceProfile = Action(\"CreateInstanceProfile\") CreateNetworkProfile = Action(\"CreateNetworkProfile\") CreateProject = Action(\"CreateProject\") CreateRemoteAccessSession =", "CreateNetworkProfile = Action(\"CreateNetworkProfile\") CreateProject = Action(\"CreateProject\") CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\") CreateTestGridProject = Action(\"CreateTestGridProject\") CreateTestGridUrl", "ListUploads = Action(\"ListUploads\") ListVPCEConfigurations = Action(\"ListVPCEConfigurations\") PurchaseOffering = Action(\"PurchaseOffering\") RenewOffering = Action(\"RenewOffering\") ScheduleRun", "file for full license. from .aws import Action as BaseAction from .aws import", "= Action(\"ListSamples\") ListSuites = Action(\"ListSuites\") ListTagsForResource = Action(\"ListTagsForResource\") ListTestGridProjects = Action(\"ListTestGridProjects\") ListTestGridSessionActions =", "Action(\"ListUniqueProblems\") ListUploads = Action(\"ListUploads\") ListVPCEConfigurations = Action(\"ListVPCEConfigurations\") PurchaseOffering = Action(\"PurchaseOffering\") RenewOffering = Action(\"RenewOffering\")", "Action(\"ListJobs\") ListNetworkProfiles = Action(\"ListNetworkProfiles\") ListOfferingPromotions = Action(\"ListOfferingPromotions\") ListOfferingTransactions = Action(\"ListOfferingTransactions\") ListOfferings = Action(\"ListOfferings\")", "# Copyright (c) 2012-2021, <NAME> <<EMAIL>> # All rights reserved. # # See", "ListRuns = Action(\"ListRuns\") ListSamples = Action(\"ListSamples\") ListSuites = Action(\"ListSuites\") ListTagsForResource = Action(\"ListTagsForResource\") ListTestGridProjects", "Action(\"ListTestGridProjects\") ListTestGridSessionActions = Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions = Action(\"ListTestGridSessions\") ListTests = Action(\"ListTests\")", "GetNetworkProfile = Action(\"GetNetworkProfile\") GetOfferingStatus = Action(\"GetOfferingStatus\") GetProject = Action(\"GetProject\") GetRemoteAccessSession = Action(\"GetRemoteAccessSession\") GetRun", "UpdateDeviceInstance = Action(\"UpdateDeviceInstance\") UpdateDevicePool = Action(\"UpdateDevicePool\") UpdateInstanceProfile = Action(\"UpdateInstanceProfile\") UpdateNetworkProfile = Action(\"UpdateNetworkProfile\") UpdateProject", "for full license. from .aws import Action as BaseAction from .aws import BaseARN", "LICENSE file for full license. from .aws import Action as BaseAction from .aws", "CreateInstanceProfile = Action(\"CreateInstanceProfile\") CreateNetworkProfile = Action(\"CreateNetworkProfile\") CreateProject = Action(\"CreateProject\") CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\") CreateTestGridProject", "GetSuite = Action(\"GetSuite\") GetTest = Action(\"GetTest\") GetTestGridProject = Action(\"GetTestGridProject\") GetTestGridSession = Action(\"GetTestGridSession\") GetUpload", "= Action(\"ListSuites\") ListTagsForResource = Action(\"ListTagsForResource\") ListTestGridProjects = Action(\"ListTestGridProjects\") ListTestGridSessionActions = Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts =", "\"devicefarm\" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action)", "Action(\"UpdateNetworkProfile\") UpdateProject = Action(\"UpdateProject\") UpdateTestGridProject = Action(\"UpdateTestGridProject\") UpdateUpload = Action(\"UpdateUpload\") UpdateVPCEConfiguration = Action(\"UpdateVPCEConfiguration\")", "= Action(\"DeleteRun\") DeleteTestGridProject = Action(\"DeleteTestGridProject\") DeleteUpload = Action(\"DeleteUpload\") DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\") GetAccountSettings =", "= Action(\"UpdateDevicePool\") UpdateInstanceProfile = Action(\"UpdateInstanceProfile\") UpdateNetworkProfile = Action(\"UpdateNetworkProfile\") UpdateProject = Action(\"UpdateProject\") UpdateTestGridProject =", "Action(\"RenewOffering\") ScheduleRun = Action(\"ScheduleRun\") StopJob = Action(\"StopJob\") StopRemoteAccessSession = Action(\"StopRemoteAccessSession\") StopRun = Action(\"StopRun\")", "Action(\"GetOfferingStatus\") GetProject = Action(\"GetProject\") GetRemoteAccessSession = Action(\"GetRemoteAccessSession\") GetRun = Action(\"GetRun\") GetSuite = Action(\"GetSuite\")", "UpdateDevicePool = Action(\"UpdateDevicePool\") UpdateInstanceProfile = Action(\"UpdateInstanceProfile\") UpdateNetworkProfile = Action(\"UpdateNetworkProfile\") UpdateProject = Action(\"UpdateProject\") UpdateTestGridProject", "Action(\"StopRemoteAccessSession\") StopRun = Action(\"StopRun\") TagResource = Action(\"TagResource\") UntagResource = Action(\"UntagResource\") UpdateDeviceInstance = Action(\"UpdateDeviceInstance\")", "Action(\"GetSuite\") GetTest = Action(\"GetTest\") GetTestGridProject = Action(\"GetTestGridProject\") GetTestGridSession = Action(\"GetTestGridSession\") GetUpload = Action(\"GetUpload\")", "ListInstanceProfiles = Action(\"ListInstanceProfiles\") ListJobs = Action(\"ListJobs\") ListNetworkProfiles = Action(\"ListNetworkProfiles\") ListOfferingPromotions = Action(\"ListOfferingPromotions\") ListOfferingTransactions", "resource: str = \"\", region: str = \"\", account: str = \"\") ->", "= Action(\"ListDevices\") ListInstanceProfiles = Action(\"ListInstanceProfiles\") ListJobs = Action(\"ListJobs\") ListNetworkProfiles = Action(\"ListNetworkProfiles\") ListOfferingPromotions =", "DeleteInstanceProfile = Action(\"DeleteInstanceProfile\") DeleteNetworkProfile = Action(\"DeleteNetworkProfile\") DeleteProject = Action(\"DeleteProject\") DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\") DeleteRun", "ListSuites = Action(\"ListSuites\") ListTagsForResource = Action(\"ListTagsForResource\") ListTestGridProjects = Action(\"ListTestGridProjects\") ListTestGridSessionActions = Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts", "ListTestGridSessionActions = Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions = Action(\"ListTestGridSessions\") ListTests = Action(\"ListTests\") ListUniqueProblems", "ListUniqueProblems = Action(\"ListUniqueProblems\") ListUploads = Action(\"ListUploads\") ListVPCEConfigurations = Action(\"ListVPCEConfigurations\") PurchaseOffering = Action(\"PurchaseOffering\") RenewOffering", "GetDevicePool = Action(\"GetDevicePool\") GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\") GetInstanceProfile = Action(\"GetInstanceProfile\") GetJob = Action(\"GetJob\") GetNetworkProfile", "Action(\"ListArtifacts\") ListDeviceInstances = Action(\"ListDeviceInstances\") ListDevicePools = Action(\"ListDevicePools\") ListDevices = Action(\"ListDevices\") ListInstanceProfiles = Action(\"ListInstanceProfiles\")", "GetDevice = Action(\"GetDevice\") GetDeviceInstance = Action(\"GetDeviceInstance\") GetDevicePool = Action(\"GetDevicePool\") GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\") GetInstanceProfile", "= Action(\"UpdateInstanceProfile\") UpdateNetworkProfile = Action(\"UpdateNetworkProfile\") UpdateProject = Action(\"UpdateProject\") UpdateTestGridProject = Action(\"UpdateTestGridProject\") UpdateUpload =", "= Action(\"CreateVPCEConfiguration\") DeleteDevicePool = Action(\"DeleteDevicePool\") DeleteInstanceProfile = Action(\"DeleteInstanceProfile\") DeleteNetworkProfile = Action(\"DeleteNetworkProfile\") DeleteProject =", "= Action(\"ListVPCEConfigurations\") PurchaseOffering = Action(\"PurchaseOffering\") RenewOffering = Action(\"RenewOffering\") ScheduleRun = Action(\"ScheduleRun\") StopJob =", "= Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions = Action(\"ListTestGridSessions\") ListTests = Action(\"ListTests\") ListUniqueProblems =", "Action(\"CreateRemoteAccessSession\") CreateTestGridProject = Action(\"CreateTestGridProject\") CreateTestGridUrl = Action(\"CreateTestGridUrl\") CreateUpload = Action(\"CreateUpload\") CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\")", "account: str = \"\") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateDevicePool", "reserved. # # See LICENSE file for full license. from .aws import Action", "= Action(\"StopRemoteAccessSession\") StopRun = Action(\"StopRun\") TagResource = Action(\"TagResource\") UntagResource = Action(\"UntagResource\") UpdateDeviceInstance =", "= Action(\"DeleteInstanceProfile\") DeleteNetworkProfile = Action(\"DeleteNetworkProfile\") DeleteProject = Action(\"DeleteProject\") DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\") DeleteRun =", "= Action(\"DeleteNetworkProfile\") DeleteProject = Action(\"DeleteProject\") DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\") DeleteRun = Action(\"DeleteRun\") DeleteTestGridProject =", "= Action(\"UntagResource\") UpdateDeviceInstance = Action(\"UpdateDeviceInstance\") UpdateDevicePool = Action(\"UpdateDevicePool\") UpdateInstanceProfile = Action(\"UpdateInstanceProfile\") UpdateNetworkProfile =", "ListTestGridSessions = Action(\"ListTestGridSessions\") ListTests = Action(\"ListTests\") ListUniqueProblems = Action(\"ListUniqueProblems\") ListUploads = Action(\"ListUploads\") ListVPCEConfigurations", "Action(\"DeleteProject\") DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\") DeleteRun = Action(\"DeleteRun\") DeleteTestGridProject = Action(\"DeleteTestGridProject\") DeleteUpload = Action(\"DeleteUpload\")", "GetRun = Action(\"GetRun\") GetSuite = Action(\"GetSuite\") GetTest = Action(\"GetTest\") GetTestGridProject = Action(\"GetTestGridProject\") GetTestGridSession", "Action(\"ListVPCEConfigurations\") PurchaseOffering = Action(\"PurchaseOffering\") RenewOffering = Action(\"RenewOffering\") ScheduleRun = Action(\"ScheduleRun\") StopJob = Action(\"StopJob\")", "= Action(\"ListUploads\") ListVPCEConfigurations = Action(\"ListVPCEConfigurations\") PurchaseOffering = Action(\"PurchaseOffering\") RenewOffering = Action(\"RenewOffering\") ScheduleRun =", "rights reserved. # # See LICENSE file for full license. from .aws import", "Action(\"CreateVPCEConfiguration\") DeleteDevicePool = Action(\"DeleteDevicePool\") DeleteInstanceProfile = Action(\"DeleteInstanceProfile\") DeleteNetworkProfile = Action(\"DeleteNetworkProfile\") DeleteProject = Action(\"DeleteProject\")", "Action(\"UpdateDevicePool\") UpdateInstanceProfile = Action(\"UpdateInstanceProfile\") UpdateNetworkProfile = Action(\"UpdateNetworkProfile\") UpdateProject = Action(\"UpdateProject\") UpdateTestGridProject = Action(\"UpdateTestGridProject\")", "StopJob = Action(\"StopJob\") StopRemoteAccessSession = Action(\"StopRemoteAccessSession\") StopRun = Action(\"StopRun\") TagResource = Action(\"TagResource\") UntagResource", "Action(\"DeleteNetworkProfile\") DeleteProject = Action(\"DeleteProject\") DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\") DeleteRun = Action(\"DeleteRun\") DeleteTestGridProject = Action(\"DeleteTestGridProject\")", "= Action(\"GetDeviceInstance\") GetDevicePool = Action(\"GetDevicePool\") GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\") GetInstanceProfile = Action(\"GetInstanceProfile\") GetJob =", "Action(\"GetTest\") GetTestGridProject = Action(\"GetTestGridProject\") GetTestGridSession = Action(\"GetTestGridSession\") GetUpload = Action(\"GetUpload\") GetVPCEConfiguration = Action(\"GetVPCEConfiguration\")", "Action(\"ListInstanceProfiles\") ListJobs = Action(\"ListJobs\") ListNetworkProfiles = Action(\"ListNetworkProfiles\") ListOfferingPromotions = Action(\"ListOfferingPromotions\") ListOfferingTransactions = Action(\"ListOfferingTransactions\")", "GetJob = Action(\"GetJob\") GetNetworkProfile = Action(\"GetNetworkProfile\") GetOfferingStatus = Action(\"GetOfferingStatus\") GetProject = Action(\"GetProject\") GetRemoteAccessSession", "# See LICENSE file for full license. from .aws import Action as BaseAction", "\"\", region: str = \"\", account: str = \"\") -> None: super().__init__( service=prefix,", "= Action(\"GetDevice\") GetDeviceInstance = Action(\"GetDeviceInstance\") GetDevicePool = Action(\"GetDevicePool\") GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\") GetInstanceProfile =", "ListOfferingPromotions = Action(\"ListOfferingPromotions\") ListOfferingTransactions = Action(\"ListOfferingTransactions\") ListOfferings = Action(\"ListOfferings\") ListProjects = Action(\"ListProjects\") ListRemoteAccessSessions", "ScheduleRun = Action(\"ScheduleRun\") StopJob = Action(\"StopJob\") StopRemoteAccessSession = Action(\"StopRemoteAccessSession\") StopRun = Action(\"StopRun\") TagResource", "str = \"\", account: str = \"\") -> None: super().__init__( service=prefix, resource=resource, region=region,", "Action(\"CreateInstanceProfile\") CreateNetworkProfile = Action(\"CreateNetworkProfile\") CreateProject = Action(\"CreateProject\") CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\") CreateTestGridProject = Action(\"CreateTestGridProject\")", "Farm\" prefix = \"devicefarm\" class Action(BaseAction): def __init__(self, action: str = None) ->", "resource=resource, region=region, account=account ) CreateDevicePool = Action(\"CreateDevicePool\") CreateInstanceProfile = Action(\"CreateInstanceProfile\") CreateNetworkProfile = Action(\"CreateNetworkProfile\")", "Action(\"ScheduleRun\") StopJob = Action(\"StopJob\") StopRemoteAccessSession = Action(\"StopRemoteAccessSession\") StopRun = Action(\"StopRun\") TagResource = Action(\"TagResource\")", "Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions = Action(\"ListTestGridSessions\") ListTests = Action(\"ListTests\") ListUniqueProblems = Action(\"ListUniqueProblems\")", "= Action(\"InstallToRemoteAccessSession\") ListArtifacts = Action(\"ListArtifacts\") ListDeviceInstances = Action(\"ListDeviceInstances\") ListDevicePools = Action(\"ListDevicePools\") ListDevices =", "super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = \"\", region: str =", "license. from .aws import Action as BaseAction from .aws import BaseARN service_name =", "ListVPCEConfigurations = Action(\"ListVPCEConfigurations\") PurchaseOffering = Action(\"PurchaseOffering\") RenewOffering = Action(\"RenewOffering\") ScheduleRun = Action(\"ScheduleRun\") StopJob", "= Action(\"GetInstanceProfile\") GetJob = Action(\"GetJob\") GetNetworkProfile = Action(\"GetNetworkProfile\") GetOfferingStatus = Action(\"GetOfferingStatus\") GetProject =", "GetInstanceProfile = Action(\"GetInstanceProfile\") GetJob = Action(\"GetJob\") GetNetworkProfile = Action(\"GetNetworkProfile\") GetOfferingStatus = Action(\"GetOfferingStatus\") GetProject", "DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\") DeleteRun = Action(\"DeleteRun\") DeleteTestGridProject = Action(\"DeleteTestGridProject\") DeleteUpload = Action(\"DeleteUpload\") DeleteVPCEConfiguration", "= Action(\"ListArtifacts\") ListDeviceInstances = Action(\"ListDeviceInstances\") ListDevicePools = Action(\"ListDevicePools\") ListDevices = Action(\"ListDevices\") ListInstanceProfiles =", "Action(\"ListNetworkProfiles\") ListOfferingPromotions = Action(\"ListOfferingPromotions\") ListOfferingTransactions = Action(\"ListOfferingTransactions\") ListOfferings = Action(\"ListOfferings\") ListProjects = Action(\"ListProjects\")", "= Action(\"GetUpload\") GetVPCEConfiguration = Action(\"GetVPCEConfiguration\") InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\") ListArtifacts = Action(\"ListArtifacts\") ListDeviceInstances =", "Action(\"UntagResource\") UpdateDeviceInstance = Action(\"UpdateDeviceInstance\") UpdateDevicePool = Action(\"UpdateDevicePool\") UpdateInstanceProfile = Action(\"UpdateInstanceProfile\") UpdateNetworkProfile = Action(\"UpdateNetworkProfile\")", "Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions = Action(\"ListTestGridSessions\") ListTests = Action(\"ListTests\") ListUniqueProblems = Action(\"ListUniqueProblems\") ListUploads = Action(\"ListUploads\")", "<<EMAIL>> # All rights reserved. # # See LICENSE file for full license.", "UpdateNetworkProfile = Action(\"UpdateNetworkProfile\") UpdateProject = Action(\"UpdateProject\") UpdateTestGridProject = Action(\"UpdateTestGridProject\") UpdateUpload = Action(\"UpdateUpload\") UpdateVPCEConfiguration", "= Action(\"DeleteDevicePool\") DeleteInstanceProfile = Action(\"DeleteInstanceProfile\") DeleteNetworkProfile = Action(\"DeleteNetworkProfile\") DeleteProject = Action(\"DeleteProject\") DeleteRemoteAccessSession =", "= Action(\"ListTagsForResource\") ListTestGridProjects = Action(\"ListTestGridProjects\") ListTestGridSessionActions = Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions =", "(c) 2012-2021, <NAME> <<EMAIL>> # All rights reserved. # # See LICENSE file", "Action(\"GetJob\") GetNetworkProfile = Action(\"GetNetworkProfile\") GetOfferingStatus = Action(\"GetOfferingStatus\") GetProject = Action(\"GetProject\") GetRemoteAccessSession = Action(\"GetRemoteAccessSession\")", "Action(\"StopRun\") TagResource = Action(\"TagResource\") UntagResource = Action(\"UntagResource\") UpdateDeviceInstance = Action(\"UpdateDeviceInstance\") UpdateDevicePool = Action(\"UpdateDevicePool\")", "str = \"\", region: str = \"\", account: str = \"\") -> None:", "from .aws import Action as BaseAction from .aws import BaseARN service_name = \"AWS", "service=prefix, resource=resource, region=region, account=account ) CreateDevicePool = Action(\"CreateDevicePool\") CreateInstanceProfile = Action(\"CreateInstanceProfile\") CreateNetworkProfile =", "= Action(\"DeleteProject\") DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\") DeleteRun = Action(\"DeleteRun\") DeleteTestGridProject = Action(\"DeleteTestGridProject\") DeleteUpload =", "= Action(\"UpdateDeviceInstance\") UpdateDevicePool = Action(\"UpdateDevicePool\") UpdateInstanceProfile = Action(\"UpdateInstanceProfile\") UpdateNetworkProfile = Action(\"UpdateNetworkProfile\") UpdateProject =", "= None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str =", "CreateTestGridUrl = Action(\"CreateTestGridUrl\") CreateUpload = Action(\"CreateUpload\") CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\") DeleteDevicePool = Action(\"DeleteDevicePool\") DeleteInstanceProfile", "DeleteNetworkProfile = Action(\"DeleteNetworkProfile\") DeleteProject = Action(\"DeleteProject\") DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\") DeleteRun = Action(\"DeleteRun\") DeleteTestGridProject", "Action(\"GetDeviceInstance\") GetDevicePool = Action(\"GetDevicePool\") GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\") GetInstanceProfile = Action(\"GetInstanceProfile\") GetJob = Action(\"GetJob\")", "= Action(\"ListOfferings\") ListProjects = Action(\"ListProjects\") ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\") ListRuns = Action(\"ListRuns\") ListSamples =", "service_name = \"AWS Device Farm\" prefix = \"devicefarm\" class Action(BaseAction): def __init__(self, action:", "Action(\"GetAccountSettings\") GetDevice = Action(\"GetDevice\") GetDeviceInstance = Action(\"GetDeviceInstance\") GetDevicePool = Action(\"GetDevicePool\") GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\")", "Action(\"ListSuites\") ListTagsForResource = Action(\"ListTagsForResource\") ListTestGridProjects = Action(\"ListTestGridProjects\") ListTestGridSessionActions = Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\")", "= Action(\"ListTests\") ListUniqueProblems = Action(\"ListUniqueProblems\") ListUploads = Action(\"ListUploads\") ListVPCEConfigurations = Action(\"ListVPCEConfigurations\") PurchaseOffering =", "def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def", "Action(\"PurchaseOffering\") RenewOffering = Action(\"RenewOffering\") ScheduleRun = Action(\"ScheduleRun\") StopJob = Action(\"StopJob\") StopRemoteAccessSession = Action(\"StopRemoteAccessSession\")", "= Action(\"DeleteUpload\") DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\") GetAccountSettings = Action(\"GetAccountSettings\") GetDevice = Action(\"GetDevice\") GetDeviceInstance =", "ListProjects = Action(\"ListProjects\") ListRemoteAccessSessions = Action(\"ListRemoteAccessSessions\") ListRuns = Action(\"ListRuns\") ListSamples = Action(\"ListSamples\") ListSuites", ".aws import BaseARN service_name = \"AWS Device Farm\" prefix = \"devicefarm\" class Action(BaseAction):", "InstallToRemoteAccessSession = Action(\"InstallToRemoteAccessSession\") ListArtifacts = Action(\"ListArtifacts\") ListDeviceInstances = Action(\"ListDeviceInstances\") ListDevicePools = Action(\"ListDevicePools\") ListDevices", "Action(\"DeleteUpload\") DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\") GetAccountSettings = Action(\"GetAccountSettings\") GetDevice = Action(\"GetDevice\") GetDeviceInstance = Action(\"GetDeviceInstance\")", "-> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = \"\", region:", "Action(\"CreateDevicePool\") CreateInstanceProfile = Action(\"CreateInstanceProfile\") CreateNetworkProfile = Action(\"CreateNetworkProfile\") CreateProject = Action(\"CreateProject\") CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\")", "Action(\"DeleteInstanceProfile\") DeleteNetworkProfile = Action(\"DeleteNetworkProfile\") DeleteProject = Action(\"DeleteProject\") DeleteRemoteAccessSession = Action(\"DeleteRemoteAccessSession\") DeleteRun = Action(\"DeleteRun\")", "= Action(\"ScheduleRun\") StopJob = Action(\"StopJob\") StopRemoteAccessSession = Action(\"StopRemoteAccessSession\") StopRun = Action(\"StopRun\") TagResource =", "CreateProject = Action(\"CreateProject\") CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\") CreateTestGridProject = Action(\"CreateTestGridProject\") CreateTestGridUrl = Action(\"CreateTestGridUrl\") CreateUpload", "= Action(\"CreateTestGridProject\") CreateTestGridUrl = Action(\"CreateTestGridUrl\") CreateUpload = Action(\"CreateUpload\") CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\") DeleteDevicePool =", "= Action(\"RenewOffering\") ScheduleRun = Action(\"ScheduleRun\") StopJob = Action(\"StopJob\") StopRemoteAccessSession = Action(\"StopRemoteAccessSession\") StopRun =", "\"\") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateDevicePool = Action(\"CreateDevicePool\") CreateInstanceProfile", "Action(\"CreateProject\") CreateRemoteAccessSession = Action(\"CreateRemoteAccessSession\") CreateTestGridProject = Action(\"CreateTestGridProject\") CreateTestGridUrl = Action(\"CreateTestGridUrl\") CreateUpload = Action(\"CreateUpload\")", "\"\", account: str = \"\") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account )", "Action(\"GetNetworkProfile\") GetOfferingStatus = Action(\"GetOfferingStatus\") GetProject = Action(\"GetProject\") GetRemoteAccessSession = Action(\"GetRemoteAccessSession\") GetRun = Action(\"GetRun\")", "Action(\"ListUploads\") ListVPCEConfigurations = Action(\"ListVPCEConfigurations\") PurchaseOffering = Action(\"PurchaseOffering\") RenewOffering = Action(\"RenewOffering\") ScheduleRun = Action(\"ScheduleRun\")", "= Action(\"TagResource\") UntagResource = Action(\"UntagResource\") UpdateDeviceInstance = Action(\"UpdateDeviceInstance\") UpdateDevicePool = Action(\"UpdateDevicePool\") UpdateInstanceProfile =", "= Action(\"GetRun\") GetSuite = Action(\"GetSuite\") GetTest = Action(\"GetTest\") GetTestGridProject = Action(\"GetTestGridProject\") GetTestGridSession =", "Action(\"ListTagsForResource\") ListTestGridProjects = Action(\"ListTestGridProjects\") ListTestGridSessionActions = Action(\"ListTestGridSessionActions\") ListTestGridSessionArtifacts = Action(\"ListTestGridSessionArtifacts\") ListTestGridSessions = Action(\"ListTestGridSessions\")", ".aws import Action as BaseAction from .aws import BaseARN service_name = \"AWS Device", "Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN):", "= Action(\"ListRemoteAccessSessions\") ListRuns = Action(\"ListRuns\") ListSamples = Action(\"ListSamples\") ListSuites = Action(\"ListSuites\") ListTagsForResource =", "class ARN(BaseARN): def __init__(self, resource: str = \"\", region: str = \"\", account:", "Action(\"CreateTestGridProject\") CreateTestGridUrl = Action(\"CreateTestGridUrl\") CreateUpload = Action(\"CreateUpload\") CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\") DeleteDevicePool = Action(\"DeleteDevicePool\")", "= Action(\"ListOfferingPromotions\") ListOfferingTransactions = Action(\"ListOfferingTransactions\") ListOfferings = Action(\"ListOfferings\") ListProjects = Action(\"ListProjects\") ListRemoteAccessSessions =", "RenewOffering = Action(\"RenewOffering\") ScheduleRun = Action(\"ScheduleRun\") StopJob = Action(\"StopJob\") StopRemoteAccessSession = Action(\"StopRemoteAccessSession\") StopRun", "= Action(\"GetOfferingStatus\") GetProject = Action(\"GetProject\") GetRemoteAccessSession = Action(\"GetRemoteAccessSession\") GetRun = Action(\"GetRun\") GetSuite =", "Action(\"GetInstanceProfile\") GetJob = Action(\"GetJob\") GetNetworkProfile = Action(\"GetNetworkProfile\") GetOfferingStatus = Action(\"GetOfferingStatus\") GetProject = Action(\"GetProject\")", "None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateDevicePool = Action(\"CreateDevicePool\") CreateInstanceProfile = Action(\"CreateInstanceProfile\")", "TagResource = Action(\"TagResource\") UntagResource = Action(\"UntagResource\") UpdateDeviceInstance = Action(\"UpdateDeviceInstance\") UpdateDevicePool = Action(\"UpdateDevicePool\") UpdateInstanceProfile", "class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class", "Action(\"ListRemoteAccessSessions\") ListRuns = Action(\"ListRuns\") ListSamples = Action(\"ListSamples\") ListSuites = Action(\"ListSuites\") ListTagsForResource = Action(\"ListTagsForResource\")", "= Action(\"CreateRemoteAccessSession\") CreateTestGridProject = Action(\"CreateTestGridProject\") CreateTestGridUrl = Action(\"CreateTestGridUrl\") CreateUpload = Action(\"CreateUpload\") CreateVPCEConfiguration =", "= Action(\"GetDevicePool\") GetDevicePoolCompatibility = Action(\"GetDevicePoolCompatibility\") GetInstanceProfile = Action(\"GetInstanceProfile\") GetJob = Action(\"GetJob\") GetNetworkProfile =", "Action(\"DeleteTestGridProject\") DeleteUpload = Action(\"DeleteUpload\") DeleteVPCEConfiguration = Action(\"DeleteVPCEConfiguration\") GetAccountSettings = Action(\"GetAccountSettings\") GetDevice = Action(\"GetDevice\")", "PurchaseOffering = Action(\"PurchaseOffering\") RenewOffering = Action(\"RenewOffering\") ScheduleRun = Action(\"ScheduleRun\") StopJob = Action(\"StopJob\") StopRemoteAccessSession", "Action(\"ListDevices\") ListInstanceProfiles = Action(\"ListInstanceProfiles\") ListJobs = Action(\"ListJobs\") ListNetworkProfiles = Action(\"ListNetworkProfiles\") ListOfferingPromotions = Action(\"ListOfferingPromotions\")", "ListArtifacts = Action(\"ListArtifacts\") ListDeviceInstances = Action(\"ListDeviceInstances\") ListDevicePools = Action(\"ListDevicePools\") ListDevices = Action(\"ListDevices\") ListInstanceProfiles", "= Action(\"ListInstanceProfiles\") ListJobs = Action(\"ListJobs\") ListNetworkProfiles = Action(\"ListNetworkProfiles\") ListOfferingPromotions = Action(\"ListOfferingPromotions\") ListOfferingTransactions =", "= Action(\"ListJobs\") ListNetworkProfiles = Action(\"ListNetworkProfiles\") ListOfferingPromotions = Action(\"ListOfferingPromotions\") ListOfferingTransactions = Action(\"ListOfferingTransactions\") ListOfferings =", "full license. from .aws import Action as BaseAction from .aws import BaseARN service_name", "Action(\"CreateTestGridUrl\") CreateUpload = Action(\"CreateUpload\") CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\") DeleteDevicePool = Action(\"DeleteDevicePool\") DeleteInstanceProfile = Action(\"DeleteInstanceProfile\")", "None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = \"\", region: str", "Action(\"CreateUpload\") CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\") DeleteDevicePool = Action(\"DeleteDevicePool\") DeleteInstanceProfile = Action(\"DeleteInstanceProfile\") DeleteNetworkProfile = Action(\"DeleteNetworkProfile\")", "action) class ARN(BaseARN): def __init__(self, resource: str = \"\", region: str = \"\",", "as BaseAction from .aws import BaseARN service_name = \"AWS Device Farm\" prefix =", "Action(\"GetRemoteAccessSession\") GetRun = Action(\"GetRun\") GetSuite = Action(\"GetSuite\") GetTest = Action(\"GetTest\") GetTestGridProject = Action(\"GetTestGridProject\")", "action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource:", "= Action(\"CreateUpload\") CreateVPCEConfiguration = Action(\"CreateVPCEConfiguration\") DeleteDevicePool = Action(\"DeleteDevicePool\") DeleteInstanceProfile = Action(\"DeleteInstanceProfile\") DeleteNetworkProfile =", "ARN(BaseARN): def __init__(self, resource: str = \"\", region: str = \"\", account: str", "__init__(self, resource: str = \"\", region: str = \"\", account: str = \"\")" ]
[ "def addDropoffControls(locs,prefix): ''' ''' ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder() for i in range(len(locs)): pre =", "mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube( crv profile=None, addCage=False, prefix=None) ''' ''' # Nurbs", "= detach[1] detachNode = detach[-1] mc.delete(detach[0],detach[2]) # Connect Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True)", "mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return Result", "mc.filterExpand(cvs,ex=True,sm=28) # Reset CVs for cv in cvList: crv = mc.ls(cv,o=True)[0] i =", "rn = False, po = 0, et = 2, ucp = 1, fpt", "glTools.tools.controlBuilder import glTools.utils.attach import glTools.utils.base import glTools.utils.attribute import glTools.utils.component import glTools.utils.stringUtils def buildProfile(radius=1,spans=8):", "po = 1, et = 2, ucp = 1, fpt = 1, upn", "detachCrv def buildCurveRig(crv): ''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Build", "glTools.utils.stringUtils.stripSuffix(crv) subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve') # Connect Sub", "prefix = glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv def", "def buildSubCurveDetach(crv): ''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Prep Curve", "# Nurbs Tube mc.extrude( ch = True, rn = False, po = 0,", "# Build Offset def buildSubCurve(crv): ''' ''' # Build Sub Curve prefix =", "pts = glTools.utils.base.getPointArray(crv) jnts = [] mc.select(cl=True) for i in range(len(pts)): ind =", "in range(len(pts)): ind = glTools.utils.stringUtils.alphaIndex(i) jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt) # Orient Joints", "= 1 ) # Polygon Tube mc.extrude( ch = True, rn = False,", "''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Build Joints pts =", "Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp =", "glTools.utils.attribute import glTools.utils.component import glTools.utils.stringUtils def buildProfile(radius=1,spans=8): ''' Create tube profile curve (circle)", "mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube( crv profile=None, addCage=False, prefix=None) ''' ''' # Nurbs Tube", "# Return Result return subCrv def resetCV(cvs): ''' ''' # Check CVs if", "# Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Build Joints pts = glTools.utils.base.getPointArray(crv) jnts", "ind = glTools.utils.stringUtils.alphaIndex(i) jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt) # Orient Joints # Build", "mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube( crv profile=None, addCage=False, prefix=None) ''' ''' # Nurbs Tube mc.extrude(", "crv = mc.ls(cv,o=True)[0] i = glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True): ''' '''", "import glTools.utils.component import glTools.utils.stringUtils def buildProfile(radius=1,spans=8): ''' Create tube profile curve (circle) @param", "= mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) #", "# Build Joints pts = glTools.utils.base.getPointArray(crv) jnts = [] mc.select(cl=True) for i in", "import glTools.utils.base import glTools.utils.attribute import glTools.utils.component import glTools.utils.stringUtils def buildProfile(radius=1,spans=8): ''' Create tube", "''' ''' ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder() for i in range(len(locs)): pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire", "2, ucp = 1, fpt = 1, upn = 1, rotation =0, scale", "fpt = 1, upn = 1, rotation =0, scale =1, rsp = 1", "mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) # Delete Orig if cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv) # Restore Intermediate Shape", "Profile radius @type radius: float @param spans: Number of profile curve spans @type", "mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True): ''' ''' # Get Spans spans = mc.getAttr(crv+'.spans')", "shapeOrig = base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs = mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) # Delete Orig if", "# Return Result return detachCrv def buildCurveRig(crv): ''' ''' # Get Prefix prefix", "jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt) # Orient Joints # Build FK # Build", "Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Build Joints pts = glTools.utils.base.getPointArray(crv) jnts =", "Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Build Joints pts = glTools.utils.base.getPointArray(crv) jnts = []", "ucp = 1, fpt = 1, upn = 1, rotation =0, scale =", "def buildSubCurve(crv): ''' ''' # Build Sub Curve prefix = glTools.utils.stringUtils.stripSuffix(crv) subCrvShape =", "Check CVs if not cvs: return None cvList = mc.filterExpand(cvs,ex=True,sm=28) # Reset CVs", "1, rsp = 1 ) # Polygon Tube mc.extrude( ch = True, rn", "Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) # Detach Curve detach", "''' ''' # Check CVs if not cvs: return None cvList = mc.filterExpand(cvs,ex=True,sm=28)", "mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True)", "mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True)", "return None cvList = mc.filterExpand(cvs,ex=True,sm=28) # Reset CVs for cv in cvList: crv", "Return Result return detachCrv def buildCurveRig(crv): ''' ''' # Get Prefix prefix =", "detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv = detach[1] detachNode = detach[-1] mc.delete(detach[0],detach[2]) # Connect Detach", "subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve') # Connect Sub Curve", "Tube mc.extrude( ch = True, rn = False, po = 1, et =", "import glTools.utils.attach import glTools.utils.base import glTools.utils.attribute import glTools.utils.component import glTools.utils.stringUtils def buildProfile(radius=1,spans=8): '''", "= 1, fpt = 1, upn = 1, rotation =0, scale = 1,", "mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return Result return detachCrv def buildCurveRig(crv): ''' ''' #", "Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp')", "buildOffsetCurve(crv): ''' ''' prefix = glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True)", "return detachCrv def buildCurveRig(crv): ''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) #", "mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv def buildSubCurveDetach(crv): ''' ''' # Get", "prefix = glTools.utils.stringUtils.stripSuffix(crv) # Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) # Detach Curve detach =", "glTools.utils.component import glTools.utils.stringUtils def buildProfile(radius=1,spans=8): ''' Create tube profile curve (circle) @param radius:", "def buildProfile(radius=1,spans=8): ''' Create tube profile curve (circle) @param radius: Profile radius @type", "Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect Sub Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True)", "Sub Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) # Return Result return subCrv", "Restore Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1) # Return Result return def attachToCurveParam(ctrl,crv): ''' ''' grp", "mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) # Return Result return subCrv def resetCV(cvs): ''' ''' #", "''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Build Joints pts = glTools.utils.base.getPointArray(crv)", "None cvList = mc.filterExpand(cvs,ex=True,sm=28) # Reset CVs for cv in cvList: crv =", "crv def buildOffsetCurve(crv): ''' ''' prefix = glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv =", "jnts = [] mc.select(cl=True) for i in range(len(pts)): ind = glTools.utils.stringUtils.alphaIndex(i) jnt =", "mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) # Return Result return subCrv def resetCV(cvs): ''' '''", "= mc.listRelatives(ctrl,p=True,pa=True)[0] param = mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix): ''' ''' ctrlBuilder =", "def buildCurveRig(crv): ''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Build Joints", "mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param = mc.getAttr(locs[i]+'.param') ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl = ctrlBuilder.create('sphere',pre+'_ctrl') grp = glTools.utils.base.group(ctrl)", "mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv = detach[1] detachNode = detach[-1] mc.delete(detach[0],detach[2]) # Connect Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True)", "Detach Curve detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv = detach[1] detachNode = detach[-1] mc.delete(detach[0],detach[2]) #", "mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv def buildOffsetCurve(crv): ''' ''' prefix = glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape')", "Build FK # Build Offset def buildSubCurve(crv): ''' ''' # Build Sub Curve", "''' # Nurbs Tube mc.extrude( ch = True, rn = False, po =", "''' # Get Spans spans = mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) # Match Shape shapeOrig =", "ch = True, rn = False, po = 0, et = 2, ucp", "mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True)", "= glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube( crv profile=None, addCage=False, prefix=None)", "''' ''' # Build Sub Curve prefix = glTools.utils.stringUtils.stripSuffix(crv) subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv", "mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) # Return Result return subCrv def resetCV(cvs): '''", "= glTools.tools.controlBuilder.ControlBuilder() for i in range(len(locs)): pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param", "Tube mc.extrude( ch = True, rn = False, po = 0, et =", "resetCV(cvs): ''' ''' # Check CVs if not cvs: return None cvList =", "Return Result return def attachToCurveParam(ctrl,crv): ''' ''' grp = mc.listRelatives(ctrl,p=True,pa=True)[0] param = mc.getAttr(ctrl+'.param')", "= 1, rsp = 1 ) # Polygon Tube mc.extrude( ch = True,", "mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True): ''' ''' # Get Spans spans = mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans)", "Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1) # Return Result return def attachToCurveParam(ctrl,crv): ''' ''' grp =", "mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True): ''' ''' # Get Spans spans = mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) #", "radius @type radius: float @param spans: Number of profile curve spans @type spans:", "FK # Build Offset def buildSubCurve(crv): ''' ''' # Build Sub Curve prefix", "mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return Result return detachCrv def", "Curve prefix = glTools.utils.stringUtils.stripSuffix(crv) subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve')", "# Delete Orig if cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv) # Restore Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1) #", "= glTools.utils.stringUtils.stripSuffix(crv) # Build Joints pts = glTools.utils.base.getPointArray(crv) jnts = [] mc.select(cl=True) for", "mc.select(cl=True) for i in range(len(pts)): ind = glTools.utils.stringUtils.alphaIndex(i) jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt)", "prefix=None) ''' ''' # Nurbs Tube mc.extrude( ch = True, rn = False,", "prefix = glTools.utils.stringUtils.stripSuffix(crv) subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve') #", "minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True)", "= mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix): ''' ''' ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder() for i", "Polygon Tube mc.extrude( ch = True, rn = False, po = 1, et", "curve spans @type spans: int ''' crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv def buildOffsetCurve(crv):", "= glTools.utils.base.getPointArray(crv) jnts = [] mc.select(cl=True) for i in range(len(pts)): ind = glTools.utils.stringUtils.alphaIndex(i)", "''' ''' prefix = glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return", "addDropoffControls(locs,prefix): ''' ''' ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder() for i in range(len(locs)): pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i])", "# Connect Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect Sub Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True)", "int ''' crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv def buildOffsetCurve(crv): ''' ''' prefix =", "i in range(len(pts)): ind = glTools.utils.stringUtils.alphaIndex(i) jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt) # Orient", "for i in range(len(locs)): pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param = mc.getAttr(locs[i]+'.param')", "''' # Build Sub Curve prefix = glTools.utils.stringUtils.stripSuffix(crv) subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv =", "buildCurveRig(crv): ''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Build Joints pts", "Build Offset def buildSubCurve(crv): ''' ''' # Build Sub Curve prefix = glTools.utils.stringUtils.stripSuffix(crv)", "mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs = mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) # Delete Orig if cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv) #", "return crv def buildOffsetCurve(crv): ''' ''' prefix = glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv", "as mc import glTools.tools.controlBuilder import glTools.utils.attach import glTools.utils.base import glTools.utils.attribute import glTools.utils.component import", "offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv def buildSubCurveDetach(crv): ''' '''", "def attachCurve(base,crv,cleanup=True): ''' ''' # Get Spans spans = mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) # Match", "offsetCrv def buildSubCurveDetach(crv): ''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Prep", "buildSubCurveDetach(crv): ''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3)", "1, rotation =0, scale = 1, rsp = 1 ) # Polygon Tube", "prefix = glTools.utils.stringUtils.stripSuffix(crv) # Build Joints pts = glTools.utils.base.getPointArray(crv) jnts = [] mc.select(cl=True)", "= [] mc.select(cl=True) for i in range(len(pts)): ind = glTools.utils.stringUtils.alphaIndex(i) jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt')", "= True, rn = False, po = 1, et = 2, ucp =", "Create tube profile curve (circle) @param radius: Profile radius @type radius: float @param", "def resetCV(cvs): ''' ''' # Check CVs if not cvs: return None cvList", "= glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl = ctrlBuilder.create('sphere',pre+'_ctrl') grp = glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True)", "= mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) # Delete Orig if cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv) # Restore Intermediate", "Match Shape shapeOrig = base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs = mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) # Delete", "scale = 1, rsp = 1 ) # Polygon Tube mc.extrude( ch =", "mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return Result return detachCrv def buildCurveRig(crv): ''' '''", "buildSubCurve(crv): ''' ''' # Build Sub Curve prefix = glTools.utils.stringUtils.stripSuffix(crv) subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape')", "bs = mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) # Delete Orig if cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv) # Restore", "= mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve') # Connect Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect", "subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve') # Connect Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) #", "ctrlBuilder.create('sphere',pre+'_ctrl') grp = glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube( crv profile=None,", "return subCrv def resetCV(cvs): ''' ''' # Check CVs if not cvs: return", "= mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) # Match Shape shapeOrig = base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs =", "''' crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv def buildOffsetCurve(crv): ''' ''' prefix = glTools.utils.stringUtils.stripSuffix(crv)", "# Orient Joints # Build FK # Build Offset def buildSubCurve(crv): ''' '''", "''' # Check CVs if not cvs: return None cvList = mc.filterExpand(cvs,ex=True,sm=28) #", "grp = mc.listRelatives(ctrl,p=True,pa=True)[0] param = mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix): ''' ''' ctrlBuilder", "not cvs: return None cvList = mc.filterExpand(cvs,ex=True,sm=28) # Reset CVs for cv in", "maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001)", "mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return Result return detachCrv def buildCurveRig(crv): ''' ''' # Get Prefix", "= glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv def buildSubCurveDetach(crv):", "= mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True)", "= mc.getAttr(locs[i]+'.param') ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl = ctrlBuilder.create('sphere',pre+'_ctrl') grp = glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True)", "ctrl = ctrlBuilder.create('sphere',pre+'_ctrl') grp = glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube(", "Joints # Build FK # Build Offset def buildSubCurve(crv): ''' ''' # Build", "= mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv def buildSubCurveDetach(crv): ''' ''' # Get Prefix prefix", "rsp = 1 ) # Polygon Tube mc.extrude( ch = True, rn =", "1, fpt = 1, upn = 1, rotation =0, scale = 1, rsp", "True, rn = False, po = 1, et = 2, ucp = 1,", "detach[1] detachNode = detach[-1] mc.delete(detach[0],detach[2]) # Connect Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd", "def attachToCurveParam(ctrl,crv): ''' ''' grp = mc.listRelatives(ctrl,p=True,pa=True)[0] param = mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def", "Number of profile curve spans @type spans: int ''' crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return", "= mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv def buildOffsetCurve(crv): ''' ''' prefix = glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape =", "mc.delete(crv) # Restore Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1) # Return Result return def attachToCurveParam(ctrl,crv): '''", "Reset CVs for cv in cvList: crv = mc.ls(cv,o=True)[0] i = glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0)", "Orient Joints # Build FK # Build Offset def buildSubCurve(crv): ''' ''' #", "crv profile=None, addCage=False, prefix=None) ''' ''' # Nurbs Tube mc.extrude( ch = True,", "glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True): ''' ''' # Get Spans spans =", "i = glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True): ''' ''' # Get Spans", "# Build FK # Build Offset def buildSubCurve(crv): ''' ''' # Build Sub", "= 1, et = 2, ucp = 1, fpt = 1, upn =", "[] mc.select(cl=True) for i in range(len(pts)): ind = glTools.utils.stringUtils.alphaIndex(i) jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint()", "mc.select(jnt) # Orient Joints # Build FK # Build Offset def buildSubCurve(crv): '''", "return offsetCrv def buildSubCurveDetach(crv): ''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) #", "range(len(locs)): pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param = mc.getAttr(locs[i]+'.param') ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param')", "mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return Result return", "prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param = mc.getAttr(locs[i]+'.param') ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl = ctrlBuilder.create('sphere',pre+'_ctrl')", "subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve') # Connect Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect Sub Curve", "0, et = 2, ucp = 1, fpt = 1, upn = 1,", "detachCrv = detach[1] detachNode = detach[-1] mc.delete(detach[0],detach[2]) # Connect Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True)", "i in range(len(locs)): pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param = mc.getAttr(locs[i]+'.param') ind", "= mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0)", "return def attachToCurveParam(ctrl,crv): ''' ''' grp = mc.listRelatives(ctrl,p=True,pa=True)[0] param = mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True)", "mc.listRelatives(ctrl,p=True,pa=True)[0] param = mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix): ''' ''' ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder()", "for i in range(len(pts)): ind = glTools.utils.stringUtils.alphaIndex(i) jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt) #", "glTools.utils.stringUtils.stripSuffix(crv) # Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) # Detach Curve detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv", "= mc.createNode('subCurve',n=prefix+'_subCurve') # Connect Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect Sub Curve Min/Max", "False, po = 1, et = 2, ucp = 1, fpt = 1,", "# Return Result return def attachToCurveParam(ctrl,crv): ''' ''' grp = mc.listRelatives(ctrl,p=True,pa=True)[0] param =", "= 1, upn = 1, rotation =0, scale = 1, rsp = 1", "grp = glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube( crv profile=None, addCage=False,", "@type radius: float @param spans: Number of profile curve spans @type spans: int", "attachCurve(base,crv,cleanup=True): ''' ''' # Get Spans spans = mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) # Match Shape", "base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs = mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) # Delete Orig if cleanup: mc.delete(shapeOrig,ch=True)", "mc.getAttr(locs[i]+'.param') ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl = ctrlBuilder.create('sphere',pre+'_ctrl') grp = glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True)", "rn = False, po = 1, et = 2, ucp = 1, fpt", "rotation =0, scale = 1, rsp = 1 ) # Polygon Tube mc.extrude(", "= 1, rotation =0, scale = 1, rsp = 1 ) # Polygon", "def buildOffsetCurve(crv): ''' ''' prefix = glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0]", "CVs for cv in cvList: crv = mc.ls(cv,o=True)[0] i = glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0)", "Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) # Detach Curve detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv = detach[1]", "mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube( crv profile=None, addCage=False, prefix=None) ''' '''", "param = mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix): ''' ''' ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder() for", "''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True)", "mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) # Match Shape shapeOrig = base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs = mc.blendShape(crv,shapeOrig)[0]", "mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) # Detach Curve detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv = detach[1] detachNode =", "spans = mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) # Match Shape shapeOrig = base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs", "= ctrlBuilder.create('sphere',pre+'_ctrl') grp = glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube( crv", "glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix): ''' ''' ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder() for i in range(len(locs)):", "cv in cvList: crv = mc.ls(cv,o=True)[0] i = glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def", "spans: int ''' crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv def buildOffsetCurve(crv): ''' ''' prefix", "= mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv def buildSubCurveDetach(crv): ''' ''' #", "def buildTube( crv profile=None, addCage=False, prefix=None) ''' ''' # Nurbs Tube mc.extrude( ch", "= detach[-1] mc.delete(detach[0],detach[2]) # Connect Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear')", "= mc.ls(cv,o=True)[0] i = glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True): ''' ''' #", "''' ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder() for i in range(len(locs)): pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire =", "mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube( crv profile=None, addCage=False, prefix=None) ''' ''' #", "= glTools.utils.stringUtils.stripSuffix(crv) # Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) # Detach Curve detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False)", "mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True)", "Result return subCrv def resetCV(cvs): ''' ''' # Check CVs if not cvs:", "upn = 1, rotation =0, scale = 1, rsp = 1 ) #", "mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt) # Orient Joints # Build FK # Build Offset def", "Get Spans spans = mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) # Match Shape shapeOrig = base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0)", "Return Result return subCrv def resetCV(cvs): ''' ''' # Check CVs if not", "mc.setAttr(shapeOrig+'.intermediateObject',1) # Return Result return def attachToCurveParam(ctrl,crv): ''' ''' grp = mc.listRelatives(ctrl,p=True,pa=True)[0] param", "glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def buildTube( crv profile=None, addCage=False, prefix=None) '''", "= mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt) # Orient Joints # Build FK # Build Offset", "mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve') # Connect Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True)", "mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve') # Connect Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect Sub", "range(len(pts)): ind = glTools.utils.stringUtils.alphaIndex(i) jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt) # Orient Joints #", "radius: float @param spans: Number of profile curve spans @type spans: int '''", "mc.joint() mc.select(jnt) # Orient Joints # Build FK # Build Offset def buildSubCurve(crv):", ") # Polygon Tube mc.extrude( ch = True, rn = False, po =", "# Connect Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear')", "=0, scale = 1, rsp = 1 ) # Polygon Tube mc.extrude( ch", "cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv) # Restore Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1) # Return Result return def", "@param radius: Profile radius @type radius: float @param spans: Number of profile curve", "= 2, ucp = 1, fpt = 1, upn = 1, rotation =0,", "Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) # Detach Curve detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv = detach[1] detachNode", "import maya.cmds as mc import glTools.tools.controlBuilder import glTools.utils.attach import glTools.utils.base import glTools.utils.attribute import", "= prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param = mc.getAttr(locs[i]+'.param') ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl =", "spans: Number of profile curve spans @type spans: int ''' crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False)", "mc.createNode('subCurve',n=prefix+'_subCurve') # Connect Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect Sub Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True)", "Delete Orig if cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv) # Restore Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1) # Return", "glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv def buildSubCurveDetach(crv): '''", "ch = True, rn = False, po = 1, et = 2, ucp", "Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) # Return Result return subCrv def resetCV(cvs):", "minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True)", "= mc.filterExpand(cvs,ex=True,sm=28) # Reset CVs for cv in cvList: crv = mc.ls(cv,o=True)[0] i", "buildProfile(radius=1,spans=8): ''' Create tube profile curve (circle) @param radius: Profile radius @type radius:", "mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix): ''' ''' ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder() for i in range(len(locs)): pre", "Build Joints pts = glTools.utils.base.getPointArray(crv) jnts = [] mc.select(cl=True) for i in range(len(pts)):", "Connect Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect Sub Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True)", "of profile curve spans @type spans: int ''' crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv", "profile=None, addCage=False, prefix=None) ''' ''' # Nurbs Tube mc.extrude( ch = True, rn", "spans @type spans: int ''' crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv def buildOffsetCurve(crv): '''", "1 ) # Polygon Tube mc.extrude( ch = True, rn = False, po", "(circle) @param radius: Profile radius @type radius: float @param spans: Number of profile", "addCage=False, prefix=None) ''' ''' # Nurbs Tube mc.extrude( ch = True, rn =", "= 1, upn = 1, rotation =0, scale =1, rsp = 1 )", "mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return Result return detachCrv def buildCurveRig(crv):", "maya.cmds as mc import glTools.tools.controlBuilder import glTools.utils.attach import glTools.utils.base import glTools.utils.attribute import glTools.utils.component", "mc.delete(crv,ch=True) # Detach Curve detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv = detach[1] detachNode = detach[-1]", "# Detach Curve detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv = detach[1] detachNode = detach[-1] mc.delete(detach[0],detach[2])", "# Reset CVs for cv in cvList: crv = mc.ls(cv,o=True)[0] i = glTools.utils.component.index(cv)", "Curve detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv = detach[1] detachNode = detach[-1] mc.delete(detach[0],detach[2]) # Connect", "''' ''' # Nurbs Tube mc.extrude( ch = True, rn = False, po", "''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) #", "= mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve') # Connect Sub Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True)", "Connect Sub Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) # Return Result return", "cvList: crv = mc.ls(cv,o=True)[0] i = glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True): '''", "mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix): ''' ''' ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder() for i in", "mc.setAttr(base+'.spans',spans) # Match Shape shapeOrig = base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs = mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1)", "import glTools.tools.controlBuilder import glTools.utils.attach import glTools.utils.base import glTools.utils.attribute import glTools.utils.component import glTools.utils.stringUtils def", "Joints pts = glTools.utils.base.getPointArray(crv) jnts = [] mc.select(cl=True) for i in range(len(pts)): ind", "= False, po = 1, et = 2, ucp = 1, fpt =", "mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return Result return detachCrv", "= base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs = mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) # Delete Orig if cleanup:", "ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder() for i in range(len(locs)): pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0]", "mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs = mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) # Delete Orig if cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv)", "profile curve (circle) @param radius: Profile radius @type radius: float @param spans: Number", "= 1, fpt = 1, upn = 1, rotation =0, scale =1, rsp", "1, fpt = 1, upn = 1, rotation =0, scale =1, rsp =", "''' ''' grp = mc.listRelatives(ctrl,p=True,pa=True)[0] param = mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix): '''", "mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return", "mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect Sub Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) # Return", "Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) # Detach Curve", "''' prefix = glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape = mc.createNode('nurbsCurve',n=prefix+'_offsetCrvShape') offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv", "= False, po = 0, et = 2, ucp = 1, fpt =", "subCrv def resetCV(cvs): ''' ''' # Check CVs if not cvs: return None", "curve (circle) @param radius: Profile radius @type radius: float @param spans: Number of", "Shape shapeOrig = base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs = mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) # Delete Orig", "for cv in cvList: crv = mc.ls(cv,o=True)[0] i = glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0)", "mc.setAttr(bs+'.w[0]',1) # Delete Orig if cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv) # Restore Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1)", "param = mc.getAttr(locs[i]+'.param') ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl = ctrlBuilder.create('sphere',pre+'_ctrl') grp = glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True)", "ucp = 1, fpt = 1, upn = 1, rotation =0, scale =1,", "''' ''' # Get Spans spans = mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) # Match Shape shapeOrig", "mc.setAttr(subCrvNode+'.relative',1) # Return Result return subCrv def resetCV(cvs): ''' ''' # Check CVs", "CVs if not cvs: return None cvList = mc.filterExpand(cvs,ex=True,sm=28) # Reset CVs for", "mc.extrude( ch = True, rn = False, po = 0, et = 2,", "mc import glTools.tools.controlBuilder import glTools.utils.attach import glTools.utils.base import glTools.utils.attribute import glTools.utils.component import glTools.utils.stringUtils", "mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv def buildSubCurveDetach(crv): ''' ''' # Get Prefix prefix =", "@param spans: Number of profile curve spans @type spans: int ''' crv =", "Result return detachCrv def buildCurveRig(crv): ''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv)", "mc.extrude( ch = True, rn = False, po = 1, et = 2,", "crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv def buildOffsetCurve(crv): ''' ''' prefix = glTools.utils.stringUtils.stripSuffix(crv) offsetCrvShape", "# Polygon Tube mc.extrude( ch = True, rn = False, po = 1,", "float @param spans: Number of profile curve spans @type spans: int ''' crv", "Spans spans = mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) # Match Shape shapeOrig = base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3)", "# Match Shape shapeOrig = base+'ShapeOrig' mc.setAttr(shapeOrig+'.intermediateObject',0) mc.rebuildCurve(shapeOrig,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=3) bs = mc.blendShape(crv,shapeOrig)[0] mc.setAttr(bs+'.w[0]',1) #", "ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl = ctrlBuilder.create('sphere',pre+'_ctrl') grp = glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True)", "glTools.utils.stringUtils.alphaIndex(i) jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt) # Orient Joints # Build FK #", "Orig if cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv) # Restore Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1) # Return Result", "cvs: return None cvList = mc.filterExpand(cvs,ex=True,sm=28) # Reset CVs for cv in cvList:", "if not cvs: return None cvList = mc.filterExpand(cvs,ex=True,sm=28) # Reset CVs for cv", "Offset def buildSubCurve(crv): ''' ''' # Build Sub Curve prefix = glTools.utils.stringUtils.stripSuffix(crv) subCrvShape", "# Check CVs if not cvs: return None cvList = mc.filterExpand(cvs,ex=True,sm=28) # Reset", "= glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True): ''' ''' # Get Spans spans", "Connect Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp", "cvList = mc.filterExpand(cvs,ex=True,sm=28) # Reset CVs for cv in cvList: crv = mc.ls(cv,o=True)[0]", "Build Sub Curve prefix = glTools.utils.stringUtils.stripSuffix(crv) subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode", "Sub Curve prefix = glTools.utils.stringUtils.stripSuffix(crv) subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode =", "glTools.utils.base import glTools.utils.attribute import glTools.utils.component import glTools.utils.stringUtils def buildProfile(radius=1,spans=8): ''' Create tube profile", "glTools.tools.controlBuilder.ControlBuilder() for i in range(len(locs)): pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param =", "et = 2, ucp = 1, fpt = 1, upn = 1, rotation", "glTools.utils.stringUtils def buildProfile(radius=1,spans=8): ''' Create tube profile curve (circle) @param radius: Profile radius", "po = 0, et = 2, ucp = 1, fpt = 1, upn", "<filename>tools/tube.py<gh_stars>100-1000 import maya.cmds as mc import glTools.tools.controlBuilder import glTools.utils.attach import glTools.utils.base import glTools.utils.attribute", "# Connect Sub Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) # Return Result", "detachNode = detach[-1] mc.delete(detach[0],detach[2]) # Connect Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd =", "glTools.utils.stringUtils.stripSuffix(crv) # Build Joints pts = glTools.utils.base.getPointArray(crv) jnts = [] mc.select(cl=True) for i", "pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param = mc.getAttr(locs[i]+'.param') ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl", "tube profile curve (circle) @param radius: Profile radius @type radius: float @param spans:", "mc.delete(detach[0],detach[2]) # Connect Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd =", "glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl = ctrlBuilder.create('sphere',pre+'_ctrl') grp = glTools.utils.base.group(ctrl) mc.connectAttr(locs[i]+'.worldPosition[0]',grp+'.translate',f=True) mc.addAttr(ctrl,ln='param',min=0,max=1,dv=param,k=True) mc.addAttr(ctrl,ln='bulge',min=-1,dv=0,k=True) mc.connectAttr(ctrl+'.param',locs[i]+'.param['+str(ind)+']',f=True) mc.connectAttr(ctrl+'.bulge',wire+'.wireLocatorEnvelope['+str(ind)+']',f=True) def", "@type spans: int ''' crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv def buildOffsetCurve(crv): ''' '''", "= 0, et = 2, ucp = 1, fpt = 1, upn =", "fpt = 1, upn = 1, rotation =0, scale = 1, rsp =", "radius: Profile radius @type radius: float @param spans: Number of profile curve spans", "= True, rn = False, po = 0, et = 2, ucp =", "''' grp = mc.listRelatives(ctrl,p=True,pa=True)[0] param = mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix): ''' '''", "1, et = 2, ucp = 1, fpt = 1, upn = 1,", "import glTools.utils.attribute import glTools.utils.component import glTools.utils.stringUtils def buildProfile(radius=1,spans=8): ''' Create tube profile curve", "buildTube( crv profile=None, addCage=False, prefix=None) ''' ''' # Nurbs Tube mc.extrude( ch =", "mc.ls(cv,o=True)[0] i = glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True): ''' ''' # Get", "Curve mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect Sub Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1)", "Nurbs Tube mc.extrude( ch = True, rn = False, po = 0, et", "mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True) mc.setAttr(minMaxClamp+'.min',0,0,0.0001) mc.setAttr(minMaxClamp+'.max',0.9999,0,0) mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return Result return detachCrv def buildCurveRig(crv): '''", "''' Create tube profile curve (circle) @param radius: Profile radius @type radius: float", "glTools.utils.base.getPointArray(crv) jnts = [] mc.select(cl=True) for i in range(len(pts)): ind = glTools.utils.stringUtils.alphaIndex(i) jnt", "in cvList: crv = mc.ls(cv,o=True)[0] i = glTools.utils.component.index(cv) mc.setAttr(crv+'.controlPoints['+i+'].xValue',0) mc.setAttr(crv+'.controlPoints['+i+'].yValue',0) mc.setAttr(crv+'.controlPoints['+i+'].zValue',0) def attachCurve(base,crv,cleanup=True):", "import glTools.utils.stringUtils def buildProfile(radius=1,spans=8): ''' Create tube profile curve (circle) @param radius: Profile", "= glTools.utils.stringUtils.alphaIndex(i) jnt = mc.joint(p=pts[i],n=prefix+'_fk'+ind+'_jnt') mc.joint() mc.select(jnt) # Orient Joints # Build FK", "mc.connectAttr(minMaxClamp+'.outputR',detachNode+'.parameter[0]',f=True) mc.connectAttr(minMaxClamp+'.outputB',detachNode+'.parameter[1]',f=True) # Return Result return detachCrv def buildCurveRig(crv): ''' ''' # Get", "Shape mc.setAttr(shapeOrig+'.intermediateObject',1) # Return Result return def attachToCurveParam(ctrl,crv): ''' ''' grp = mc.listRelatives(ctrl,p=True,pa=True)[0]", "offsetCrv = mc.listRelatives(offsetCrvShape,p=True,pa=True)[0] mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv def buildSubCurveDetach(crv): ''' ''' # Get Prefix", "= mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv = detach[1] detachNode = detach[-1] mc.delete(detach[0],detach[2]) # Connect Detach Min/Max", "# Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) # Detach Curve detach = mc.detachCurve(crv,p=(0.001,0.999),k=(0,1,0),rpo=False) detachCrv =", "attachToCurveParam(ctrl,crv): ''' ''' grp = mc.listRelatives(ctrl,p=True,pa=True)[0] param = mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param') mc.connectAttr(ctrl+'.param',grp+'.param',f=True) def addDropoffControls(locs,prefix):", "= mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param = mc.getAttr(locs[i]+'.param') ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl = ctrlBuilder.create('sphere',pre+'_ctrl') grp =", "False, po = 0, et = 2, ucp = 1, fpt = 1,", "1, upn = 1, rotation =0, scale = 1, rsp = 1 )", "if cleanup: mc.delete(shapeOrig,ch=True) mc.delete(crv) # Restore Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1) # Return Result return", "True, rn = False, po = 0, et = 2, ucp = 1,", "detach[-1] mc.delete(detach[0],detach[2]) # Connect Detach Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.addAttr(subCrv,ln='offset',min=-1,max=1,dv=1,k=True) minAdd = mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd", "Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) # Return Result return subCrv def", "# Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv) # Prep Curve mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=1,kep=1,kt=0,s=0,d=3) mc.delete(crv,ch=True) # Detach", "mc.connectAttr(crv+'.worldSpace[0]',offsetCrvShape+'.create',f=True) return offsetCrv def buildSubCurveDetach(crv): ''' ''' # Get Prefix prefix = glTools.utils.stringUtils.stripSuffix(crv)", "glTools.utils.attach import glTools.utils.base import glTools.utils.attribute import glTools.utils.component import glTools.utils.stringUtils def buildProfile(radius=1,spans=8): ''' Create", "= glTools.utils.stringUtils.stripSuffix(crv) subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0] subCrvNode = mc.createNode('subCurve',n=prefix+'_subCurve') # Connect", "profile curve spans @type spans: int ''' crv = mc.circle(c=[0,0,0],nr=[0,0,1],sw=360,r=radius,s=spans,d=3,ch=False) return crv def", "mc.delete(shapeOrig,ch=True) mc.delete(crv) # Restore Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1) # Return Result return def attachToCurveParam(ctrl,crv):", "mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) # Return Result return subCrv def resetCV(cvs): ''' ''' # Check", "mc.createNode('addDoubleLinear',n=prefix+'_minAdd_addDoubleLinear') maxAdd = mc.createNode('addDoubleLinear',n=prefix+'_maxAdd_addDoubleLinear') minMaxClamp = mc.createNode('clamp',n=prefix+'_minMax_clamp') mc.connectAttr(subCrv+'.min',minAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',minAdd+'.input2',f=True) mc.connectAttr(subCrv+'.max',maxAdd+'.input1',f=True) mc.connectAttr(subCrv+'.offset',maxAdd+'.input2',f=True) mc.connectAttr(minAdd+'.output',minMaxClamp+'.inputR',f=True) mc.connectAttr(maxAdd+'.output',minMaxClamp+'.inputB',f=True)", "mc.connectAttr(crv+'.worldSpace[0]',subCrvNode+'.inputCurve',f=True) mc.connectAttr(subCrvNode+'.outputCurve',subCrvShape+'.create',f=True) # Connect Sub Curve Min/Max mc.addAttr(subCrv,ln='min',min=0,max=0.999,dv=0,k=True) mc.addAttr(subCrv,ln='max',min=0.001,max=1,dv=1,k=True) mc.connectAttr(subCrv+'.min',subCrvNode+'.minValue',f=True) mc.connectAttr(subCrv+'.max',subCrvNode+'.maxValue',f=True) mc.setAttr(subCrvNode+'.relative',1) #", "wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param = mc.getAttr(locs[i]+'.param') ind = glTools.utils.attribute.getConnectionIndex(locs[i]+'.param') ctrl = ctrlBuilder.create('sphere',pre+'_ctrl') grp", "# Build Sub Curve prefix = glTools.utils.stringUtils.stripSuffix(crv) subCrvShape = mc.createNode('nurbsCurve',n=prefix+'_subCrvShape') subCrv = mc.listRelatives(subCrvShape,p=True,pa=True)[0]", "Result return def attachToCurveParam(ctrl,crv): ''' ''' grp = mc.listRelatives(ctrl,p=True,pa=True)[0] param = mc.getAttr(ctrl+'.param') glTools.utils.attach.attachToCurve(crv,grp,param,uAttr='param')", "# Restore Intermediate Shape mc.setAttr(shapeOrig+'.intermediateObject',1) # Return Result return def attachToCurveParam(ctrl,crv): ''' '''", "in range(len(locs)): pre = prefix+glTools.utils.stringUtils.stripSuffix(locs[i]) wire = mc.listConnections(locs[i]+'.param',s=False,d=True)[0] param = mc.getAttr(locs[i]+'.param') ind =", "# Get Spans spans = mc.getAttr(crv+'.spans') mc.setAttr(base+'.spans',spans) # Match Shape shapeOrig = base+'ShapeOrig'" ]
[ "import BackupPath from .Container import Container from .DobaContainersConfig import DobaContainersConfig from .Image import", ".BackupPath import BackupPath from .Container import Container from .DobaContainersConfig import DobaContainersConfig from .Image", ".DobaContainersConfig import DobaContainersConfig from .Image import Image from .Port import Port from .Volume", "import Container from .DobaContainersConfig import DobaContainersConfig from .Image import Image from .Port import", "DobaContainersConfig from .Image import Image from .Port import Port from .Volume import Volume", "from .Container import Container from .DobaContainersConfig import DobaContainersConfig from .Image import Image from", "from .BackupPath import BackupPath from .Container import Container from .DobaContainersConfig import DobaContainersConfig from", ".Container import Container from .DobaContainersConfig import DobaContainersConfig from .Image import Image from .Port", "from .DobaContainersConfig import DobaContainersConfig from .Image import Image from .Port import Port from", "BackupPath from .Container import Container from .DobaContainersConfig import DobaContainersConfig from .Image import Image", "import DobaContainersConfig from .Image import Image from .Port import Port from .Volume import", "Container from .DobaContainersConfig import DobaContainersConfig from .Image import Image from .Port import Port" ]
[ "sentinel2_tiles.append(temp_tile) return sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This function returns the useful bathy points", "tidal = get_tidal_elevation_for_image(safe_id) temp_safe = Sentinel2Safe() temp_safe.date = date temp_safe.time = t_time temp_safe.s2_path", "safe_path x, y, epsg = get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners = (x, y) temp_safe.epsg = epsg", "it is not to close to others if len(ind[0]) == 0: if isin_tile(x_point,", "time.time() while nb < cfg.nb_max_pt_per_tile and n < cfg.line_max_read: n += 1 n_tot", "i_y in range(n_y): ncd_time = ncd.variables['time'][i_t] ncd_x = ncd.variables['x'][i_x] ncd_y = ncd.variables['y'][i_y] z", "pass # Different snapshots of the same tile should have the exact same", "# t_time = safe_id[20:26] # a = os.listdir(os.path.join(safe_path, 'GRANULE')) # path = os.path.join(safe_path,", "out_y = [] out_z = [] n_err = 0 n_good = 0 n_all", "= np.linspace(0, len(bins) - 2, len(bins) - 1) bathy_points['depth label'] = pd.cut(bathy_points['depth(m -", "{temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if temp_safe.epsg not in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs)", "bathy points :param z: z coordinates of already kept bathy points :return: (x,", "(around the actual tile center) a = timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0] + b)) &", "= safe_id[20:26] tidal = get_tidal_elevation_for_image(safe_id) temp_safe = Sentinel2Safe() temp_safe.date = date temp_safe.time =", "= new_z n_err += 1 else: n_dash += 1 if n_all % 5000", "COME BACK TO THIS sentinel2_tiles = [] i = -1 for tile in", "timing_start) & (df['S2_time'] < timing_end) timing_search = df.loc[mask] b = 1 # +/-", "= timing - delta_t timing_end = timing + delta_t timing_start = timing_start.strftime('%Y-%m-%d %H:%M:%S')", "borders & depth limited (+ & -) :param path: path of the bathymetry", "= safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}') date = safe_id[11:19] t_time = safe_id[20:26] tidal =", "= 0 return temp_safe def parse_sentinel2_tiles_metadata(): \"\"\" This function returns the info of", "n_dash += 1 if n_all % 5000 == 0: print(f'all: {n_all}, keep: {n_good},", "n_t = len(ncd.variables['time']) out_x = [] out_y = [] out_z = [] n_err", ":param path:(str) path to the .SAFE repository of the image :return: cloud_coverage (float)", "in sentinel2_tiles: in_tiles = True temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles = False print(f'--------------TILE:", "exit() if temp_tile.corner['x'] and temp_tile.corner['y']: if temp_safe.corners[0] != temp_tile.corner['x'] or temp_safe.corners[1] != temp_tile.corner['y']:", ":return: (x, y, z): coordinates of the bathy points kept, appended to the", "lat = np.array(df.lat) z = np.array(df.z) if projection_in and projection_out: proj = pyproj.Proj(proj='utm',", "[] with open(cfg.in_path_safes_list, 'r') as file: safe_ids = file.read().splitlines() for safe_id in safe_ids:", "1) bathy_points['depth label'] = pd.cut(bathy_points['depth(m - down positive - LAT)'], bins=bins, labels=labels) print(bathy_points['depth", "1 out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z) else: new_z = (z + ncd_z) / 2 z", "'GRANULE', a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') # ds = gdal.Open(path + 'B04.jp2') # return ds.GetGeoTransform()", "the top left corner of the S2-L1C image in the WGS84 coordinate system", "TO THIS sentinel2_tiles = [] i = -1 for tile in cfg.tiles: temp_tile", "os.path.join(path_t, safe) cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc and n < cfg.nb_max_date:", "y, z = [[]] * nb_tiles, [[]] * nb_tiles, [[]] * nb_tiles proj", "* nb_tiles, [[]] * nb_tiles proj = [[]] * nb_tiles for i in", "temp_safe.s2_path = safe_path x, y, epsg = get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners = (x, y) temp_safe.epsg", "have the exact same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] if", "date temp_safe.time = t_time temp_safe.s2_path = safe_path x, y, epsg = get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners", "ncd['depth'][i_y, i_x, i_k, i_t] n_all += 1 if ncd_z != '--': if z", "[] n_err = 0 n_good = 0 n_all = 0 n_dash = 0", "np.linspace(cfg.depth_lim_min, 100, 10) max_depth = bathy_points['depth(m - down positive - LAT)'].max() if max_depth", "n += 1 sentinel2_tiles.append(temp_tile) return sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This function returns the", "coverage of the S2-L1C image in the xml file :param path:(str) path to", "b = 1 # +/- 1 degree to search for the tidal information", "print(f'len(bathy_label_points) at label:{label} == 0') print('nb of lines read/selected :', n_tot, '/', nb_tot)", "i_k in range(n_k): ncd_z = ncd['depth'][i_y, i_x, i_k, i_t] n_all += 1 if", "kept bathy points :param y: y coordinates of already kept bathy points :param", "bathy_points['depth label'] = pd.cut(bathy_points['depth(m - down positive - LAT)'], bins=bins, labels=labels) print(bathy_points['depth label'].value_counts(sort=False))", "keep: {n_good}, errs: {n_err}, dash: {n_dash}') fn = path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}') print(f' Total:", "month = safe_id[15:17] day = safe_id[17:19] tile_id = safe_id[39:44] temp_tile = Sentinel2Tile() temp_tile.id", "out_x, out_y, out_z def read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None): df = pd.read_csv(path_to_xyz, header=0) lng =", "bathymetry :param x: x coordinates of already kept bathy points :param y: y", "cfg.max_cc and n < cfg.nb_max_date: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}')", "the actual tile center) a = timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0] + b)) & (timing_search['S2_lon']", "= 0 n_good = 0 n_all = 0 n_dash = 0 for i_t", "- y_point) < precision) # keep the point only if it is not", "et.parse(xml) root = tree.getroot() x_corner = int(root[1][0][5][0].text) y_corner = int(root[1][0][5][1].text) epsg = root[1][0][1].text", "LAT)']) if n % 1000 == 0: print(n) print('label :', label, nb, '/',", "for i_t in range(n_t): for i_x in range(n_x): for i_y in range(n_y): ncd_time", "close to tile borders & depth limited (+ & -) :param path: path", "timing_end = timing + delta_t timing_start = timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end = timing_end.strftime('%Y-%m-%d %H:%M:%S')", "====================================== didn\\'t find tile {tile.id}\\'s epsg?') exit() bathy_points = pd.DataFrame() for directory in", "return x, y, z def __flip_bathymetry_y_axis(arr): unique_values = np.unique(arr) flipped = np.empty(np.array(arr).shape) for", "exit() else: pass # Different snapshots of the same tile should have the", "points kept, appended to the previous ones \"\"\" precision = 10 nb_tiles =", "1 degree to search for the tidal information (around the actual tile center)", "for {fn}...') out_y = __flip_bathymetry_y_axis(out_y) return out_x, out_y, out_z def read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None):", "{n_err}, --: {n_dash}') print(f' len(x): {len(out_x)}, len(y): {len(out_y)}, len(z): {len(out_z)}') print(f' Creating CSV", "1 sentinel2_tiles.append(temp_tile) return sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This function returns the info of", "b)) & (timing_search['S2_lat'] < (tid['S2_lat'].values[0] + b)) & (timing_search['S2_lat'] > (tid['S2_lat'].values[0] - b))]", "of the S2-L1C image in the xml file :param path:(str) path to the", "safe[11:19] time = safe[20:26] tidal_path = cfg.in_path_tidal df = xr.open_dataset(tidal_path).to_dataframe() tid = df[df['S2_fname']", "of the image :return: x_corner, y_corner, epsg (int, int, str) \"\"\" xml =", "safe_id[15:17] day = safe_id[17:19] tile_id = safe_id[39:44] temp_tile = Sentinel2Tile() temp_tile.id = tile_id", "else: warnings.warn( f'THIS SHOULD NEVER HAPPEN ====================================== didn\\'t find tile {tile.id}\\'s epsg?') exit()", "2, len(bins) - 1) bathy_points['depth label'] = pd.cut(bathy_points['depth(m - down positive - LAT)'],", "the image :return: cloud_coverage (float) \"\"\" xml = os.path.join(path, 'MTD_MSIL1C.xml') tree = et.parse(xml)", "xarray as xr import pandas as pd import netCDF4 as nc import xml.etree.ElementTree", "f'============================================ Tile {id}: multiple corners') exit() else: pass # Different snapshots of the", "temp_safe.date = date temp_safe.time = t_time temp_safe.s2_path = safe_path x, y, epsg =", "if temp_tile in sentinel2_tiles: in_tiles = True temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles =", "None for i_k in range(n_k): ncd_z = ncd['depth'][i_y, i_x, i_k, i_t] n_all +=", "safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}') date = safe_id[11:19] t_time = safe_id[20:26] tidal = get_tidal_elevation_for_image(safe_id)", "z = np.array(df.z) if projection_in and projection_out: proj = pyproj.Proj(proj='utm', init=projection_out, ellps=projection_in) lng,", "time = safe[20:26] tidal_path = cfg.in_path_tidal df = xr.open_dataset(tidal_path).to_dataframe() tid = df[df['S2_fname'] ==", "\"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc and n < cfg.nb_max_date: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if", "from utilities.wrappers import Sentinel2Safe # TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO", "tidal elevation data') return None else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t = timedelta(hours=1) timing =", "label'] = pd.cut(bathy_points['depth(m - down positive - LAT)'], bins=bins, labels=labels) print(bathy_points['depth label'].value_counts(sort=False)) n_tot", "1 if n_all % 5000 == 0: print(f'all: {n_all}, keep: {n_good}, errs: {n_err},", "else: in_tiles = False print(f'--------------TILE: {temp_tile.id}') path_t = os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s = os.path.join(path_t,", "0: for i in range(nb_tiles): tile = sentinel2tile_list[i] if tile.epsgs[0] != 'EPSG:32628': #", "i_t] n_all += 1 if ncd_z != '--': if z is None: z", "= np.nanmean(a['prediction_at_ERA5_point'].values) return tidal else: tidal = tid['prediction_at_ERA5_point'].values[0] return tidal # def get_geo_transform_for_image(s2_path,", "timing - delta_t timing_end = timing + delta_t timing_start = timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end", "False print(f'--------------TILE: {temp_tile.id}') path_t = os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s = os.path.join(path_t, year, month, day,", "the tile and its epsg reference number :param path:(str) path to the .SAFE", "temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs) > 1: warnings.warn(f'==================================== Tile {temp_tile.id}: multiple epsg\\'s') exit() if temp_tile.corner['x']", "& (timing_search['S2_lat'] < (tid['S2_lat'].values[0] + b)) & (timing_search['S2_lat'] > (tid['S2_lat'].values[0] - b))] tidal", "in the xml file :param path:(str) path to the .SAFE repository of the", "Different snapshots of the same tile should have the exact same corners else:", "image :return: cloud_coverage (float) \"\"\" xml = os.path.join(path, 'MTD_MSIL1C.xml') tree = et.parse(xml) root", "reference number :param path:(str) path to the .SAFE repository of the image :return:", "= len(ncd.variables['kKeep']) n_t = len(ncd.variables['time']) out_x = [] out_y = [] out_z =", "UNCOMMENT MAIN IMPORT AND COME BACK TO THIS sentinel2_tiles = [] with open(cfg.in_path_safes_list,", "tile and its epsg reference number :param path:(str) path to the .SAFE repository", "temp_tile = Sentinel2Tile() temp_tile.id = tile print(f'--------------TILE: {temp_tile.id}') n = 0 i +=", "smallest cloud coverage :return: corners, paths, dates, epsgs: infos of the selected tiles", "if cfg.depth_lim_min <= random_point['depth(m - down positive - LAT)'] <= cfg.depth_lim_max: if not", "= [] out_y = [] out_z = [] n_err = 0 n_good =", "delta_t = timedelta(hours=1) timing = datetime.strptime(date + time, '%Y%m%d%H%M%S') timing_start = timing -", "the indices of the points to close to the actual point ind =", "to much redundancy) & not to close to tile borders & depth limited", "- LAT)'] <= cfg.depth_lim_max: if not len(sentinel2tile_list) == 0: for i in range(nb_tiles):", "proj[i](random_point['long(DD)'], random_point['lat(DD)']) else: # bathy and s2 are already on the same coordinate", "2 criteria : distance to each others (not to much redundancy) & not", "to tile borders & depth limited (+ & -) :param path: path of", "len(ncd.variables['x']) n_y = len(ncd.variables['y']) n_k = len(ncd.variables['kKeep']) n_t = len(ncd.variables['time']) out_x = []", "print(f' {date} - {time}: no tidal elevation data') return None else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]):", "utilities.wrappers import Sentinel2Tile, Sentinel2Safe def get_cloud_coverage(path): \"\"\" Find the cloud coverage of the", "header=2) bathy_points = bathy_points.append(df, ignore_index=True) bins = np.linspace(cfg.depth_lim_min, 100, 10) max_depth = bathy_points['depth(m", "= temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] n += 1 sentinel2_tiles.append(temp_tile) return sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake():", "1 # tile index path_t = os.path.join(cfg.in_path_s2, tile) safes = os.listdir(path_t) temp =", "= [[]] * nb_tiles for i in range(nb_tiles): tile = sentinel2tile_list[i] if len(tile.epsgs)", "ellps='WGS84') elif len(tile.epsgs) > 1: warnings.warn(f'AGAIN =================================================== Tile {tile.id}: multiple epsg\\'s') exit() else:", "import numpy as np import xarray as xr import pandas as pd import", "= 0 for label in labels: bathy_label_points = bathy_points[bathy_points['depth label'] == label] if", "multiple epsg\\'s') exit() else: warnings.warn( f'THIS SHOULD NEVER HAPPEN ====================================== didn\\'t find tile", "0 for i_t in range(n_t): for i_x in range(n_x): for i_y in range(n_y):", "# date = safe_id[11:19] # t_time = safe_id[20:26] # a = os.listdir(os.path.join(safe_path, 'GRANULE'))", "the smallest cloud coverage :return: corners, paths, dates, epsgs: infos of the selected", "np.nanmean(a['prediction_at_ERA5_point'].values) return tidal else: tidal = tid['prediction_at_ERA5_point'].values[0] return tidal # def get_geo_transform_for_image(s2_path, tile_id,", "import gdal import pyproj import tarfile import warnings import numpy as np import", "0 i += 1 # tile index path_t = os.path.join(cfg.in_path_s2, tile) safes =", "!= 'EPSG:32628': # proj to the good coordinate system & round to the", "0 n_dash = 0 for i_t in range(n_t): for i_x in range(n_x): for", "unique_values = np.unique(arr) flipped = np.empty(np.array(arr).shape) for i in range(len(arr)): flipped[i] = np.flipud(unique_values)[np.where(unique_values", "distance to each others (not to much redundancy) & not to close to", "0') print('nb of lines read/selected :', n_tot, '/', nb_tot) return x, y, z", "- 5]] if tid['prediction_at_ERA5_point'].empty: print(f' {date} - {time}: no tidal elevation data') return", "i in range(nb_tiles): tile = sentinel2tile_list[i] if tile.epsgs[0] != 'EPSG:32628': # proj to", "y_point) < precision) # keep the point only if it is not to", "tile should have the exact same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] =", "z = None for i_k in range(n_k): ncd_z = ncd['depth'][i_y, i_x, i_k, i_t]", "ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers import Sentinel2Safe # TODO: UNCOMMENT MAIN IMPORT AND", "y_corner, epsg def make_tarfile(output_filename, source_dir): with tarfile.open(output_filename, \"w:gz\") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) def", "of the bathy points kept, appended to the previous ones \"\"\" precision =", "safe: {safe_id}') temp_safe.tidal_elevation = 0 return temp_safe def parse_sentinel2_tiles_metadata(): \"\"\" This function returns", "1 chosen_idx = np.random.choice(len(bathy_label_points)) random_point = bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min <= random_point['depth(m - down", "and its epsg reference number :param path:(str) path to the .SAFE repository of", "i += 1 # tile index path_t = os.path.join(cfg.in_path_s2, tile) safes = os.listdir(path_t)", "if float(cloud_coverage) < cfg.max_cc: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path:", "xml = os.path.join(path, 'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml') tree = et.parse(xml) root = tree.getroot()", "print(bathy_points['depth label'].value_counts(sort=False)) n_tot = 0 nb_tot = 0 for label in labels: bathy_label_points", "+= 1 nb_tot += 1 x[i] = np.append(x[i], [x_point]) y[i] = np.append(y[i], [y_point])", "= 0 n_dash = 0 for i_t in range(n_t): for i_x in range(n_x):", "print(f'--------------TILE: {temp_tile.id}') path_t = os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s = os.path.join(path_t, year, month, day, safe_id", "= pd.cut(bathy_points['depth(m - down positive - LAT)'], bins=bins, labels=labels) print(bathy_points['depth label'].value_counts(sort=False)) n_tot =", "np.where(np.abs(np.array(x[i], copy=False) - x_point) < precision) ind = np.where(np.abs(np.array(y[i], copy=False)[ind] - y_point) <", "read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None): df = pd.read_csv(path_to_xyz, header=0) lng = np.array(df.lng) lat = np.array(df.lat)", "print('label :', label, nb, '/', n, time.time() - t) else: print(f'len(bathy_label_points) at label:{label}", "= np.unique(arr) flipped = np.empty(np.array(arr).shape) for i in range(len(arr)): flipped[i] = np.flipud(unique_values)[np.where(unique_values ==", "= temp_tile.id warnings.warn( f'============================================ Tile {id}: multiple corners') exit() else: pass # Different", "bins=bins, labels=labels) print(bathy_points['depth label'].value_counts(sort=False)) n_tot = 0 nb_tot = 0 for label in", "image in the xml file :param path:(str) path to the .SAFE repository of", "+ b)) & (timing_search['S2_lat'] > (tid['S2_lat'].values[0] - b))] tidal = np.nanmean(a['prediction_at_ERA5_point'].values) return tidal", "(z + ncd_z) / 2 z = new_z n_err += 1 else: n_dash", "np.array(df.lng) lat = np.array(df.lat) z = np.array(df.z) if projection_in and projection_out: proj =", "= 0 nb = 0 t = time.time() while nb < cfg.nb_max_pt_per_tile and", "timing_end.strftime('%Y-%m-%d %H:%M:%S') mask = (df['S2_time'] > timing_start) & (df['S2_time'] < timing_end) timing_search =", "safe_id[20:26] # a = os.listdir(os.path.join(safe_path, 'GRANULE')) # path = os.path.join(safe_path, 'GRANULE', a[0], 'IMG_DATA',", "tile_id, safe_id) # date = safe_id[11:19] # t_time = safe_id[20:26] # a =", "to the tenth to fit on the sentinel 2 max precision x_point, y_point", "np.append(z[i], random_point['depth(m - down positive - LAT)']) if n % 1000 == 0:", "actual point ind = np.where(np.abs(np.array(x[i], copy=False) - x_point) < precision) ind = np.where(np.abs(np.array(y[i],", "ncd_z) / 2 z = new_z n_err += 1 else: n_dash += 1", "netCDF4 as nc import xml.etree.ElementTree as et import datagen_config as cfg from datetime", "np.array(df.lat) z = np.array(df.z) if projection_in and projection_out: proj = pyproj.Proj(proj='utm', init=projection_out, ellps=projection_in)", "cfg.nb_max_pt_per_tile and n < cfg.line_max_read: n += 1 n_tot += 1 chosen_idx =", "for safe in safes: path_s = os.path.join(path_t, safe) cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage)", "BACK TO THIS safe_id = safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}') date = safe_id[11:19] t_time", "# TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS sentinel2_tiles = []", "gdal import pyproj import tarfile import warnings import numpy as np import xarray", "on the same coordinate system x_point, y_point = random_point['long(DD)'], random_point['lat(DD)'] x_point = int(round(x_point,", "timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end = timing_end.strftime('%Y-%m-%d %H:%M:%S') mask = (df['S2_time'] > timing_start) & (df['S2_time']", "1 nb_tot += 1 x[i] = np.append(x[i], [x_point]) y[i] = np.append(y[i], [y_point]) z[i]", "= Sentinel2Safe() temp_safe.date = date temp_safe.time = t_time temp_safe.s2_path = safe_path x, y,", "+= 1 out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z) else: new_z = (z + ncd_z) / 2", "a = os.listdir(os.path.join(safe_path, 'GRANULE')) # path = os.path.join(safe_path, 'GRANULE', a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') #", "ignore_index=True) bins = np.linspace(cfg.depth_lim_min, 100, 10) max_depth = bathy_points['depth(m - down positive -", "print(f' len(x): {len(out_x)}, len(y): {len(out_y)}, len(z): {len(out_z)}') print(f' Creating CSV file for {fn}...')", "= (df['S2_time'] > timing_start) & (df['S2_time'] < timing_end) timing_search = df.loc[mask] b =", "safe_path = os.path.join(s2_path, tile_id, safe_id) # date = safe_id[11:19] # t_time = safe_id[20:26]", "- LAT)'], bins=bins, labels=labels) print(bathy_points['depth label'].value_counts(sort=False)) n_tot = 0 nb_tot = 0 for", "in_tiles: sentinel2_tiles.append(temp_tile) return sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This function returns the useful bathy", "def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This function returns the info of the nb_max_date tiles with", "nb_tiles, [[]] * nb_tiles proj = [[]] * nb_tiles for i in range(nb_tiles):", "nb_tot = 0 for label in labels: bathy_label_points = bathy_points[bathy_points['depth label'] == label]", "- LAT)']) if n % 1000 == 0: print(n) print('label :', label, nb,", "of the image :return: cloud_coverage (float) \"\"\" xml = os.path.join(path, 'MTD_MSIL1C.xml') tree =", "cloud_coverage def get_top_left_corner_coordinates_for_image(path): \"\"\" Find the x, y coordinates of the top left", ":return: corners, paths, dates, epsgs: infos of the selected tiles \"\"\" from utilities.wrappers", "= proj[i](random_point['long(DD)'], random_point['lat(DD)']) else: # bathy and s2 are already on the same", "close to others if len(ind[0]) == 0: if isin_tile(x_point, y_point, tile.corner['x'], tile.corner['y']): nb", "safe_id = safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}') date = safe_id[11:19] t_time = safe_id[20:26] tidal", "5]] if tid['prediction_at_ERA5_point'].empty: print(f' {date} - {time}: no tidal elevation data') return None", "epsg def make_tarfile(output_filename, source_dir): with tarfile.open(output_filename, \"w:gz\") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe):", "tile borders & depth limited (+ & -) :param path: path of the", "import time import gdal import pyproj import tarfile import warnings import numpy as", "delta_t timing_start = timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end = timing_end.strftime('%Y-%m-%d %H:%M:%S') mask = (df['S2_time'] >", "> 1: warnings.warn(f'AGAIN =================================================== Tile {tile.id}: multiple epsg\\'s') exit() else: warnings.warn( f'THIS SHOULD", "cfg.depth_lim_min <= random_point['depth(m - down positive - LAT)'] <= cfg.depth_lim_max: if not len(sentinel2tile_list)", "- down positive - LAT)'] <= cfg.depth_lim_max: if not len(sentinel2tile_list) == 0: for", "= os.listdir(path_t) temp = [] for safe in safes: if safe.endswith('SAFE'): temp.append(safe) safes", "\"\"\" Find the x, y coordinates of the top left corner of the", "=================================================== Tile {tile.id}: multiple epsg\\'s') exit() else: warnings.warn( f'THIS SHOULD NEVER HAPPEN ======================================", "bathy_points['depth(m - down positive - LAT)'].max() if max_depth > 100: bins = np.append(bins,", "def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This function returns the useful bathy points according to 2", "nb_max_date tiles with the smallest cloud coverage :return: corners, paths, dates, epsgs: infos", "import warnings import numpy as np import xarray as xr import pandas as", "= ncd.variables['y'][i_y] z = None for i_k in range(n_k): ncd_z = ncd['depth'][i_y, i_x,", "date = safe_id[11:19] t_time = safe_id[20:26] tidal = get_tidal_elevation_for_image(safe_id) temp_safe = Sentinel2Safe() temp_safe.date", "{temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}') print(f'safe.time: {temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if temp_safe.epsg not in", "bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min <= random_point['depth(m - down positive - LAT)'] <= cfg.depth_lim_max: if", "fit on the sentinel 2 max precision x_point, y_point = proj[i](random_point['long(DD)'], random_point['lat(DD)']) else:", "'.SAFE') cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe:", "{n_all}, keep: {n_good}, errs: {n_err}, dash: {n_dash}') fn = path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}') print(f'", "+ ncd_z) / 2 z = new_z n_err += 1 else: n_dash +=", "y coordinates of the top left corner of the S2-L1C image in the", "projection_in=None, projection_out=None): ncd = nc.Dataset(path_to_nc) print(ncd) n_x = len(ncd.variables['x']) n_y = len(ncd.variables['y']) n_k", "number :param path:(str) path to the .SAFE repository of the image :return: x_corner,", "= sentinel2tile_list[i] if len(tile.epsgs) == 1: proj[i] = pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84') elif len(tile.epsgs)", "temp_tile in sentinel2_tiles: in_tiles = True temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles = False", "Sentinel2Tile() temp_tile.id = tile print(f'--------------TILE: {temp_tile.id}') n = 0 i += 1 #", "= len(ncd.variables['x']) n_y = len(ncd.variables['y']) n_k = len(ncd.variables['kKeep']) n_t = len(ncd.variables['time']) out_x =", "i_t in range(n_t): for i_x in range(n_x): for i_y in range(n_y): ncd_time =", "out_y = __flip_bathymetry_y_axis(out_y) return out_x, out_y, out_z def read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None): df =", "tile center) a = timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0] + b)) & (timing_search['S2_lon'] > (tid['S2_lon'].values[0]", "exact same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] n += 1", "f'THIS SHOULD NEVER HAPPEN ====================================== didn\\'t find tile {tile.id}\\'s epsg?') exit() bathy_points =", "tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe): date = safe[11:19] time = safe[20:26] tidal_path =", "(timing_search['S2_lat'] > (tid['S2_lat'].values[0] - b))] tidal = np.nanmean(a['prediction_at_ERA5_point'].values) return tidal else: tidal =", "= file.read().splitlines() for safe_id in safe_ids: year = safe_id[11:15] month = safe_id[15:17] day", "datagen_config as cfg from datetime import datetime, timedelta from utilities.common import isin_tile #", "Find the x, y coordinates of the top left corner of the S2-L1C", "# get the indices of the points to close to the actual point", "t_time = safe_id[20:26] tidal = get_tidal_elevation_for_image(safe_id) temp_safe = Sentinel2Safe() temp_safe.date = date temp_safe.time", "n_dash = 0 for i_t in range(n_t): for i_x in range(n_x): for i_y", "+= 1 n_tot += 1 chosen_idx = np.random.choice(len(bathy_label_points)) random_point = bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min", "np.append(bins, max_depth) labels = np.linspace(0, len(bins) - 2, len(bins) - 1) bathy_points['depth label']", "TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS sentinel2_tiles = [] with", "str) \"\"\" xml = os.path.join(path, 'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml') tree = et.parse(xml) root", "x_point, y_point = random_point['long(DD)'], random_point['lat(DD)'] x_point = int(round(x_point, -1)) y_point = int(round(y_point, -1))", "new_z = (z + ncd_z) / 2 z = new_z n_err += 1", "timing_end = timing_end.strftime('%Y-%m-%d %H:%M:%S') mask = (df['S2_time'] > timing_start) & (df['S2_time'] < timing_end)", "coordinate system of the tile and its epsg reference number :param path:(str) path", "epsg (int, int, str) \"\"\" xml = os.path.join(path, 'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml') tree", "ncd_z n_good += 1 out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z) else: new_z = (z + ncd_z)", "temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs) > 1: warnings.warn(f'==================================== Tile {temp_tile.id}: multiple epsg\\'s') exit() if", "coordinates of the bathy points kept, appended to the previous ones \"\"\" precision", "= df.loc[mask] b = 1 # +/- 1 degree to search for the", "tarfile.open(output_filename, \"w:gz\") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe): date = safe[11:19] time =", "cfg.depth_lim_max: if not len(sentinel2tile_list) == 0: for i in range(nb_tiles): tile = sentinel2tile_list[i]", "LAT)'] <= cfg.depth_lim_max: if not len(sentinel2tile_list) == 0: for i in range(nb_tiles): tile", "get_tidal_elevation_for_image(safe): date = safe[11:19] time = safe[20:26] tidal_path = cfg.in_path_tidal df = xr.open_dataset(tidal_path).to_dataframe()", "TO THIS sentinel2_tiles = [] with open(cfg.in_path_safes_list, 'r') as file: safe_ids = file.read().splitlines()", ":', label, nb, '/', n, time.time() - t) else: print(f'len(bathy_label_points) at label:{label} ==", "== safe[0:len(safe) - 5]] if tid['prediction_at_ERA5_point'].empty: print(f' {date} - {time}: no tidal elevation", "def get_geo_transform_for_image(s2_path, tile_id, safe_id): # safe_path = os.path.join(s2_path, tile_id, safe_id) # date =", "COME BACK TO THIS safe_id = safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}') date = safe_id[11:19]", "'/', nb_tot) return x, y, z def __flip_bathymetry_y_axis(arr): unique_values = np.unique(arr) flipped =", "t_time temp_safe.s2_path = safe_path x, y, epsg = get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners = (x, y)", "safe in safes: path_s = os.path.join(path_t, safe) cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) <", "nc.Dataset(path_to_nc) print(ncd) n_x = len(ncd.variables['x']) n_y = len(ncd.variables['y']) n_k = len(ncd.variables['kKeep']) n_t =", "for i_x in range(n_x): for i_y in range(n_y): ncd_time = ncd.variables['time'][i_t] ncd_x =", "tree = et.parse(xml) root = tree.getroot() cloud_coverage = float(root[3][0].text) return cloud_coverage def get_top_left_corner_coordinates_for_image(path):", "warnings.warn(f'==================================== Tile {temp_tile.id}: multiple epsg\\'s') exit() if temp_tile.corner['x'] and temp_tile.corner['y']: if temp_safe.corners[0] !=", "np.linspace(0, len(bins) - 2, len(bins) - 1) bathy_points['depth label'] = pd.cut(bathy_points['depth(m - down", "of already kept bathy points :return: (x, y, z): coordinates of the bathy", "This function returns the useful bathy points according to 2 criteria : distance", "def get_tidal_elevation_for_image(safe): date = safe[11:19] time = safe[20:26] tidal_path = cfg.in_path_tidal df =", "tile_id if temp_tile in sentinel2_tiles: in_tiles = True temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles", "= parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}') print(f'safe.time: {temp_safe.time}')", "lines read/selected :', n_tot, '/', nb_tot) return x, y, z def __flip_bathymetry_y_axis(arr): unique_values", "temp_tile.id = tile print(f'--------------TILE: {temp_tile.id}') n = 0 i += 1 # tile", "z def __flip_bathymetry_y_axis(arr): unique_values = np.unique(arr) flipped = np.empty(np.array(arr).shape) for i in range(len(arr)):", "chosen_idx = np.random.choice(len(bathy_label_points)) random_point = bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min <= random_point['depth(m - down positive", "{date} - {time}: no tidal elevation data') return None else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t", "{len(out_x)}, len(y): {len(out_y)}, len(z): {len(out_z)}') print(f' Creating CSV file for {fn}...') out_y =", "{temp_tile.id}') n = 0 i += 1 # tile index path_t = os.path.join(cfg.in_path_s2,", "bathy_points = bathy_points.append(df, ignore_index=True) bins = np.linspace(cfg.depth_lim_min, 100, 10) max_depth = bathy_points['depth(m -", "safe) cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc and n < cfg.nb_max_date: temp_safe", "as cfg from datetime import datetime, timedelta from utilities.common import isin_tile # from", "get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners = (x, y) temp_safe.epsg = epsg if tidal: temp_safe.tidal_elevation = tidal", "timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0] + b)) & (timing_search['S2_lon'] > (tid['S2_lon'].values[0] - b)) & (timing_search['S2_lat']", "points :return: (x, y, z): coordinates of the bathy points kept, appended to", "the tenth to fit on the sentinel 2 max precision x_point, y_point =", "= 0 n_all = 0 n_dash = 0 for i_t in range(n_t): for", "if temp_tile.corner['x'] and temp_tile.corner['y']: if temp_safe.corners[0] != temp_tile.corner['x'] or temp_safe.corners[1] != temp_tile.corner['y']: id", "the exact same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] n +=", "len(bins) - 2, len(bins) - 1) bathy_points['depth label'] = pd.cut(bathy_points['depth(m - down positive", "a = timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0] + b)) & (timing_search['S2_lon'] > (tid['S2_lon'].values[0] - b))", "sentinel2_tiles = [] i = -1 for tile in cfg.tiles: temp_tile = Sentinel2Tile()", "+ '.SAFE') cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if", "gdal.Open(path + 'B04.jp2') # return ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers import Sentinel2Safe #", "else: print(f'len(bathy_label_points) at label:{label} == 0') print('nb of lines read/selected :', n_tot, '/',", "= sentinel2tile_list[i] if tile.epsgs[0] != 'EPSG:32628': # proj to the good coordinate system", "root = tree.getroot() x_corner = int(root[1][0][5][0].text) y_corner = int(root[1][0][5][1].text) epsg = root[1][0][1].text return", "max_depth = bathy_points['depth(m - down positive - LAT)'].max() if max_depth > 100: bins", "xr import pandas as pd import netCDF4 as nc import xml.etree.ElementTree as et", "{temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}') print(f'safe.time: {temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if temp_safe.epsg", "f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz' df = pd.read_csv(path, header=2) bathy_points = bathy_points.append(df, ignore_index=True) bins =", "int, str) \"\"\" xml = os.path.join(path, 'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml') tree = et.parse(xml)", "sentinel2tile_list[i] if len(tile.epsgs) == 1: proj[i] = pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84') elif len(tile.epsgs) >", "the WGS84 coordinate system of the tile and its epsg reference number :param", "# first bathy pts filtering x, y, z = [[]] * nb_tiles, [[]]", "safe.endswith('SAFE'): temp.append(safe) safes = temp for safe in safes: path_s = os.path.join(path_t, safe)", "= cfg.in_path_tidal df = xr.open_dataset(tidal_path).to_dataframe() tid = df[df['S2_fname'] == safe[0:len(safe) - 5]] if", "nb_tiles = len(cfg.tiles) # first bathy pts filtering x, y, z = [[]]", "n_err += 1 else: n_dash += 1 if n_all % 5000 == 0:", "the point only if it is not to close to others if len(ind[0])", "= os.path.join(path_t, safe) cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc and n <", "= timing + delta_t timing_start = timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end = timing_end.strftime('%Y-%m-%d %H:%M:%S') mask", "and temp_tile.corner['y']: if temp_safe.corners[0] != temp_tile.corner['x'] or temp_safe.corners[1] != temp_tile.corner['y']: id = temp_tile.id", "arr[i])] return flipped def read_nc_file(path_to_nc, projection_in=None, projection_out=None): ncd = nc.Dataset(path_to_nc) print(ncd) n_x =", "of the S2-L1C image in the WGS84 coordinate system of the tile and", "os.path.join(s2_path, tile_id, safe_id) # date = safe_id[11:19] # t_time = safe_id[20:26] # a", "'%Y%m%d%H%M%S') timing_start = timing - delta_t timing_end = timing + delta_t timing_start =", "date = safe_id[11:19] # t_time = safe_id[20:26] # a = os.listdir(os.path.join(safe_path, 'GRANULE')) #", "out_z def read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None): df = pd.read_csv(path_to_xyz, header=0) lng = np.array(df.lng) lat", "not to close to others if len(ind[0]) == 0: if isin_tile(x_point, y_point, tile.corner['x'],", "BACK TO THIS sentinel2_tiles = [] i = -1 for tile in cfg.tiles:", "% 1000 == 0: print(n) print('label :', label, nb, '/', n, time.time() -", "of the tile and its epsg reference number :param path:(str) path to the", "n_tot = 0 nb_tot = 0 for label in labels: bathy_label_points = bathy_points[bathy_points['depth", "as et import datagen_config as cfg from datetime import datetime, timedelta from utilities.common", "are already on the same coordinate system x_point, y_point = random_point['long(DD)'], random_point['lat(DD)'] x_point", "[x_point]) y[i] = np.append(y[i], [y_point]) z[i] = np.append(z[i], random_point['depth(m - down positive -", "in_tiles = False print(f'--------------TILE: {temp_tile.id}') path_t = os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s = os.path.join(path_t, year,", "1: warnings.warn(f'AGAIN =================================================== Tile {tile.id}: multiple epsg\\'s') exit() else: warnings.warn( f'THIS SHOULD NEVER", "temp_tile.corner['x'] and temp_tile.corner['y']: if temp_safe.corners[0] != temp_tile.corner['x'] or temp_safe.corners[1] != temp_tile.corner['y']: id =", "y_point = random_point['long(DD)'], random_point['lat(DD)'] x_point = int(round(x_point, -1)) y_point = int(round(y_point, -1)) #", "= [] i = -1 for tile in cfg.tiles: temp_tile = Sentinel2Tile() temp_tile.id", "down positive - LAT)'].max() if max_depth > 100: bins = np.append(bins, max_depth) labels", "== label] if len(bathy_label_points) > 0: n = 0 nb = 0 t", "print(f'Filename: {fn}') print(f' Total: {n_all}, 1k: {n_good}, nk: {n_err}, --: {n_dash}') print(f' len(x):", "cloud coverage of the S2-L1C image in the xml file :param path:(str) path", "out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z) else: new_z = (z + ncd_z) / 2 z =", "print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}') date = safe_id[11:19] t_time = safe_id[20:26] tidal = get_tidal_elevation_for_image(safe_id) temp_safe", "epsgs: infos of the selected tiles \"\"\" from utilities.wrappers import Sentinel2Tile # TODO:", "= [[]] * nb_tiles, [[]] * nb_tiles, [[]] * nb_tiles proj = [[]]", "if z is None: z = ncd_z n_good += 1 out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z)", "import Sentinel2Tile, Sentinel2Safe def get_cloud_coverage(path): \"\"\" Find the cloud coverage of the S2-L1C", "returns the info of the nb_max_date tiles with the smallest cloud coverage :return:", "= [] with open(cfg.in_path_safes_list, 'r') as file: safe_ids = file.read().splitlines() for safe_id in", "print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if temp_safe.epsg not in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs) > 1: warnings.warn(f'====================================", "temp_tile.id warnings.warn( f'============================================ Tile {id}: multiple corners') exit() else: pass # Different snapshots", "= safe_path x, y, epsg = get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners = (x, y) temp_safe.epsg =", "= root[1][0][1].text return x_corner, y_corner, epsg def make_tarfile(output_filename, source_dir): with tarfile.open(output_filename, \"w:gz\") as", "'EPSG:32628': # proj to the good coordinate system & round to the tenth", "random_point['lat(DD)'] x_point = int(round(x_point, -1)) y_point = int(round(y_point, -1)) # get the indices", "- 2, len(bins) - 1) bathy_points['depth label'] = pd.cut(bathy_points['depth(m - down positive -", "no tidal elevation data') return None else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t = timedelta(hours=1) timing", "safe_id): # safe_path = os.path.join(s2_path, tile_id, safe_id) # date = safe_id[11:19] # t_time", "[] for safe in safes: if safe.endswith('SAFE'): temp.append(safe) safes = temp for safe", "criteria : distance to each others (not to much redundancy) & not to", "precision x_point, y_point = proj[i](random_point['long(DD)'], random_point['lat(DD)']) else: # bathy and s2 are already", "os.path.join(path, 'MTD_MSIL1C.xml') tree = et.parse(xml) root = tree.getroot() cloud_coverage = float(root[3][0].text) return cloud_coverage", ":return: cloud_coverage (float) \"\"\" xml = os.path.join(path, 'MTD_MSIL1C.xml') tree = et.parse(xml) root =", "0 n_good = 0 n_all = 0 n_dash = 0 for i_t in", "didn\\'t find tile {tile.id}\\'s epsg?') exit() bathy_points = pd.DataFrame() for directory in os.listdir(cfg.in_path_bathy):", "Sentinel2Tile, Sentinel2Safe def get_cloud_coverage(path): \"\"\" Find the cloud coverage of the S2-L1C image", "root = tree.getroot() cloud_coverage = float(root[3][0].text) return cloud_coverage def get_top_left_corner_coordinates_for_image(path): \"\"\" Find the", "THIS safe_id = safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}') date = safe_id[11:19] t_time = safe_id[20:26]", "* nb_tiles for i in range(nb_tiles): tile = sentinel2tile_list[i] if len(tile.epsgs) == 1:", "max_depth) labels = np.linspace(0, len(bins) - 2, len(bins) - 1) bathy_points['depth label'] =", "WGS84 coordinate system of the tile and its epsg reference number :param path:(str)", "tidal elevation data for safe: {safe_id}') temp_safe.tidal_elevation = 0 return temp_safe def parse_sentinel2_tiles_metadata():", "system & round to the tenth to fit on the sentinel 2 max", "header=0) lng = np.array(df.lng) lat = np.array(df.lat) z = np.array(df.z) if projection_in and", "ncd_x = ncd.variables['x'][i_x] ncd_y = ncd.variables['y'][i_y] z = None for i_k in range(n_k):", "= pyproj.Proj(proj='utm', init=projection_out, ellps=projection_in) lng, lat = proj(lng, lat) return lng, lat, z", "the x, y coordinates of the top left corner of the S2-L1C image", "{temp_safe.date}') print(f'safe.time: {temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if temp_safe.epsg not in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg)", "directory)}.xyz' df = pd.read_csv(path, header=2) bathy_points = bathy_points.append(df, ignore_index=True) bins = np.linspace(cfg.depth_lim_min, 100,", "< cfg.max_cc: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date:", "copy=False)[ind] - y_point) < precision) # keep the point only if it is", "temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] if not in_tiles: sentinel2_tiles.append(temp_tile) return sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\"", "= int(round(x_point, -1)) y_point = int(round(y_point, -1)) # get the indices of the", "mask = (df['S2_time'] > timing_start) & (df['S2_time'] < timing_end) timing_search = df.loc[mask] b", "safe_id[11:19] t_time = safe_id[20:26] tidal = get_tidal_elevation_for_image(safe_id) temp_safe = Sentinel2Safe() temp_safe.date = date", "= True temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles = False print(f'--------------TILE: {temp_tile.id}') path_t =", "exit() bathy_points = pd.DataFrame() for directory in os.listdir(cfg.in_path_bathy): path = f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz'", ": distance to each others (not to much redundancy) & not to close", "projection_in=None, projection_out=None): df = pd.read_csv(path_to_xyz, header=0) lng = np.array(df.lng) lat = np.array(df.lat) z", "x, y, z = [[]] * nb_tiles, [[]] * nb_tiles, [[]] * nb_tiles", "temp_safe def parse_sentinel2_tiles_metadata(): \"\"\" This function returns the info of the nb_max_date tiles", "same coordinate system x_point, y_point = random_point['long(DD)'], random_point['lat(DD)'] x_point = int(round(x_point, -1)) y_point", "at label:{label} == 0') print('nb of lines read/selected :', n_tot, '/', nb_tot) return", "to each others (not to much redundancy) & not to close to tile", "i = -1 for tile in cfg.tiles: temp_tile = Sentinel2Tile() temp_tile.id = tile", "others if len(ind[0]) == 0: if isin_tile(x_point, y_point, tile.corner['x'], tile.corner['y']): nb += 1", "new_z n_err += 1 else: n_dash += 1 if n_all % 5000 ==", "warnings.warn(f'No tidal elevation data for safe: {safe_id}') temp_safe.tidal_elevation = 0 return temp_safe def", "\"\"\" from utilities.wrappers import Sentinel2Tile # TODO: UNCOMMENT MAIN IMPORT AND COME BACK", "of the points to close to the actual point ind = np.where(np.abs(np.array(x[i], copy=False)", "ones \"\"\" precision = 10 nb_tiles = len(cfg.tiles) # first bathy pts filtering", "the same coordinate system x_point, y_point = random_point['long(DD)'], random_point['lat(DD)'] x_point = int(round(x_point, -1))", "random_point['depth(m - down positive - LAT)'] <= cfg.depth_lim_max: if not len(sentinel2tile_list) == 0:", "if n_all % 5000 == 0: print(f'all: {n_all}, keep: {n_good}, errs: {n_err}, dash:", "tile_id = safe_id[39:44] temp_tile = Sentinel2Tile() temp_tile.id = tile_id if temp_tile in sentinel2_tiles:", "indices of the points to close to the actual point ind = np.where(np.abs(np.array(x[i],", "the tidal information (around the actual tile center) a = timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0]", "from datetime import datetime, timedelta from utilities.common import isin_tile # from utilities.wrappers import", "datetime import datetime, timedelta from utilities.common import isin_tile # from utilities.wrappers import Sentinel2Tile,", "# a = os.listdir(os.path.join(safe_path, 'GRANULE')) # path = os.path.join(safe_path, 'GRANULE', a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_')", "1: proj[i] = pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84') elif len(tile.epsgs) > 1: warnings.warn(f'AGAIN =================================================== Tile", "int(round(y_point, -1)) # get the indices of the points to close to the", "def make_tarfile(output_filename, source_dir): with tarfile.open(output_filename, \"w:gz\") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe): date", "round to the tenth to fit on the sentinel 2 max precision x_point,", "the sentinel 2 max precision x_point, y_point = proj[i](random_point['long(DD)'], random_point['lat(DD)']) else: # bathy", "nb < cfg.nb_max_pt_per_tile and n < cfg.line_max_read: n += 1 n_tot += 1", "= pd.read_csv(path, header=2) bathy_points = bathy_points.append(df, ignore_index=True) bins = np.linspace(cfg.depth_lim_min, 100, 10) max_depth", "ncd.variables['y'][i_y] z = None for i_k in range(n_k): ncd_z = ncd['depth'][i_y, i_x, i_k,", "= ncd['depth'][i_y, i_x, i_k, i_t] n_all += 1 if ncd_z != '--': if", "> timing_start) & (df['S2_time'] < timing_end) timing_search = df.loc[mask] b = 1 #", "tile_id, safe_id): # safe_path = os.path.join(s2_path, tile_id, safe_id) # date = safe_id[11:19] #", "path = f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz' df = pd.read_csv(path, header=2) bathy_points = bathy_points.append(df, ignore_index=True)", "time.time() - t) else: print(f'len(bathy_label_points) at label:{label} == 0') print('nb of lines read/selected", "points according to 2 criteria : distance to each others (not to much", "Tile {id}: multiple corners') exit() else: pass # Different snapshots of the same", "pandas as pd import netCDF4 as nc import xml.etree.ElementTree as et import datagen_config", "& not to close to tile borders & depth limited (+ & -)", "z coordinates of already kept bathy points :return: (x, y, z): coordinates of", "temp_safe.corners[1] != temp_tile.corner['y']: id = temp_tile.id warnings.warn( f'============================================ Tile {id}: multiple corners') exit()", "pts filtering x, y, z = [[]] * nb_tiles, [[]] * nb_tiles, [[]]", "import os import time import gdal import pyproj import tarfile import warnings import", "None else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t = timedelta(hours=1) timing = datetime.strptime(date + time, '%Y%m%d%H%M%S')", "import netCDF4 as nc import xml.etree.ElementTree as et import datagen_config as cfg from", "nb_tiles proj = [[]] * nb_tiles for i in range(nb_tiles): tile = sentinel2tile_list[i]", "UNCOMMENT MAIN IMPORT AND COME BACK TO THIS safe_id = safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id:", "* nb_tiles proj = [[]] * nb_tiles for i in range(nb_tiles): tile =", "temp_safe.epsg = epsg if tidal: temp_safe.tidal_elevation = tidal else: warnings.warn(f'No tidal elevation data", "nc import xml.etree.ElementTree as et import datagen_config as cfg from datetime import datetime,", "= time.time() while nb < cfg.nb_max_pt_per_tile and n < cfg.line_max_read: n += 1", "temp_tile.corner['y']: if temp_safe.corners[0] != temp_tile.corner['x'] or temp_safe.corners[1] != temp_tile.corner['y']: id = temp_tile.id warnings.warn(", "epsg\\'s') exit() else: warnings.warn( f'THIS SHOULD NEVER HAPPEN ====================================== didn\\'t find tile {tile.id}\\'s", "!= temp_tile.corner['x'] or temp_safe.corners[1] != temp_tile.corner['y']: id = temp_tile.id warnings.warn( f'============================================ Tile {id}:", "directory in os.listdir(cfg.in_path_bathy): path = f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz' df = pd.read_csv(path, header=2) bathy_points", "epsg\\'s') exit() if temp_tile.corner['x'] and temp_tile.corner['y']: if temp_safe.corners[0] != temp_tile.corner['x'] or temp_safe.corners[1] !=", "Creating CSV file for {fn}...') out_y = __flip_bathymetry_y_axis(out_y) return out_x, out_y, out_z def", "for i in range(len(arr)): flipped[i] = np.flipud(unique_values)[np.where(unique_values == arr[i])] return flipped def read_nc_file(path_to_nc,", "= np.append(y[i], [y_point]) z[i] = np.append(z[i], random_point['depth(m - down positive - LAT)']) if", "'r') as file: safe_ids = file.read().splitlines() for safe_id in safe_ids: year = safe_id[11:15]", "in cfg.tiles: temp_tile = Sentinel2Tile() temp_tile.id = tile print(f'--------------TILE: {temp_tile.id}') n = 0", "get_tidal_elevation_for_image(safe_id) temp_safe = Sentinel2Safe() temp_safe.date = date temp_safe.time = t_time temp_safe.s2_path = safe_path", "0 nb = 0 t = time.time() while nb < cfg.nb_max_pt_per_tile and n", "TO THIS safe_id = safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}') date = safe_id[11:19] t_time =", "1 if ncd_z != '--': if z is None: z = ncd_z n_good", "tidal else: warnings.warn(f'No tidal elevation data for safe: {safe_id}') temp_safe.tidal_elevation = 0 return", "= bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min <= random_point['depth(m - down positive - LAT)'] <= cfg.depth_lim_max:", "sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This function returns the useful bathy points according to", "-) :param path: path of the bathymetry :param x: x coordinates of already", "[] i = -1 for tile in cfg.tiles: temp_tile = Sentinel2Tile() temp_tile.id =", "warnings.warn( f'THIS SHOULD NEVER HAPPEN ====================================== didn\\'t find tile {tile.id}\\'s epsg?') exit() bathy_points", "x_corner = int(root[1][0][5][0].text) y_corner = int(root[1][0][5][1].text) epsg = root[1][0][1].text return x_corner, y_corner, epsg", "open(cfg.in_path_safes_list, 'r') as file: safe_ids = file.read().splitlines() for safe_id in safe_ids: year =", "{tile.id}\\'s epsg?') exit() bathy_points = pd.DataFrame() for directory in os.listdir(cfg.in_path_bathy): path = f'{os.path.join(cfg.in_path_bathy,", "def read_nc_file(path_to_nc, projection_in=None, projection_out=None): ncd = nc.Dataset(path_to_nc) print(ncd) n_x = len(ncd.variables['x']) n_y =", "to close to tile borders & depth limited (+ & -) :param path:", "tile.epsgs[0] != 'EPSG:32628': # proj to the good coordinate system & round to", "utilities.wrappers import Sentinel2Tile # TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS", "= [] out_z = [] n_err = 0 n_good = 0 n_all =", "cfg.in_path_tidal df = xr.open_dataset(tidal_path).to_dataframe() tid = df[df['S2_fname'] == safe[0:len(safe) - 5]] if tid['prediction_at_ERA5_point'].empty:", "n_x = len(ncd.variables['x']) n_y = len(ncd.variables['y']) n_k = len(ncd.variables['kKeep']) n_t = len(ncd.variables['time']) out_x", ":param z: z coordinates of already kept bathy points :return: (x, y, z):", "= int(root[1][0][5][0].text) y_corner = int(root[1][0][5][1].text) epsg = root[1][0][1].text return x_corner, y_corner, epsg def", "# TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS safe_id = safe_path.split('/')[-1]", "label in labels: bathy_label_points = bathy_points[bathy_points['depth label'] == label] if len(bathy_label_points) > 0:", "bathy_label_points = bathy_points[bathy_points['depth label'] == label] if len(bathy_label_points) > 0: n = 0", "= safe[11:19] time = safe[20:26] tidal_path = cfg.in_path_tidal df = xr.open_dataset(tidal_path).to_dataframe() tid =", "0: if isin_tile(x_point, y_point, tile.corner['x'], tile.corner['y']): nb += 1 nb_tot += 1 x[i]", "flipped[i] = np.flipud(unique_values)[np.where(unique_values == arr[i])] return flipped def read_nc_file(path_to_nc, projection_in=None, projection_out=None): ncd =", "temp.append(safe) safes = temp for safe in safes: path_s = os.path.join(path_t, safe) cloud_coverage", "0: n = 0 nb = 0 t = time.time() while nb <", "in the WGS84 coordinate system of the tile and its epsg reference number", "UNCOMMENT MAIN IMPORT AND COME BACK TO THIS sentinel2_tiles = [] i =", "= np.where(np.abs(np.array(x[i], copy=False) - x_point) < precision) ind = np.where(np.abs(np.array(y[i], copy=False)[ind] - y_point)", "return ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers import Sentinel2Safe # TODO: UNCOMMENT MAIN IMPORT", "(timing_search['S2_lat'] < (tid['S2_lat'].values[0] + b)) & (timing_search['S2_lat'] > (tid['S2_lat'].values[0] - b))] tidal =", "xml = os.path.join(path, 'MTD_MSIL1C.xml') tree = et.parse(xml) root = tree.getroot() cloud_coverage = float(root[3][0].text)", "< cfg.nb_max_pt_per_tile and n < cfg.line_max_read: n += 1 n_tot += 1 chosen_idx", "& depth limited (+ & -) :param path: path of the bathymetry :param", "SHOULD NEVER HAPPEN ====================================== didn\\'t find tile {tile.id}\\'s epsg?') exit() bathy_points = pd.DataFrame()", "= os.path.join(safe_path, 'GRANULE', a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') # ds = gdal.Open(path + 'B04.jp2') #", "\"w:gz\") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe): date = safe[11:19] time = safe[20:26]", "bathy points :return: (x, y, z): coordinates of the bathy points kept, appended", "year = safe_id[11:15] month = safe_id[15:17] day = safe_id[17:19] tile_id = safe_id[39:44] temp_tile", "< timing_end) timing_search = df.loc[mask] b = 1 # +/- 1 degree to", "return tidal else: tidal = tid['prediction_at_ERA5_point'].values[0] return tidal # def get_geo_transform_for_image(s2_path, tile_id, safe_id):", ".SAFE repository of the image :return: x_corner, y_corner, epsg (int, int, str) \"\"\"", "y_corner, epsg (int, int, str) \"\"\" xml = os.path.join(path, 'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml')", "!= '--': if z is None: z = ncd_z n_good += 1 out_x.append(ncd_x)", "fn = path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}') print(f' Total: {n_all}, 1k: {n_good}, nk: {n_err}, --:", "down positive - LAT)']) if n % 1000 == 0: print(n) print('label :',", "proj to the good coordinate system & round to the tenth to fit", "= len(ncd.variables['time']) out_x = [] out_y = [] out_z = [] n_err =", "temp_safe.epsg not in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs) > 1: warnings.warn(f'==================================== Tile {temp_tile.id}: multiple", "CSV file for {fn}...') out_y = __flip_bathymetry_y_axis(out_y) return out_x, out_y, out_z def read_fxyz_file(path_to_xyz,", "the info of the nb_max_date tiles with the smallest cloud coverage :return: corners,", "epsg if tidal: temp_safe.tidal_elevation = tidal else: warnings.warn(f'No tidal elevation data for safe:", "temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles = False print(f'--------------TILE: {temp_tile.id}') path_t = os.path.join(cfg.in_path_datalake_s2, temp_tile.id)", "def get_top_left_corner_coordinates_for_image(path): \"\"\" Find the x, y coordinates of the top left corner", "path:(str) path to the .SAFE repository of the image :return: cloud_coverage (float) \"\"\"", "returns the useful bathy points according to 2 criteria : distance to each", "same tile should have the exact same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y']", "not in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs) > 1: warnings.warn(f'==================================== Tile {temp_tile.id}: multiple epsg\\'s')", "path: path of the bathymetry :param x: x coordinates of already kept bathy", "exit() else: warnings.warn( f'THIS SHOULD NEVER HAPPEN ====================================== didn\\'t find tile {tile.id}\\'s epsg?')", "cfg.tiles: temp_tile = Sentinel2Tile() temp_tile.id = tile print(f'--------------TILE: {temp_tile.id}') n = 0 i", "else: n_dash += 1 if n_all % 5000 == 0: print(f'all: {n_all}, keep:", "epsg = get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners = (x, y) temp_safe.epsg = epsg if tidal: temp_safe.tidal_elevation", "temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] n += 1 sentinel2_tiles.append(temp_tile) return sentinel2_tiles def", "n_good = 0 n_all = 0 n_dash = 0 for i_t in range(n_t):", "= os.listdir(os.path.join(safe_path, 'GRANULE')) # path = os.path.join(safe_path, 'GRANULE', a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') # ds", "same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] n += 1 sentinel2_tiles.append(temp_tile)", "len(ncd.variables['y']) n_k = len(ncd.variables['kKeep']) n_t = len(ncd.variables['time']) out_x = [] out_y = []", "the nb_max_date tiles with the smallest cloud coverage :return: corners, paths, dates, epsgs:", "temp_safe.corners[1] if not in_tiles: sentinel2_tiles.append(temp_tile) return sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This function returns", "+ 'B04.jp2') # return ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers import Sentinel2Safe # TODO:", "'--': if z is None: z = ncd_z n_good += 1 out_x.append(ncd_x) out_y.append(ncd_y)", "function returns the info of the nb_max_date tiles with the smallest cloud coverage", "(tid['S2_lat'].values[0] + b)) & (timing_search['S2_lat'] > (tid['S2_lat'].values[0] - b))] tidal = np.nanmean(a['prediction_at_ERA5_point'].values) return", "df[df['S2_fname'] == safe[0:len(safe) - 5]] if tid['prediction_at_ERA5_point'].empty: print(f' {date} - {time}: no tidal", "= safe_id[11:19] # t_time = safe_id[20:26] # a = os.listdir(os.path.join(safe_path, 'GRANULE')) # path", "[] out_z = [] n_err = 0 n_good = 0 n_all = 0", "+= 1 chosen_idx = np.random.choice(len(bathy_label_points)) random_point = bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min <= random_point['depth(m -", "timedelta from utilities.common import isin_tile # from utilities.wrappers import Sentinel2Tile, Sentinel2Safe def get_cloud_coverage(path):", "selected tiles \"\"\" from utilities.wrappers import Sentinel2Tile # TODO: UNCOMMENT MAIN IMPORT AND", "random_point['lat(DD)']) else: # bathy and s2 are already on the same coordinate system", "epsg?') exit() bathy_points = pd.DataFrame() for directory in os.listdir(cfg.in_path_bathy): path = f'{os.path.join(cfg.in_path_bathy, directory,", "= safe[20:26] tidal_path = cfg.in_path_tidal df = xr.open_dataset(tidal_path).to_dataframe() tid = df[df['S2_fname'] == safe[0:len(safe)", "== 1: proj[i] = pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84') elif len(tile.epsgs) > 1: warnings.warn(f'AGAIN ===================================================", "safe_id + '.SAFE') cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc: temp_safe = parse_sentinel2_imagesafe_metadata(path_s)", "xml.etree.ElementTree as et import datagen_config as cfg from datetime import datetime, timedelta from", "the same tile should have the exact same corners else: temp_tile.corner['x'] = temp_safe.corners[0]", "import tarfile import warnings import numpy as np import xarray as xr import", "else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] if not in_tiles: sentinel2_tiles.append(temp_tile) return sentinel2_tiles", "'GRANULE'))[0], 'MTD_TL.xml') tree = et.parse(xml) root = tree.getroot() x_corner = int(root[1][0][5][0].text) y_corner =", "nb_tot) return x, y, z def __flip_bathymetry_y_axis(arr): unique_values = np.unique(arr) flipped = np.empty(np.array(arr).shape)", "nb_tot += 1 x[i] = np.append(x[i], [x_point]) y[i] = np.append(y[i], [y_point]) z[i] =", "print(ncd) n_x = len(ncd.variables['x']) n_y = len(ncd.variables['y']) n_k = len(ncd.variables['kKeep']) n_t = len(ncd.variables['time'])", "--: {n_dash}') print(f' len(x): {len(out_x)}, len(y): {len(out_y)}, len(z): {len(out_z)}') print(f' Creating CSV file", "np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t = timedelta(hours=1) timing = datetime.strptime(date + time, '%Y%m%d%H%M%S') timing_start = timing", "= np.append(z[i], random_point['depth(m - down positive - LAT)']) if n % 1000 ==", "# +/- 1 degree to search for the tidal information (around the actual", "len(tile.epsgs) > 1: warnings.warn(f'AGAIN =================================================== Tile {tile.id}: multiple epsg\\'s') exit() else: warnings.warn( f'THIS", "if temp_safe.corners[0] != temp_tile.corner['x'] or temp_safe.corners[1] != temp_tile.corner['y']: id = temp_tile.id warnings.warn( f'============================================", "if len(bathy_label_points) > 0: n = 0 nb = 0 t = time.time()", "others (not to much redundancy) & not to close to tile borders &", "n_tot, '/', nb_tot) return x, y, z def __flip_bathymetry_y_axis(arr): unique_values = np.unique(arr) flipped", "i in range(nb_tiles): tile = sentinel2tile_list[i] if len(tile.epsgs) == 1: proj[i] = pyproj.Proj(proj='utm',", "= tid['prediction_at_ERA5_point'].values[0] return tidal # def get_geo_transform_for_image(s2_path, tile_id, safe_id): # safe_path = os.path.join(s2_path,", "and projection_out: proj = pyproj.Proj(proj='utm', init=projection_out, ellps=projection_in) lng, lat = proj(lng, lat) return", "tidal # def get_geo_transform_for_image(s2_path, tile_id, safe_id): # safe_path = os.path.join(s2_path, tile_id, safe_id) #", ":param path: path of the bathymetry :param x: x coordinates of already kept", "== arr[i])] return flipped def read_nc_file(path_to_nc, projection_in=None, projection_out=None): ncd = nc.Dataset(path_to_nc) print(ncd) n_x", "of already kept bathy points :param z: z coordinates of already kept bathy", "positive - LAT)'].max() if max_depth > 100: bins = np.append(bins, max_depth) labels =", "if len(temp_tile.epsgs) > 1: warnings.warn(f'==================================== Tile {temp_tile.id}: multiple epsg\\'s') exit() if temp_tile.corner['x'] and", ":param x: x coordinates of already kept bathy points :param y: y coordinates", "len(sentinel2tile_list) == 0: for i in range(nb_tiles): tile = sentinel2tile_list[i] if tile.epsgs[0] !=", "= pd.DataFrame() for directory in os.listdir(cfg.in_path_bathy): path = f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz' df =", "corners, paths, dates, epsgs: infos of the selected tiles \"\"\" from utilities.wrappers import", "Sentinel2Safe def get_cloud_coverage(path): \"\"\" Find the cloud coverage of the S2-L1C image in", "pd.read_csv(path_to_xyz, header=0) lng = np.array(df.lng) lat = np.array(df.lat) z = np.array(df.z) if projection_in", "len(z): {len(out_z)}') print(f' Creating CSV file for {fn}...') out_y = __flip_bathymetry_y_axis(out_y) return out_x,", "timing_start = timing - delta_t timing_end = timing + delta_t timing_start = timing_start.strftime('%Y-%m-%d", "= os.path.join(path, 'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml') tree = et.parse(xml) root = tree.getroot() x_corner", "= 0 t = time.time() while nb < cfg.nb_max_pt_per_tile and n < cfg.line_max_read:", "nb = 0 t = time.time() while nb < cfg.nb_max_pt_per_tile and n <", "[[]] * nb_tiles, [[]] * nb_tiles proj = [[]] * nb_tiles for i", "to the .SAFE repository of the image :return: x_corner, y_corner, epsg (int, int,", "in range(n_x): for i_y in range(n_y): ncd_time = ncd.variables['time'][i_t] ncd_x = ncd.variables['x'][i_x] ncd_y", "% 5000 == 0: print(f'all: {n_all}, keep: {n_good}, errs: {n_err}, dash: {n_dash}') fn", "paths, dates, epsgs: infos of the selected tiles \"\"\" from utilities.wrappers import Sentinel2Tile", "\"\"\" xml = os.path.join(path, 'MTD_MSIL1C.xml') tree = et.parse(xml) root = tree.getroot() cloud_coverage =", "temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}') print(f'safe.time: {temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation:", "+ time, '%Y%m%d%H%M%S') timing_start = timing - delta_t timing_end = timing + delta_t", "sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This function returns the info of the nb_max_date tiles", "n_all = 0 n_dash = 0 for i_t in range(n_t): for i_x in", "= 0 for i_t in range(n_t): for i_x in range(n_x): for i_y in", "__flip_bathymetry_y_axis(out_y) return out_x, out_y, out_z def read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None): df = pd.read_csv(path_to_xyz, header=0)", "of the bathymetry :param x: x coordinates of already kept bathy points :param", "(tid['S2_lon'].values[0] + b)) & (timing_search['S2_lon'] > (tid['S2_lon'].values[0] - b)) & (timing_search['S2_lat'] < (tid['S2_lat'].values[0]", "bathy points :param y: y coordinates of already kept bathy points :param z:", "(timing_search['S2_lon'] > (tid['S2_lon'].values[0] - b)) & (timing_search['S2_lat'] < (tid['S2_lat'].values[0] + b)) & (timing_search['S2_lat']", "Tile {temp_tile.id}: multiple epsg\\'s') exit() if temp_tile.corner['x'] and temp_tile.corner['y']: if temp_safe.corners[0] != temp_tile.corner['x']", "import datagen_config as cfg from datetime import datetime, timedelta from utilities.common import isin_tile", "= timing_end.strftime('%Y-%m-%d %H:%M:%S') mask = (df['S2_time'] > timing_start) & (df['S2_time'] < timing_end) timing_search", "already kept bathy points :param z: z coordinates of already kept bathy points", "cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe)", "(+ & -) :param path: path of the bathymetry :param x: x coordinates", "= ncd.variables['time'][i_t] ncd_x = ncd.variables['x'][i_x] ncd_y = ncd.variables['y'][i_y] z = None for i_k", "= __flip_bathymetry_y_axis(out_y) return out_x, out_y, out_z def read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None): df = pd.read_csv(path_to_xyz,", "(not to much redundancy) & not to close to tile borders & depth", "corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] n += 1 sentinel2_tiles.append(temp_tile) return", "# ds = gdal.Open(path + 'B04.jp2') # return ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers", "out_x = [] out_y = [] out_z = [] n_err = 0 n_good", "random_point = bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min <= random_point['depth(m - down positive - LAT)'] <=", "timedelta(hours=1) timing = datetime.strptime(date + time, '%Y%m%d%H%M%S') timing_start = timing - delta_t timing_end", "temp_tile.corner['x'] or temp_safe.corners[1] != temp_tile.corner['y']: id = temp_tile.id warnings.warn( f'============================================ Tile {id}: multiple", "temp_safe.corners[0] != temp_tile.corner['x'] or temp_safe.corners[1] != temp_tile.corner['y']: id = temp_tile.id warnings.warn( f'============================================ Tile", "tarfile import warnings import numpy as np import xarray as xr import pandas", "temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] if not in_tiles: sentinel2_tiles.append(temp_tile) return sentinel2_tiles def", "'/', n, time.time() - t) else: print(f'len(bathy_label_points) at label:{label} == 0') print('nb of", "print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}') print(f'safe.time: {temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if temp_safe.epsg not", "in safe_ids: year = safe_id[11:15] month = safe_id[15:17] day = safe_id[17:19] tile_id =", "ds = gdal.Open(path + 'B04.jp2') # return ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers import", "nb += 1 nb_tot += 1 x[i] = np.append(x[i], [x_point]) y[i] = np.append(y[i],", "= os.path.join(s2_path, tile_id, safe_id) # date = safe_id[11:19] # t_time = safe_id[20:26] #", "tid['prediction_at_ERA5_point'].values[0] return tidal # def get_geo_transform_for_image(s2_path, tile_id, safe_id): # safe_path = os.path.join(s2_path, tile_id,", "previous ones \"\"\" precision = 10 nb_tiles = len(cfg.tiles) # first bathy pts", "else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] n += 1 sentinel2_tiles.append(temp_tile) return sentinel2_tiles", "is None: z = ncd_z n_good += 1 out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z) else: new_z", "cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc and n < cfg.nb_max_date: temp_safe =", "path_t = os.path.join(cfg.in_path_s2, tile) safes = os.listdir(path_t) temp = [] for safe in", "(df['S2_time'] > timing_start) & (df['S2_time'] < timing_end) timing_search = df.loc[mask] b = 1", "x, y, z def __flip_bathymetry_y_axis(arr): unique_values = np.unique(arr) flipped = np.empty(np.array(arr).shape) for i", "np.flipud(unique_values)[np.where(unique_values == arr[i])] return flipped def read_nc_file(path_to_nc, projection_in=None, projection_out=None): ncd = nc.Dataset(path_to_nc) print(ncd)", "range(n_k): ncd_z = ncd['depth'][i_y, i_x, i_k, i_t] n_all += 1 if ncd_z !=", "label'].value_counts(sort=False)) n_tot = 0 nb_tot = 0 for label in labels: bathy_label_points =", "= get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners = (x, y) temp_safe.epsg = epsg if tidal: temp_safe.tidal_elevation =", "projection_in and projection_out: proj = pyproj.Proj(proj='utm', init=projection_out, ellps=projection_in) lng, lat = proj(lng, lat)", "= np.random.choice(len(bathy_label_points)) random_point = bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min <= random_point['depth(m - down positive -", "0: print(n) print('label :', label, nb, '/', n, time.time() - t) else: print(f'len(bathy_label_points)", "actual tile center) a = timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0] + b)) & (timing_search['S2_lon'] >", "limited (+ & -) :param path: path of the bathymetry :param x: x", "point ind = np.where(np.abs(np.array(x[i], copy=False) - x_point) < precision) ind = np.where(np.abs(np.array(y[i], copy=False)[ind]", "if tile.epsgs[0] != 'EPSG:32628': # proj to the good coordinate system & round", "sentinel 2 max precision x_point, y_point = proj[i](random_point['long(DD)'], random_point['lat(DD)']) else: # bathy and", "return sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This function returns the info of the nb_max_date", "= tidal else: warnings.warn(f'No tidal elevation data for safe: {safe_id}') temp_safe.tidal_elevation = 0", "to close to others if len(ind[0]) == 0: if isin_tile(x_point, y_point, tile.corner['x'], tile.corner['y']):", "= get_tidal_elevation_for_image(safe_id) temp_safe = Sentinel2Safe() temp_safe.date = date temp_safe.time = t_time temp_safe.s2_path =", "return temp_safe def parse_sentinel2_tiles_metadata(): \"\"\" This function returns the info of the nb_max_date", "'GRANULE')) # path = os.path.join(safe_path, 'GRANULE', a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') # ds = gdal.Open(path", "and n < cfg.line_max_read: n += 1 n_tot += 1 chosen_idx = np.random.choice(len(bathy_label_points))", "coordinates of the top left corner of the S2-L1C image in the WGS84", "first bathy pts filtering x, y, z = [[]] * nb_tiles, [[]] *", "elevation data for safe: {safe_id}') temp_safe.tidal_elevation = 0 return temp_safe def parse_sentinel2_tiles_metadata(): \"\"\"", "useful bathy points according to 2 criteria : distance to each others (not", "len(y): {len(out_y)}, len(z): {len(out_z)}') print(f' Creating CSV file for {fn}...') out_y = __flip_bathymetry_y_axis(out_y)", "import datetime, timedelta from utilities.common import isin_tile # from utilities.wrappers import Sentinel2Tile, Sentinel2Safe", "= pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84') elif len(tile.epsgs) > 1: warnings.warn(f'AGAIN =================================================== Tile {tile.id}: multiple", "kept bathy points :return: (x, y, z): coordinates of the bathy points kept,", "return None else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t = timedelta(hours=1) timing = datetime.strptime(date + time,", "from utilities.wrappers import Sentinel2Tile, Sentinel2Safe def get_cloud_coverage(path): \"\"\" Find the cloud coverage of", "== 0') print('nb of lines read/selected :', n_tot, '/', nb_tot) return x, y,", "degree to search for the tidal information (around the actual tile center) a", "in_tiles = True temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles = False print(f'--------------TILE: {temp_tile.id}') path_t", "y_corner = int(root[1][0][5][1].text) epsg = root[1][0][1].text return x_corner, y_corner, epsg def make_tarfile(output_filename, source_dir):", "ncd_z = ncd['depth'][i_y, i_x, i_k, i_t] n_all += 1 if ncd_z != '--':", "temp_safe.tidal_elevation = 0 return temp_safe def parse_sentinel2_tiles_metadata(): \"\"\" This function returns the info", "temp_tile.id) path_s = os.path.join(path_t, year, month, day, safe_id + '.SAFE') cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s))", "x_point, y_point = proj[i](random_point['long(DD)'], random_point['lat(DD)']) else: # bathy and s2 are already on", "safe_ids = file.read().splitlines() for safe_id in safe_ids: year = safe_id[11:15] month = safe_id[15:17]", "not len(sentinel2tile_list) == 0: for i in range(nb_tiles): tile = sentinel2tile_list[i] if tile.epsgs[0]", "warnings import numpy as np import xarray as xr import pandas as pd", "& (timing_search['S2_lat'] > (tid['S2_lat'].values[0] - b))] tidal = np.nanmean(a['prediction_at_ERA5_point'].values) return tidal else: tidal", "ncd.variables['x'][i_x] ncd_y = ncd.variables['y'][i_y] z = None for i_k in range(n_k): ncd_z =", "n < cfg.line_max_read: n += 1 n_tot += 1 chosen_idx = np.random.choice(len(bathy_label_points)) random_point", "< cfg.max_cc and n < cfg.nb_max_date: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners:", "left corner of the S2-L1C image in the WGS84 coordinate system of the", "pyproj import tarfile import warnings import numpy as np import xarray as xr", "os.listdir(os.path.join(safe_path, 'GRANULE')) # path = os.path.join(safe_path, 'GRANULE', a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') # ds =", "snapshots of the same tile should have the exact same corners else: temp_tile.corner['x']", "elevation data') return None else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t = timedelta(hours=1) timing = datetime.strptime(date", "of the top left corner of the S2-L1C image in the WGS84 coordinate", "int(round(x_point, -1)) y_point = int(round(y_point, -1)) # get the indices of the points", "-1 for tile in cfg.tiles: temp_tile = Sentinel2Tile() temp_tile.id = tile print(f'--------------TILE: {temp_tile.id}')", "10) max_depth = bathy_points['depth(m - down positive - LAT)'].max() if max_depth > 100:", "= np.array(df.lat) z = np.array(df.z) if projection_in and projection_out: proj = pyproj.Proj(proj='utm', init=projection_out,", "+= 1 # tile index path_t = os.path.join(cfg.in_path_s2, tile) safes = os.listdir(path_t) temp", "temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}') print(f'safe.time:", "t) else: print(f'len(bathy_label_points) at label:{label} == 0') print('nb of lines read/selected :', n_tot,", "same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] if not in_tiles: sentinel2_tiles.append(temp_tile)", "tiles \"\"\" from utilities.wrappers import Sentinel2Tile # TODO: UNCOMMENT MAIN IMPORT AND COME", "100, 10) max_depth = bathy_points['depth(m - down positive - LAT)'].max() if max_depth >", "bathy points kept, appended to the previous ones \"\"\" precision = 10 nb_tiles", "bathy pts filtering x, y, z = [[]] * nb_tiles, [[]] * nb_tiles,", "__flip_bathymetry_y_axis(arr): unique_values = np.unique(arr) flipped = np.empty(np.array(arr).shape) for i in range(len(arr)): flipped[i] =", "cfg.line_max_read: n += 1 n_tot += 1 chosen_idx = np.random.choice(len(bathy_label_points)) random_point = bathy_label_points.iloc[chosen_idx]", "= xr.open_dataset(tidal_path).to_dataframe() tid = df[df['S2_fname'] == safe[0:len(safe) - 5]] if tid['prediction_at_ERA5_point'].empty: print(f' {date}", "to search for the tidal information (around the actual tile center) a =", "1k: {n_good}, nk: {n_err}, --: {n_dash}') print(f' len(x): {len(out_x)}, len(y): {len(out_y)}, len(z): {len(out_z)}')", "pd import netCDF4 as nc import xml.etree.ElementTree as et import datagen_config as cfg", "== 0: print(f'all: {n_all}, keep: {n_good}, errs: {n_err}, dash: {n_dash}') fn = path_to_nc.split(\"/\")[-1]", "= (x, y) temp_safe.epsg = epsg if tidal: temp_safe.tidal_elevation = tidal else: warnings.warn(f'No", "(tid['S2_lat'].values[0] - b))] tidal = np.nanmean(a['prediction_at_ERA5_point'].values) return tidal else: tidal = tid['prediction_at_ERA5_point'].values[0] return", "parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}') print(f'safe.time: {temp_safe.time}') print(f'safe.epsg:", "os.path.join(path_t, year, month, day, safe_id + '.SAFE') cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) <", "xml file :param path:(str) path to the .SAFE repository of the image :return:", "day, safe_id + '.SAFE') cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc: temp_safe =", "to others if len(ind[0]) == 0: if isin_tile(x_point, y_point, tile.corner['x'], tile.corner['y']): nb +=", "= [] n_err = 0 n_good = 0 n_all = 0 n_dash =", "(x, y, z): coordinates of the bathy points kept, appended to the previous", "{fn}...') out_y = __flip_bathymetry_y_axis(out_y) return out_x, out_y, out_z def read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None): df", "corner of the S2-L1C image in the WGS84 coordinate system of the tile", "0: print(f'all: {n_all}, keep: {n_good}, errs: {n_err}, dash: {n_dash}') fn = path_to_nc.split(\"/\")[-1] print(f'Filename:", "y, z def __flip_bathymetry_y_axis(arr): unique_values = np.unique(arr) flipped = np.empty(np.array(arr).shape) for i in", "points to close to the actual point ind = np.where(np.abs(np.array(x[i], copy=False) - x_point)", "b)) & (timing_search['S2_lat'] > (tid['S2_lat'].values[0] - b))] tidal = np.nanmean(a['prediction_at_ERA5_point'].values) return tidal else:", "n += 1 n_tot += 1 chosen_idx = np.random.choice(len(bathy_label_points)) random_point = bathy_label_points.iloc[chosen_idx] if", "already kept bathy points :param y: y coordinates of already kept bathy points", "to the .SAFE repository of the image :return: cloud_coverage (float) \"\"\" xml =", "multiple corners') exit() else: pass # Different snapshots of the same tile should", "& round to the tenth to fit on the sentinel 2 max precision", "with the smallest cloud coverage :return: corners, paths, dates, epsgs: infos of the", "2 z = new_z n_err += 1 else: n_dash += 1 if n_all", "{fn}') print(f' Total: {n_all}, 1k: {n_good}, nk: {n_err}, --: {n_dash}') print(f' len(x): {len(out_x)},", "points :param z: z coordinates of already kept bathy points :return: (x, y,", "arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe): date = safe[11:19] time = safe[20:26] tidal_path = cfg.in_path_tidal df", "# Different snapshots of the same tile should have the exact same corners", "data') return None else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t = timedelta(hours=1) timing = datetime.strptime(date +", "= np.where(np.abs(np.array(y[i], copy=False)[ind] - y_point) < precision) # keep the point only if", "the cloud coverage of the S2-L1C image in the xml file :param path:(str)", "for safe_id in safe_ids: year = safe_id[11:15] month = safe_id[15:17] day = safe_id[17:19]", "isin_tile(x_point, y_point, tile.corner['x'], tile.corner['y']): nb += 1 nb_tot += 1 x[i] = np.append(x[i],", "+= 1 if n_all % 5000 == 0: print(f'all: {n_all}, keep: {n_good}, errs:", "precision) # keep the point only if it is not to close to", "path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}') print(f' Total: {n_all}, 1k: {n_good}, nk: {n_err}, --: {n_dash}') print(f'", "as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe): date = safe[11:19] time = safe[20:26] tidal_path", "as xr import pandas as pd import netCDF4 as nc import xml.etree.ElementTree as", "points :param y: y coordinates of already kept bathy points :param z: z", "positive - LAT)'] <= cfg.depth_lim_max: if not len(sentinel2tile_list) == 0: for i in", "z = new_z n_err += 1 else: n_dash += 1 if n_all %", "tile = sentinel2tile_list[i] if tile.epsgs[0] != 'EPSG:32628': # proj to the good coordinate", "else: warnings.warn(f'No tidal elevation data for safe: {safe_id}') temp_safe.tidal_elevation = 0 return temp_safe", "None: z = ncd_z n_good += 1 out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z) else: new_z =", "copy=False) - x_point) < precision) ind = np.where(np.abs(np.array(y[i], copy=False)[ind] - y_point) < precision)", "tile in cfg.tiles: temp_tile = Sentinel2Tile() temp_tile.id = tile print(f'--------------TILE: {temp_tile.id}') n =", "kept bathy points :param z: z coordinates of already kept bathy points :return:", "1000 == 0: print(n) print('label :', label, nb, '/', n, time.time() - t)", "MAIN IMPORT AND COME BACK TO THIS safe_id = safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}')", "return cloud_coverage def get_top_left_corner_coordinates_for_image(path): \"\"\" Find the x, y coordinates of the top", "1 # +/- 1 degree to search for the tidal information (around the", "out_y.append(ncd_y) out_z.append(z) else: new_z = (z + ncd_z) / 2 z = new_z", "TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS sentinel2_tiles = [] i", "-1)) # get the indices of the points to close to the actual", "IMPORT AND COME BACK TO THIS safe_id = safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}') date", "temp_safe.tidal_elevation = tidal else: warnings.warn(f'No tidal elevation data for safe: {safe_id}') temp_safe.tidal_elevation =", "if float(cloud_coverage) < cfg.max_cc and n < cfg.nb_max_date: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe:", "= None for i_k in range(n_k): ncd_z = ncd['depth'][i_y, i_x, i_k, i_t] n_all", "= temp_safe.corners[1] if not in_tiles: sentinel2_tiles.append(temp_tile) return sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This function", "%H:%M:%S') mask = (df['S2_time'] > timing_start) & (df['S2_time'] < timing_end) timing_search = df.loc[mask]", "or temp_safe.corners[1] != temp_tile.corner['y']: id = temp_tile.id warnings.warn( f'============================================ Tile {id}: multiple corners')", "COME BACK TO THIS sentinel2_tiles = [] with open(cfg.in_path_safes_list, 'r') as file: safe_ids", "temp_tile = Sentinel2Tile() temp_tile.id = tile_id if temp_tile in sentinel2_tiles: in_tiles = True", "according to 2 criteria : distance to each others (not to much redundancy)", "x: x coordinates of already kept bathy points :param y: y coordinates of", "the exact same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] if not", "get the indices of the points to close to the actual point ind", "path_t = os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s = os.path.join(path_t, year, month, day, safe_id + '.SAFE')", "%H:%M:%S') timing_end = timing_end.strftime('%Y-%m-%d %H:%M:%S') mask = (df['S2_time'] > timing_start) & (df['S2_time'] <", "z = ncd_z n_good += 1 out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z) else: new_z = (z", "(x, y) temp_safe.epsg = epsg if tidal: temp_safe.tidal_elevation = tidal else: warnings.warn(f'No tidal", "y: y coordinates of already kept bathy points :param z: z coordinates of", "the bathymetry :param x: x coordinates of already kept bathy points :param y:", "labels=labels) print(bathy_points['depth label'].value_counts(sort=False)) n_tot = 0 nb_tot = 0 for label in labels:", "def get_cloud_coverage(path): \"\"\" Find the cloud coverage of the S2-L1C image in the", "path to the .SAFE repository of the image :return: cloud_coverage (float) \"\"\" xml", "timing_start = timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end = timing_end.strftime('%Y-%m-%d %H:%M:%S') mask = (df['S2_time'] > timing_start)", "f'T{tile_id}_{date}T{t_time}_') # ds = gdal.Open(path + 'B04.jp2') # return ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path): from", "== 0: for i in range(nb_tiles): tile = sentinel2tile_list[i] if tile.epsgs[0] != 'EPSG:32628':", "n % 1000 == 0: print(n) print('label :', label, nb, '/', n, time.time()", "Find the cloud coverage of the S2-L1C image in the xml file :param", "projection_out: proj = pyproj.Proj(proj='utm', init=projection_out, ellps=projection_in) lng, lat = proj(lng, lat) return lng,", "time import gdal import pyproj import tarfile import warnings import numpy as np", "= epsg if tidal: temp_safe.tidal_elevation = tidal else: warnings.warn(f'No tidal elevation data for", "y_point, tile.corner['x'], tile.corner['y']): nb += 1 nb_tot += 1 x[i] = np.append(x[i], [x_point])", "the selected tiles \"\"\" from utilities.wrappers import Sentinel2Tile # TODO: UNCOMMENT MAIN IMPORT", "precision = 10 nb_tiles = len(cfg.tiles) # first bathy pts filtering x, y,", "positive - LAT)'], bins=bins, labels=labels) print(bathy_points['depth label'].value_counts(sort=False)) n_tot = 0 nb_tot = 0", "the S2-L1C image in the WGS84 coordinate system of the tile and its", "= 10 nb_tiles = len(cfg.tiles) # first bathy pts filtering x, y, z", "projection_out=None): df = pd.read_csv(path_to_xyz, header=0) lng = np.array(df.lng) lat = np.array(df.lat) z =", "{time}: no tidal elevation data') return None else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t = timedelta(hours=1)", "bathy and s2 are already on the same coordinate system x_point, y_point =", "if tid['prediction_at_ERA5_point'].empty: print(f' {date} - {time}: no tidal elevation data') return None else:", "file for {fn}...') out_y = __flip_bathymetry_y_axis(out_y) return out_x, out_y, out_z def read_fxyz_file(path_to_xyz, projection_in=None,", "len(x): {len(out_x)}, len(y): {len(out_y)}, len(z): {len(out_z)}') print(f' Creating CSV file for {fn}...') out_y", "in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs) > 1: warnings.warn(f'==================================== Tile {temp_tile.id}: multiple epsg\\'s') exit()", "n = 0 nb = 0 t = time.time() while nb < cfg.nb_max_pt_per_tile", "LAT)'].max() if max_depth > 100: bins = np.append(bins, max_depth) labels = np.linspace(0, len(bins)", "- b))] tidal = np.nanmean(a['prediction_at_ERA5_point'].values) return tidal else: tidal = tid['prediction_at_ERA5_point'].values[0] return tidal", "ind = np.where(np.abs(np.array(x[i], copy=False) - x_point) < precision) ind = np.where(np.abs(np.array(y[i], copy=False)[ind] -", "return x_corner, y_corner, epsg def make_tarfile(output_filename, source_dir): with tarfile.open(output_filename, \"w:gz\") as tar: tar.add(source_dir,", "to the actual point ind = np.where(np.abs(np.array(x[i], copy=False) - x_point) < precision) ind", "datetime, timedelta from utilities.common import isin_tile # from utilities.wrappers import Sentinel2Tile, Sentinel2Safe def", "= ncd_z n_good += 1 out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z) else: new_z = (z +", "in os.listdir(cfg.in_path_bathy): path = f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz' df = pd.read_csv(path, header=2) bathy_points =", "positive - LAT)']) if n % 1000 == 0: print(n) print('label :', label,", "len(temp_tile.epsgs) > 1: warnings.warn(f'==================================== Tile {temp_tile.id}: multiple epsg\\'s') exit() if temp_tile.corner['x'] and temp_tile.corner['y']:", "corners') exit() else: pass # Different snapshots of the same tile should have", "bathy_points.append(df, ignore_index=True) bins = np.linspace(cfg.depth_lim_min, 100, 10) max_depth = bathy_points['depth(m - down positive", "+/- 1 degree to search for the tidal information (around the actual tile", "range(n_x): for i_y in range(n_y): ncd_time = ncd.variables['time'][i_t] ncd_x = ncd.variables['x'][i_x] ncd_y =", "10 nb_tiles = len(cfg.tiles) # first bathy pts filtering x, y, z =", "== 0: print(n) print('label :', label, nb, '/', n, time.time() - t) else:", "coverage :return: corners, paths, dates, epsgs: infos of the selected tiles \"\"\" from", "information (around the actual tile center) a = timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0] + b))", "file :param path:(str) path to the .SAFE repository of the image :return: cloud_coverage", "= len(ncd.variables['y']) n_k = len(ncd.variables['kKeep']) n_t = len(ncd.variables['time']) out_x = [] out_y =", "# def get_geo_transform_for_image(s2_path, tile_id, safe_id): # safe_path = os.path.join(s2_path, tile_id, safe_id) # date", "y) temp_safe.epsg = epsg if tidal: temp_safe.tidal_elevation = tidal else: warnings.warn(f'No tidal elevation", "os.path.join(safe_path, 'GRANULE', a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') # ds = gdal.Open(path + 'B04.jp2') # return", "len(tile.epsgs) == 1: proj[i] = pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84') elif len(tile.epsgs) > 1: warnings.warn(f'AGAIN", "-1)) y_point = int(round(y_point, -1)) # get the indices of the points to", "ncd = nc.Dataset(path_to_nc) print(ncd) n_x = len(ncd.variables['x']) n_y = len(ncd.variables['y']) n_k = len(ncd.variables['kKeep'])", "parse_sentinel2_tiles_metadata(): \"\"\" This function returns the info of the nb_max_date tiles with the", "= tile print(f'--------------TILE: {temp_tile.id}') n = 0 i += 1 # tile index", "np.append(y[i], [y_point]) z[i] = np.append(z[i], random_point['depth(m - down positive - LAT)']) if n", "from utilities.wrappers import Sentinel2Tile # TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO", "np.where(np.abs(np.array(y[i], copy=False)[ind] - y_point) < precision) # keep the point only if it", "tidal = tid['prediction_at_ERA5_point'].values[0] return tidal # def get_geo_transform_for_image(s2_path, tile_id, safe_id): # safe_path =", "print(n) print('label :', label, nb, '/', n, time.time() - t) else: print(f'len(bathy_label_points) at", "0 nb_tot = 0 for label in labels: bathy_label_points = bathy_points[bathy_points['depth label'] ==", "HAPPEN ====================================== didn\\'t find tile {tile.id}\\'s epsg?') exit() bathy_points = pd.DataFrame() for directory", "z = [[]] * nb_tiles, [[]] * nb_tiles, [[]] * nb_tiles proj =", "print(f' Creating CSV file for {fn}...') out_y = __flip_bathymetry_y_axis(out_y) return out_x, out_y, out_z", "& (timing_search['S2_lon'] > (tid['S2_lon'].values[0] - b)) & (timing_search['S2_lat'] < (tid['S2_lat'].values[0] + b)) &", "tidal information (around the actual tile center) a = timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0] +", "dates, epsgs: infos of the selected tiles \"\"\" from utilities.wrappers import Sentinel2Tile #", ":param path:(str) path to the .SAFE repository of the image :return: x_corner, y_corner,", "t = time.time() while nb < cfg.nb_max_pt_per_tile and n < cfg.line_max_read: n +=", "= safe_id[20:26] # a = os.listdir(os.path.join(safe_path, 'GRANULE')) # path = os.path.join(safe_path, 'GRANULE', a[0],", "0 return temp_safe def parse_sentinel2_tiles_metadata(): \"\"\" This function returns the info of the", "parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This function returns the info of the nb_max_date tiles with the", "index path_t = os.path.join(cfg.in_path_s2, tile) safes = os.listdir(path_t) temp = [] for safe", "{safe_id}') date = safe_id[11:19] t_time = safe_id[20:26] tidal = get_tidal_elevation_for_image(safe_id) temp_safe = Sentinel2Safe()", "point only if it is not to close to others if len(ind[0]) ==", "n_good += 1 out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z) else: new_z = (z + ncd_z) /", "bathy_points[bathy_points['depth label'] == label] if len(bathy_label_points) > 0: n = 0 nb =", "n < cfg.nb_max_date: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}')", "= temp for safe in safes: path_s = os.path.join(path_t, safe) cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s))", "coordinate system x_point, y_point = random_point['long(DD)'], random_point['lat(DD)'] x_point = int(round(x_point, -1)) y_point =", "not to close to tile borders & depth limited (+ & -) :param", "tidal_path = cfg.in_path_tidal df = xr.open_dataset(tidal_path).to_dataframe() tid = df[df['S2_fname'] == safe[0:len(safe) - 5]]", "= timedelta(hours=1) timing = datetime.strptime(date + time, '%Y%m%d%H%M%S') timing_start = timing - delta_t", "if not in_tiles: sentinel2_tiles.append(temp_tile) return sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This function returns the", "= os.path.join(path, 'MTD_MSIL1C.xml') tree = et.parse(xml) root = tree.getroot() cloud_coverage = float(root[3][0].text) return", "random_point['depth(m - down positive - LAT)']) if n % 1000 == 0: print(n)", "print(f'all: {n_all}, keep: {n_good}, errs: {n_err}, dash: {n_dash}') fn = path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}')", "x_point = int(round(x_point, -1)) y_point = int(round(y_point, -1)) # get the indices of", "(tid['S2_lon'].values[0] - b)) & (timing_search['S2_lat'] < (tid['S2_lat'].values[0] + b)) & (timing_search['S2_lat'] > (tid['S2_lat'].values[0]", "function returns the useful bathy points according to 2 criteria : distance to", "- LAT)'].max() if max_depth > 100: bins = np.append(bins, max_depth) labels = np.linspace(0,", "1 n_tot += 1 chosen_idx = np.random.choice(len(bathy_label_points)) random_point = bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min <=", "Sentinel2Safe() temp_safe.date = date temp_safe.time = t_time temp_safe.s2_path = safe_path x, y, epsg", "cloud coverage :return: corners, paths, dates, epsgs: infos of the selected tiles \"\"\"", "the .SAFE repository of the image :return: x_corner, y_corner, epsg (int, int, str)", "range(nb_tiles): tile = sentinel2tile_list[i] if len(tile.epsgs) == 1: proj[i] = pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84')", "0 t = time.time() while nb < cfg.nb_max_pt_per_tile and n < cfg.line_max_read: n", "> (tid['S2_lat'].values[0] - b))] tidal = np.nanmean(a['prediction_at_ERA5_point'].values) return tidal else: tidal = tid['prediction_at_ERA5_point'].values[0]", "< (tid['S2_lon'].values[0] + b)) & (timing_search['S2_lon'] > (tid['S2_lon'].values[0] - b)) & (timing_search['S2_lat'] <", "else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t = timedelta(hours=1) timing = datetime.strptime(date + time, '%Y%m%d%H%M%S') timing_start", "Tile {tile.id}: multiple epsg\\'s') exit() else: warnings.warn( f'THIS SHOULD NEVER HAPPEN ====================================== didn\\'t", "if projection_in and projection_out: proj = pyproj.Proj(proj='utm', init=projection_out, ellps=projection_in) lng, lat = proj(lng,", "<= random_point['depth(m - down positive - LAT)'] <= cfg.depth_lim_max: if not len(sentinel2tile_list) ==", "(float) \"\"\" xml = os.path.join(path, 'MTD_MSIL1C.xml') tree = et.parse(xml) root = tree.getroot() cloud_coverage", "0 for label in labels: bathy_label_points = bathy_points[bathy_points['depth label'] == label] if len(bathy_label_points)", "coordinates of already kept bathy points :return: (x, y, z): coordinates of the", "'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml') tree = et.parse(xml) root = tree.getroot() x_corner = int(root[1][0][5][0].text)", "for label in labels: bathy_label_points = bathy_points[bathy_points['depth label'] == label] if len(bathy_label_points) >", "range(nb_tiles): tile = sentinel2tile_list[i] if tile.epsgs[0] != 'EPSG:32628': # proj to the good", "utilities.common import isin_tile # from utilities.wrappers import Sentinel2Tile, Sentinel2Safe def get_cloud_coverage(path): \"\"\" Find", "random_point['long(DD)'], random_point['lat(DD)'] x_point = int(round(x_point, -1)) y_point = int(round(y_point, -1)) # get the", "'MTD_MSIL1C.xml') tree = et.parse(xml) root = tree.getroot() cloud_coverage = float(root[3][0].text) return cloud_coverage def", "z): coordinates of the bathy points kept, appended to the previous ones \"\"\"", "for i_k in range(n_k): ncd_z = ncd['depth'][i_y, i_x, i_k, i_t] n_all += 1", "\"\"\" This function returns the useful bathy points according to 2 criteria :", "to close to the actual point ind = np.where(np.abs(np.array(x[i], copy=False) - x_point) <", "= timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0] + b)) & (timing_search['S2_lon'] > (tid['S2_lon'].values[0] - b)) &", "int(root[1][0][5][0].text) y_corner = int(root[1][0][5][1].text) epsg = root[1][0][1].text return x_corner, y_corner, epsg def make_tarfile(output_filename,", "n_tot += 1 chosen_idx = np.random.choice(len(bathy_label_points)) random_point = bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min <= random_point['depth(m", "the .SAFE repository of the image :return: cloud_coverage (float) \"\"\" xml = os.path.join(path,", "< precision) # keep the point only if it is not to close", "= False print(f'--------------TILE: {temp_tile.id}') path_t = os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s = os.path.join(path_t, year, month,", "source_dir): with tarfile.open(output_filename, \"w:gz\") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe): date = safe[11:19]", "df = xr.open_dataset(tidal_path).to_dataframe() tid = df[df['S2_fname'] == safe[0:len(safe) - 5]] if tid['prediction_at_ERA5_point'].empty: print(f'", "= Sentinel2Tile() temp_tile.id = tile_id if temp_tile in sentinel2_tiles: in_tiles = True temp_tile", "its epsg reference number :param path:(str) path to the .SAFE repository of the", "sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles = False print(f'--------------TILE: {temp_tile.id}') path_t = os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s =", "+ b)) & (timing_search['S2_lon'] > (tid['S2_lon'].values[0] - b)) & (timing_search['S2_lat'] < (tid['S2_lat'].values[0] +", "= os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s = os.path.join(path_t, year, month, day, safe_id + '.SAFE') cloud_coverage", "safes = temp for safe in safes: path_s = os.path.join(path_t, safe) cloud_coverage =", "already on the same coordinate system x_point, y_point = random_point['long(DD)'], random_point['lat(DD)'] x_point =", "temp_safe = Sentinel2Safe() temp_safe.date = date temp_safe.time = t_time temp_safe.s2_path = safe_path x,", "bins = np.linspace(cfg.depth_lim_min, 100, 10) max_depth = bathy_points['depth(m - down positive - LAT)'].max()", "should have the exact same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1]", "close to the actual point ind = np.where(np.abs(np.array(x[i], copy=False) - x_point) < precision)", "np.empty(np.array(arr).shape) for i in range(len(arr)): flipped[i] = np.flipud(unique_values)[np.where(unique_values == arr[i])] return flipped def", "{temp_safe.tidal_elevation}') if temp_safe.epsg not in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs) > 1: warnings.warn(f'==================================== Tile", "float(root[3][0].text) return cloud_coverage def get_top_left_corner_coordinates_for_image(path): \"\"\" Find the x, y coordinates of the", "df.loc[mask] b = 1 # +/- 1 degree to search for the tidal", "Total: {n_all}, 1k: {n_good}, nk: {n_err}, --: {n_dash}') print(f' len(x): {len(out_x)}, len(y): {len(out_y)},", "flipped = np.empty(np.array(arr).shape) for i in range(len(arr)): flipped[i] = np.flipud(unique_values)[np.where(unique_values == arr[i])] return", "= bathy_points['depth(m - down positive - LAT)'].max() if max_depth > 100: bins =", "keep the point only if it is not to close to others if", "import Sentinel2Tile # TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS sentinel2_tiles", "tile = sentinel2tile_list[i] if len(tile.epsgs) == 1: proj[i] = pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84') elif", "= gdal.Open(path + 'B04.jp2') # return ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers import Sentinel2Safe", "os.listdir(cfg.in_path_bathy): path = f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz' df = pd.read_csv(path, header=2) bathy_points = bathy_points.append(df,", "in range(nb_tiles): tile = sentinel2tile_list[i] if len(tile.epsgs) == 1: proj[i] = pyproj.Proj(proj='utm', init=tile.epsgs[0],", "< cfg.line_max_read: n += 1 n_tot += 1 chosen_idx = np.random.choice(len(bathy_label_points)) random_point =", "root[1][0][1].text return x_corner, y_corner, epsg def make_tarfile(output_filename, source_dir): with tarfile.open(output_filename, \"w:gz\") as tar:", "tidal: temp_safe.tidal_elevation = tidal else: warnings.warn(f'No tidal elevation data for safe: {safe_id}') temp_safe.tidal_elevation", "{n_err}, dash: {n_dash}') fn = path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}') print(f' Total: {n_all}, 1k: {n_good},", "= 0 i += 1 # tile index path_t = os.path.join(cfg.in_path_s2, tile) safes", "= datetime.strptime(date + time, '%Y%m%d%H%M%S') timing_start = timing - delta_t timing_end = timing", "tile index path_t = os.path.join(cfg.in_path_s2, tile) safes = os.listdir(path_t) temp = [] for", "repository of the image :return: cloud_coverage (float) \"\"\" xml = os.path.join(path, 'MTD_MSIL1C.xml') tree", "b)) & (timing_search['S2_lon'] > (tid['S2_lon'].values[0] - b)) & (timing_search['S2_lat'] < (tid['S2_lat'].values[0] + b))", "AND COME BACK TO THIS safe_id = safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata() safe_id: {safe_id}') date =", "elif len(tile.epsgs) > 1: warnings.warn(f'AGAIN =================================================== Tile {tile.id}: multiple epsg\\'s') exit() else: warnings.warn(", "else: pass # Different snapshots of the same tile should have the exact", "to the good coordinate system & round to the tenth to fit on", "if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t = timedelta(hours=1) timing = datetime.strptime(date + time, '%Y%m%d%H%M%S') timing_start =", "get_cloud_coverage(path): \"\"\" Find the cloud coverage of the S2-L1C image in the xml", "float(cloud_coverage) < cfg.max_cc and n < cfg.nb_max_date: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe)", ":', n_tot, '/', nb_tot) return x, y, z def __flip_bathymetry_y_axis(arr): unique_values = np.unique(arr)", "= os.path.join(cfg.in_path_s2, tile) safes = os.listdir(path_t) temp = [] for safe in safes:", "\"\"\" Find the cloud coverage of the S2-L1C image in the xml file", "the useful bathy points according to 2 criteria : distance to each others", "sentinel2_tiles.append(temp_tile) return sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This function returns the info of the", "\"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}')", "5000 == 0: print(f'all: {n_all}, keep: {n_good}, errs: {n_err}, dash: {n_dash}') fn =", "bins = np.append(bins, max_depth) labels = np.linspace(0, len(bins) - 2, len(bins) - 1)", "import xarray as xr import pandas as pd import netCDF4 as nc import", "float(cloud_coverage) < cfg.max_cc: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}')", "nb_tiles for i in range(nb_tiles): tile = sentinel2tile_list[i] if len(tile.epsgs) == 1: proj[i]", "parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers import Sentinel2Safe # TODO: UNCOMMENT MAIN IMPORT AND COME BACK", "= random_point['long(DD)'], random_point['lat(DD)'] x_point = int(round(x_point, -1)) y_point = int(round(y_point, -1)) # get", "= 1 # +/- 1 degree to search for the tidal information (around", "et.parse(xml) root = tree.getroot() cloud_coverage = float(root[3][0].text) return cloud_coverage def get_top_left_corner_coordinates_for_image(path): \"\"\" Find", "y_point = int(round(y_point, -1)) # get the indices of the points to close", "THIS sentinel2_tiles = [] i = -1 for tile in cfg.tiles: temp_tile =", "range(n_y): ncd_time = ncd.variables['time'][i_t] ncd_x = ncd.variables['x'][i_x] ncd_y = ncd.variables['y'][i_y] z = None", "lng = np.array(df.lng) lat = np.array(df.lat) z = np.array(df.z) if projection_in and projection_out:", "else: new_z = (z + ncd_z) / 2 z = new_z n_err +=", "os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml') tree = et.parse(xml) root = tree.getroot() x_corner = int(root[1][0][5][0].text) y_corner", "file.read().splitlines() for safe_id in safe_ids: year = safe_id[11:15] month = safe_id[15:17] day =", "coordinate system & round to the tenth to fit on the sentinel 2", "{n_good}, errs: {n_err}, dash: {n_dash}') fn = path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}') print(f' Total: {n_all},", "= Sentinel2Tile() temp_tile.id = tile print(f'--------------TILE: {temp_tile.id}') n = 0 i += 1", "- down positive - LAT)'].max() if max_depth > 100: bins = np.append(bins, max_depth)", "100: bins = np.append(bins, max_depth) labels = np.linspace(0, len(bins) - 2, len(bins) -", "find tile {tile.id}\\'s epsg?') exit() bathy_points = pd.DataFrame() for directory in os.listdir(cfg.in_path_bathy): path", "cloud_coverage (float) \"\"\" xml = os.path.join(path, 'MTD_MSIL1C.xml') tree = et.parse(xml) root = tree.getroot()", "> (tid['S2_lon'].values[0] - b)) & (timing_search['S2_lat'] < (tid['S2_lat'].values[0] + b)) & (timing_search['S2_lat'] >", "= bathy_points[bathy_points['depth label'] == label] if len(bathy_label_points) > 0: n = 0 nb", "image in the WGS84 coordinate system of the tile and its epsg reference", "= np.array(df.z) if projection_in and projection_out: proj = pyproj.Proj(proj='utm', init=projection_out, ellps=projection_in) lng, lat", "{n_dash}') fn = path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}') print(f' Total: {n_all}, 1k: {n_good}, nk: {n_err},", "errs: {n_err}, dash: {n_dash}') fn = path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}') print(f' Total: {n_all}, 1k:", "& -) :param path: path of the bathymetry :param x: x coordinates of", "out_z.append(z) else: new_z = (z + ncd_z) / 2 z = new_z n_err", "S2-L1C image in the xml file :param path:(str) path to the .SAFE repository", "path = os.path.join(safe_path, 'GRANULE', a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') # ds = gdal.Open(path + 'B04.jp2')", "flipped def read_nc_file(path_to_nc, projection_in=None, projection_out=None): ncd = nc.Dataset(path_to_nc) print(ncd) n_x = len(ncd.variables['x']) n_y", "have the exact same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] n", "bathy points according to 2 criteria : distance to each others (not to", "repository of the image :return: x_corner, y_corner, epsg (int, int, str) \"\"\" xml", "z: z coordinates of already kept bathy points :return: (x, y, z): coordinates", "- x_point) < precision) ind = np.where(np.abs(np.array(y[i], copy=False)[ind] - y_point) < precision) #", "pd.read_csv(path, header=2) bathy_points = bathy_points.append(df, ignore_index=True) bins = np.linspace(cfg.depth_lim_min, 100, 10) max_depth =", "temp_tile.corner['y'] = temp_safe.corners[1] if not in_tiles: sentinel2_tiles.append(temp_tile) return sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This", "the good coordinate system & round to the tenth to fit on the", "y, epsg = get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners = (x, y) temp_safe.epsg = epsg if tidal:", "the previous ones \"\"\" precision = 10 nb_tiles = len(cfg.tiles) # first bathy", "\"\"\" This function returns the info of the nb_max_date tiles with the smallest", "i_k, i_t] n_all += 1 if ncd_z != '--': if z is None:", "- b)) & (timing_search['S2_lat'] < (tid['S2_lat'].values[0] + b)) & (timing_search['S2_lat'] > (tid['S2_lat'].values[0] -", "i_x, i_k, i_t] n_all += 1 if ncd_z != '--': if z is", "day = safe_id[17:19] tile_id = safe_id[39:44] temp_tile = Sentinel2Tile() temp_tile.id = tile_id if", "< precision) ind = np.where(np.abs(np.array(y[i], copy=False)[ind] - y_point) < precision) # keep the", "safe_id: {safe_id}') date = safe_id[11:19] t_time = safe_id[20:26] tidal = get_tidal_elevation_for_image(safe_id) temp_safe =", "init=tile.epsgs[0], ellps='WGS84') elif len(tile.epsgs) > 1: warnings.warn(f'AGAIN =================================================== Tile {tile.id}: multiple epsg\\'s') exit()", "import Sentinel2Safe # TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS safe_id", "import xml.etree.ElementTree as et import datagen_config as cfg from datetime import datetime, timedelta", "to fit on the sentinel 2 max precision x_point, y_point = proj[i](random_point['long(DD)'], random_point['lat(DD)'])", "make_tarfile(output_filename, source_dir): with tarfile.open(output_filename, \"w:gz\") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe): date =", "== 0: if isin_tile(x_point, y_point, tile.corner['x'], tile.corner['y']): nb += 1 nb_tot += 1", "x_corner, y_corner, epsg def make_tarfile(output_filename, source_dir): with tarfile.open(output_filename, \"w:gz\") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir))", "len(bins) - 1) bathy_points['depth label'] = pd.cut(bathy_points['depth(m - down positive - LAT)'], bins=bins,", "print(f'safe.time: {temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if temp_safe.epsg not in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if", "proj[i] = pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84') elif len(tile.epsgs) > 1: warnings.warn(f'AGAIN =================================================== Tile {tile.id}:", "data for safe: {safe_id}') temp_safe.tidal_elevation = 0 return temp_safe def parse_sentinel2_tiles_metadata(): \"\"\" This", "= -1 for tile in cfg.tiles: temp_tile = Sentinel2Tile() temp_tile.id = tile print(f'--------------TILE:", "in safes: if safe.endswith('SAFE'): temp.append(safe) safes = temp for safe in safes: path_s", "exact same corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] if not in_tiles:", "len(ncd.variables['time']) out_x = [] out_y = [] out_z = [] n_err = 0", "# bathy and s2 are already on the same coordinate system x_point, y_point", "if len(ind[0]) == 0: if isin_tile(x_point, y_point, tile.corner['x'], tile.corner['y']): nb += 1 nb_tot", "of already kept bathy points :param y: y coordinates of already kept bathy", "[[]] * nb_tiles for i in range(nb_tiles): tile = sentinel2tile_list[i] if len(tile.epsgs) ==", "= temp_safe.corners[1] n += 1 sentinel2_tiles.append(temp_tile) return sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This function", "MAIN IMPORT AND COME BACK TO THIS sentinel2_tiles = [] with open(cfg.in_path_safes_list, 'r')", "if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}') print(f'safe.time: {temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}')", "= pd.read_csv(path_to_xyz, header=0) lng = np.array(df.lng) lat = np.array(df.lat) z = np.array(df.z) if", "= timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end = timing_end.strftime('%Y-%m-%d %H:%M:%S') mask = (df['S2_time'] > timing_start) &", "for safe: {safe_id}') temp_safe.tidal_elevation = 0 return temp_safe def parse_sentinel2_tiles_metadata(): \"\"\" This function", "is not to close to others if len(ind[0]) == 0: if isin_tile(x_point, y_point,", "= tree.getroot() x_corner = int(root[1][0][5][0].text) y_corner = int(root[1][0][5][1].text) epsg = root[1][0][1].text return x_corner,", "for the tidal information (around the actual tile center) a = timing_search[(timing_search['S2_lon'] <", "cfg.nb_max_date: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}')", "return flipped def read_nc_file(path_to_nc, projection_in=None, projection_out=None): ncd = nc.Dataset(path_to_nc) print(ncd) n_x = len(ncd.variables['x'])", "{safe_id}') temp_safe.tidal_elevation = 0 return temp_safe def parse_sentinel2_tiles_metadata(): \"\"\" This function returns the", "redundancy) & not to close to tile borders & depth limited (+ &", "return tidal # def get_geo_transform_for_image(s2_path, tile_id, safe_id): # safe_path = os.path.join(s2_path, tile_id, safe_id)", "np.unique(arr) flipped = np.empty(np.array(arr).shape) for i in range(len(arr)): flipped[i] = np.flipud(unique_values)[np.where(unique_values == arr[i])]", "path_s = os.path.join(path_t, year, month, day, safe_id + '.SAFE') cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if", "= ncd.variables['x'][i_x] ncd_y = ncd.variables['y'][i_y] z = None for i_k in range(n_k): ncd_z", "labels = np.linspace(0, len(bins) - 2, len(bins) - 1) bathy_points['depth label'] = pd.cut(bathy_points['depth(m", "for i in range(nb_tiles): tile = sentinel2tile_list[i] if len(tile.epsgs) == 1: proj[i] =", "[[]] * nb_tiles, [[]] * nb_tiles, [[]] * nb_tiles proj = [[]] *", "< (tid['S2_lat'].values[0] + b)) & (timing_search['S2_lat'] > (tid['S2_lat'].values[0] - b))] tidal = np.nanmean(a['prediction_at_ERA5_point'].values)", "system x_point, y_point = random_point['long(DD)'], random_point['lat(DD)'] x_point = int(round(x_point, -1)) y_point = int(round(y_point,", "+ delta_t timing_start = timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end = timing_end.strftime('%Y-%m-%d %H:%M:%S') mask = (df['S2_time']", "datetime.strptime(date + time, '%Y%m%d%H%M%S') timing_start = timing - delta_t timing_end = timing +", "bathy_points = pd.DataFrame() for directory in os.listdir(cfg.in_path_bathy): path = f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz' df", "if not len(sentinel2tile_list) == 0: for i in range(nb_tiles): tile = sentinel2tile_list[i] if", "of the selected tiles \"\"\" from utilities.wrappers import Sentinel2Tile # TODO: UNCOMMENT MAIN", "os import time import gdal import pyproj import tarfile import warnings import numpy", "date = safe[11:19] time = safe[20:26] tidal_path = cfg.in_path_tidal df = xr.open_dataset(tidal_path).to_dataframe() tid", "cfg.max_cc: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}')", "= nc.Dataset(path_to_nc) print(ncd) n_x = len(ncd.variables['x']) n_y = len(ncd.variables['y']) n_k = len(ncd.variables['kKeep']) n_t", "path_s = os.path.join(path_t, safe) cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc and n", "safe_id[20:26] tidal = get_tidal_elevation_for_image(safe_id) temp_safe = Sentinel2Safe() temp_safe.date = date temp_safe.time = t_time", "labels: bathy_label_points = bathy_points[bathy_points['depth label'] == label] if len(bathy_label_points) > 0: n =", "def read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None): df = pd.read_csv(path_to_xyz, header=0) lng = np.array(df.lng) lat =", "in labels: bathy_label_points = bathy_points[bathy_points['depth label'] == label] if len(bathy_label_points) > 0: n", "= [] for safe in safes: if safe.endswith('SAFE'): temp.append(safe) safes = temp for", "Sentinel2Tile # TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS sentinel2_tiles =", "MAIN IMPORT AND COME BACK TO THIS sentinel2_tiles = [] i = -1", "tree.getroot() x_corner = int(root[1][0][5][0].text) y_corner = int(root[1][0][5][1].text) epsg = root[1][0][1].text return x_corner, y_corner,", "if it is not to close to others if len(ind[0]) == 0: if", "down positive - LAT)'] <= cfg.depth_lim_max: if not len(sentinel2tile_list) == 0: for i", "<filename>utilities/data_io.py import os import time import gdal import pyproj import tarfile import warnings", "os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s = os.path.join(path_t, year, month, day, safe_id + '.SAFE') cloud_coverage =", "i_x in range(n_x): for i_y in range(n_y): ncd_time = ncd.variables['time'][i_t] ncd_x = ncd.variables['x'][i_x]", "print('nb of lines read/selected :', n_tot, '/', nb_tot) return x, y, z def", "kept, appended to the previous ones \"\"\" precision = 10 nb_tiles = len(cfg.tiles)", "- delta_t timing_end = timing + delta_t timing_start = timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end =", "coordinates of already kept bathy points :param y: y coordinates of already kept", "max precision x_point, y_point = proj[i](random_point['long(DD)'], random_point['lat(DD)']) else: # bathy and s2 are", "= df[df['S2_fname'] == safe[0:len(safe) - 5]] if tid['prediction_at_ERA5_point'].empty: print(f' {date} - {time}: no", "in range(len(arr)): flipped[i] = np.flipud(unique_values)[np.where(unique_values == arr[i])] return flipped def read_nc_file(path_to_nc, projection_in=None, projection_out=None):", "import pandas as pd import netCDF4 as nc import xml.etree.ElementTree as et import", "{id}: multiple corners') exit() else: pass # Different snapshots of the same tile", "AND COME BACK TO THIS sentinel2_tiles = [] i = -1 for tile", "- {time}: no tidal elevation data') return None else: if np.isnan(tid['prediction_at_ERA5_point'].values[0]): delta_t =", "temp_safe.time = t_time temp_safe.s2_path = safe_path x, y, epsg = get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners =", "!= temp_tile.corner['y']: id = temp_tile.id warnings.warn( f'============================================ Tile {id}: multiple corners') exit() else:", "os.listdir(path_t) temp = [] for safe in safes: if safe.endswith('SAFE'): temp.append(safe) safes =", "of the nb_max_date tiles with the smallest cloud coverage :return: corners, paths, dates,", "= safe_id[39:44] temp_tile = Sentinel2Tile() temp_tile.id = tile_id if temp_tile in sentinel2_tiles: in_tiles", "safe[20:26] tidal_path = cfg.in_path_tidal df = xr.open_dataset(tidal_path).to_dataframe() tid = df[df['S2_fname'] == safe[0:len(safe) -", "timing_end) timing_search = df.loc[mask] b = 1 # +/- 1 degree to search", "center) a = timing_search[(timing_search['S2_lon'] < (tid['S2_lon'].values[0] + b)) & (timing_search['S2_lon'] > (tid['S2_lon'].values[0] -", "{n_good}, nk: {n_err}, --: {n_dash}') print(f' len(x): {len(out_x)}, len(y): {len(out_y)}, len(z): {len(out_z)}') print(f'", "read/selected :', n_tot, '/', nb_tot) return x, y, z def __flip_bathymetry_y_axis(arr): unique_values =", "pd.DataFrame() for directory in os.listdir(cfg.in_path_bathy): path = f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz' df = pd.read_csv(path,", "= temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] if not in_tiles: sentinel2_tiles.append(temp_tile) return sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list):", "tile.corner['y']): nb += 1 nb_tot += 1 x[i] = np.append(x[i], [x_point]) y[i] =", "1: warnings.warn(f'==================================== Tile {temp_tile.id}: multiple epsg\\'s') exit() if temp_tile.corner['x'] and temp_tile.corner['y']: if temp_safe.corners[0]", "if max_depth > 100: bins = np.append(bins, max_depth) labels = np.linspace(0, len(bins) -", "n_all += 1 if ncd_z != '--': if z is None: z =", "def __flip_bathymetry_y_axis(arr): unique_values = np.unique(arr) flipped = np.empty(np.array(arr).shape) for i in range(len(arr)): flipped[i]", "month, day, safe_id + '.SAFE') cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc: temp_safe", "range(len(arr)): flipped[i] = np.flipud(unique_values)[np.where(unique_values == arr[i])] return flipped def read_nc_file(path_to_nc, projection_in=None, projection_out=None): ncd", "S2-L1C image in the WGS84 coordinate system of the tile and its epsg", "< cfg.nb_max_date: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date:", "tiles with the smallest cloud coverage :return: corners, paths, dates, epsgs: infos of", "n_y = len(ncd.variables['y']) n_k = len(ncd.variables['kKeep']) n_t = len(ncd.variables['time']) out_x = [] out_y", "n_err = 0 n_good = 0 n_all = 0 n_dash = 0 for", "top left corner of the S2-L1C image in the WGS84 coordinate system of", "isin_tile # from utilities.wrappers import Sentinel2Tile, Sentinel2Safe def get_cloud_coverage(path): \"\"\" Find the cloud", "{temp_tile.id}: multiple epsg\\'s') exit() if temp_tile.corner['x'] and temp_tile.corner['y']: if temp_safe.corners[0] != temp_tile.corner['x'] or", "This function returns the info of the nb_max_date tiles with the smallest cloud", "ncd.variables['time'][i_t] ncd_x = ncd.variables['x'][i_x] ncd_y = ncd.variables['y'][i_y] z = None for i_k in", "proj = [[]] * nb_tiles for i in range(nb_tiles): tile = sentinel2tile_list[i] if", "infos of the selected tiles \"\"\" from utilities.wrappers import Sentinel2Tile # TODO: UNCOMMENT", "t_time = safe_id[20:26] # a = os.listdir(os.path.join(safe_path, 'GRANULE')) # path = os.path.join(safe_path, 'GRANULE',", "delta_t timing_end = timing + delta_t timing_start = timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end = timing_end.strftime('%Y-%m-%d", "each others (not to much redundancy) & not to close to tile borders", "in range(n_t): for i_x in range(n_x): for i_y in range(n_y): ncd_time = ncd.variables['time'][i_t]", "+= 1 else: n_dash += 1 if n_all % 5000 == 0: print(f'all:", "def parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers import Sentinel2Safe # TODO: UNCOMMENT MAIN IMPORT AND COME", "year, month, day, safe_id + '.SAFE') cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc:", "{temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if temp_safe.epsg not in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs) > 1:", "AND COME BACK TO THIS sentinel2_tiles = [] with open(cfg.in_path_safes_list, 'r') as file:", "temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}') print(f'safe.time: {temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}')", "filtering x, y, z = [[]] * nb_tiles, [[]] * nb_tiles, [[]] *", "the bathy points kept, appended to the previous ones \"\"\" precision = 10", "for safe in safes: if safe.endswith('SAFE'): temp.append(safe) safes = temp for safe in", "path of the bathymetry :param x: x coordinates of already kept bathy points", "if tidal: temp_safe.tidal_elevation = tidal else: warnings.warn(f'No tidal elevation data for safe: {safe_id}')", "# return ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers import Sentinel2Safe # TODO: UNCOMMENT MAIN", "b))] tidal = np.nanmean(a['prediction_at_ERA5_point'].values) return tidal else: tidal = tid['prediction_at_ERA5_point'].values[0] return tidal #", "of the same tile should have the exact same corners else: temp_tile.corner['x'] =", "nk: {n_err}, --: {n_dash}') print(f' len(x): {len(out_x)}, len(y): {len(out_y)}, len(z): {len(out_z)}') print(f' Creating", "coordinates of already kept bathy points :param z: z coordinates of already kept", "> 0: n = 0 nb = 0 t = time.time() while nb", "[[]] * nb_tiles proj = [[]] * nb_tiles for i in range(nb_tiles): tile", "1 else: n_dash += 1 if n_all % 5000 == 0: print(f'all: {n_all},", "temp = [] for safe in safes: if safe.endswith('SAFE'): temp.append(safe) safes = temp", "print(f'--------------TILE: {temp_tile.id}') n = 0 i += 1 # tile index path_t =", "= np.array(df.lng) lat = np.array(df.lat) z = np.array(df.z) if projection_in and projection_out: proj", "- down positive - LAT)'], bins=bins, labels=labels) print(bathy_points['depth label'].value_counts(sort=False)) n_tot = 0 nb_tot", "get_geo_transform_for_image(s2_path, tile_id, safe_id): # safe_path = os.path.join(s2_path, tile_id, safe_id) # date = safe_id[11:19]", "timing = datetime.strptime(date + time, '%Y%m%d%H%M%S') timing_start = timing - delta_t timing_end =", "= date temp_safe.time = t_time temp_safe.s2_path = safe_path x, y, epsg = get_top_left_corner_coordinates_for_image(safe_path)", "and n < cfg.nb_max_date: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path:", "y[i] = np.append(y[i], [y_point]) z[i] = np.append(z[i], random_point['depth(m - down positive - LAT)'])", "if safe.endswith('SAFE'): temp.append(safe) safes = temp for safe in safes: path_s = os.path.join(path_t,", "with open(cfg.in_path_safes_list, 'r') as file: safe_ids = file.read().splitlines() for safe_id in safe_ids: year", "search for the tidal information (around the actual tile center) a = timing_search[(timing_search['S2_lon']", "= bathy_points.append(df, ignore_index=True) bins = np.linspace(cfg.depth_lim_min, 100, 10) max_depth = bathy_points['depth(m - down", "out_z = [] n_err = 0 n_good = 0 n_all = 0 n_dash", "safe_id[17:19] tile_id = safe_id[39:44] temp_tile = Sentinel2Tile() temp_tile.id = tile_id if temp_tile in", "utilities.wrappers import Sentinel2Safe # TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS", "for i_y in range(n_y): ncd_time = ncd.variables['time'][i_t] ncd_x = ncd.variables['x'][i_x] ncd_y = ncd.variables['y'][i_y]", "safe_id[11:15] month = safe_id[15:17] day = safe_id[17:19] tile_id = safe_id[39:44] temp_tile = Sentinel2Tile()", "os.path.join(cfg.in_path_s2, tile) safes = os.listdir(path_t) temp = [] for safe in safes: if", "z[i] = np.append(z[i], random_point['depth(m - down positive - LAT)']) if n % 1000", "= len(cfg.tiles) # first bathy pts filtering x, y, z = [[]] *", "system of the tile and its epsg reference number :param path:(str) path to", "np import xarray as xr import pandas as pd import netCDF4 as nc", "len(bathy_label_points) > 0: n = 0 nb = 0 t = time.time() while", "[y_point]) z[i] = np.append(z[i], random_point['depth(m - down positive - LAT)']) if n %", "pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84') elif len(tile.epsgs) > 1: warnings.warn(f'AGAIN =================================================== Tile {tile.id}: multiple epsg\\'s')", "Sentinel2Safe # TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS safe_id =", "corners else: temp_tile.corner['x'] = temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] if not in_tiles: sentinel2_tiles.append(temp_tile) return", "tree = et.parse(xml) root = tree.getroot() x_corner = int(root[1][0][5][0].text) y_corner = int(root[1][0][5][1].text) epsg", "= np.flipud(unique_values)[np.where(unique_values == arr[i])] return flipped def read_nc_file(path_to_nc, projection_in=None, projection_out=None): ncd = nc.Dataset(path_to_nc)", "{len(out_z)}') print(f' Creating CSV file for {fn}...') out_y = __flip_bathymetry_y_axis(out_y) return out_x, out_y,", "label:{label} == 0') print('nb of lines read/selected :', n_tot, '/', nb_tot) return x,", "'B04.jp2') # return ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path): from utilities.wrappers import Sentinel2Safe # TODO: UNCOMMENT", "= tree.getroot() cloud_coverage = float(root[3][0].text) return cloud_coverage def get_top_left_corner_coordinates_for_image(path): \"\"\" Find the x,", "TODO: UNCOMMENT MAIN IMPORT AND COME BACK TO THIS safe_id = safe_path.split('/')[-1] print(f'parse_sentinel2_imagesafe_metadata()", "image :return: x_corner, y_corner, epsg (int, int, str) \"\"\" xml = os.path.join(path, 'GRANULE',", "in safes: path_s = os.path.join(path_t, safe) cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc", "temp_tile.corner['y']: id = temp_tile.id warnings.warn( f'============================================ Tile {id}: multiple corners') exit() else: pass", "pd.cut(bathy_points['depth(m - down positive - LAT)'], bins=bins, labels=labels) print(bathy_points['depth label'].value_counts(sort=False)) n_tot = 0", "df = pd.read_csv(path, header=2) bathy_points = bathy_points.append(df, ignore_index=True) bins = np.linspace(cfg.depth_lim_min, 100, 10)", "z is None: z = ncd_z n_good += 1 out_x.append(ncd_x) out_y.append(ncd_y) out_z.append(z) else:", "not in_tiles: sentinel2_tiles.append(temp_tile) return sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This function returns the useful", "the image :return: x_corner, y_corner, epsg (int, int, str) \"\"\" xml = os.path.join(path,", "to 2 criteria : distance to each others (not to much redundancy) &", "safe_id[39:44] temp_tile = Sentinel2Tile() temp_tile.id = tile_id if temp_tile in sentinel2_tiles: in_tiles =", "sentinel2tile_list[i] if tile.epsgs[0] != 'EPSG:32628': # proj to the good coordinate system &", "epsg reference number :param path:(str) path to the .SAFE repository of the image", "print(f'safe.corners: {temp_safe.corners}') print(f'safe.s2_path: {temp_safe.s2_path}') print(f'safe.date: {temp_safe.date}') print(f'safe.time: {temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if", "temp_safe.corners[0] temp_tile.corner['y'] = temp_safe.corners[1] n += 1 sentinel2_tiles.append(temp_tile) return sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\"", "sentinel2_tiles: in_tiles = True temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles = False print(f'--------------TILE: {temp_tile.id}')", "NEVER HAPPEN ====================================== didn\\'t find tile {tile.id}\\'s epsg?') exit() bathy_points = pd.DataFrame() for", "= f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz' df = pd.read_csv(path, header=2) bathy_points = bathy_points.append(df, ignore_index=True) bins", "print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if temp_safe.epsg not in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs) >", "'MTD_TL.xml') tree = et.parse(xml) root = tree.getroot() x_corner = int(root[1][0][5][0].text) y_corner = int(root[1][0][5][1].text)", "dash: {n_dash}') fn = path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}') print(f' Total: {n_all}, 1k: {n_good}, nk:", "(df['S2_time'] < timing_end) timing_search = df.loc[mask] b = 1 # +/- 1 degree", "of lines read/selected :', n_tot, '/', nb_tot) return x, y, z def __flip_bathymetry_y_axis(arr):", "+= 1 x[i] = np.append(x[i], [x_point]) y[i] = np.append(y[i], [y_point]) z[i] = np.append(z[i],", "safe_id) # date = safe_id[11:19] # t_time = safe_id[20:26] # a = os.listdir(os.path.join(safe_path,", "(int, int, str) \"\"\" xml = os.path.join(path, 'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml') tree =", "= np.linspace(cfg.depth_lim_min, 100, 10) max_depth = bathy_points['depth(m - down positive - LAT)'].max() if", "len(ncd.variables['kKeep']) n_t = len(ncd.variables['time']) out_x = [] out_y = [] out_z = []", "range(n_t): for i_x in range(n_x): for i_y in range(n_y): ncd_time = ncd.variables['time'][i_t] ncd_x", "a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') # ds = gdal.Open(path + 'B04.jp2') # return ds.GetGeoTransform() def", "- t) else: print(f'len(bathy_label_points) at label:{label} == 0') print('nb of lines read/selected :',", "while nb < cfg.nb_max_pt_per_tile and n < cfg.line_max_read: n += 1 n_tot +=", "= sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles = False print(f'--------------TILE: {temp_tile.id}') path_t = os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s", "tid['prediction_at_ERA5_point'].empty: print(f' {date} - {time}: no tidal elevation data') return None else: if", "as file: safe_ids = file.read().splitlines() for safe_id in safe_ids: year = safe_id[11:15] month", "= np.append(bins, max_depth) labels = np.linspace(0, len(bins) - 2, len(bins) - 1) bathy_points['depth", "ncd_z != '--': if z is None: z = ncd_z n_good += 1", "multiple epsg\\'s') exit() if temp_tile.corner['x'] and temp_tile.corner['y']: if temp_safe.corners[0] != temp_tile.corner['x'] or temp_safe.corners[1]", "# proj to the good coordinate system & round to the tenth to", "safes: path_s = os.path.join(path_t, safe) cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc and", "# path = os.path.join(safe_path, 'GRANULE', a[0], 'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') # ds = gdal.Open(path +", "depth limited (+ & -) :param path: path of the bathymetry :param x:", "already kept bathy points :return: (x, y, z): coordinates of the bathy points", "\"\"\" precision = 10 nb_tiles = len(cfg.tiles) # first bathy pts filtering x,", "temp_tile.id = tile_id if temp_tile in sentinel2_tiles: in_tiles = True temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)]", "label, nb, '/', n, time.time() - t) else: print(f'len(bathy_label_points) at label:{label} == 0')", "= safe_id[17:19] tile_id = safe_id[39:44] temp_tile = Sentinel2Tile() temp_tile.id = tile_id if temp_tile", "tile print(f'--------------TILE: {temp_tile.id}') n = 0 i += 1 # tile index path_t", "np.array(df.z) if projection_in and projection_out: proj = pyproj.Proj(proj='utm', init=projection_out, ellps=projection_in) lng, lat =", "{len(out_y)}, len(z): {len(out_z)}') print(f' Creating CSV file for {fn}...') out_y = __flip_bathymetry_y_axis(out_y) return", "= \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc: temp_safe = parse_sentinel2_imagesafe_metadata(path_s) if temp_safe: temp_tile.safes.append(temp_safe) print(f'safe.corners:", "in range(n_y): ncd_time = ncd.variables['time'][i_t] ncd_x = ncd.variables['x'][i_x] ncd_y = ncd.variables['y'][i_y] z =", "good coordinate system & round to the tenth to fit on the sentinel", "ncd_time = ncd.variables['time'][i_t] ncd_x = ncd.variables['x'][i_x] ncd_y = ncd.variables['y'][i_y] z = None for", "if len(tile.epsgs) == 1: proj[i] = pyproj.Proj(proj='utm', init=tile.epsgs[0], ellps='WGS84') elif len(tile.epsgs) > 1:", "# keep the point only if it is not to close to others", "{n_dash}') print(f' len(x): {len(out_x)}, len(y): {len(out_y)}, len(z): {len(out_z)}') print(f' Creating CSV file for", "0 n_all = 0 n_dash = 0 for i_t in range(n_t): for i_x", "Sentinel2Tile() temp_tile.id = tile_id if temp_tile in sentinel2_tiles: in_tiles = True temp_tile =", "id = temp_tile.id warnings.warn( f'============================================ Tile {id}: multiple corners') exit() else: pass #", "1 x[i] = np.append(x[i], [x_point]) y[i] = np.append(y[i], [y_point]) z[i] = np.append(z[i], random_point['depth(m", "np.random.choice(len(bathy_label_points)) random_point = bathy_label_points.iloc[chosen_idx] if cfg.depth_lim_min <= random_point['depth(m - down positive - LAT)']", "y, z): coordinates of the bathy points kept, appended to the previous ones", "from utilities.common import isin_tile # from utilities.wrappers import Sentinel2Tile, Sentinel2Safe def get_cloud_coverage(path): \"\"\"", "THIS sentinel2_tiles = [] with open(cfg.in_path_safes_list, 'r') as file: safe_ids = file.read().splitlines() for", ".SAFE repository of the image :return: cloud_coverage (float) \"\"\" xml = os.path.join(path, 'MTD_MSIL1C.xml')", "ind = np.where(np.abs(np.array(y[i], copy=False)[ind] - y_point) < precision) # keep the point only", "with tarfile.open(output_filename, \"w:gz\") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe): date = safe[11:19] time", "tile) safes = os.listdir(path_t) temp = [] for safe in safes: if safe.endswith('SAFE'):", "= (z + ncd_z) / 2 z = new_z n_err += 1 else:", "tar.add(source_dir, arcname=os.path.basename(source_dir)) def get_tidal_elevation_for_image(safe): date = safe[11:19] time = safe[20:26] tidal_path = cfg.in_path_tidal", "for tile in cfg.tiles: temp_tile = Sentinel2Tile() temp_tile.id = tile print(f'--------------TILE: {temp_tile.id}') n", "in range(nb_tiles): tile = sentinel2tile_list[i] if tile.epsgs[0] != 'EPSG:32628': # proj to the", ":return: x_corner, y_corner, epsg (int, int, str) \"\"\" xml = os.path.join(path, 'GRANULE', os.listdir(os.path.join(path,", "n_k = len(ncd.variables['kKeep']) n_t = len(ncd.variables['time']) out_x = [] out_y = [] out_z", "path to the .SAFE repository of the image :return: x_corner, y_corner, epsg (int,", "epsg = root[1][0][1].text return x_corner, y_corner, epsg def make_tarfile(output_filename, source_dir): with tarfile.open(output_filename, \"w:gz\")", "cfg from datetime import datetime, timedelta from utilities.common import isin_tile # from utilities.wrappers", "int(root[1][0][5][1].text) epsg = root[1][0][1].text return x_corner, y_corner, epsg def make_tarfile(output_filename, source_dir): with tarfile.open(output_filename,", "n = 0 i += 1 # tile index path_t = os.path.join(cfg.in_path_s2, tile)", "= 0 nb_tot = 0 for label in labels: bathy_label_points = bathy_points[bathy_points['depth label']", "x coordinates of already kept bathy points :param y: y coordinates of already", "cloud_coverage = float(root[3][0].text) return cloud_coverage def get_top_left_corner_coordinates_for_image(path): \"\"\" Find the x, y coordinates", "s2 are already on the same coordinate system x_point, y_point = random_point['long(DD)'], random_point['lat(DD)']", "> 1: warnings.warn(f'==================================== Tile {temp_tile.id}: multiple epsg\\'s') exit() if temp_tile.corner['x'] and temp_tile.corner['y']: if", "x_corner, y_corner, epsg (int, int, str) \"\"\" xml = os.path.join(path, 'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0],", "projection_out=None): ncd = nc.Dataset(path_to_nc) print(ncd) n_x = len(ncd.variables['x']) n_y = len(ncd.variables['y']) n_k =", "np.append(x[i], [x_point]) y[i] = np.append(y[i], [y_point]) z[i] = np.append(z[i], random_point['depth(m - down positive", "- down positive - LAT)']) if n % 1000 == 0: print(n) print('label", "the actual point ind = np.where(np.abs(np.array(x[i], copy=False) - x_point) < precision) ind =", "n, time.time() - t) else: print(f'len(bathy_label_points) at label:{label} == 0') print('nb of lines", "et import datagen_config as cfg from datetime import datetime, timedelta from utilities.common import", "y coordinates of already kept bathy points :param z: z coordinates of already", "ncd_y = ncd.variables['y'][i_y] z = None for i_k in range(n_k): ncd_z = ncd['depth'][i_y,", "safes: if safe.endswith('SAFE'): temp.append(safe) safes = temp for safe in safes: path_s =", "datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This function returns the useful bathy points according to 2 criteria", "& (df['S2_time'] < timing_end) timing_search = df.loc[mask] b = 1 # +/- 1", "temp_safe.corners[1] n += 1 sentinel2_tiles.append(temp_tile) return sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This function returns", "= t_time temp_safe.s2_path = safe_path x, y, epsg = get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners = (x,", "safe in safes: if safe.endswith('SAFE'): temp.append(safe) safes = temp for safe in safes:", "df = pd.read_csv(path_to_xyz, header=0) lng = np.array(df.lng) lat = np.array(df.lat) z = np.array(df.z)", "= \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage) < cfg.max_cc and n < cfg.nb_max_date: temp_safe = parse_sentinel2_imagesafe_metadata(path_s)", "os.path.join(path, 'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml') tree = et.parse(xml) root = tree.getroot() x_corner =", "max_depth > 100: bins = np.append(bins, max_depth) labels = np.linspace(0, len(bins) - 2,", "out_y, out_z def read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None): df = pd.read_csv(path_to_xyz, header=0) lng = np.array(df.lng)", "appended to the previous ones \"\"\" precision = 10 nb_tiles = len(cfg.tiles) #", "= path_to_nc.split(\"/\")[-1] print(f'Filename: {fn}') print(f' Total: {n_all}, 1k: {n_good}, nk: {n_err}, --: {n_dash}')", "= os.path.join(path_t, year, month, day, safe_id + '.SAFE') cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if float(cloud_coverage)", "{temp_tile.id}') path_t = os.path.join(cfg.in_path_datalake_s2, temp_tile.id) path_s = os.path.join(path_t, year, month, day, safe_id +", "time, '%Y%m%d%H%M%S') timing_start = timing - delta_t timing_end = timing + delta_t timing_start", "{n_all}, 1k: {n_good}, nk: {n_err}, --: {n_dash}') print(f' len(x): {len(out_x)}, len(y): {len(out_y)}, len(z):", "n_all % 5000 == 0: print(f'all: {n_all}, keep: {n_good}, errs: {n_err}, dash: {n_dash}')", "tidal = np.nanmean(a['prediction_at_ERA5_point'].values) return tidal else: tidal = tid['prediction_at_ERA5_point'].values[0] return tidal # def", "2 max precision x_point, y_point = proj[i](random_point['long(DD)'], random_point['lat(DD)']) else: # bathy and s2", "= et.parse(xml) root = tree.getroot() cloud_coverage = float(root[3][0].text) return cloud_coverage def get_top_left_corner_coordinates_for_image(path): \"\"\"", "i in range(len(arr)): flipped[i] = np.flipud(unique_values)[np.where(unique_values == arr[i])] return flipped def read_nc_file(path_to_nc, projection_in=None,", "much redundancy) & not to close to tile borders & depth limited (+", "path:(str) path to the .SAFE repository of the image :return: x_corner, y_corner, epsg", "label] if len(bathy_label_points) > 0: n = 0 nb = 0 t =", "in range(n_k): ncd_z = ncd['depth'][i_y, i_x, i_k, i_t] n_all += 1 if ncd_z", "for directory in os.listdir(cfg.in_path_bathy): path = f'{os.path.join(cfg.in_path_bathy, directory, directory)}.xyz' df = pd.read_csv(path, header=2)", "= tile_id if temp_tile in sentinel2_tiles: in_tiles = True temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else:", "True temp_tile = sentinel2_tiles[sentinel2_tiles.index(temp_tile)] else: in_tiles = False print(f'--------------TILE: {temp_tile.id}') path_t = os.path.join(cfg.in_path_datalake_s2,", "label'] == label] if len(bathy_label_points) > 0: n = 0 nb = 0", "as np import xarray as xr import pandas as pd import netCDF4 as", "\"\"\" xml = os.path.join(path, 'GRANULE', os.listdir(os.path.join(path, 'GRANULE'))[0], 'MTD_TL.xml') tree = et.parse(xml) root =", "tree.getroot() cloud_coverage = float(root[3][0].text) return cloud_coverage def get_top_left_corner_coordinates_for_image(path): \"\"\" Find the x, y", "+= 1 sentinel2_tiles.append(temp_tile) return sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This function returns the info", "else: # bathy and s2 are already on the same coordinate system x_point,", "and s2 are already on the same coordinate system x_point, y_point = random_point['long(DD)'],", "/ 2 z = new_z n_err += 1 else: n_dash += 1 if", "the xml file :param path:(str) path to the .SAFE repository of the image", "directory, directory)}.xyz' df = pd.read_csv(path, header=2) bathy_points = bathy_points.append(df, ignore_index=True) bins = np.linspace(cfg.depth_lim_min,", "safe_ids: year = safe_id[11:15] month = safe_id[15:17] day = safe_id[17:19] tile_id = safe_id[39:44]", "[] out_y = [] out_z = [] n_err = 0 n_good = 0", "# from utilities.wrappers import Sentinel2Tile, Sentinel2Safe def get_cloud_coverage(path): \"\"\" Find the cloud coverage", "as nc import xml.etree.ElementTree as et import datagen_config as cfg from datetime import", "the points to close to the actual point ind = np.where(np.abs(np.array(x[i], copy=False) -", "y_point = proj[i](random_point['long(DD)'], random_point['lat(DD)']) else: # bathy and s2 are already on the", "x, y, epsg = get_top_left_corner_coordinates_for_image(safe_path) temp_safe.corners = (x, y) temp_safe.epsg = epsg if", "# safe_path = os.path.join(s2_path, tile_id, safe_id) # date = safe_id[11:19] # t_time =", "if isin_tile(x_point, y_point, tile.corner['x'], tile.corner['y']): nb += 1 nb_tot += 1 x[i] =", "LAT)'], bins=bins, labels=labels) print(bathy_points['depth label'].value_counts(sort=False)) n_tot = 0 nb_tot = 0 for label", "warnings.warn( f'============================================ Tile {id}: multiple corners') exit() else: pass # Different snapshots of", "if temp_safe.epsg not in temp_tile.epsgs: temp_tile.epsgs.append(temp_safe.epsg) if len(temp_tile.epsgs) > 1: warnings.warn(f'==================================== Tile {temp_tile.id}:", "> 100: bins = np.append(bins, max_depth) labels = np.linspace(0, len(bins) - 2, len(bins)", "= np.empty(np.array(arr).shape) for i in range(len(arr)): flipped[i] = np.flipud(unique_values)[np.where(unique_values == arr[i])] return flipped", "print(f' Total: {n_all}, 1k: {n_good}, nk: {n_err}, --: {n_dash}') print(f' len(x): {len(out_x)}, len(y):", "return sentinel2_tiles def datagen_get_bathy_xyz(sentinel2tile_list): \"\"\" This function returns the useful bathy points according", "<= cfg.depth_lim_max: if not len(sentinel2tile_list) == 0: for i in range(nb_tiles): tile =", "IMPORT AND COME BACK TO THIS sentinel2_tiles = [] i = -1 for", "= int(root[1][0][5][1].text) epsg = root[1][0][1].text return x_corner, y_corner, epsg def make_tarfile(output_filename, source_dir): with", "= np.append(x[i], [x_point]) y[i] = np.append(y[i], [y_point]) z[i] = np.append(z[i], random_point['depth(m - down", ":param y: y coordinates of already kept bathy points :param z: z coordinates", "'IMG_DATA', f'T{tile_id}_{date}T{t_time}_') # ds = gdal.Open(path + 'B04.jp2') # return ds.GetGeoTransform() def parse_sentinel2_imagesafe_metadata(safe_path):", "len(ind[0]) == 0: if isin_tile(x_point, y_point, tile.corner['x'], tile.corner['y']): nb += 1 nb_tot +=", "x[i] = np.append(x[i], [x_point]) y[i] = np.append(y[i], [y_point]) z[i] = np.append(z[i], random_point['depth(m -", "safes = os.listdir(path_t) temp = [] for safe in safes: if safe.endswith('SAFE'): temp.append(safe)", "- 1) bathy_points['depth label'] = pd.cut(bathy_points['depth(m - down positive - LAT)'], bins=bins, labels=labels)", "info of the nb_max_date tiles with the smallest cloud coverage :return: corners, paths,", "def parse_sentinel2_tiles_metadata(): \"\"\" This function returns the info of the nb_max_date tiles with", "IMPORT AND COME BACK TO THIS sentinel2_tiles = [] with open(cfg.in_path_safes_list, 'r') as", "print(f'safe.date: {temp_safe.date}') print(f'safe.time: {temp_safe.time}') print(f'safe.epsg: {temp_safe.epsg}') print(f'safe.tidal_elevation: {temp_safe.tidal_elevation}') if temp_safe.epsg not in temp_tile.epsgs:", "safe[0:len(safe) - 5]] if tid['prediction_at_ERA5_point'].empty: print(f' {date} - {time}: no tidal elevation data')", "nb, '/', n, time.time() - t) else: print(f'len(bathy_label_points) at label:{label} == 0') print('nb", "return out_x, out_y, out_z def read_fxyz_file(path_to_xyz, projection_in=None, projection_out=None): df = pd.read_csv(path_to_xyz, header=0) lng", "= safe_id[15:17] day = safe_id[17:19] tile_id = safe_id[39:44] temp_tile = Sentinel2Tile() temp_tile.id =", "only if it is not to close to others if len(ind[0]) == 0:", "safe_id in safe_ids: year = safe_id[11:15] month = safe_id[15:17] day = safe_id[17:19] tile_id", "get_top_left_corner_coordinates_for_image(path): \"\"\" Find the x, y coordinates of the top left corner of", "tidal else: tidal = tid['prediction_at_ERA5_point'].values[0] return tidal # def get_geo_transform_for_image(s2_path, tile_id, safe_id): #", "nb_tiles, [[]] * nb_tiles, [[]] * nb_tiles proj = [[]] * nb_tiles for", "temp_safe.corners = (x, y) temp_safe.epsg = epsg if tidal: temp_safe.tidal_elevation = tidal else:", "numpy as np import xarray as xr import pandas as pd import netCDF4", "warnings.warn(f'AGAIN =================================================== Tile {tile.id}: multiple epsg\\'s') exit() else: warnings.warn( f'THIS SHOULD NEVER HAPPEN", "= int(round(y_point, -1)) # get the indices of the points to close to", "file: safe_ids = file.read().splitlines() for safe_id in safe_ids: year = safe_id[11:15] month =", "import pyproj import tarfile import warnings import numpy as np import xarray as", "tile.corner['x'], tile.corner['y']): nb += 1 nb_tot += 1 x[i] = np.append(x[i], [x_point]) y[i]", "temp_tile.corner['y'] = temp_safe.corners[1] n += 1 sentinel2_tiles.append(temp_tile) return sentinel2_tiles def parse_sentinel2_tiles_metadata_from_datalake(): \"\"\" This", "# tile index path_t = os.path.join(cfg.in_path_s2, tile) safes = os.listdir(path_t) temp = []", "temp for safe in safes: path_s = os.path.join(path_t, safe) cloud_coverage = \"{0:0.2f}\".format(get_cloud_coverage(path_s)) if", "= safe_id[11:19] t_time = safe_id[20:26] tidal = get_tidal_elevation_for_image(safe_id) temp_safe = Sentinel2Safe() temp_safe.date =", "x_point) < precision) ind = np.where(np.abs(np.array(y[i], copy=False)[ind] - y_point) < precision) # keep", "for i in range(nb_tiles): tile = sentinel2tile_list[i] if tile.epsgs[0] != 'EPSG:32628': # proj", "BACK TO THIS sentinel2_tiles = [] with open(cfg.in_path_safes_list, 'r') as file: safe_ids =", "else: tidal = tid['prediction_at_ERA5_point'].values[0] return tidal # def get_geo_transform_for_image(s2_path, tile_id, safe_id): # safe_path", "to the previous ones \"\"\" precision = 10 nb_tiles = len(cfg.tiles) # first", "+= 1 if ncd_z != '--': if z is None: z = ncd_z", "tile {tile.id}\\'s epsg?') exit() bathy_points = pd.DataFrame() for directory in os.listdir(cfg.in_path_bathy): path =", "the S2-L1C image in the xml file :param path:(str) path to the .SAFE", "= safe_id[11:15] month = safe_id[15:17] day = safe_id[17:19] tile_id = safe_id[39:44] temp_tile =", "import isin_tile # from utilities.wrappers import Sentinel2Tile, Sentinel2Safe def get_cloud_coverage(path): \"\"\" Find the", "as pd import netCDF4 as nc import xml.etree.ElementTree as et import datagen_config as", "down positive - LAT)'], bins=bins, labels=labels) print(bathy_points['depth label'].value_counts(sort=False)) n_tot = 0 nb_tot =", "= et.parse(xml) root = tree.getroot() x_corner = int(root[1][0][5][0].text) y_corner = int(root[1][0][5][1].text) epsg =", "read_nc_file(path_to_nc, projection_in=None, projection_out=None): ncd = nc.Dataset(path_to_nc) print(ncd) n_x = len(ncd.variables['x']) n_y = len(ncd.variables['y'])", "xr.open_dataset(tidal_path).to_dataframe() tid = df[df['S2_fname'] == safe[0:len(safe) - 5]] if tid['prediction_at_ERA5_point'].empty: print(f' {date} -", "x, y coordinates of the top left corner of the S2-L1C image in", "{tile.id}: multiple epsg\\'s') exit() else: warnings.warn( f'THIS SHOULD NEVER HAPPEN ====================================== didn\\'t find", "tid = df[df['S2_fname'] == safe[0:len(safe) - 5]] if tid['prediction_at_ERA5_point'].empty: print(f' {date} - {time}:", "if ncd_z != '--': if z is None: z = ncd_z n_good +=", "on the sentinel 2 max precision x_point, y_point = proj[i](random_point['long(DD)'], random_point['lat(DD)']) else: #", "precision) ind = np.where(np.abs(np.array(y[i], copy=False)[ind] - y_point) < precision) # keep the point", "timing + delta_t timing_start = timing_start.strftime('%Y-%m-%d %H:%M:%S') timing_end = timing_end.strftime('%Y-%m-%d %H:%M:%S') mask =", "sentinel2_tiles = [] with open(cfg.in_path_safes_list, 'r') as file: safe_ids = file.read().splitlines() for safe_id", "* nb_tiles, [[]] * nb_tiles, [[]] * nb_tiles proj = [[]] * nb_tiles", "timing_search = df.loc[mask] b = 1 # +/- 1 degree to search for", "= float(root[3][0].text) return cloud_coverage def get_top_left_corner_coordinates_for_image(path): \"\"\" Find the x, y coordinates of", "tenth to fit on the sentinel 2 max precision x_point, y_point = proj[i](random_point['long(DD)'],", "proj = pyproj.Proj(proj='utm', init=projection_out, ellps=projection_in) lng, lat = proj(lng, lat) return lng, lat,", "safe_id[11:19] # t_time = safe_id[20:26] # a = os.listdir(os.path.join(safe_path, 'GRANULE')) # path =", "if n % 1000 == 0: print(n) print('label :', label, nb, '/', n,", "len(cfg.tiles) # first bathy pts filtering x, y, z = [[]] * nb_tiles," ]
[ "total_command_bytes(self): return self.reliableCommandBytes + self.unreliableCommandBytes + \\ self.fragmentCommandBytes + self.controlCommandBytes def total_packet_bytes(self): return", "the License. \"\"\" class TrafficStats: def __init__(self): self.packageHeaderSize = 0 self.reliableCommandCount = 0", "= 0 self.totalPacketCount = 0 self.totalCommandsInPackets = 0 self.reliableCommandBytes = 0 self.unreliableCommandBytes =", "permissions and limitations under the License. \"\"\" class TrafficStats: def __init__(self): self.packageHeaderSize =", "= 0 self.totalCommandsInPackets = 0 self.reliableCommandBytes = 0 self.unreliableCommandBytes = 0 self.fragmentCommandBytes =", "the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in", "self.controlCommandBytes = 0 def total_command_count(self): return self.reliableCommandCount + self.unreliableCommandCount + \\ self.fragmentCommandCount +", "self.reliableCommandCount + self.unreliableCommandCount + \\ self.fragmentCommandCount + self.controlCommandCount def total_command_bytes(self): return self.reliableCommandBytes +", "count_unreliable_op_command(self, size): self.unreliableCommandBytes += size self.unreliableCommandCount += 1 def count_fragment_op_command(self, size): self.fragmentCommandBytes +=", "0 self.reliableCommandCount = 0 self.unreliableCommandCount = 0 self.fragmentCommandCount = 0 self.controlCommandCount = 0", "self.controlCommandCount = 0 self.totalPacketCount = 0 self.totalCommandsInPackets = 0 self.reliableCommandBytes = 0 self.unreliableCommandBytes", "self.totalPacketCount * self.packageHeaderSize def count_control_command(self, size): self.controlCommandBytes += size self.controlCommandCount += 1 def", "def count_reliable_op_command(self, size): self.reliableCommandBytes += size self.reliableCommandCount += 1 def count_unreliable_op_command(self, size): self.unreliableCommandBytes", "+ self.controlCommandBytes def total_packet_bytes(self): return self.total_command_bytes() + self.totalPacketCount * self.packageHeaderSize def count_control_command(self, size):", "+= size self.unreliableCommandCount += 1 def count_fragment_op_command(self, size): self.fragmentCommandBytes += size self.fragmentCommandCount +=", "CONDITIONS OF ANY KIND, either express or implied. See the License for the", "0 self.controlCommandCount = 0 self.totalPacketCount = 0 self.totalCommandsInPackets = 0 self.reliableCommandBytes = 0", "OR CONDITIONS OF ANY KIND, either express or implied. See the License for", "0 def total_command_count(self): return self.reliableCommandCount + self.unreliableCommandCount + \\ self.fragmentCommandCount + self.controlCommandCount def", "OF ANY KIND, either express or implied. See the License for the specific", "to in writing, software distributed under the License is distributed on an \"AS", "count_fragment_op_command(self, size): self.fragmentCommandBytes += size self.fragmentCommandCount += 1 def __str__(self, *args, **kwargs): return", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "self.controlCommandCount def total_command_bytes(self): return self.reliableCommandBytes + self.unreliableCommandBytes + \\ self.fragmentCommandBytes + self.controlCommandBytes def", "language governing permissions and limitations under the License. \"\"\" class TrafficStats: def __init__(self):", "self.reliableCommandBytes += size self.reliableCommandCount += 1 def count_unreliable_op_command(self, size): self.unreliableCommandBytes += size self.unreliableCommandCount", "not use this file except in compliance with the License. You may obtain", "License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required", "under the License. \"\"\" class TrafficStats: def __init__(self): self.packageHeaderSize = 0 self.reliableCommandCount =", "__str__(self, *args, **kwargs): return \"TotalPacketBytes: {}\\nTotalCommandBytes: {}\\nTotalPacketCount: {}\\nTotalCommandsInPackets: {}\" \\ .format(self.total_packet_bytes(), self.total_command_bytes(), self.totalPacketCount,", "self.reliableCommandCount = 0 self.unreliableCommandCount = 0 self.fragmentCommandCount = 0 self.controlCommandCount = 0 self.totalPacketCount", "= 0 self.reliableCommandBytes = 0 self.unreliableCommandBytes = 0 self.fragmentCommandBytes = 0 self.controlCommandBytes =", "except in compliance with the License. You may obtain a copy of the", "and limitations under the License. \"\"\" class TrafficStats: def __init__(self): self.packageHeaderSize = 0", "may not use this file except in compliance with the License. You may", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the", "under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "0 self.fragmentCommandCount = 0 self.controlCommandCount = 0 self.totalPacketCount = 0 self.totalCommandsInPackets = 0", "+ self.totalPacketCount * self.packageHeaderSize def count_control_command(self, size): self.controlCommandBytes += size self.controlCommandCount += 1", "+= size self.controlCommandCount += 1 def count_reliable_op_command(self, size): self.reliableCommandBytes += size self.reliableCommandCount +=", "size self.controlCommandCount += 1 def count_reliable_op_command(self, size): self.reliableCommandBytes += size self.reliableCommandCount += 1", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "self.packageHeaderSize = 0 self.reliableCommandCount = 0 self.unreliableCommandCount = 0 self.fragmentCommandCount = 0 self.controlCommandCount", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "1 def count_fragment_op_command(self, size): self.fragmentCommandBytes += size self.fragmentCommandCount += 1 def __str__(self, *args,", "def __str__(self, *args, **kwargs): return \"TotalPacketBytes: {}\\nTotalCommandBytes: {}\\nTotalPacketCount: {}\\nTotalCommandsInPackets: {}\" \\ .format(self.total_packet_bytes(), self.total_command_bytes(),", "self.unreliableCommandCount + \\ self.fragmentCommandCount + self.controlCommandCount def total_command_bytes(self): return self.reliableCommandBytes + self.unreliableCommandBytes +", "0 self.fragmentCommandBytes = 0 self.controlCommandBytes = 0 def total_command_count(self): return self.reliableCommandCount + self.unreliableCommandCount", "size self.reliableCommandCount += 1 def count_unreliable_op_command(self, size): self.unreliableCommandBytes += size self.unreliableCommandCount += 1", "self.unreliableCommandBytes += size self.unreliableCommandCount += 1 def count_fragment_op_command(self, size): self.fragmentCommandBytes += size self.fragmentCommandCount", "obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law", "the License for the specific language governing permissions and limitations under the License.", "1 def __str__(self, *args, **kwargs): return \"TotalPacketBytes: {}\\nTotalCommandBytes: {}\\nTotalPacketCount: {}\\nTotalCommandsInPackets: {}\" \\ .format(self.total_packet_bytes(),", "ANY KIND, either express or implied. See the License for the specific language", "def count_fragment_op_command(self, size): self.fragmentCommandBytes += size self.fragmentCommandCount += 1 def __str__(self, *args, **kwargs):", "\\ self.fragmentCommandCount + self.controlCommandCount def total_command_bytes(self): return self.reliableCommandBytes + self.unreliableCommandBytes + \\ self.fragmentCommandBytes", "file except in compliance with the License. You may obtain a copy of", "License for the specific language governing permissions and limitations under the License. \"\"\"", "return self.total_command_bytes() + self.totalPacketCount * self.packageHeaderSize def count_control_command(self, size): self.controlCommandBytes += size self.controlCommandCount", "Unless required by applicable law or agreed to in writing, software distributed under", "count_control_command(self, size): self.controlCommandBytes += size self.controlCommandCount += 1 def count_reliable_op_command(self, size): self.reliableCommandBytes +=", "= 0 self.fragmentCommandBytes = 0 self.controlCommandBytes = 0 def total_command_count(self): return self.reliableCommandCount +", "License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,", "2.0 (the \"License\"); you may not use this file except in compliance with", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "2015 <NAME> Licensed under the Apache License, Version 2.0 (the \"License\"); you may", "See the License for the specific language governing permissions and limitations under the", "self.controlCommandCount += 1 def count_reliable_op_command(self, size): self.reliableCommandBytes += size self.reliableCommandCount += 1 def", "= 0 self.controlCommandCount = 0 self.totalPacketCount = 0 self.totalCommandsInPackets = 0 self.reliableCommandBytes =", "copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed", "self.reliableCommandBytes + self.unreliableCommandBytes + \\ self.fragmentCommandBytes + self.controlCommandBytes def total_packet_bytes(self): return self.total_command_bytes() +", "self.fragmentCommandCount = 0 self.controlCommandCount = 0 self.totalPacketCount = 0 self.totalCommandsInPackets = 0 self.reliableCommandBytes", "+= 1 def __str__(self, *args, **kwargs): return \"TotalPacketBytes: {}\\nTotalCommandBytes: {}\\nTotalPacketCount: {}\\nTotalCommandsInPackets: {}\" \\", "self.packageHeaderSize def count_control_command(self, size): self.controlCommandBytes += size self.controlCommandCount += 1 def count_reliable_op_command(self, size):", "self.reliableCommandBytes = 0 self.unreliableCommandBytes = 0 self.fragmentCommandBytes = 0 self.controlCommandBytes = 0 def", "the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless", "governing permissions and limitations under the License. \"\"\" class TrafficStats: def __init__(self): self.packageHeaderSize", "the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "self.controlCommandBytes def total_packet_bytes(self): return self.total_command_bytes() + self.totalPacketCount * self.packageHeaderSize def count_control_command(self, size): self.controlCommandBytes", "specific language governing permissions and limitations under the License. \"\"\" class TrafficStats: def", "*args, **kwargs): return \"TotalPacketBytes: {}\\nTotalCommandBytes: {}\\nTotalPacketCount: {}\\nTotalCommandsInPackets: {}\" \\ .format(self.total_packet_bytes(), self.total_command_bytes(), self.totalPacketCount, self.totalCommandsInPackets)", "License, Version 2.0 (the \"License\"); you may not use this file except in", "compliance with the License. You may obtain a copy of the License at", "(the \"License\"); you may not use this file except in compliance with the", "self.controlCommandBytes += size self.controlCommandCount += 1 def count_reliable_op_command(self, size): self.reliableCommandBytes += size self.reliableCommandCount", "this file except in compliance with the License. You may obtain a copy", "total_packet_bytes(self): return self.total_command_bytes() + self.totalPacketCount * self.packageHeaderSize def count_control_command(self, size): self.controlCommandBytes += size", "0 self.unreliableCommandCount = 0 self.fragmentCommandCount = 0 self.controlCommandCount = 0 self.totalPacketCount = 0", "def total_command_bytes(self): return self.reliableCommandBytes + self.unreliableCommandBytes + \\ self.fragmentCommandBytes + self.controlCommandBytes def total_packet_bytes(self):", "\"License\"); you may not use this file except in compliance with the License.", "express or implied. See the License for the specific language governing permissions and", "self.fragmentCommandBytes += size self.fragmentCommandCount += 1 def __str__(self, *args, **kwargs): return \"TotalPacketBytes: {}\\nTotalCommandBytes:", "count_reliable_op_command(self, size): self.reliableCommandBytes += size self.reliableCommandCount += 1 def count_unreliable_op_command(self, size): self.unreliableCommandBytes +=", "is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "self.totalCommandsInPackets = 0 self.reliableCommandBytes = 0 self.unreliableCommandBytes = 0 self.fragmentCommandBytes = 0 self.controlCommandBytes", "self.fragmentCommandCount + self.controlCommandCount def total_command_bytes(self): return self.reliableCommandBytes + self.unreliableCommandBytes + \\ self.fragmentCommandBytes +", "size): self.unreliableCommandBytes += size self.unreliableCommandCount += 1 def count_fragment_op_command(self, size): self.fragmentCommandBytes += size", "you may not use this file except in compliance with the License. You", "1 def count_reliable_op_command(self, size): self.reliableCommandBytes += size self.reliableCommandCount += 1 def count_unreliable_op_command(self, size):", "self.unreliableCommandCount += 1 def count_fragment_op_command(self, size): self.fragmentCommandBytes += size self.fragmentCommandCount += 1 def", "+= size self.fragmentCommandCount += 1 def __str__(self, *args, **kwargs): return \"TotalPacketBytes: {}\\nTotalCommandBytes: {}\\nTotalPacketCount:", "agreed to in writing, software distributed under the License is distributed on an", "TrafficStats: def __init__(self): self.packageHeaderSize = 0 self.reliableCommandCount = 0 self.unreliableCommandCount = 0 self.fragmentCommandCount", "self.unreliableCommandBytes = 0 self.fragmentCommandBytes = 0 self.controlCommandBytes = 0 def total_command_count(self): return self.reliableCommandCount", "size): self.fragmentCommandBytes += size self.fragmentCommandCount += 1 def __str__(self, *args, **kwargs): return \"TotalPacketBytes:", "0 self.reliableCommandBytes = 0 self.unreliableCommandBytes = 0 self.fragmentCommandBytes = 0 self.controlCommandBytes = 0", "= 0 def total_command_count(self): return self.reliableCommandCount + self.unreliableCommandCount + \\ self.fragmentCommandCount + self.controlCommandCount", "distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by", "= 0 self.fragmentCommandCount = 0 self.controlCommandCount = 0 self.totalPacketCount = 0 self.totalCommandsInPackets =", "= 0 self.controlCommandBytes = 0 def total_command_count(self): return self.reliableCommandCount + self.unreliableCommandCount + \\", "self.totalPacketCount = 0 self.totalCommandsInPackets = 0 self.reliableCommandBytes = 0 self.unreliableCommandBytes = 0 self.fragmentCommandBytes", "self.reliableCommandCount += 1 def count_unreliable_op_command(self, size): self.unreliableCommandBytes += size self.unreliableCommandCount += 1 def", "may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable", "+ \\ self.fragmentCommandBytes + self.controlCommandBytes def total_packet_bytes(self): return self.total_command_bytes() + self.totalPacketCount * self.packageHeaderSize", "software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT", "by applicable law or agreed to in writing, software distributed under the License", "applicable law or agreed to in writing, software distributed under the License is", "Copyright 2015 <NAME> Licensed under the Apache License, Version 2.0 (the \"License\"); you", "implied. See the License for the specific language governing permissions and limitations under", "self.unreliableCommandCount = 0 self.fragmentCommandCount = 0 self.controlCommandCount = 0 self.totalPacketCount = 0 self.totalCommandsInPackets", "= 0 self.unreliableCommandBytes = 0 self.fragmentCommandBytes = 0 self.controlCommandBytes = 0 def total_command_count(self):", "+= size self.reliableCommandCount += 1 def count_unreliable_op_command(self, size): self.unreliableCommandBytes += size self.unreliableCommandCount +=", "http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed", "limitations under the License. \"\"\" class TrafficStats: def __init__(self): self.packageHeaderSize = 0 self.reliableCommandCount", "+ \\ self.fragmentCommandCount + self.controlCommandCount def total_command_bytes(self): return self.reliableCommandBytes + self.unreliableCommandBytes + \\", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License", "return self.reliableCommandCount + self.unreliableCommandCount + \\ self.fragmentCommandCount + self.controlCommandCount def total_command_bytes(self): return self.reliableCommandBytes", "0 self.totalPacketCount = 0 self.totalCommandsInPackets = 0 self.reliableCommandBytes = 0 self.unreliableCommandBytes = 0", "License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "def total_command_count(self): return self.reliableCommandCount + self.unreliableCommandCount + \\ self.fragmentCommandCount + self.controlCommandCount def total_command_bytes(self):", "+ self.unreliableCommandBytes + \\ self.fragmentCommandBytes + self.controlCommandBytes def total_packet_bytes(self): return self.total_command_bytes() + self.totalPacketCount", "<NAME> Licensed under the Apache License, Version 2.0 (the \"License\"); you may not", "= 0 self.unreliableCommandCount = 0 self.fragmentCommandCount = 0 self.controlCommandCount = 0 self.totalPacketCount =", "+= 1 def count_fragment_op_command(self, size): self.fragmentCommandBytes += size self.fragmentCommandCount += 1 def __str__(self,", "size self.fragmentCommandCount += 1 def __str__(self, *args, **kwargs): return \"TotalPacketBytes: {}\\nTotalCommandBytes: {}\\nTotalPacketCount: {}\\nTotalCommandsInPackets:", "self.fragmentCommandBytes = 0 self.controlCommandBytes = 0 def total_command_count(self): return self.reliableCommandCount + self.unreliableCommandCount +", "self.fragmentCommandBytes + self.controlCommandBytes def total_packet_bytes(self): return self.total_command_bytes() + self.totalPacketCount * self.packageHeaderSize def count_control_command(self,", "size self.unreliableCommandCount += 1 def count_fragment_op_command(self, size): self.fragmentCommandBytes += size self.fragmentCommandCount += 1", "law or agreed to in writing, software distributed under the License is distributed", "0 self.unreliableCommandBytes = 0 self.fragmentCommandBytes = 0 self.controlCommandBytes = 0 def total_command_count(self): return", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\\ self.fragmentCommandBytes + self.controlCommandBytes def total_packet_bytes(self): return self.total_command_bytes() + self.totalPacketCount * self.packageHeaderSize def", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See", "License. \"\"\" class TrafficStats: def __init__(self): self.packageHeaderSize = 0 self.reliableCommandCount = 0 self.unreliableCommandCount", "<reponame>logarithm/photon-python<gh_stars>1-10 \"\"\" Copyright 2015 <NAME> Licensed under the Apache License, Version 2.0 (the", "Version 2.0 (the \"License\"); you may not use this file except in compliance", "0 self.totalCommandsInPackets = 0 self.reliableCommandBytes = 0 self.unreliableCommandBytes = 0 self.fragmentCommandBytes = 0", "in compliance with the License. You may obtain a copy of the License", "+ self.unreliableCommandCount + \\ self.fragmentCommandCount + self.controlCommandCount def total_command_bytes(self): return self.reliableCommandBytes + self.unreliableCommandBytes", "the Apache License, Version 2.0 (the \"License\"); you may not use this file", "use this file except in compliance with the License. You may obtain a", "KIND, either express or implied. See the License for the specific language governing", "of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to", "Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use", "the specific language governing permissions and limitations under the License. \"\"\" class TrafficStats:", "def __init__(self): self.packageHeaderSize = 0 self.reliableCommandCount = 0 self.unreliableCommandCount = 0 self.fragmentCommandCount =", "1 def count_unreliable_op_command(self, size): self.unreliableCommandBytes += size self.unreliableCommandCount += 1 def count_fragment_op_command(self, size):", "for the specific language governing permissions and limitations under the License. \"\"\" class", "\"\"\" Copyright 2015 <NAME> Licensed under the Apache License, Version 2.0 (the \"License\");", "in writing, software distributed under the License is distributed on an \"AS IS\"", "__init__(self): self.packageHeaderSize = 0 self.reliableCommandCount = 0 self.unreliableCommandCount = 0 self.fragmentCommandCount = 0", "+= 1 def count_unreliable_op_command(self, size): self.unreliableCommandBytes += size self.unreliableCommandCount += 1 def count_fragment_op_command(self,", "under the Apache License, Version 2.0 (the \"License\"); you may not use this", "class TrafficStats: def __init__(self): self.packageHeaderSize = 0 self.reliableCommandCount = 0 self.unreliableCommandCount = 0", "return self.reliableCommandBytes + self.unreliableCommandBytes + \\ self.fragmentCommandBytes + self.controlCommandBytes def total_packet_bytes(self): return self.total_command_bytes()", "* self.packageHeaderSize def count_control_command(self, size): self.controlCommandBytes += size self.controlCommandCount += 1 def count_reliable_op_command(self,", "writing, software distributed under the License is distributed on an \"AS IS\" BASIS,", "+= 1 def count_reliable_op_command(self, size): self.reliableCommandBytes += size self.reliableCommandCount += 1 def count_unreliable_op_command(self,", "a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or", "either express or implied. See the License for the specific language governing permissions", "def count_unreliable_op_command(self, size): self.unreliableCommandBytes += size self.unreliableCommandCount += 1 def count_fragment_op_command(self, size): self.fragmentCommandBytes", "or agreed to in writing, software distributed under the License is distributed on", "\"\"\" class TrafficStats: def __init__(self): self.packageHeaderSize = 0 self.reliableCommandCount = 0 self.unreliableCommandCount =", "total_command_count(self): return self.reliableCommandCount + self.unreliableCommandCount + \\ self.fragmentCommandCount + self.controlCommandCount def total_command_bytes(self): return", "size): self.controlCommandBytes += size self.controlCommandCount += 1 def count_reliable_op_command(self, size): self.reliableCommandBytes += size", "def count_control_command(self, size): self.controlCommandBytes += size self.controlCommandCount += 1 def count_reliable_op_command(self, size): self.reliableCommandBytes", "Apache License, Version 2.0 (the \"License\"); you may not use this file except", "or implied. See the License for the specific language governing permissions and limitations", "self.fragmentCommandCount += 1 def __str__(self, *args, **kwargs): return \"TotalPacketBytes: {}\\nTotalCommandBytes: {}\\nTotalPacketCount: {}\\nTotalCommandsInPackets: {}\"", "with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0", "self.total_command_bytes() + self.totalPacketCount * self.packageHeaderSize def count_control_command(self, size): self.controlCommandBytes += size self.controlCommandCount +=", "required by applicable law or agreed to in writing, software distributed under the", "+ self.controlCommandCount def total_command_bytes(self): return self.reliableCommandBytes + self.unreliableCommandBytes + \\ self.fragmentCommandBytes + self.controlCommandBytes", "at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software", "size): self.reliableCommandBytes += size self.reliableCommandCount += 1 def count_unreliable_op_command(self, size): self.unreliableCommandBytes += size", "0 self.controlCommandBytes = 0 def total_command_count(self): return self.reliableCommandCount + self.unreliableCommandCount + \\ self.fragmentCommandCount", "self.unreliableCommandBytes + \\ self.fragmentCommandBytes + self.controlCommandBytes def total_packet_bytes(self): return self.total_command_bytes() + self.totalPacketCount *", "= 0 self.reliableCommandCount = 0 self.unreliableCommandCount = 0 self.fragmentCommandCount = 0 self.controlCommandCount =", "def total_packet_bytes(self): return self.total_command_bytes() + self.totalPacketCount * self.packageHeaderSize def count_control_command(self, size): self.controlCommandBytes +=" ]
[ "0 def incr(self): self.count += 1 def get(self): return self.count a = Counter()", "today.' print(s.split()) print(s.isalpha()) print(s.isdigit()) print(s.upper()) print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never')) a = input() b =", "def incr(self): self.count += 1 def get(self): return self.count a = Counter() a.reset()", "for i in range(b - 1, -1, -1): c = c + a[i]", "class Counter: def reset(self): self.count = 0 def incr(self): self.count += 1 def", "you can do today.' print(s.split()) print(s.isalpha()) print(s.isdigit()) print(s.upper()) print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never')) a =", "-1, -1): c = c + a[i] if c == a : print(\"회문", "for j in num: print(j,end=\"\") for k in num: print(k,end=\"\") s = 'Never", "off till tomorrow what you can do today.' print(s.split()) print(s.isalpha()) print(s.isdigit()) print(s.upper()) print(s.lower())", "a : print(\"회문 입니다.\") else: print(\"회문이 아닙니다.\") class Counter: def reset(self): self.count =", "reset(self): self.count = 0 def incr(self): self.count += 1 def get(self): return self.count", "-1): c = c + a[i] if c == a : print(\"회문 입니다.\")", "print(\"회문이 아닙니다.\") class Counter: def reset(self): self.count = 0 def incr(self): self.count +=", "num: print(j,end=\"\") for k in num: print(k,end=\"\") s = 'Never put off till", "can do today.' print(s.split()) print(s.isalpha()) print(s.isdigit()) print(s.upper()) print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never')) a = input()", "do today.' print(s.split()) print(s.isalpha()) print(s.isdigit()) print(s.upper()) print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never')) a = input() b", "== a : print(\"회문 입니다.\") else: print(\"회문이 아닙니다.\") class Counter: def reset(self): self.count", "입니다.\") else: print(\"회문이 아닙니다.\") class Counter: def reset(self): self.count = 0 def incr(self):", "get(self): return self.count a = Counter() a.reset() for i in range(5): a.incr() print(a.get())", "x in num: print(x,end=\"\",) for j in num: print(j,end=\"\") for k in num:", "i in range(b - 1, -1, -1): c = c + a[i] if", "for k in num: print(k,end=\"\") s = 'Never put off till tomorrow what", "print(s.upper()) print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never')) a = input() b = len(a) c = ''", "<gh_stars>0 num ={2,1,3} for x in num: print(x,end=\"\",) for j in num: print(j,end=\"\")", "a = input() b = len(a) c = '' for i in range(b", "len(a) c = '' for i in range(b - 1, -1, -1): c", "in num: print(k,end=\"\") s = 'Never put off till tomorrow what you can", "print(k,end=\"\") s = 'Never put off till tomorrow what you can do today.'", "a[i] if c == a : print(\"회문 입니다.\") else: print(\"회문이 아닙니다.\") class Counter:", "c = c + a[i] if c == a : print(\"회문 입니다.\") else:", "+= 1 def get(self): return self.count a = Counter() a.reset() for i in", "self.count += 1 def get(self): return self.count a = Counter() a.reset() for i", "in num: print(x,end=\"\",) for j in num: print(j,end=\"\") for k in num: print(k,end=\"\")", "= len(a) c = '' for i in range(b - 1, -1, -1):", "print(\"회문 입니다.\") else: print(\"회문이 아닙니다.\") class Counter: def reset(self): self.count = 0 def", "print(s.replace('put','off')) print(s.startswith('Never')) a = input() b = len(a) c = '' for i", "b = len(a) c = '' for i in range(b - 1, -1,", "if c == a : print(\"회문 입니다.\") else: print(\"회문이 아닙니다.\") class Counter: def", "s = 'Never put off till tomorrow what you can do today.' print(s.split())", "till tomorrow what you can do today.' print(s.split()) print(s.isalpha()) print(s.isdigit()) print(s.upper()) print(s.lower()) print(s.replace('put','off'))", "1 def get(self): return self.count a = Counter() a.reset() for i in range(5):", "c = '' for i in range(b - 1, -1, -1): c =", "print(s.startswith('Never')) a = input() b = len(a) c = '' for i in", "={2,1,3} for x in num: print(x,end=\"\",) for j in num: print(j,end=\"\") for k", "for x in num: print(x,end=\"\",) for j in num: print(j,end=\"\") for k in", "else: print(\"회문이 아닙니다.\") class Counter: def reset(self): self.count = 0 def incr(self): self.count", "print(x,end=\"\",) for j in num: print(j,end=\"\") for k in num: print(k,end=\"\") s =", "1, -1, -1): c = c + a[i] if c == a :", ": print(\"회문 입니다.\") else: print(\"회문이 아닙니다.\") class Counter: def reset(self): self.count = 0", "Counter: def reset(self): self.count = 0 def incr(self): self.count += 1 def get(self):", "= input() b = len(a) c = '' for i in range(b -", "tomorrow what you can do today.' print(s.split()) print(s.isalpha()) print(s.isdigit()) print(s.upper()) print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never'))", "print(s.isalpha()) print(s.isdigit()) print(s.upper()) print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never')) a = input() b = len(a) c", "num: print(x,end=\"\",) for j in num: print(j,end=\"\") for k in num: print(k,end=\"\") s", "= c + a[i] if c == a : print(\"회문 입니다.\") else: print(\"회문이", "print(s.split()) print(s.isalpha()) print(s.isdigit()) print(s.upper()) print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never')) a = input() b = len(a)", "c == a : print(\"회문 입니다.\") else: print(\"회문이 아닙니다.\") class Counter: def reset(self):", "'' for i in range(b - 1, -1, -1): c = c +", "c + a[i] if c == a : print(\"회문 입니다.\") else: print(\"회문이 아닙니다.\")", "what you can do today.' print(s.split()) print(s.isalpha()) print(s.isdigit()) print(s.upper()) print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never')) a", "'Never put off till tomorrow what you can do today.' print(s.split()) print(s.isalpha()) print(s.isdigit())", "print(s.isdigit()) print(s.upper()) print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never')) a = input() b = len(a) c =", "put off till tomorrow what you can do today.' print(s.split()) print(s.isalpha()) print(s.isdigit()) print(s.upper())", "= 'Never put off till tomorrow what you can do today.' print(s.split()) print(s.isalpha())", "range(b - 1, -1, -1): c = c + a[i] if c ==", "= '' for i in range(b - 1, -1, -1): c = c", "아닙니다.\") class Counter: def reset(self): self.count = 0 def incr(self): self.count += 1", "print(j,end=\"\") for k in num: print(k,end=\"\") s = 'Never put off till tomorrow", "num ={2,1,3} for x in num: print(x,end=\"\",) for j in num: print(j,end=\"\") for", "- 1, -1, -1): c = c + a[i] if c == a", "+ a[i] if c == a : print(\"회문 입니다.\") else: print(\"회문이 아닙니다.\") class", "input() b = len(a) c = '' for i in range(b - 1,", "self.count = 0 def incr(self): self.count += 1 def get(self): return self.count a", "= 0 def incr(self): self.count += 1 def get(self): return self.count a =", "j in num: print(j,end=\"\") for k in num: print(k,end=\"\") s = 'Never put", "incr(self): self.count += 1 def get(self): return self.count a = Counter() a.reset() for", "def get(self): return self.count a = Counter() a.reset() for i in range(5): a.incr()", "in range(b - 1, -1, -1): c = c + a[i] if c", "def reset(self): self.count = 0 def incr(self): self.count += 1 def get(self): return", "print(s.lower()) print(s.replace('put','off')) print(s.startswith('Never')) a = input() b = len(a) c = '' for", "k in num: print(k,end=\"\") s = 'Never put off till tomorrow what you", "in num: print(j,end=\"\") for k in num: print(k,end=\"\") s = 'Never put off", "num: print(k,end=\"\") s = 'Never put off till tomorrow what you can do" ]
[]
[ "-> Any: \"\"\"Evaluate the operator No data passed to the operator function. It", "isinstance(context, Enum) else context ) extra_contexts2 = extra_contexts or {} func.extra_contexts = {", "op_func if self.op[0] == 'r': # if we get radd, swap left and", "left_op_func(arg_a, arg_b, *args, **kwargs): return op_func(arg_b, arg_a, *args, **kwargs) return left_op_func raise ValueError(", "No data argument for the operator function. Attributes: REGISTERED: The registered Operator class.", "= ( context.value if isinstance(context, Enum) else context ) extra_contexts2 = extra_contexts or", "wraps from typing import Any, Callable, Mapping, Tuple, ClassVar, Type from .context import", "operator kwargs: The keyword arguments of the operator datarg: Should be False. No", "op_func: @wraps(op_func) def left_op_func(arg_a, arg_b, *args, **kwargs): return op_func(arg_b, arg_a, *args, **kwargs) return", "None while initialization. It depends on the verb or the function that uses", "wrapper def _pipda_eval( self, data: Any, context: ContextBase = None ) -> Any:", "the Operator class\"\"\" import operator from enum import Enum from functools import wraps", "operator module by name\"\"\" def _opfunc(opname: str) -> Callable: self_op_name = f\"_op_{opname}\" if", "kwargs: Mapping[str, Any], datarg: bool = False, ) -> None: self.op = op", "getattr(operator, opname, None) op_func = _opfunc(self.op) if op_func: return op_func if self.op[0] ==", "Enum from functools import wraps from typing import Any, Callable, Mapping, Tuple, ClassVar,", "arguments of the operator datarg: Should be False. No data argument for the", "datarg: bool = False, ) -> None: self.op = op self.data = None", "'r': # if we get radd, swap left and right operands op_func =", "class, defining how the operators in verb/function arguments should be evaluated Args: op:", "operator No data passed to the operator function. It should be used to", "the operator kwargs: The keyword arguments of the operator datarg: Should be False.", "in case they need to be used # inside the function. self.data =", "_opfunc(opname: str) -> Callable: self_op_name = f\"_op_{opname}\" if hasattr(self.__class__, self_op_name): return getattr(self, self_op_name)", "Operator(Function): \"\"\"Operator class, defining how the operators in verb/function arguments should be evaluated", "<gh_stars>10-100 \"\"\"Provide the Operator class\"\"\" import operator from enum import Enum from functools", "_pipda_eval( self, data: Any, context: ContextBase = None ) -> Any: \"\"\"Evaluate the", "should be used to evaluate the arguments. \"\"\" # set the context and", "the operator module by name\"\"\" def _opfunc(opname: str) -> Callable: self_op_name = f\"_op_{opname}\"", "else ctx for key, ctx in extra_contexts2.items() } return func return wrapper def", ".function import Function class Operator(Function): \"\"\"Operator class, defining how the operators in verb/function", "the operator No data passed to the operator function. It should be used", "function from the operator module by name\"\"\" def _opfunc(opname: str) -> Callable: self_op_name", "Args: op: The operator context: Should be None while initialization. It depends on", "from .function import Function class Operator(Function): \"\"\"Operator class, defining how the operators in", "context and data in case they need to be used # inside the", "if isinstance(ctx, Enum) else ctx for key, ctx in extra_contexts2.items() } return func", ") -> Any: \"\"\"Evaluate the operator No data passed to the operator function.", "function. Attributes: REGISTERED: The registered Operator class. It's this class by default Use", "case they need to be used # inside the function. self.data = data", ") -> Callable[[Callable], Callable]: \"\"\"Set custom context for a operator method\"\"\" def wrapper(func):", "class Operator(Function): \"\"\"Operator class, defining how the operators in verb/function arguments should be", "ContextAnnoType, ContextBase from .function import Function class Operator(Function): \"\"\"Operator class, defining how the", "depends on the verb or the function that uses it as an argument", "keyword arguments of the operator datarg: Should be False. No data argument for", "context.value if isinstance(context, Enum) else context ) extra_contexts2 = extra_contexts or {} func.extra_contexts", "verb or the function that uses it as an argument args: The arguments", "kwargs, datarg) @staticmethod def set_context( context: ContextAnnoType, extra_contexts: Mapping[str, ContextAnnoType] = None, )", "be False. No data argument for the operator function. Attributes: REGISTERED: The registered", "\"\"\" REGISTERED: ClassVar[Type[\"Operator\"]] = None def __init__( self, op: str, args: Tuple, kwargs:", "def __init__( self, op: str, args: Tuple, kwargs: Mapping[str, Any], datarg: bool =", "Operator class\"\"\" import operator from enum import Enum from functools import wraps from", "op_func = _opfunc(self.op[1:]) if op_func: @wraps(op_func) def left_op_func(arg_a, arg_b, *args, **kwargs): return op_func(arg_b,", "the function that uses it as an argument args: The arguments of the", "The registered Operator class. It's this class by default Use `register_operator` as a", "if isinstance(context, Enum) else context ) extra_contexts2 = extra_contexts or {} func.extra_contexts =", "the operator function from the operator module by name\"\"\" def _opfunc(opname: str) ->", "The operator context: Should be None while initialization. It depends on the verb", "Mapping, Tuple, ClassVar, Type from .context import ContextAnnoType, ContextBase from .function import Function", "Tuple, kwargs: Mapping[str, Any], datarg: bool = False, ) -> None: self.op =", "return getattr(operator, opname, None) op_func = _opfunc(self.op) if op_func: return op_func if self.op[0]", "Any: \"\"\"Evaluate the operator No data passed to the operator function. It should", "Any], datarg: bool = False, ) -> None: self.op = op self.data =", "REGISTERED: The registered Operator class. It's this class by default Use `register_operator` as", "= _opfunc(self.op) if op_func: return op_func if self.op[0] == 'r': # if we", "args, kwargs, datarg) @staticmethod def set_context( context: ContextAnnoType, extra_contexts: Mapping[str, ContextAnnoType] = None,", "ContextBase = None ) -> Any: \"\"\"Evaluate the operator No data passed to", "op_func: return op_func if self.op[0] == 'r': # if we get radd, swap", "a operator method\"\"\" def wrapper(func): func.context = ( context.value if isinstance(context, Enum) else", "function. It should be used to evaluate the arguments. \"\"\" # set the", "opname, None) op_func = _opfunc(self.op) if op_func: return op_func if self.op[0] == 'r':", ") -> None: self.op = op self.data = None op_func = self._get_op_func() super().__init__(op_func,", "Enum) else ctx for key, ctx in extra_contexts2.items() } return func return wrapper", "Attributes: REGISTERED: The registered Operator class. It's this class by default Use `register_operator`", "op_func = self._get_op_func() super().__init__(op_func, args, kwargs, datarg) @staticmethod def set_context( context: ContextAnnoType, extra_contexts:", "passed to the operator function. It should be used to evaluate the arguments.", "import wraps from typing import Any, Callable, Mapping, Tuple, ClassVar, Type from .context", "operator class \"\"\" REGISTERED: ClassVar[Type[\"Operator\"]] = None def __init__( self, op: str, args:", "context) def _get_op_func(self) -> Callable: \"\"\"Get the operator function from the operator module", "ClassVar[Type[\"Operator\"]] = None def __init__( self, op: str, args: Tuple, kwargs: Mapping[str, Any],", "return op_func if self.op[0] == 'r': # if we get radd, swap left", "operator datarg: Should be False. No data argument for the operator function. Attributes:", "we get radd, swap left and right operands op_func = _opfunc(self.op[1:]) if op_func:", "by default Use `register_operator` as a decorator to register a operator class \"\"\"", "`register_operator` as a decorator to register a operator class \"\"\" REGISTERED: ClassVar[Type[\"Operator\"]] =", "Enum) else context ) extra_contexts2 = extra_contexts or {} func.extra_contexts = { key:", "None def __init__( self, op: str, args: Tuple, kwargs: Mapping[str, Any], datarg: bool", "and right operands op_func = _opfunc(self.op[1:]) if op_func: @wraps(op_func) def left_op_func(arg_a, arg_b, *args,", "\"\"\"Set custom context for a operator method\"\"\" def wrapper(func): func.context = ( context.value", "class \"\"\" REGISTERED: ClassVar[Type[\"Operator\"]] = None def __init__( self, op: str, args: Tuple,", "wrapper(func): func.context = ( context.value if isinstance(context, Enum) else context ) extra_contexts2 =", "**kwargs): return op_func(arg_b, arg_a, *args, **kwargs) return left_op_func raise ValueError( f\"No operator function", "\"\"\" # set the context and data in case they need to be", "It depends on the verb or the function that uses it as an", "= { key: ctx.value if isinstance(ctx, Enum) else ctx for key, ctx in", "= False, ) -> None: self.op = op self.data = None op_func =", "func.context = ( context.value if isinstance(context, Enum) else context ) extra_contexts2 = extra_contexts", "key: ctx.value if isinstance(ctx, Enum) else ctx for key, ctx in extra_contexts2.items() }", "self, op: str, args: Tuple, kwargs: Mapping[str, Any], datarg: bool = False, )", "ctx for key, ctx in extra_contexts2.items() } return func return wrapper def _pipda_eval(", "argument args: The arguments of the operator kwargs: The keyword arguments of the", "f\"_op_{opname}\" if hasattr(self.__class__, self_op_name): return getattr(self, self_op_name) return getattr(operator, opname, None) op_func =", "while initialization. It depends on the verb or the function that uses it", "return getattr(self, self_op_name) return getattr(operator, opname, None) op_func = _opfunc(self.op) if op_func: return", "context ) extra_contexts2 = extra_contexts or {} func.extra_contexts = { key: ctx.value if", "the operators in verb/function arguments should be evaluated Args: op: The operator context:", "None, ) -> Callable[[Callable], Callable]: \"\"\"Set custom context for a operator method\"\"\" def", "the context and data in case they need to be used # inside", "evaluate the arguments. \"\"\" # set the context and data in case they", "It should be used to evaluate the arguments. \"\"\" # set the context", "left and right operands op_func = _opfunc(self.op[1:]) if op_func: @wraps(op_func) def left_op_func(arg_a, arg_b,", "Function class Operator(Function): \"\"\"Operator class, defining how the operators in verb/function arguments should", "self_op_name): return getattr(self, self_op_name) return getattr(operator, opname, None) op_func = _opfunc(self.op) if op_func:", "arguments of the operator kwargs: The keyword arguments of the operator datarg: Should", "the arguments. \"\"\" # set the context and data in case they need", "= None op_func = self._get_op_func() super().__init__(op_func, args, kwargs, datarg) @staticmethod def set_context( context:", "def wrapper(func): func.context = ( context.value if isinstance(context, Enum) else context ) extra_contexts2", "def _get_op_func(self) -> Callable: \"\"\"Get the operator function from the operator module by", "operators in verb/function arguments should be evaluated Args: op: The operator context: Should", "= _opfunc(self.op[1:]) if op_func: @wraps(op_func) def left_op_func(arg_a, arg_b, *args, **kwargs): return op_func(arg_b, arg_a,", "the operator function. Attributes: REGISTERED: The registered Operator class. It's this class by", "Tuple, ClassVar, Type from .context import ContextAnnoType, ContextBase from .function import Function class", "arg_a, *args, **kwargs) return left_op_func raise ValueError( f\"No operator function defined for {self.op!r}\"", "on the verb or the function that uses it as an argument args:", "# if we get radd, swap left and right operands op_func = _opfunc(self.op[1:])", "method\"\"\" def wrapper(func): func.context = ( context.value if isinstance(context, Enum) else context )", "import Any, Callable, Mapping, Tuple, ClassVar, Type from .context import ContextAnnoType, ContextBase from", "from enum import Enum from functools import wraps from typing import Any, Callable,", "data return super()._pipda_eval(data, context) def _get_op_func(self) -> Callable: \"\"\"Get the operator function from", "this class by default Use `register_operator` as a decorator to register a operator", "operator function. It should be used to evaluate the arguments. \"\"\" # set", "( context.value if isinstance(context, Enum) else context ) extra_contexts2 = extra_contexts or {}", "op self.data = None op_func = self._get_op_func() super().__init__(op_func, args, kwargs, datarg) @staticmethod def", "get radd, swap left and right operands op_func = _opfunc(self.op[1:]) if op_func: @wraps(op_func)", "arguments. \"\"\" # set the context and data in case they need to", "\"\"\"Evaluate the operator No data passed to the operator function. It should be", "data in case they need to be used # inside the function. self.data", "default Use `register_operator` as a decorator to register a operator class \"\"\" REGISTERED:", "extra_contexts: Mapping[str, ContextAnnoType] = None, ) -> Callable[[Callable], Callable]: \"\"\"Set custom context for", "function. self.data = data return super()._pipda_eval(data, context) def _get_op_func(self) -> Callable: \"\"\"Get the", "datarg) @staticmethod def set_context( context: ContextAnnoType, extra_contexts: Mapping[str, ContextAnnoType] = None, ) ->", "None: self.op = op self.data = None op_func = self._get_op_func() super().__init__(op_func, args, kwargs,", "-> Callable[[Callable], Callable]: \"\"\"Set custom context for a operator method\"\"\" def wrapper(func): func.context", "operator from enum import Enum from functools import wraps from typing import Any,", "name\"\"\" def _opfunc(opname: str) -> Callable: self_op_name = f\"_op_{opname}\" if hasattr(self.__class__, self_op_name): return", "how the operators in verb/function arguments should be evaluated Args: op: The operator", "arguments should be evaluated Args: op: The operator context: Should be None while", "False. No data argument for the operator function. Attributes: REGISTERED: The registered Operator", "Operator class. It's this class by default Use `register_operator` as a decorator to", "import Function class Operator(Function): \"\"\"Operator class, defining how the operators in verb/function arguments", "operator method\"\"\" def wrapper(func): func.context = ( context.value if isinstance(context, Enum) else context", "Callable: \"\"\"Get the operator function from the operator module by name\"\"\" def _opfunc(opname:", "@staticmethod def set_context( context: ContextAnnoType, extra_contexts: Mapping[str, ContextAnnoType] = None, ) -> Callable[[Callable],", "the function. self.data = data return super()._pipda_eval(data, context) def _get_op_func(self) -> Callable: \"\"\"Get", "str) -> Callable: self_op_name = f\"_op_{opname}\" if hasattr(self.__class__, self_op_name): return getattr(self, self_op_name) return", "from .context import ContextAnnoType, ContextBase from .function import Function class Operator(Function): \"\"\"Operator class,", "context: ContextAnnoType, extra_contexts: Mapping[str, ContextAnnoType] = None, ) -> Callable[[Callable], Callable]: \"\"\"Set custom", "by name\"\"\" def _opfunc(opname: str) -> Callable: self_op_name = f\"_op_{opname}\" if hasattr(self.__class__, self_op_name):", "as a decorator to register a operator class \"\"\" REGISTERED: ClassVar[Type[\"Operator\"]] = None", "context for a operator method\"\"\" def wrapper(func): func.context = ( context.value if isinstance(context,", "args: Tuple, kwargs: Mapping[str, Any], datarg: bool = False, ) -> None: self.op", "datarg: Should be False. No data argument for the operator function. Attributes: REGISTERED:", "argument for the operator function. Attributes: REGISTERED: The registered Operator class. It's this", "typing import Any, Callable, Mapping, Tuple, ClassVar, Type from .context import ContextAnnoType, ContextBase", "they need to be used # inside the function. self.data = data return", "def set_context( context: ContextAnnoType, extra_contexts: Mapping[str, ContextAnnoType] = None, ) -> Callable[[Callable], Callable]:", "right operands op_func = _opfunc(self.op[1:]) if op_func: @wraps(op_func) def left_op_func(arg_a, arg_b, *args, **kwargs):", "decorator to register a operator class \"\"\" REGISTERED: ClassVar[Type[\"Operator\"]] = None def __init__(", "be evaluated Args: op: The operator context: Should be None while initialization. It", "ContextAnnoType, extra_contexts: Mapping[str, ContextAnnoType] = None, ) -> Callable[[Callable], Callable]: \"\"\"Set custom context", "self.data = data return super()._pipda_eval(data, context) def _get_op_func(self) -> Callable: \"\"\"Get the operator", "data argument for the operator function. Attributes: REGISTERED: The registered Operator class. It's", "args: The arguments of the operator kwargs: The keyword arguments of the operator", "return op_func(arg_b, arg_a, *args, **kwargs) return left_op_func raise ValueError( f\"No operator function defined", "str, args: Tuple, kwargs: Mapping[str, Any], datarg: bool = False, ) -> None:", "= None, ) -> Callable[[Callable], Callable]: \"\"\"Set custom context for a operator method\"\"\"", "evaluated Args: op: The operator context: Should be None while initialization. It depends", "enum import Enum from functools import wraps from typing import Any, Callable, Mapping,", "if self.op[0] == 'r': # if we get radd, swap left and right", "extra_contexts2.items() } return func return wrapper def _pipda_eval( self, data: Any, context: ContextBase", "class by default Use `register_operator` as a decorator to register a operator class", "Mapping[str, Any], datarg: bool = False, ) -> None: self.op = op self.data", "be None while initialization. It depends on the verb or the function that", "self._get_op_func() super().__init__(op_func, args, kwargs, datarg) @staticmethod def set_context( context: ContextAnnoType, extra_contexts: Mapping[str, ContextAnnoType]", "ctx in extra_contexts2.items() } return func return wrapper def _pipda_eval( self, data: Any,", "ContextBase from .function import Function class Operator(Function): \"\"\"Operator class, defining how the operators", ") extra_contexts2 = extra_contexts or {} func.extra_contexts = { key: ctx.value if isinstance(ctx,", "the operator datarg: Should be False. No data argument for the operator function.", "used # inside the function. self.data = data return super()._pipda_eval(data, context) def _get_op_func(self)", "need to be used # inside the function. self.data = data return super()._pipda_eval(data,", "hasattr(self.__class__, self_op_name): return getattr(self, self_op_name) return getattr(operator, opname, None) op_func = _opfunc(self.op) if", "\"\"\"Provide the Operator class\"\"\" import operator from enum import Enum from functools import", "from functools import wraps from typing import Any, Callable, Mapping, Tuple, ClassVar, Type", "self.data = None op_func = self._get_op_func() super().__init__(op_func, args, kwargs, datarg) @staticmethod def set_context(", "used to evaluate the arguments. \"\"\" # set the context and data in", "ClassVar, Type from .context import ContextAnnoType, ContextBase from .function import Function class Operator(Function):", "The arguments of the operator kwargs: The keyword arguments of the operator datarg:", "{ key: ctx.value if isinstance(ctx, Enum) else ctx for key, ctx in extra_contexts2.items()", "super()._pipda_eval(data, context) def _get_op_func(self) -> Callable: \"\"\"Get the operator function from the operator", "data: Any, context: ContextBase = None ) -> Any: \"\"\"Evaluate the operator No", "key, ctx in extra_contexts2.items() } return func return wrapper def _pipda_eval( self, data:", "registered Operator class. It's this class by default Use `register_operator` as a decorator", ".context import ContextAnnoType, ContextBase from .function import Function class Operator(Function): \"\"\"Operator class, defining", "# set the context and data in case they need to be used", "_opfunc(self.op) if op_func: return op_func if self.op[0] == 'r': # if we get", "that uses it as an argument args: The arguments of the operator kwargs:", "None) op_func = _opfunc(self.op) if op_func: return op_func if self.op[0] == 'r': #", "= data return super()._pipda_eval(data, context) def _get_op_func(self) -> Callable: \"\"\"Get the operator function", "Use `register_operator` as a decorator to register a operator class \"\"\" REGISTERED: ClassVar[Type[\"Operator\"]]", "-> None: self.op = op self.data = None op_func = self._get_op_func() super().__init__(op_func, args,", "operator function from the operator module by name\"\"\" def _opfunc(opname: str) -> Callable:", "import ContextAnnoType, ContextBase from .function import Function class Operator(Function): \"\"\"Operator class, defining how", "bool = False, ) -> None: self.op = op self.data = None op_func", "it as an argument args: The arguments of the operator kwargs: The keyword", "\"\"\"Get the operator function from the operator module by name\"\"\" def _opfunc(opname: str)", "Callable: self_op_name = f\"_op_{opname}\" if hasattr(self.__class__, self_op_name): return getattr(self, self_op_name) return getattr(operator, opname,", "No data passed to the operator function. It should be used to evaluate", "to register a operator class \"\"\" REGISTERED: ClassVar[Type[\"Operator\"]] = None def __init__( self,", "in verb/function arguments should be evaluated Args: op: The operator context: Should be", "inside the function. self.data = data return super()._pipda_eval(data, context) def _get_op_func(self) -> Callable:", "@wraps(op_func) def left_op_func(arg_a, arg_b, *args, **kwargs): return op_func(arg_b, arg_a, *args, **kwargs) return left_op_func", "set the context and data in case they need to be used #", "function that uses it as an argument args: The arguments of the operator", "verb/function arguments should be evaluated Args: op: The operator context: Should be None", "_get_op_func(self) -> Callable: \"\"\"Get the operator function from the operator module by name\"\"\"", "import Enum from functools import wraps from typing import Any, Callable, Mapping, Tuple,", "= self._get_op_func() super().__init__(op_func, args, kwargs, datarg) @staticmethod def set_context( context: ContextAnnoType, extra_contexts: Mapping[str,", "register a operator class \"\"\" REGISTERED: ClassVar[Type[\"Operator\"]] = None def __init__( self, op:", "be used to evaluate the arguments. \"\"\" # set the context and data", "self.op[0] == 'r': # if we get radd, swap left and right operands", "a operator class \"\"\" REGISTERED: ClassVar[Type[\"Operator\"]] = None def __init__( self, op: str,", "self_op_name) return getattr(operator, opname, None) op_func = _opfunc(self.op) if op_func: return op_func if", "\"\"\"Operator class, defining how the operators in verb/function arguments should be evaluated Args:", "or {} func.extra_contexts = { key: ctx.value if isinstance(ctx, Enum) else ctx for", "self.op = op self.data = None op_func = self._get_op_func() super().__init__(op_func, args, kwargs, datarg)", "None ) -> Any: \"\"\"Evaluate the operator No data passed to the operator", "return super()._pipda_eval(data, context) def _get_op_func(self) -> Callable: \"\"\"Get the operator function from the", "the operator function. It should be used to evaluate the arguments. \"\"\" #", "ctx.value if isinstance(ctx, Enum) else ctx for key, ctx in extra_contexts2.items() } return", "Callable[[Callable], Callable]: \"\"\"Set custom context for a operator method\"\"\" def wrapper(func): func.context =", "super().__init__(op_func, args, kwargs, datarg) @staticmethod def set_context( context: ContextAnnoType, extra_contexts: Mapping[str, ContextAnnoType] =", "= op self.data = None op_func = self._get_op_func() super().__init__(op_func, args, kwargs, datarg) @staticmethod", "operator context: Should be None while initialization. It depends on the verb or", "REGISTERED: ClassVar[Type[\"Operator\"]] = None def __init__( self, op: str, args: Tuple, kwargs: Mapping[str,", "op_func(arg_b, arg_a, *args, **kwargs) return left_op_func raise ValueError( f\"No operator function defined for", "functools import wraps from typing import Any, Callable, Mapping, Tuple, ClassVar, Type from", "def _pipda_eval( self, data: Any, context: ContextBase = None ) -> Any: \"\"\"Evaluate", "a decorator to register a operator class \"\"\" REGISTERED: ClassVar[Type[\"Operator\"]] = None def", "= extra_contexts or {} func.extra_contexts = { key: ctx.value if isinstance(ctx, Enum) else", "and data in case they need to be used # inside the function.", "Should be None while initialization. It depends on the verb or the function", "Any, Callable, Mapping, Tuple, ClassVar, Type from .context import ContextAnnoType, ContextBase from .function", "return func return wrapper def _pipda_eval( self, data: Any, context: ContextBase = None", "Callable]: \"\"\"Set custom context for a operator method\"\"\" def wrapper(func): func.context = (", "{} func.extra_contexts = { key: ctx.value if isinstance(ctx, Enum) else ctx for key,", "-> Callable: self_op_name = f\"_op_{opname}\" if hasattr(self.__class__, self_op_name): return getattr(self, self_op_name) return getattr(operator,", "module by name\"\"\" def _opfunc(opname: str) -> Callable: self_op_name = f\"_op_{opname}\" if hasattr(self.__class__,", "self, data: Any, context: ContextBase = None ) -> Any: \"\"\"Evaluate the operator", "return wrapper def _pipda_eval( self, data: Any, context: ContextBase = None ) ->", "from typing import Any, Callable, Mapping, Tuple, ClassVar, Type from .context import ContextAnnoType,", "to be used # inside the function. self.data = data return super()._pipda_eval(data, context)", "import operator from enum import Enum from functools import wraps from typing import", "op_func = _opfunc(self.op) if op_func: return op_func if self.op[0] == 'r': # if", "-> Callable: \"\"\"Get the operator function from the operator module by name\"\"\" def", "for key, ctx in extra_contexts2.items() } return func return wrapper def _pipda_eval( self,", "self_op_name = f\"_op_{opname}\" if hasattr(self.__class__, self_op_name): return getattr(self, self_op_name) return getattr(operator, opname, None)", "swap left and right operands op_func = _opfunc(self.op[1:]) if op_func: @wraps(op_func) def left_op_func(arg_a,", "be used # inside the function. self.data = data return super()._pipda_eval(data, context) def", "The keyword arguments of the operator datarg: Should be False. No data argument", "# inside the function. self.data = data return super()._pipda_eval(data, context) def _get_op_func(self) ->", "of the operator kwargs: The keyword arguments of the operator datarg: Should be", "if we get radd, swap left and right operands op_func = _opfunc(self.op[1:]) if", "ContextAnnoType] = None, ) -> Callable[[Callable], Callable]: \"\"\"Set custom context for a operator", "for the operator function. Attributes: REGISTERED: The registered Operator class. It's this class", "It's this class by default Use `register_operator` as a decorator to register a", "radd, swap left and right operands op_func = _opfunc(self.op[1:]) if op_func: @wraps(op_func) def", "op: The operator context: Should be None while initialization. It depends on the", "Mapping[str, ContextAnnoType] = None, ) -> Callable[[Callable], Callable]: \"\"\"Set custom context for a", "func return wrapper def _pipda_eval( self, data: Any, context: ContextBase = None )", "= f\"_op_{opname}\" if hasattr(self.__class__, self_op_name): return getattr(self, self_op_name) return getattr(operator, opname, None) op_func", "False, ) -> None: self.op = op self.data = None op_func = self._get_op_func()", "data passed to the operator function. It should be used to evaluate the", "context: Should be None while initialization. It depends on the verb or the", "arg_b, *args, **kwargs): return op_func(arg_b, arg_a, *args, **kwargs) return left_op_func raise ValueError( f\"No", "context: ContextBase = None ) -> Any: \"\"\"Evaluate the operator No data passed", "from the operator module by name\"\"\" def _opfunc(opname: str) -> Callable: self_op_name =", "or the function that uses it as an argument args: The arguments of", "func.extra_contexts = { key: ctx.value if isinstance(ctx, Enum) else ctx for key, ctx", "== 'r': # if we get radd, swap left and right operands op_func", "extra_contexts2 = extra_contexts or {} func.extra_contexts = { key: ctx.value if isinstance(ctx, Enum)", "if op_func: return op_func if self.op[0] == 'r': # if we get radd,", "if hasattr(self.__class__, self_op_name): return getattr(self, self_op_name) return getattr(operator, opname, None) op_func = _opfunc(self.op)", "} return func return wrapper def _pipda_eval( self, data: Any, context: ContextBase =", "should be evaluated Args: op: The operator context: Should be None while initialization.", "extra_contexts or {} func.extra_contexts = { key: ctx.value if isinstance(ctx, Enum) else ctx", "custom context for a operator method\"\"\" def wrapper(func): func.context = ( context.value if", "Type from .context import ContextAnnoType, ContextBase from .function import Function class Operator(Function): \"\"\"Operator", "def left_op_func(arg_a, arg_b, *args, **kwargs): return op_func(arg_b, arg_a, *args, **kwargs) return left_op_func raise", "class. It's this class by default Use `register_operator` as a decorator to register", "*args, **kwargs): return op_func(arg_b, arg_a, *args, **kwargs) return left_op_func raise ValueError( f\"No operator", "*args, **kwargs) return left_op_func raise ValueError( f\"No operator function defined for {self.op!r}\" )", "kwargs: The keyword arguments of the operator datarg: Should be False. No data", "in extra_contexts2.items() } return func return wrapper def _pipda_eval( self, data: Any, context:", "__init__( self, op: str, args: Tuple, kwargs: Mapping[str, Any], datarg: bool = False,", "uses it as an argument args: The arguments of the operator kwargs: The", "_opfunc(self.op[1:]) if op_func: @wraps(op_func) def left_op_func(arg_a, arg_b, *args, **kwargs): return op_func(arg_b, arg_a, *args,", "to evaluate the arguments. \"\"\" # set the context and data in case", "the verb or the function that uses it as an argument args: The", "if op_func: @wraps(op_func) def left_op_func(arg_a, arg_b, *args, **kwargs): return op_func(arg_b, arg_a, *args, **kwargs)", "of the operator datarg: Should be False. No data argument for the operator", "an argument args: The arguments of the operator kwargs: The keyword arguments of", "as an argument args: The arguments of the operator kwargs: The keyword arguments", "operator function. Attributes: REGISTERED: The registered Operator class. It's this class by default", "Should be False. No data argument for the operator function. Attributes: REGISTERED: The", "to the operator function. It should be used to evaluate the arguments. \"\"\"", "class\"\"\" import operator from enum import Enum from functools import wraps from typing", "= None ) -> Any: \"\"\"Evaluate the operator No data passed to the", "initialization. It depends on the verb or the function that uses it as", "def _opfunc(opname: str) -> Callable: self_op_name = f\"_op_{opname}\" if hasattr(self.__class__, self_op_name): return getattr(self,", "Callable, Mapping, Tuple, ClassVar, Type from .context import ContextAnnoType, ContextBase from .function import", "operands op_func = _opfunc(self.op[1:]) if op_func: @wraps(op_func) def left_op_func(arg_a, arg_b, *args, **kwargs): return", "else context ) extra_contexts2 = extra_contexts or {} func.extra_contexts = { key: ctx.value", "= None def __init__( self, op: str, args: Tuple, kwargs: Mapping[str, Any], datarg:", "None op_func = self._get_op_func() super().__init__(op_func, args, kwargs, datarg) @staticmethod def set_context( context: ContextAnnoType,", "Any, context: ContextBase = None ) -> Any: \"\"\"Evaluate the operator No data", "getattr(self, self_op_name) return getattr(operator, opname, None) op_func = _opfunc(self.op) if op_func: return op_func", "op: str, args: Tuple, kwargs: Mapping[str, Any], datarg: bool = False, ) ->", "set_context( context: ContextAnnoType, extra_contexts: Mapping[str, ContextAnnoType] = None, ) -> Callable[[Callable], Callable]: \"\"\"Set", "defining how the operators in verb/function arguments should be evaluated Args: op: The", "for a operator method\"\"\" def wrapper(func): func.context = ( context.value if isinstance(context, Enum)", "isinstance(ctx, Enum) else ctx for key, ctx in extra_contexts2.items() } return func return" ]
[ "time\" model.eval() scores = model(words) ptags = LinearCRF(scores).argmax() assert ptags.shape == tags.shape if", "is None: load_src = {\"src\": (\"artifacts\", \"model.pth\")} main_src = \"src\" elif main_src not", "= pickle.load(f) else: samples = { wh: list(read_tagging_samples(wh, max_length.get(wh))) for wh in [\"train\",", "if None not in (mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config def default(): # directory", "in srcs: _log.info(\"Removing %s from src parsers because it's the tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"])", "@ex.config def default(): # directory to save finetuning artifacts artifacts_dir = \"\" #", "to combine PPTX charts combine = \"union\" # whether to evaluate on train", "\"\" # device to run on [cpu, cuda] device = \"cuda\" if torch.cuda.is_available()", "path.write_text(dump(vocab), encoding=\"utf8\") path = artifacts_dir / \"model.yml\" _log.info(\"Saving model metadata to %s\", path)", "not in srcs for src in src2ws): _log.warning(\"Too many srcs in src2ws, weights", "assert len(runner.state[\"_ids\"]) == len(samples_[wh]) if \"pptx_masks\" in runner.state: for i, pptx_mask in zip(runner.state[\"_ids\"],", "-> slen nntags ntags\", ntags=len(vocab[\"tags\"]) ) lms = lms.unsqueeze(0) mask = compute_ambiguous_tag_pairs_mask(lms, thresh,", "marginals\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): lms = samples[wh][i].get(\"log_marginals\", 0) pts =", "acc, step=state[\"n_iters\"]) if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda s: len(s[\"words\"])) trn_iter =", "load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src not in src2ws for src in srcs): _log.warning(\"Some srcs have", "in samples[wh]) continue for i, s in enumerate(samples_[wh]): s[\"_id\"] = i runner =", "1.0 # max number of epochs max_epoch = 10 # whether to save", "finetuning from main_src = \"\" # device to run on [cpu, cuda] device", "import pickle from einops import rearrange from gensim.models.keyedvectors import KeyedVectors from rnnr import", "(tags[:, 0] == vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags = tags[:, 1:], ptags[:, 1:] if (tags[:,", "extended word embedding layer\", src) assert model.word_emb.embedding_dim == kv.vector_size with torch.no_grad(): model.word_emb =", "src in srcs): _log.warning(\"Some srcs have no weights, will be set to zero\")", "state[\"scores\"] = scores state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def maybe_compute_loss(state): if not compute_loss: return", "scores.shape == (bsz, slen - 1, len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert pptx_mask.shape == scores.shape masked_scores", "main_src=None, load_src2ws_from=None, artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\", combine=\"union\", thresh=0.95, batch_size=16, save_samples=False, lr=1e-5, l2_coef=1.0,", "position from mask crf_z = LinearCRF(scores.contiguous(), mask[:, :-1]) # exclude last position from", "math import os import pickle from einops import rearrange from gensim.models.keyedvectors import KeyedVectors", "// 10, batch_size), rng=_rnd ) _log.info(\"Starting finetuning\") try: finetuner.run(trn_iter, max_epoch) except KeyboardInterrupt: _log.info(\"Interrupt", "== len(samples[wh]) if combine == \"geom_mean\": _log.info(\"Combining the marginals\") for i in tqdm(range(len(samples_[wh])),", "if load_samples_from: _log.info(\"Skipping non-main src because samples are processed and loaded\") srcs =", "chart on %s set\", wh) log_ntags = [] for s in tqdm(samples_[wh], unit=\"sample\",", "utils import extend_word_embedding ex = Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter = apply_backspaces_and_linefeeds # Setup mongodb", "_log.info(\"dev_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"] = acc @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state): if", "value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for s in samples), unit=\"tok\", leave=False).attach_on( runner ) if", "len(runner.state[x]) == len(samples_[wh]) assert len(runner.state[\"_ids\"]) == len(samples_[wh]) if \"pptx_masks\" in runner.state: for i,", "if combine == \"geom_mean\": _log.info( \"Computing marginals and best tags for %s set", "slen nntags ntags\", ntags=len(vocab[\"tags\"]) ) lms = lms.unsqueeze(0) mask = compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True)", "zips = [runner.state[x] for x in \"log_marginals pred_tags\".split()] for i, lms, pts in", "to %s\", path) with open(path, \"wb\") as f: pickle.dump(samples, f) samples = {wh:", "batch_size)) for x in \"pptx_masks log_marginals pred_tags\".split(): assert x not in runner.state or", "else: max_ = max(log_ntags[mid - 1], log_ntags[mid]) log_med = ( max_ + math.log(", "# whether to treat keys in load_src as lang codes src_key_as_lang = False", "path = Path(load_from) / \"model.yml\" _log.info(\"Loading %s model from metadata %s\", src, path)", "state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) tags = torch.from_numpy(batch[\"tags\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert", "- max_) ) - math.log(2) ) _log.info(\"Median number of tag sequences in chart:", "_log, _run, _rnd, max_length=None, load_src=None, main_src=None, load_src2ws_from=None, artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\", combine=\"union\",", "# device to run on [cpu, cuda] device = \"cuda\" if torch.cuda.is_available() else", "Copyright (c) 2021 <NAME> from itertools import chain from pathlib import Path import", "Path(load_from) / load_params _log.info(\"Loading %s model parameters from %s\", src, path) model.load_state_dict(torch.load(path, \"cpu\"))", "(nntags ntags) -> slen nntags ntags\", ntags=len(vocab[\"tags\"]) ) lms = lms.unsqueeze(0) mask =", "artifacts_dir / \"samples.pkl\" _log.info(\"Saving samples to %s\", path) with open(path, \"wb\") as f:", "%s model parameters from %s\", src, path) model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating %s extended word", "ntags -> slen (nntags ntags)\") lms = lms.log_softmax(dim=1) lms = rearrange( lms, \"slen", "for name in vocab: _log.info(\"Found %d %s\", len(vocab[name]), name) _log.info(\"Extending %s vocabulary with", "for wh in [\"train\", \"dev\"]: if load_samples_from: assert all(\"pptx_mask\" in s for s", "eval_on_train=False, max_epoch=10, ): \"\"\"Finetune/adapt a trained tagger with PPTX.\"\"\" if max_length is None:", "vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found %d words now\", len(vocab[\"words\"])) samples_ = {wh: list(vocab.stoi(samples[wh])) for wh", "%d %s\", len(vocab[name]), name) _log.info(\"Extending %s vocabulary with target words\", src) vocab.extend(chain(*samples.values()), [\"words\"])", "load_src\") if artifacts_dir: artifacts_dir = Path(artifacts_dir) if load_samples_from: _log.info(\"Loading samples from %s\", load_samples_from)", "state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] = words.numel() n_toks = sum(len(s[\"words\"]) for s in samples_[wh]) ProgressBar(total=n_toks,", "words now\", len(vocab[\"words\"])) samples_ = {wh: list(vocab.stoi(samples[wh])) for wh in samples} path =", "lms, pts in zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"] = lms samples_[wh][i][\"pred_tags\"] = pts if combine", "prag(): l2_coef = 0.1 lr = 5.9e-5 combine = \"union\" @ex.named_config def prag_gmean():", "def run_eval(model, vocab, samples, device=\"cpu\", batch_size=16, compute_loss=True): runner = Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\",", "in srcs): _log.warning(\"Some srcs have no weights, will be set to zero\") if", "n_toks) kv = KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from: _log.info(\"Skipping non-main src because samples are processed", "word embedding layer\", src) assert model.word_emb.embedding_dim == kv.vector_size with torch.no_grad(): model.word_emb = torch.nn.Embedding.from_pretrained(", "mid = len(log_ntags) // 2 if len(log_ntags) % 2: log_med = log_ntags[mid] else:", "%.1f%%\", 100 * acc) _run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"train_pptx_loss:", "chart: %.1e\", math.exp(log_med)) assert len(samples_[wh]) == len(samples[wh]) if combine == \"geom_mean\": _log.info(\"Combining the", "save_state_dict, update_params from crf import LinearCRF from ingredients.corpus import ing as corpus_ing, read_tagging_samples", "x not in runner.state or len(runner.state[x]) == len(samples_[wh]) assert len(runner.state[\"_ids\"]) == len(samples_[wh]) if", "{key: (load_from, load_params)} load_src = {} # whether to treat keys in load_src", "* acc) _run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"dev_pptx_loss: %.4f\", pptx_loss)", "artifacts_dir and save_samples: path = artifacts_dir / \"samples.pkl\" _log.info(\"Saving samples to %s\", path)", "masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf = LinearCRF(masked_scores.contiguous()) crf_z = LinearCRF(state[\"scores\"].contiguous()) pptx_loss = -crf.log_partitions().sum()", "last position from mask pptx_loss = (-crf.log_partitions().sum() + crf_z.log_partitions().sum()) / bsz loss =", "LinearCRF from ingredients.corpus import ing as corpus_ing, read_tagging_samples from serialization import dump, load", "len(samples[wh]), wh, n_toks) kv = KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from: _log.info(\"Skipping non-main src because samples", "n_toks = sum(len(s[\"words\"]) for s in samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if combine == \"geom_mean\":", "now\", len(vocab[\"words\"])) samples_ = {wh: list(vocab.stoi(samples[wh])) for wh in samples} path = Path(load_from)", "from mask crf_z = LinearCRF(scores.contiguous(), mask[:, :-1]) # exclude last position from mask", "crf_z = LinearCRF(scores.contiguous(), mask[:, :-1]) # exclude last position from mask pptx_loss =", ") else: _log.info( \"Computing PPTX ambiguous tag pairs mask for %s set with", "= KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from: _log.info(\"Skipping non-main src because samples are processed and loaded\")", "for i, lms, pts in zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"] = lms samples_[wh][i][\"pred_tags\"] = pts", "save the final samples as an artifact save_samples = False # load samples", "ingredients=[corpus_ing]) ex.captured_out_filter = apply_backspaces_and_linefeeds # Setup mongodb observer mongo_url = os.getenv(\"SACRED_MONGO_URL\") db_name =", "wh) log_ntags = [] for s in tqdm(samples_[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0)", "combine != \"geom_mean\": _log.info(\"Computing median number of tag sequences in chart on %s", "finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda s: len(s[\"words\"])) trn_iter = ShuffleIterator( BucketIterator(samples[\"train\"], lambda s:", "_log.info(\"test_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"]) if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model,", "load_src = {\"src\": (\"artifacts\", \"model.pth\")} main_src = \"src\" elif main_src not in load_src:", "from %s\", load_samples_from) with open(load_samples_from, \"rb\") as f: samples = pickle.load(f) else: samples", "max number of epochs max_epoch = 10 # whether to save the final", "= 0.95 # batch size batch_size = 80 # learning rate lr =", "1] - max_) + math.exp(log_ntags[mid] - max_) ) - math.log(2) ) _log.info(\"Median number", "acc) _run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"train_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\",", "regularization against initial parameters l2_coef = 1.0 # max number of epochs max_epoch", "= torch.from_numpy(batch[\"words\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have masking", "samples are processed and loaded\") srcs = [] else: srcs = [src for", "= model(words) ptags = LinearCRF(scores).argmax() assert ptags.shape == tags.shape if (tags[:, 0] ==", "len(samples_[wh]) assert len(runner.state[\"_ids\"]) == len(samples_[wh]) if \"pptx_masks\" in runner.state: for i, pptx_mask in", "for i, s in enumerate(samples_[wh]): s[\"_id\"] = i runner = Runner() runner.state[\"_ids\"] =", "load from utils import extend_word_embedding ex = Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter = apply_backspaces_and_linefeeds #", "= 1.0 # max number of epochs max_epoch = 10 # whether to", "\"pred_tags\": []}) elif combine == \"union\": runner.state[\"pptx_masks\"] = [] else: raise ValueError(f\"unknown value", "whether to save the final samples as an artifact save_samples = False #", "= scores state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def maybe_compute_loss(state): if not compute_loss: return masked_scores", "for %s set with source %s\", wh, src ) else: _log.info( \"Computing PPTX", "load_params = load_src[src] path = Path(load_from) / \"vocab.yml\" _log.info(\"Loading %s vocabulary from %s\",", "model.eval() scores = model(words) if combine == \"geom_mean\": crf = LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() +", "is_log_marginals=True) assert mask.shape == lms.shape mask = mask.squeeze(0) for pts in s[\"pred_tags\"]: for", "max_epoch=10, ): \"\"\"Finetune/adapt a trained tagger with PPTX.\"\"\" if max_length is None: max_length", "_rnd, max_length=None, load_src=None, main_src=None, load_src2ws_from=None, artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\", combine=\"union\", thresh=0.95, batch_size=16,", "assert pptx_mask.shape == scores.shape masked_scores = scores.masked_fill(~pptx_mask, -1e9) lengths = mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths", "masking at test time\" model.eval() scores = model(words) ptags = LinearCRF(scores).argmax() assert ptags.shape", "prag_lopw(): l2_coef = 0.062 lr = 4.7e-4 combine = \"geom_mean\" @ex.named_config def testrun():", "samples_[wh][i][\"pred_tags\"] = pts if combine != \"geom_mean\": _log.info(\"Computing median number of tag sequences", "= run_eval(model, vocab, samples[\"train\"]) _log.info(\"train_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"]) assert", "import Path import math import os import pickle from einops import rearrange from", "with PPTX.\"\"\" if max_length is None: max_length = {} if load_src is None:", "srcs): _log.warning(\"Some srcs have no weights, will be set to zero\") if any(src", "ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"]) for s in samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner) origin_params = {name: p.clone().detach()", "i, s in enumerate(samples_[wh]): s[\"_id\"] = i runner = Runner() runner.state[\"_ids\"] = []", "and lms.size(1) == lms.size(2) # Renormalise the marginal probabilities lms = rearrange(lms, \"slen", "else: old_mask = torch.zeros(1, 1, 1).bool() samples[wh][i][\"pptx_mask\"] = (old_mask | pptx_mask).tolist() if not", "import compute_l2_loss, log_grads, log_stats, save_state_dict, update_params from crf import LinearCRF from ingredients.corpus import", "+ 1, len(srcs)) load_from, load_params = load_src[src] path = Path(load_from) / \"vocab.yml\" _log.info(\"Loading", "/ \"vocab.yml\" _log.info(\"Loading %s vocabulary from %s\", src, path) vocab = load(path.read_text(encoding=\"utf8\")) for", "%.1f%%\", 100 * acc) _run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"dev_pptx_loss:", "compute_loss: state[\"scores\"] = scores state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def maybe_compute_loss(state): if not compute_loss:", "non-main src because samples are processed and loaded\") srcs = [] else: srcs", "src ) with torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda s: len(s[\"words\"]), batch_size)) for x in \"pptx_masks", "load_src as lang codes src_key_as_lang = False # the main source to start", "state[\"dev_acc\"] = acc @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state): if state[\"epoch\"] != max_epoch: return _log.info(\"Evaluating on", "# whether to evaluate on train set at every epoch end eval_on_train =", "/ \"vocab.yml\" _log.info(\"Saving vocabulary to %s\", path) path.write_text(dump(vocab), encoding=\"utf8\") path = artifacts_dir /", "model.word_emb = torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight, vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN), ) ) model.to(device) for wh", "in chart: %.1e\", math.exp(log_med)) assert len(samples_[wh]) == len(samples[wh]) if combine == \"geom_mean\": _log.info(\"Combining", "-1e9) lengths = mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths - 1] = False # exclude last", "model parameters from %s\", src, path) model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating %s extended word embedding", "_run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"] = acc @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state): if state[\"epoch\"] != max_epoch:", "words.numel() if compute_loss: state[\"scores\"] = scores state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def maybe_compute_loss(state): if", "= \"src\" elif main_src not in load_src: raise ValueError(f\"{main_src} not found in load_src\")", "p.clone().detach() for name, p in model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH) def compute_loss(state): batch", "torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda s: len(s[\"words\"]), batch_size)) for x in \"pptx_masks log_marginals pred_tags\".split(): assert", "load_src is None: load_src = {\"src\": (\"artifacts\", \"model.pth\")} main_src = \"src\" elif main_src", "def evaluate_batch(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) tags = torch.from_numpy(batch[\"tags\"]).to(device) mask =", "all(\"pptx_mask\" in s for s in samples[wh]) continue for i, s in enumerate(samples_[wh]):", "{wh: list(vocab.stoi(samples[wh])) for wh in samples} for wh in [\"train\", \"dev\"]: _log.info(\"Computing median", "from sacred.utils import apply_backspaces_and_linefeeds from text2array import BucketIterator, ShuffleIterator from tqdm import tqdm", "with torch.no_grad(): runner.run(BucketIterator(samples, lambda s: len(s[\"words\"]), batch_size)) return runner.state[\"corr\"] / runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain", "of tag sequences in chart: %.1e\", math.exp(log_med)) _log.info(\"Creating optimizer\") opt = torch.optim.Adam(model.parameters(), lr=lr)", "vocab, samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is", "evaluate_batch(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) tags = torch.from_numpy(batch[\"tags\"]).to(device) mask = words", "load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\", combine=\"union\", thresh=0.95, batch_size=16, save_samples=False, lr=1e-5, l2_coef=1.0, eval_on_train=False, max_epoch=10, ):", "tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): lms = samples[wh][i].get(\"log_marginals\", 0) pts = samples[wh][i].get(\"pred_tags\", []) lms =", "math.exp(log_ntags[mid - 1] - max_) + math.exp(log_ntags[mid] - max_) ) - math.log(2) )", "wh, src ) else: _log.info( \"Computing PPTX ambiguous tag pairs mask for %s", "words != vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores = model(words, mask) bsz, slen = words.shape assert", "_log.info(\"train_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None", "with length greater than these numbers max_length = {\"train\": 60} # load source", "words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have masking at test time\" model.eval()", "%s set with source %s\", wh, src ) else: _log.info( \"Computing PPTX ambiguous", "pptx_loss = run_eval(model, vocab, samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"])", "torch.from_numpy(batch[\"words\"]).to(device) pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores = model(words,", "assert len(samples_[wh]) == len(samples[wh]) if combine == \"geom_mean\": _log.info(\"Combining the marginals\") for i", "log_med = log_ntags[mid] else: max_ = max(log_ntags[mid - 1], log_ntags[mid]) log_med = (", "rnnr import Event, Runner from rnnr.attachments import EpochTimer, MeanReducer, ProgressBar, SumReducer from sacred", "word_emb_path = \"wiki.en.vec\" # cumulative prob threshold thresh = 0.95 # batch size", "import extend_word_embedding ex = Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter = apply_backspaces_and_linefeeds # Setup mongodb observer", "_log.info(\"Weights: %s\", [src2ws[src] for src in srcs]) else: src2ws = {src: 1 /", "= rearrange( lms, \"slen (nntags ntags) -> slen nntags ntags\", ntags=len(vocab[\"tags\"]) ) lms", "ProgressBar, SumReducer from sacred import Experiment from sacred.observers import MongoObserver from sacred.utils import", "sacred.utils import apply_backspaces_and_linefeeds from text2array import BucketIterator, ShuffleIterator from tqdm import tqdm import", "import torch from aatrn import compute_ambiguous_tag_pairs_mask from callbacks import compute_l2_loss, log_grads, log_stats, save_state_dict,", "Path(artifacts_dir) if load_samples_from: _log.info(\"Loading samples from %s\", load_samples_from) with open(load_samples_from, \"rb\") as f:", "loss = pptx_loss + l2_coef * state[\"l2_loss\"] state[\"loss\"] = loss state[\"stats\"] = {", "runner = Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for s in samples), unit=\"tok\",", "the tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if load_src2ws_from: _log.info(\"Loading src weights from %s\", load_src2ws_from)", "10 # whether to save the final samples as an artifact save_samples =", "size batch_size = 80 # learning rate lr = 1e-5 # coefficient of", "source is %s\", src) if artifacts_dir: path = artifacts_dir / \"vocab.yml\" _log.info(\"Saving vocabulary", "!= vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores = model(words, mask) bsz, slen = words.shape assert scores.shape", "in samples[wh]) # don't count BOS/EOS tokens _log.info(\"Read %d %s samples and %d", "= len(log_ntags) // 2 if len(log_ntags) % 2: log_med = log_ntags[mid] else: max_", "return masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf = LinearCRF(masked_scores.contiguous()) crf_z = LinearCRF(state[\"scores\"].contiguous()) pptx_loss =", "runner.state: for i, pptx_mask in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist() else: zips =", "load source models from these directories and parameters {key: (load_from, load_params)} load_src =", "wh in samples} path = Path(load_from) / \"model.yml\" _log.info(\"Loading %s model from metadata", "combine == \"geom_mean\": runner.state.update({\"log_marginals\": [], \"pred_tags\": []}) elif combine == \"union\": runner.state[\"pptx_masks\"] =", "%s\", src, path) model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating %s extended word embedding layer\", src) assert", "in srcs for src in src2ws): _log.warning(\"Too many srcs in src2ws, weights won't", "prob threshold thresh = 0.95 # batch size batch_size = 80 # learning", "def finetune( corpus, _log, _run, _rnd, max_length=None, load_src=None, main_src=None, load_src2ws_from=None, artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\",", "- math.log(2) ) _log.info(\"Median number of tag sequences in chart: %.1e\", math.exp(log_med)) assert", "i, pptx_mask in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist() else: zips = [runner.state[x] for", "sequences in chart on %s set\", wh) log_ntags = [] for s in", "\"vocab.yml\" _log.info(\"Saving vocabulary to %s\", path) path.write_text(dump(vocab), encoding=\"utf8\") path = artifacts_dir / \"model.yml\"", "in [\"train\", \"dev\"]: _log.info(\"Computing median number of tag sequences in chart on %s", ") ) model.to(device) for wh in [\"train\", \"dev\"]: if load_samples_from: assert all(\"pptx_mask\" in", "assert mask.all(), \"must not have masking at test time\" model.eval() scores = model(words)", "(c) 2021 <NAME> from itertools import chain from pathlib import Path import math", "if combine == \"geom_mean\": crf = LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask", "= Runner() runner.state[\"_ids\"] = [] if combine == \"geom_mean\": runner.state.update({\"log_marginals\": [], \"pred_tags\": []})", "math.exp(log_ntags[mid] - max_) ) - math.log(2) ) _log.info(\"Median number of tag sequences in", "tqdm import tqdm import torch from aatrn import compute_ambiguous_tag_pairs_mask from callbacks import compute_l2_loss,", "in chart on %s set\", wh) log_ntags = [] for s in tqdm(samples[wh],", "MeanReducer, ProgressBar, SumReducer from sacred import Experiment from sacred.observers import MongoObserver from sacred.utils", "from gensim.models.keyedvectors import KeyedVectors from rnnr import Event, Runner from rnnr.attachments import EpochTimer,", "100 * acc) _run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"dev_pptx_loss: %.4f\",", "- 1, pts[j], pts[j - 1]] = True s[\"pptx_mask\"] = mask.tolist() for k", "path to word embedding in word2vec format word_emb_path = \"wiki.en.vec\" # cumulative prob", "origin_params)) @finetuner.on(Event.BATCH) def compute_loss(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool()", "SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for s in samples), unit=\"tok\", leave=False).attach_on( runner ) if compute_loss:", "tags for %s set with source %s\", wh, src ) else: _log.info( \"Computing", "lms.tolist() samples[wh][i][\"pred_tags\"] = pts else: _log.info(\"Combining the ambiguous tag pairs mask\") for i", "leave=False): lms = torch.tensor(s[\"log_marginals\"]) assert lms.dim() == 3 and lms.size(1) == lms.size(2) #", "corpus_ing, read_tagging_samples from serialization import dump, load from utils import extend_word_embedding ex =", "import BucketIterator, ShuffleIterator from tqdm import tqdm import torch from aatrn import compute_ambiguous_tag_pairs_mask", "vocab = load(path.read_text(encoding=\"utf8\")) for name in vocab: _log.info(\"Found %d %s\", len(vocab[name]), name) _log.info(\"Extending", "mask for %s set with source %s\", wh, src ) with torch.no_grad(): runner.run(BucketIterator(samples_[wh],", "vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags = tags[:, 1:], ptags[:, 1:] if (tags[:, -1] == vocab[\"tags\"].index(\"</s>\")).all():", "learning rate lr = 1e-5 # coefficient of L2 regularization against initial parameters", "-> slen (nntags ntags)\") lms = lms.log_softmax(dim=1) lms = rearrange( lms, \"slen (nntags", "= -crf.log_partitions().sum() + crf_z.log_partitions().sum() state[\"pptx_loss\"] = pptx_loss.item() state[\"size\"] = masked_scores.size(0) with torch.no_grad(): runner.run(BucketIterator(samples,", "state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask = compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] = words.numel() n_toks =", "from this file (*.pkl) load_samples_from = \"\" # how to combine PPTX charts", "evaluate on train set at every epoch end eval_on_train = False # load", "%s\", len(vocab[name]), name) _log.info(\"Extending %s vocabulary with target words\", src) vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found", "source %s\", wh, src ) with torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda s: len(s[\"words\"]), batch_size)) for", "= \"wiki.en.vec\" # cumulative prob threshold thresh = 0.95 # batch size batch_size", "for src in src2ws): _log.warning(\"Too many srcs in src2ws, weights won't sum to", "= dict(portion=0.05) @ex.capture def run_eval(model, vocab, samples, device=\"cpu\", batch_size=16, compute_loss=True): runner = Runner()", "from %s\", src, path) model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating %s extended word embedding layer\", src)", "samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner) origin_params = {name: p.clone().detach() for name, p in model.named_parameters()} finetuner.on(Event.BATCH,", "from rnnr.attachments import EpochTimer, MeanReducer, ProgressBar, SumReducer from sacred import Experiment from sacred.observers", "2.6e-4 combine = \"geom_mean\" @ex.named_config def prag_lopw(): l2_coef = 0.062 lr = 4.7e-4", "= mask.squeeze(0) for pts in s[\"pred_tags\"]: for j in range(1, len(pts)): mask[j -", "+ crf_z.log_partitions().sum()) / bsz loss = pptx_loss + l2_coef * state[\"l2_loss\"] state[\"loss\"] =", "runner.state[\"_ids\"] = [] if combine == \"geom_mean\": runner.state.update({\"log_marginals\": [], \"pred_tags\": []}) elif combine", "f: samples = pickle.load(f) else: samples = { wh: list(read_tagging_samples(wh, max_length.get(wh))) for wh", "= False # the main source to start finetuning from main_src = \"\"", "as f: samples = pickle.load(f) else: samples = { wh: list(read_tagging_samples(wh, max_length.get(wh))) for", "= torch.from_numpy(batch[\"words\"]).to(device) tags = torch.from_numpy(batch[\"tags\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must", "because it's the tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if load_src2ws_from: _log.info(\"Loading src weights from", "\"union\" @ex.named_config def prag_gmean(): l2_coef = 4.7e-3 lr = 2.6e-4 combine = \"geom_mean\"", "_log.info(\"Removing %s from src parsers because it's the tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if", "corpus[\"lang\"] in srcs: _log.info(\"Removing %s from src parsers because it's the tgt\", corpus[\"lang\"])", "(tags[:, -1] == vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags = tags[:, :-1], ptags[:, :-1] state[\"bcorr\"] =", "ing as corpus_ing, read_tagging_samples from serialization import dump, load from utils import extend_word_embedding", "mask pptx_loss = (-crf.log_partitions().sum() + crf_z.log_partitions().sum()) / bsz loss = pptx_loss + l2_coef", "= lms.log_softmax(dim=1) lms = rearrange( lms, \"slen (nntags ntags) -> slen nntags ntags\",", "if not load_samples_from and combine == \"geom_mean\": for wh in [\"train\", \"dev\"]: _log.info(\"Computing", "_log.warning(\"Too many srcs in src2ws, weights won't sum to one\") _log.info(\"Sources: %s\", list(srcs))", "len(runner.state[\"_ids\"]) == len(samples_[wh]) if \"pptx_masks\" in runner.state: for i, pptx_mask in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]):", "load(path.read_text(encoding=\"utf8\")) path = Path(load_from) / load_params _log.info(\"Loading %s model parameters from %s\", src,", "= [] for s in tqdm(samples[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores =", "with torch.no_grad(): model.word_emb = torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight, vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN), ) ) model.to(device)", "load_samples_from = \"\" # how to combine PPTX charts combine = \"union\" #", "{\"loss\": loss.item()} state[\"n_items\"] = lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run, model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state):", "log_ntags[mid]) log_med = ( max_ + math.log( math.exp(log_ntags[mid - 1] - max_) +", "from main_src = \"\" # device to run on [cpu, cuda] device =", "load_src2ws_from = \"\" @ex.named_config def prag(): l2_coef = 0.1 lr = 5.9e-5 combine", "for s in samples[wh]) # don't count BOS/EOS tokens _log.info(\"Read %d %s samples", "PPTX charts combine = \"union\" # whether to evaluate on train set at", "these directories and parameters {key: (load_from, load_params)} load_src = {} # whether to", "state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not", "pairs mask on %s set\", wh) for s in tqdm(samples[wh], unit=\"sample\", leave=False): lms", "src in srcs]) else: src2ws = {src: 1 / len(srcs) for src in", "= torch.tensor(s[\"log_marginals\"]) assert lms.dim() == 3 and lms.size(1) == lms.size(2) # Renormalise the", "vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores = model(words, mask) bsz, slen = words.shape assert scores.shape ==", "state[\"loss\"] = loss state[\"stats\"] = { \"pptx_loss\": pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(), } state[\"extra_stats\"] =", "continue for i, s in enumerate(samples_[wh]): s[\"_id\"] = i runner = Runner() runner.state[\"_ids\"]", "= [src for src in load_src if src != main_src] if src_key_as_lang and", "src, path) model = load(path.read_text(encoding=\"utf8\")) path = Path(load_from) / load_params _log.info(\"Loading %s model", "an artifact save_samples = False # load samples from this file (*.pkl) load_samples_from", "_log.info(\"Saving vocabulary to %s\", path) path.write_text(dump(vocab), encoding=\"utf8\") path = artifacts_dir / \"model.yml\" _log.info(\"Saving", "best tags for %s set with source %s\", wh, src ) else: _log.info(", "max_) ) - math.log(2) ) _log.info(\"Median number of tag sequences in chart: %.1e\",", "apply_backspaces_and_linefeeds # Setup mongodb observer mongo_url = os.getenv(\"SACRED_MONGO_URL\") db_name = os.getenv(\"SACRED_DB_NAME\") if None", "model(words) if combine == \"geom_mean\": crf = LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else:", "# directory to save finetuning artifacts artifacts_dir = \"\" # discard train/dev/test samples", "mask.all(), \"must not have masking at test time\" model.eval() scores = model(words) if", "# don't count BOS/EOS tokens _log.info(\"Read %d %s samples and %d tokens\", len(samples[wh]),", "parsers because it's the tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if load_src2ws_from: _log.info(\"Loading src weights", "batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(),", "main_src _log.info(\"Main source is %s\", src) if artifacts_dir: path = artifacts_dir / \"vocab.yml\"", "mongo_url = os.getenv(\"SACRED_MONGO_URL\") db_name = os.getenv(\"SACRED_DB_NAME\") if None not in (mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url,", "torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight, vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN), ) ) model.to(device) for wh in [\"train\",", "artifacts artifacts_dir = \"\" # discard train/dev/test samples with length greater than these", "state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) model.train()", "assert ptags.shape == tags.shape if (tags[:, 0] == vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags = tags[:,", "tqdm(samples[wh], unit=\"sample\", leave=False): lms = torch.tensor(s[\"log_marginals\"]) assert lms.dim() == 3 and lms.size(1) ==", "path = artifacts_dir / \"samples.pkl\" _log.info(\"Saving samples to %s\", path) with open(path, \"wb\")", "[update_params(opt), log_grads(_run, model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state): if not eval_on_train: return _log.info(\"Evaluating on", "# cumulative prob threshold thresh = 0.95 # batch size batch_size = 80", "finetune( corpus, _log, _run, _rnd, max_length=None, load_src=None, main_src=None, load_src2ws_from=None, artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False,", "if load_src is None: load_src = {\"src\": (\"artifacts\", \"model.pth\")} main_src = \"src\" elif", "= (-crf.log_partitions().sum() + crf_z.log_partitions().sum()) / bsz loss = pptx_loss + l2_coef * state[\"l2_loss\"]", "%s extended word embedding layer\", src) assert model.word_emb.embedding_dim == kv.vector_size with torch.no_grad(): model.word_emb", "i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim() == 3 if", "step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"dev_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"]", "= words.numel() n_toks = sum(len(s[\"words\"]) for s in samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if combine", "state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf = LinearCRF(masked_scores.contiguous()) crf_z = LinearCRF(state[\"scores\"].contiguous()) pptx_loss = -crf.log_partitions().sum() + crf_z.log_partitions().sum()", "tag sequences in chart: %.1e\", math.exp(log_med)) _log.info(\"Creating optimizer\") opt = torch.optim.Adam(model.parameters(), lr=lr) finetuner", "ex = Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter = apply_backspaces_and_linefeeds # Setup mongodb observer mongo_url =", "set to zero\") if any(src not in srcs for src in src2ws): _log.warning(\"Too", "acc, pptx_loss = run_eval(model, vocab, samples[\"train\"]) _log.info(\"train_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"train_acc\", acc,", "eval_on_train: return _log.info(\"Evaluating on train\") acc, pptx_loss = run_eval(model, vocab, samples[\"train\"]) _log.info(\"train_acc: %.1f%%\",", "log_marginals pred_tags\".split(): assert x not in runner.state or len(runner.state[x]) == len(samples_[wh]) assert len(runner.state[\"_ids\"])", "in srcs} for src_i, src in enumerate(srcs): _log.info(\"Processing src %s [%d/%d]\", src, src_i", "unit=\"sample\", leave=False): pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim() == 3 if \"pptx_mask\" in samples[wh][i]:", "weights won't sum to one\") _log.info(\"Sources: %s\", list(srcs)) _log.info(\"Weights: %s\", [src2ws[src] for src", "for s in samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if combine == \"geom_mean\": _log.info( \"Computing marginals", "on dev\") acc, pptx_loss = run_eval(model, vocab, samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\", 100 * acc)", "state[\"epoch\"] != max_epoch: return _log.info(\"Evaluating on test\") acc, _ = run_eval(model, vocab, samples[\"test\"],", "the ambiguous tag pairs mask on %s set\", wh) for s in tqdm(samples[wh],", "end eval_on_train = False # load src2ws from this path load_src2ws_from = \"\"", "mongodb observer mongo_url = os.getenv(\"SACRED_MONGO_URL\") db_name = os.getenv(\"SACRED_DB_NAME\") if None not in (mongo_url,", "pickle.dump(samples, f) samples = {wh: list(vocab.stoi(samples[wh])) for wh in samples} for wh in", "== lms.shape mask = mask.squeeze(0) for pts in s[\"pred_tags\"]: for j in range(1,", "* acc) _run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"train_pptx_loss: %.4f\", pptx_loss)", "\"model.yml\" _log.info(\"Saving model metadata to %s\", path) path.write_text(dump(model), encoding=\"utf8\") if artifacts_dir and save_samples:", "Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for s in samples), unit=\"tok\", leave=False).attach_on( runner", "in samples} for wh in [\"train\", \"dev\"]: _log.info(\"Computing median number of tag sequences", "[] else: raise ValueError(f\"unknown value for combine: {combine}\") @runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state): batch =", "1]] = True s[\"pptx_mask\"] = mask.tolist() for k in \"log_marginals pred_tags\".split(): s.pop(k) assert", "# load samples from this file (*.pkl) load_samples_from = \"\" # how to", "on [cpu, cuda] device = \"cuda\" if torch.cuda.is_available() else \"cpu\" # path to", "( max_ + math.log( math.exp(log_ntags[mid - 1] - max_) + math.exp(log_ntags[mid] - max_)", "model.train() scores = model(words, mask) bsz, slen = words.shape assert scores.shape == (bsz,", "+ math.log( math.exp(log_ntags[mid - 1] - max_) + math.exp(log_ntags[mid] - max_) ) -", "len(samples[wh]) if combine == \"geom_mean\": _log.info(\"Combining the marginals\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\",", "src) vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found %d words now\", len(vocab[\"words\"])) samples_ = {wh: list(vocab.stoi(samples[wh])) for", "thresh, is_log_marginals=True) assert mask.shape == lms.shape mask = mask.squeeze(0) for pts in s[\"pred_tags\"]:", "and %d tokens\", len(samples[wh]), wh, n_toks) kv = KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from: _log.info(\"Skipping non-main", "from sacred.observers import MongoObserver from sacred.utils import apply_backspaces_and_linefeeds from text2array import BucketIterator, ShuffleIterator", "default(): # directory to save finetuning artifacts artifacts_dir = \"\" # discard train/dev/test", "maybe_eval_on_test(state): if state[\"epoch\"] != max_epoch: return _log.info(\"Evaluating on test\") acc, _ = run_eval(model,", "and combine == \"geom_mean\": for wh in [\"train\", \"dev\"]: _log.info(\"Computing the ambiguous tag", "directories and parameters {key: (load_from, load_params)} load_src = {} # whether to treat", "unit=\"sample\", leave=False): lms = torch.tensor(s[\"log_marginals\"]) assert lms.dim() == 3 and lms.size(1) == lms.size(2)", "format word_emb_path = \"wiki.en.vec\" # cumulative prob threshold thresh = 0.95 # batch", "mask = compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True) assert mask.shape == lms.shape mask = mask.squeeze(0) for", "%s\", list(srcs)) _log.info(\"Weights: %s\", [src2ws[src] for src in srcs]) else: src2ws = {src:", "\"test\"] } for wh in samples: n_toks = sum(len(s[\"words\"]) - 2 for s", "srcs have no weights, will be set to zero\") if any(src not in", "thresh=0.95, batch_size=16, save_samples=False, lr=1e-5, l2_coef=1.0, eval_on_train=False, max_epoch=10, ): \"\"\"Finetune/adapt a trained tagger with", "compute_pptx_ambiguous_tag_pairs_mask(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert", "for s in samples), unit=\"tok\", leave=False).attach_on( runner ) if compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH)", "% 2: log_med = log_ntags[mid] else: max_ = max(log_ntags[mid - 1], log_ntags[mid]) log_med", "pptx_loss + l2_coef * state[\"l2_loss\"] state[\"loss\"] = loss state[\"stats\"] = { \"pptx_loss\": pptx_loss.item(),", "in enumerate(srcs): _log.info(\"Processing src %s [%d/%d]\", src, src_i + 1, len(srcs)) load_from, load_params", "in s[\"pred_tags\"]: for j in range(1, len(pts)): mask[j - 1, pts[j], pts[j -", "srcs} for src_i, src in enumerate(srcs): _log.info(\"Processing src %s [%d/%d]\", src, src_i +", "crf import LinearCRF from ingredients.corpus import ing as corpus_ing, read_tagging_samples from serialization import", "pts in zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"] = lms samples_[wh][i][\"pred_tags\"] = pts if combine !=", "lr=1e-5, l2_coef=1.0, eval_on_train=False, max_epoch=10, ): \"\"\"Finetune/adapt a trained tagger with PPTX.\"\"\" if max_length", "} for wh in samples: n_toks = sum(len(s[\"words\"]) - 2 for s in", "= {wh: list(vocab.stoi(samples[wh])) for wh in samples} for wh in [\"train\", \"dev\"]: _log.info(\"Computing", "_run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state): _log.info(\"Evaluating on dev\") acc, pptx_loss = run_eval(model,", "} state[\"extra_stats\"] = {\"loss\": loss.item()} state[\"n_items\"] = lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run, model), log_stats(_run)])", "# exclude last position from mask pptx_loss = (-crf.log_partitions().sum() + crf_z.log_partitions().sum()) / bsz", "runner.state or len(runner.state[x]) == len(samples_[wh]) assert len(runner.state[\"_ids\"]) == len(samples_[wh]) if \"pptx_masks\" in runner.state:", "at test time\" model.eval() scores = model(words) ptags = LinearCRF(scores).argmax() assert ptags.shape ==", "finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH) def compute_loss(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) pptx_mask", "def prag_gmean(): l2_coef = 4.7e-3 lr = 2.6e-4 combine = \"geom_mean\" @ex.named_config def", "Path(load_from) / \"model.yml\" _log.info(\"Loading %s model from metadata %s\", src, path) model =", "runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist() else: zips = [runner.state[x] for x in \"log_marginals pred_tags\".split()]", "to %s\", path) path.write_text(dump(vocab), encoding=\"utf8\") path = artifacts_dir / \"model.yml\" _log.info(\"Saving model metadata", "vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have masking at test time\" model.eval() scores =", "samples} path = Path(load_from) / \"model.yml\" _log.info(\"Loading %s model from metadata %s\", src,", "= LinearCRF(masked_scores.contiguous()) crf_z = LinearCRF(state[\"scores\"].contiguous()) pptx_loss = -crf.log_partitions().sum() + crf_z.log_partitions().sum() state[\"pptx_loss\"] = pptx_loss.item()", "Setup mongodb observer mongo_url = os.getenv(\"SACRED_MONGO_URL\") db_name = os.getenv(\"SACRED_DB_NAME\") if None not in", "raise ValueError(f\"unknown value for combine: {combine}\") @runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state): batch = state[\"batch\"].to_array() words", "with source %s\", wh, src ) else: _log.info( \"Computing PPTX ambiguous tag pairs", "\"dev\"]: if load_samples_from: assert all(\"pptx_mask\" in s for s in samples[wh]) continue for", "length greater than these numbers max_length = {\"train\": 60} # load source models", "= torch.optim.Adam(model.parameters(), lr=lr) finetuner = Runner() EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"]) for s in", "chart: %.1e\", math.exp(log_med)) _log.info(\"Creating optimizer\") opt = torch.optim.Adam(model.parameters(), lr=lr) finetuner = Runner() EpochTimer().attach_on(finetuner)", "= torch.zeros(1, 1, 1).bool() samples[wh][i][\"pptx_mask\"] = (old_mask | pptx_mask).tolist() if not load_samples_from and", "srcs = [] else: srcs = [src for src in load_src if src", "path) model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating %s extended word embedding layer\", src) assert model.word_emb.embedding_dim ==", "in samples: n_toks = sum(len(s[\"words\"]) - 2 for s in samples[wh]) # don't", "stats=\"stats\", total=sum(len(s[\"words\"]) for s in samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner) origin_params = {name: p.clone().detach() for", "= \"union\" # whether to evaluate on train set at every epoch end", "\"samples.pkl\" _log.info(\"Saving samples to %s\", path) with open(path, \"wb\") as f: pickle.dump(samples, f)", "mask.tolist() for k in \"log_marginals pred_tags\".split(): s.pop(k) assert src == main_src _log.info(\"Main source", "= Path(load_from) / load_params _log.info(\"Loading %s model parameters from %s\", src, path) model.load_state_dict(torch.load(path,", "KeyedVectors from rnnr import Event, Runner from rnnr.attachments import EpochTimer, MeanReducer, ProgressBar, SumReducer", "wh, src ) with torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda s: len(s[\"words\"]), batch_size)) for x in", "state[\"l2_loss\"].item(), } state[\"extra_stats\"] = {\"loss\": loss.item()} state[\"n_items\"] = lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run, model),", "masking at test time\" model.eval() scores = model(words) if combine == \"geom_mean\": crf", "%s\", path) with open(path, \"wb\") as f: pickle.dump(samples, f) samples = {wh: list(vocab.stoi(samples[wh]))", "set with source %s\", wh, src ) else: _log.info( \"Computing PPTX ambiguous tag", "slen - 1, len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert pptx_mask.shape == scores.shape masked_scores = scores.masked_fill(~pptx_mask, -1e9)", "= pptx_loss + l2_coef * state[\"l2_loss\"] state[\"loss\"] = loss state[\"stats\"] = { \"pptx_loss\":", "src in src2ws): _log.warning(\"Too many srcs in src2ws, weights won't sum to one\")", "are processed and loaded\") srcs = [] else: srcs = [src for src", "with source %s\", wh, src ) with torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda s: len(s[\"words\"]), batch_size))", "5.9e-5 combine = \"union\" @ex.named_config def prag_gmean(): l2_coef = 4.7e-3 lr = 2.6e-4", "if compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def evaluate_batch(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device)", "len(pts)): mask[j - 1, pts[j], pts[j - 1]] = True s[\"pptx_mask\"] = mask.tolist()", "\"\" # discard train/dev/test samples with length greater than these numbers max_length =", "gensim.models.keyedvectors import KeyedVectors from rnnr import Event, Runner from rnnr.attachments import EpochTimer, MeanReducer,", "samples to %s\", path) with open(path, \"wb\") as f: pickle.dump(samples, f) samples =", "= samples[wh][i].get(\"pred_tags\", []) lms = torch.tensor(lms, device=device) + src2ws[src] * samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"]", "s in tqdm(samples[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item())", "import KeyedVectors from rnnr import Event, Runner from rnnr.attachments import EpochTimer, MeanReducer, ProgressBar,", "not None _log.info(\"dev_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"] = acc @finetuner.on(Event.EPOCH_FINISHED) def", "# the main source to start finetuning from main_src = \"\" # device", "mask crf_z = LinearCRF(scores.contiguous(), mask[:, :-1]) # exclude last position from mask pptx_loss", "{combine}\") @runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) mask = words", "model = load(path.read_text(encoding=\"utf8\")) path = Path(load_from) / load_params _log.info(\"Loading %s model parameters from", "= pptx_mask.tolist() else: zips = [runner.state[x] for x in \"log_marginals pred_tags\".split()] for i,", "1 / len(srcs) for src in srcs} for src_i, src in enumerate(srcs): _log.info(\"Processing", "SumReducer from sacred import Experiment from sacred.observers import MongoObserver from sacred.utils import apply_backspaces_and_linefeeds", "\"vocab.yml\" _log.info(\"Loading %s vocabulary from %s\", src, path) vocab = load(path.read_text(encoding=\"utf8\")) for name", "!= max_epoch: return _log.info(\"Evaluating on test\") acc, _ = run_eval(model, vocab, samples[\"test\"], compute_loss=False)", "vocab[\"words\"].index(vocab.UNK_TOKEN), ) ) model.to(device) for wh in [\"train\", \"dev\"]: if load_samples_from: assert all(\"pptx_mask\"", "aatrn import compute_ambiguous_tag_pairs_mask from callbacks import compute_l2_loss, log_grads, log_stats, save_state_dict, update_params from crf", "ntags)\") lms = lms.log_softmax(dim=1) lms = rearrange( lms, \"slen (nntags ntags) -> slen", "batch_size=16, save_samples=False, lr=1e-5, l2_coef=1.0, eval_on_train=False, max_epoch=10, ): \"\"\"Finetune/adapt a trained tagger with PPTX.\"\"\"", "mask[:, :-1] ) # exclude last position from mask crf_z = LinearCRF(scores.contiguous(), mask[:,", "@ex.named_config def prag_gmean(): l2_coef = 4.7e-3 lr = 2.6e-4 combine = \"geom_mean\" @ex.named_config", "@runner.on(Event.BATCH) def maybe_compute_loss(state): if not compute_loss: return masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf =", "in samples} path = Path(load_from) / \"model.yml\" _log.info(\"Loading %s model from metadata %s\",", "acc @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state): if state[\"epoch\"] != max_epoch: return _log.info(\"Evaluating on test\") acc,", "= scores.masked_fill(~pptx_mask, -1e9) lengths = mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths - 1] = False #", "leave=False): lms = samples[wh][i].get(\"log_marginals\", 0) pts = samples[wh][i].get(\"pred_tags\", []) lms = torch.tensor(lms, device=device)", "pptx_loss = (-crf.log_partitions().sum() + crf_z.log_partitions().sum()) / bsz loss = pptx_loss + l2_coef *", "directory to save finetuning artifacts artifacts_dir = \"\" # discard train/dev/test samples with", "src2ws from this path load_src2ws_from = \"\" @ex.named_config def prag(): l2_coef = 0.1", "import Experiment from sacred.observers import MongoObserver from sacred.utils import apply_backspaces_and_linefeeds from text2array import", "\"dev\", \"test\"] } for wh in samples: n_toks = sum(len(s[\"words\"]) - 2 for", "== 3 and lms.size(1) == lms.size(2) # Renormalise the marginal probabilities lms =", "elif combine == \"union\": runner.state[\"pptx_masks\"] = [] else: raise ValueError(f\"unknown value for combine:", "count BOS/EOS tokens _log.info(\"Read %d %s samples and %d tokens\", len(samples[wh]), wh, n_toks)", "apply_backspaces_and_linefeeds from text2array import BucketIterator, ShuffleIterator from tqdm import tqdm import torch from", "lr = 2.6e-4 combine = \"geom_mean\" @ex.named_config def prag_lopw(): l2_coef = 0.062 lr", "einops import rearrange from gensim.models.keyedvectors import KeyedVectors from rnnr import Event, Runner from", "pts in s[\"pred_tags\"]: for j in range(1, len(pts)): mask[j - 1, pts[j], pts[j", "not None _log.info(\"train_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state): _log.info(\"Evaluating on", "| pptx_mask).tolist() if not load_samples_from and combine == \"geom_mean\": for wh in [\"train\",", "lms = torch.tensor(s[\"log_marginals\"]) assert lms.dim() == 3 and lms.size(1) == lms.size(2) # Renormalise", "= Path(artifacts_dir) if load_samples_from: _log.info(\"Loading samples from %s\", load_samples_from) with open(load_samples_from, \"rb\") as", "3 if \"pptx_mask\" in samples[wh][i]: old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask = torch.zeros(1, 1,", "= pts if combine != \"geom_mean\": _log.info(\"Computing median number of tag sequences in", ") if compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def evaluate_batch(state): batch = state[\"batch\"].to_array() words =", "torch.from_numpy(batch[\"words\"]).to(device) tags = torch.from_numpy(batch[\"tags\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not", "rnnr.attachments import EpochTimer, MeanReducer, ProgressBar, SumReducer from sacred import Experiment from sacred.observers import", "tag pairs mask for %s set with source %s\", wh, src ) with", "serialization import dump, load from utils import extend_word_embedding ex = Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter", "main source to start finetuning from main_src = \"\" # device to run", "torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask = torch.zeros(1, 1, 1).bool() samples[wh][i][\"pptx_mask\"] = (old_mask | pptx_mask).tolist() if", "log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state): if not eval_on_train: return _log.info(\"Evaluating on train\") acc, pptx_loss", "assert pptx_mask.dim() == 3 if \"pptx_mask\" in samples[wh][i]: old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask", "words.shape assert scores.shape == (bsz, slen - 1, len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert pptx_mask.shape ==", "run_eval(model, vocab, samples, device=\"cpu\", batch_size=16, compute_loss=True): runner = Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner)", "4.7e-4 combine = \"geom_mean\" @ex.named_config def testrun(): seed = 12345 max_epoch = 2", "step=state[\"n_iters\"]) if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda s: len(s[\"words\"])) trn_iter = ShuffleIterator(", "(-crf.log_partitions().sum() + crf_z.log_partitions().sum()) / bsz loss = pptx_loss + l2_coef * state[\"l2_loss\"] state[\"loss\"]", "initial parameters l2_coef = 1.0 # max number of epochs max_epoch = 10", "in samples[wh][i]: old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask = torch.zeros(1, 1, 1).bool() samples[wh][i][\"pptx_mask\"] =", "state[\"l2_loss\"] state[\"loss\"] = loss state[\"stats\"] = { \"pptx_loss\": pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(), } state[\"extra_stats\"]", "models from these directories and parameters {key: (load_from, load_params)} load_src = {} #", "import dump, load from utils import extend_word_embedding ex = Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter =", "ingredients.corpus import ing as corpus_ing, read_tagging_samples from serialization import dump, load from utils", "max_length.get(wh))) for wh in [\"train\", \"dev\", \"test\"] } for wh in samples: n_toks", "value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for s in samples), unit=\"tok\", leave=False).attach_on( runner ) if compute_loss: MeanReducer(\"mean_pptx_loss\",", "samples[wh][i].get(\"pred_tags\", []) lms = torch.tensor(lms, device=device) + src2ws[src] * samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] =", "loaded\") srcs = [] else: srcs = [src for src in load_src if", "@ex.named_config def testrun(): seed = 12345 max_epoch = 2 corpus = dict(portion=0.05) @ex.capture", "\"cpu\" # path to word embedding in word2vec format word_emb_path = \"wiki.en.vec\" #", "ptags = tags[:, :-1], ptags[:, :-1] state[\"bcorr\"] = (ptags == tags).long().sum().item() state[\"btotal\"] =", "time\" model.eval() scores = model(words) if combine == \"geom_mean\": crf = LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals()", "{\"train\": 60} # load source models from these directories and parameters {key: (load_from,", "lms = rearrange(lms, \"slen nntags ntags -> slen (nntags ntags)\") lms = lms.log_softmax(dim=1)", "unit=\"tok\", leave=False).attach_on( runner ) if compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def evaluate_batch(state): batch =", "lms, \"slen (nntags ntags) -> slen nntags ntags\", ntags=len(vocab[\"tags\"]) ) lms = lms.unsqueeze(0)", "unit=\"tok\" ).attach_on(finetuner) origin_params = {name: p.clone().detach() for name, p in model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model,", "wh in [\"train\", \"dev\"]: _log.info(\"Computing median number of tag sequences in chart on", "start finetuning from main_src = \"\" # device to run on [cpu, cuda]", "\"union\": runner.state[\"pptx_masks\"] = [] else: raise ValueError(f\"unknown value for combine: {combine}\") @runner.on(Event.BATCH) def", "acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"dev_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"])", "f) samples = {wh: list(vocab.stoi(samples[wh])) for wh in samples} for wh in [\"train\",", "wh, n_toks) kv = KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from: _log.info(\"Skipping non-main src because samples are", "# path to word embedding in word2vec format word_emb_path = \"wiki.en.vec\" # cumulative", "= [runner.state[x] for x in \"log_marginals pred_tags\".split()] for i, lms, pts in zip(runner.state[\"_ids\"],", "\"Computing marginals and best tags for %s set with source %s\", wh, src", "math.log(2) ) _log.info(\"Median number of tag sequences in chart: %.1e\", math.exp(log_med)) _log.info(\"Creating optimizer\")", "cuda] device = \"cuda\" if torch.cuda.is_available() else \"cpu\" # path to word embedding", "is not None _log.info(\"dev_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"] = acc @finetuner.on(Event.EPOCH_FINISHED)", "in [\"train\", \"dev\", \"test\"] } for wh in samples: n_toks = sum(len(s[\"words\"]) -", "_log.info(\"Found %d %s\", len(vocab[name]), name) _log.info(\"Extending %s vocabulary with target words\", src) vocab.extend(chain(*samples.values()),", "lms.shape mask = mask.squeeze(0) for pts in s[\"pred_tags\"]: for j in range(1, len(pts)):", "_log.info(\"Loading samples from %s\", load_samples_from) with open(load_samples_from, \"rb\") as f: samples = pickle.load(f)", "/ \"samples.pkl\" _log.info(\"Saving samples to %s\", path) with open(path, \"wb\") as f: pickle.dump(samples,", "1:], ptags[:, 1:] if (tags[:, -1] == vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags = tags[:, :-1],", "2: log_med = log_ntags[mid] else: max_ = max(log_ntags[mid - 1], log_ntags[mid]) log_med =", "acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"train_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"])", "words.numel() n_toks = sum(len(s[\"words\"]) for s in samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if combine ==", "name) _log.info(\"Extending %s vocabulary with target words\", src) vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found %d words", "else \"cpu\" # path to word embedding in word2vec format word_emb_path = \"wiki.en.vec\"", "log_stats, save_state_dict, update_params from crf import LinearCRF from ingredients.corpus import ing as corpus_ing,", "= tags.numel() state[\"n_items\"] = words.numel() if compute_loss: state[\"scores\"] = scores state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool()", "from sacred import Experiment from sacred.observers import MongoObserver from sacred.utils import apply_backspaces_and_linefeeds from", "assert lms.dim() == 3 and lms.size(1) == lms.size(2) # Renormalise the marginal probabilities", "this file (*.pkl) load_samples_from = \"\" # how to combine PPTX charts combine", "1, 1).bool() samples[wh][i][\"pptx_mask\"] = (old_mask | pptx_mask).tolist() if not load_samples_from and combine ==", "s in samples), unit=\"tok\", leave=False).attach_on( runner ) if compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def", "from %s\", load_src2ws_from) src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src not in src2ws for src", "for wh in samples} for wh in [\"train\", \"dev\"]: _log.info(\"Computing median number of", "to word embedding in word2vec format word_emb_path = \"wiki.en.vec\" # cumulative prob threshold", "to %s\", path) path.write_text(dump(model), encoding=\"utf8\") if artifacts_dir and save_samples: path = artifacts_dir /", "if combine == \"geom_mean\": _log.info(\"Combining the marginals\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False):", "in model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH) def compute_loss(state): batch = state[\"batch\"].to_array() words =", "dev\") acc, pptx_loss = run_eval(model, vocab, samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"dev_acc\",", "_log.info(\"Saving model metadata to %s\", path) path.write_text(dump(model), encoding=\"utf8\") if artifacts_dir and save_samples: path", "device=device) + src2ws[src] * samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] = lms.tolist() samples[wh][i][\"pred_tags\"] = pts else:", "in runner.state or len(runner.state[x]) == len(samples_[wh]) assert len(runner.state[\"_ids\"]) == len(samples_[wh]) if \"pptx_masks\" in", "[%d/%d]\", src, src_i + 1, len(srcs)) load_from, load_params = load_src[src] path = Path(load_from)", "extend_word_embedding ex = Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter = apply_backspaces_and_linefeeds # Setup mongodb observer mongo_url", "tags[:, :-1], ptags[:, :-1] state[\"bcorr\"] = (ptags == tags).long().sum().item() state[\"btotal\"] = tags.numel() state[\"n_items\"]", "len(s[\"words\"]), batch_size)) return runner.state[\"corr\"] / runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain def finetune( corpus, _log, _run,", "_log.info(\"Creating optimizer\") opt = torch.optim.Adam(model.parameters(), lr=lr) finetuner = Runner() EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"])", "= os.getenv(\"SACRED_DB_NAME\") if None not in (mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config def default():", ":-1]) # exclude last position from mask pptx_loss = (-crf.log_partitions().sum() + crf_z.log_partitions().sum()) /", "= 4.7e-3 lr = 2.6e-4 combine = \"geom_mean\" @ex.named_config def prag_lopw(): l2_coef =", "model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH) def compute_loss(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device)", "== vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags = tags[:, :-1], ptags[:, :-1] state[\"bcorr\"] = (ptags ==", "\"must not have masking at test time\" model.eval() scores = model(words) ptags =", "src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src not in src2ws for src in srcs): _log.warning(\"Some", "[\"train\", \"dev\"]: _log.info(\"Computing median number of tag sequences in chart on %s set\",", "slen = words.shape assert scores.shape == (bsz, slen - 1, len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert", "number of epochs max_epoch = 10 # whether to save the final samples", "_log.info(\"Loading %s model from metadata %s\", src, path) model = load(path.read_text(encoding=\"utf8\")) path =", "batch_size)) return runner.state[\"corr\"] / runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain def finetune( corpus, _log, _run, _rnd,", "compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def evaluate_batch(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) tags", "ShuffleIterator from tqdm import tqdm import torch from aatrn import compute_ambiguous_tag_pairs_mask from callbacks", "/ bsz loss = pptx_loss + l2_coef * state[\"l2_loss\"] state[\"loss\"] = loss state[\"stats\"]", "samples[\"train\"].sort(key=lambda s: len(s[\"words\"])) trn_iter = ShuffleIterator( BucketIterator(samples[\"train\"], lambda s: len(s[\"words\"]) // 10, batch_size),", "3 and lms.size(1) == lms.size(2) # Renormalise the marginal probabilities lms = rearrange(lms,", "ptags[:, 1:] if (tags[:, -1] == vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags = tags[:, :-1], ptags[:,", "bsz loss = pptx_loss + l2_coef * state[\"l2_loss\"] state[\"loss\"] = loss state[\"stats\"] =", "in [\"train\", \"dev\"]: if load_samples_from: assert all(\"pptx_mask\" in s for s in samples[wh])", "[\"train\", \"dev\", \"test\"] } for wh in samples: n_toks = sum(len(s[\"words\"]) - 2", "eval_on_train = False # load src2ws from this path load_src2ws_from = \"\" @ex.named_config", "else: _log.info(\"Combining the ambiguous tag pairs mask\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False):", "epochs max_epoch = 10 # whether to save the final samples as an", "= load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src not in src2ws for src in srcs): _log.warning(\"Some srcs", "words\", src) vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found %d words now\", len(vocab[\"words\"])) samples_ = {wh: list(vocab.stoi(samples[wh]))", "step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state): _log.info(\"Evaluating on dev\") acc, pptx_loss = run_eval(model, vocab, samples[\"dev\"])", "= (old_mask | pptx_mask).tolist() if not load_samples_from and combine == \"geom_mean\": for wh", "= Path(load_from) / \"model.yml\" _log.info(\"Loading %s model from metadata %s\", src, path) model", "= \"\" # device to run on [cpu, cuda] device = \"cuda\" if", "_log.info(\"Loading %s model parameters from %s\", src, path) model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating %s extended", "srcs]) else: src2ws = {src: 1 / len(srcs) for src in srcs} for", "@finetuner.on(Event.BATCH) def compute_loss(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask", "state[\"n_items\"] = lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run, model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state): if not", "= [] for s in tqdm(samples_[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores =", "100 * acc) _run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"]) if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda", "from these directories and parameters {key: (load_from, load_params)} load_src = {} # whether", "batch_size), rng=_rnd ) _log.info(\"Starting finetuning\") try: finetuner.run(trn_iter, max_epoch) except KeyboardInterrupt: _log.info(\"Interrupt detected, training", "model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda s: len(s[\"words\"])) trn_iter = ShuffleIterator( BucketIterator(samples[\"train\"], lambda s: len(s[\"words\"]) //", "mask on %s set\", wh) for s in tqdm(samples[wh], unit=\"sample\", leave=False): lms =", "- 1, len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert pptx_mask.shape == scores.shape masked_scores = scores.masked_fill(~pptx_mask, -1e9) lengths", "the ambiguous tag pairs mask\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): pptx_mask =", "_log.info( \"Computing PPTX ambiguous tag pairs mask for %s set with source %s\",", "pickle.load(f) else: samples = { wh: list(read_tagging_samples(wh, max_length.get(wh))) for wh in [\"train\", \"dev\",", "= run_eval(model, vocab, samples[\"test\"], compute_loss=False) _log.info(\"test_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"])", "torch.no_grad(): runner.run(BucketIterator(samples, lambda s: len(s[\"words\"]), batch_size)) return runner.state[\"corr\"] / runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain def", "vocab, samples, device=\"cpu\", batch_size=16, compute_loss=True): runner = Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"])", "set\", wh) for s in tqdm(samples[wh], unit=\"sample\", leave=False): lms = torch.tensor(s[\"log_marginals\"]) assert lms.dim()", "scores.shape masked_scores = scores.masked_fill(~pptx_mask, -1e9) lengths = mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths - 1] =", "elif main_src not in load_src: raise ValueError(f\"{main_src} not found in load_src\") if artifacts_dir:", "100 * acc) _run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"train_pptx_loss: %.4f\",", "acc) _run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"]) if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda s: len(s[\"words\"]))", "2 if len(log_ntags) % 2: log_med = log_ntags[mid] else: max_ = max(log_ntags[mid -", "for wh in [\"train\", \"dev\"]: _log.info(\"Computing median number of tag sequences in chart", "= max(log_ntags[mid - 1], log_ntags[mid]) log_med = ( max_ + math.log( math.exp(log_ntags[mid -", "src == main_src _log.info(\"Main source is %s\", src) if artifacts_dir: path = artifacts_dir", "Path import math import os import pickle from einops import rearrange from gensim.models.keyedvectors", "parameters l2_coef = 1.0 # max number of epochs max_epoch = 10 #", "tag sequences in chart on %s set\", wh) log_ntags = [] for s", "%s\", load_samples_from) with open(load_samples_from, \"rb\") as f: samples = pickle.load(f) else: samples =", "_run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"dev_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss,", "s for s in samples[wh]) continue for i, s in enumerate(samples_[wh]): s[\"_id\"] =", "\"log_marginals pred_tags\".split(): s.pop(k) assert src == main_src _log.info(\"Main source is %s\", src) if", "EpochTimer, MeanReducer, ProgressBar, SumReducer from sacred import Experiment from sacred.observers import MongoObserver from", "masked_scores = scores.masked_fill(~pptx_mask, -1e9) lengths = mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths - 1] = False", "= mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths - 1] = False # exclude last position crf", "corpus = dict(portion=0.05) @ex.capture def run_eval(model, vocab, samples, device=\"cpu\", batch_size=16, compute_loss=True): runner =", "= 1e-5 # coefficient of L2 regularization against initial parameters l2_coef = 1.0", "%s set\", wh) log_ntags = [] for s in tqdm(samples_[wh], unit=\"sample\", leave=False): mask", "- 1], log_ntags[mid]) log_med = ( max_ + math.log( math.exp(log_ntags[mid - 1] -", "lms = samples[wh][i].get(\"log_marginals\", 0) pts = samples[wh][i].get(\"pred_tags\", []) lms = torch.tensor(lms, device=device) +", "log_ntags.sort() mid = len(log_ntags) // 2 if len(log_ntags) % 2: log_med = log_ntags[mid]", "Path(load_from) / \"vocab.yml\" _log.info(\"Loading %s vocabulary from %s\", src, path) vocab = load(path.read_text(encoding=\"utf8\"))", ") _log.info(\"Starting finetuning\") try: finetuner.run(trn_iter, max_epoch) except KeyboardInterrupt: _log.info(\"Interrupt detected, training will abort\")", "(ptags == tags).long().sum().item() state[\"btotal\"] = tags.numel() state[\"n_items\"] = words.numel() if compute_loss: state[\"scores\"] =", "os import pickle from einops import rearrange from gensim.models.keyedvectors import KeyedVectors from rnnr", "compute_loss: return masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf = LinearCRF(masked_scores.contiguous()) crf_z = LinearCRF(state[\"scores\"].contiguous()) pptx_loss", "= torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim() == 3 if \"pptx_mask\" in samples[wh][i]: old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"])", "for x in \"log_marginals pred_tags\".split()] for i, lms, pts in zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"]", "log_ntags = [] for s in tqdm(samples[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores", "len(log_ntags) // 2 if len(log_ntags) % 2: log_med = log_ntags[mid] else: max_ =", "torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def maybe_compute_loss(state): if not compute_loss: return masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf", "import apply_backspaces_and_linefeeds from text2array import BucketIterator, ShuffleIterator from tqdm import tqdm import torch", "LinearCRF(masked_scores.contiguous()) crf_z = LinearCRF(state[\"scores\"].contiguous()) pptx_loss = -crf.log_partitions().sum() + crf_z.log_partitions().sum() state[\"pptx_loss\"] = pptx_loss.item() state[\"size\"]", "sacred.observers import MongoObserver from sacred.utils import apply_backspaces_and_linefeeds from text2array import BucketIterator, ShuffleIterator from", "in runner.state: for i, pptx_mask in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist() else: zips", "/ len(srcs) for src in srcs} for src_i, src in enumerate(srcs): _log.info(\"Processing src", "load_src: raise ValueError(f\"{main_src} not found in load_src\") if artifacts_dir: artifacts_dir = Path(artifacts_dir) if", "== \"union\": runner.state[\"pptx_masks\"] = [] else: raise ValueError(f\"unknown value for combine: {combine}\") @runner.on(Event.BATCH)", "tqdm import torch from aatrn import compute_ambiguous_tag_pairs_mask from callbacks import compute_l2_loss, log_grads, log_stats,", "in src2ws): _log.warning(\"Too many srcs in src2ws, weights won't sum to one\") _log.info(\"Sources:", "run_eval(model, vocab, samples[\"test\"], compute_loss=False) _log.info(\"test_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"]) if", ":-1], ptags[:, :-1] state[\"bcorr\"] = (ptags == tags).long().sum().item() state[\"btotal\"] = tags.numel() state[\"n_items\"] =", "testrun(): seed = 12345 max_epoch = 2 corpus = dict(portion=0.05) @ex.capture def run_eval(model,", "0) pts = samples[wh][i].get(\"pred_tags\", []) lms = torch.tensor(lms, device=device) + src2ws[src] * samples_[wh][i][\"log_marginals\"]", "_log.info(\"Main source is %s\", src) if artifacts_dir: path = artifacts_dir / \"vocab.yml\" _log.info(\"Saving", "load_samples_from and combine == \"geom_mean\": for wh in [\"train\", \"dev\"]: _log.info(\"Computing the ambiguous", "2021 <NAME> from itertools import chain from pathlib import Path import math import", "source models from these directories and parameters {key: (load_from, load_params)} load_src = {}", "model from metadata %s\", src, path) model = load(path.read_text(encoding=\"utf8\")) path = Path(load_from) /", "artifacts_dir / \"vocab.yml\" _log.info(\"Saving vocabulary to %s\", path) path.write_text(dump(vocab), encoding=\"utf8\") path = artifacts_dir", "len(vocab[name]), name) _log.info(\"Extending %s vocabulary with target words\", src) vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found %d", "= True s[\"pptx_mask\"] = mask.tolist() for k in \"log_marginals pred_tags\".split(): s.pop(k) assert src", "!= vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have masking at test time\" model.eval() scores", "batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask = words !=", "%s\", wh, src ) else: _log.info( \"Computing PPTX ambiguous tag pairs mask for", "max(log_ntags[mid - 1], log_ntags[mid]) log_med = ( max_ + math.log( math.exp(log_ntags[mid - 1]", "db_name=db_name)) @ex.config def default(): # directory to save finetuning artifacts artifacts_dir = \"\"", "samples[wh][i][\"pptx_mask\"] = (old_mask | pptx_mask).tolist() if not load_samples_from and combine == \"geom_mean\": for", "# how to combine PPTX charts combine = \"union\" # whether to evaluate", "src, path) vocab = load(path.read_text(encoding=\"utf8\")) for name in vocab: _log.info(\"Found %d %s\", len(vocab[name]),", "len(srcs) for src in srcs} for src_i, src in enumerate(srcs): _log.info(\"Processing src %s", "as an artifact save_samples = False # load samples from this file (*.pkl)", "os.getenv(\"SACRED_DB_NAME\") if None not in (mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config def default(): #", "60} # load source models from these directories and parameters {key: (load_from, load_params)}", "max_length = {} if load_src is None: load_src = {\"src\": (\"artifacts\", \"model.pth\")} main_src", "to one\") _log.info(\"Sources: %s\", list(srcs)) _log.info(\"Weights: %s\", [src2ws[src] for src in srcs]) else:", "len(s[\"words\"]), batch_size)) for x in \"pptx_masks log_marginals pred_tags\".split(): assert x not in runner.state", "pptx_loss is not None _log.info(\"train_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state):", "@ex.automain def finetune( corpus, _log, _run, _rnd, max_length=None, load_src=None, main_src=None, load_src2ws_from=None, artifacts_dir=None, load_samples_from=None,", "combine = \"union\" @ex.named_config def prag_gmean(): l2_coef = 4.7e-3 lr = 2.6e-4 combine", "state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def maybe_compute_loss(state): if not compute_loss: return masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"],", "/ \"model.yml\" _log.info(\"Saving model metadata to %s\", path) path.write_text(dump(model), encoding=\"utf8\") if artifacts_dir and", "kv = KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from: _log.info(\"Skipping non-main src because samples are processed and", "assert mask.shape == lms.shape mask = mask.squeeze(0) for pts in s[\"pred_tags\"]: for j", "with torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda s: len(s[\"words\"]), batch_size)) for x in \"pptx_masks log_marginals pred_tags\".split():", "artifacts_dir / \"model.yml\" _log.info(\"Saving model metadata to %s\", path) path.write_text(dump(model), encoding=\"utf8\") if artifacts_dir", "not have masking at test time\" model.eval() scores = model(words) ptags = LinearCRF(scores).argmax()", "codes src_key_as_lang = False # the main source to start finetuning from main_src", "torch.no_grad(): model.word_emb = torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight, vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN), ) ) model.to(device) for", "tags.numel() state[\"n_items\"] = words.numel() if compute_loss: state[\"scores\"] = scores state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH)", "for j in range(1, len(pts)): mask[j - 1, pts[j], pts[j - 1]] =", "compute_loss=True): runner = Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for s in samples),", "mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have masking at test", "wh in [\"train\", \"dev\", \"test\"] } for wh in samples: n_toks = sum(len(s[\"words\"])", "# learning rate lr = 1e-5 # coefficient of L2 regularization against initial", "state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] = words.numel() n_toks = sum(len(s[\"words\"]) for s in samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner)", "len(samples_[wh]) if \"pptx_masks\" in runner.state: for i, pptx_mask in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] =", "masked_scores.contiguous(), mask[:, :-1] ) # exclude last position from mask crf_z = LinearCRF(scores.contiguous(),", "combine == \"geom_mean\": for wh in [\"train\", \"dev\"]: _log.info(\"Computing the ambiguous tag pairs", "artifacts_dir = Path(artifacts_dir) if load_samples_from: _log.info(\"Loading samples from %s\", load_samples_from) with open(load_samples_from, \"rb\")", "src_key_as_lang and corpus[\"lang\"] in srcs: _log.info(\"Removing %s from src parsers because it's the", "path = Path(load_from) / \"vocab.yml\" _log.info(\"Loading %s vocabulary from %s\", src, path) vocab", "for s in samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner) origin_params = {name: p.clone().detach() for name, p", "True s[\"pptx_mask\"] = mask.tolist() for k in \"log_marginals pred_tags\".split(): s.pop(k) assert src ==", "assert pptx_loss is not None _log.info(\"train_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def", "if max_length is None: max_length = {} if load_src is None: load_src =", "vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags = tags[:, :-1], ptags[:, :-1] state[\"bcorr\"] = (ptags == tags).long().sum().item()", "final samples as an artifact save_samples = False # load samples from this", "crf = LinearCRF( masked_scores.contiguous(), mask[:, :-1] ) # exclude last position from mask", "Runner() EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"]) for s in samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner) origin_params =", "+ crf_z.log_partitions().sum() state[\"pptx_loss\"] = pptx_loss.item() state[\"size\"] = masked_scores.size(0) with torch.no_grad(): runner.run(BucketIterator(samples, lambda s:", ":-1] state[\"bcorr\"] = (ptags == tags).long().sum().item() state[\"btotal\"] = tags.numel() state[\"n_items\"] = words.numel() if", "in \"log_marginals pred_tags\".split()] for i, lms, pts in zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"] = lms", "samples = { wh: list(read_tagging_samples(wh, max_length.get(wh))) for wh in [\"train\", \"dev\", \"test\"] }", "list(read_tagging_samples(wh, max_length.get(wh))) for wh in [\"train\", \"dev\", \"test\"] } for wh in samples:", "= pptx_loss.item() state[\"size\"] = masked_scores.size(0) with torch.no_grad(): runner.run(BucketIterator(samples, lambda s: len(s[\"words\"]), batch_size)) return", "samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if combine == \"geom_mean\": _log.info( \"Computing marginals and best tags", "mask = mask.squeeze(0) for pts in s[\"pred_tags\"]: for j in range(1, len(pts)): mask[j", "_log.info(\"Extending %s vocabulary with target words\", src) vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found %d words now\",", "= lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run, model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state): if not eval_on_train:", "-crf.log_partitions().sum() + crf_z.log_partitions().sum() state[\"pptx_loss\"] = pptx_loss.item() state[\"size\"] = masked_scores.size(0) with torch.no_grad(): runner.run(BucketIterator(samples, lambda", "k in \"log_marginals pred_tags\".split(): s.pop(k) assert src == main_src _log.info(\"Main source is %s\",", "train/dev/test samples with length greater than these numbers max_length = {\"train\": 60} #", "ShuffleIterator( BucketIterator(samples[\"train\"], lambda s: len(s[\"words\"]) // 10, batch_size), rng=_rnd ) _log.info(\"Starting finetuning\") try:", "tags.shape if (tags[:, 0] == vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags = tags[:, 1:], ptags[:, 1:]", "12345 max_epoch = 2 corpus = dict(portion=0.05) @ex.capture def run_eval(model, vocab, samples, device=\"cpu\",", "def eval_on_dev(state): _log.info(\"Evaluating on dev\") acc, pptx_loss = run_eval(model, vocab, samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\",", "batch size batch_size = 80 # learning rate lr = 1e-5 # coefficient", "vocabulary from %s\", src, path) vocab = load(path.read_text(encoding=\"utf8\")) for name in vocab: _log.info(\"Found", "nntags ntags -> slen (nntags ntags)\") lms = lms.log_softmax(dim=1) lms = rearrange( lms,", "ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config def default(): # directory to save finetuning artifacts artifacts_dir =", "ProgressBar(total=sum(len(s[\"words\"]) for s in samples), unit=\"tok\", leave=False).attach_on( runner ) if compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner)", "of L2 regularization against initial parameters l2_coef = 1.0 # max number of", "= state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) tags = torch.from_numpy(batch[\"tags\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN)", "LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask = compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"]", "* samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] = lms.tolist() samples[wh][i][\"pred_tags\"] = pts else: _log.info(\"Combining the ambiguous", "vocabulary with target words\", src) vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found %d words now\", len(vocab[\"words\"])) samples_", "False # load src2ws from this path load_src2ws_from = \"\" @ex.named_config def prag():", "[cpu, cuda] device = \"cuda\" if torch.cuda.is_available() else \"cpu\" # path to word", "s[\"_id\"] = i runner = Runner() runner.state[\"_ids\"] = [] if combine == \"geom_mean\":", "max_ + math.log( math.exp(log_ntags[mid - 1] - max_) + math.exp(log_ntags[mid] - max_) )", "{} # whether to treat keys in load_src as lang codes src_key_as_lang =", "run on [cpu, cuda] device = \"cuda\" if torch.cuda.is_available() else \"cpu\" # path", "= 4.7e-4 combine = \"geom_mean\" @ex.named_config def testrun(): seed = 12345 max_epoch =", "masked_scores.size(0) with torch.no_grad(): runner.run(BucketIterator(samples, lambda s: len(s[\"words\"]), batch_size)) return runner.state[\"corr\"] / runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\")", "thresh = 0.95 # batch size batch_size = 80 # learning rate lr", "0.062 lr = 4.7e-4 combine = \"geom_mean\" @ex.named_config def testrun(): seed = 12345", "text2array import BucketIterator, ShuffleIterator from tqdm import tqdm import torch from aatrn import", "\"geom_mean\": _log.info(\"Combining the marginals\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): lms = samples[wh][i].get(\"log_marginals\",", "samples[wh][i].get(\"log_marginals\", 0) pts = samples[wh][i].get(\"pred_tags\", []) lms = torch.tensor(lms, device=device) + src2ws[src] *", "word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\", combine=\"union\", thresh=0.95, batch_size=16, save_samples=False, lr=1e-5, l2_coef=1.0, eval_on_train=False, max_epoch=10, ): \"\"\"Finetune/adapt", "artifact save_samples = False # load samples from this file (*.pkl) load_samples_from =", "s: len(s[\"words\"]) // 10, batch_size), rng=_rnd ) _log.info(\"Starting finetuning\") try: finetuner.run(trn_iter, max_epoch) except", "from utils import extend_word_embedding ex = Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter = apply_backspaces_and_linefeeds # Setup", "[]}) elif combine == \"union\": runner.state[\"pptx_masks\"] = [] else: raise ValueError(f\"unknown value for", "@finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state): if not eval_on_train: return _log.info(\"Evaluating on train\") acc, pptx_loss =", "[], \"pred_tags\": []}) elif combine == \"union\": runner.state[\"pptx_masks\"] = [] else: raise ValueError(f\"unknown", "= samples[wh][i].get(\"log_marginals\", 0) pts = samples[wh][i].get(\"pred_tags\", []) lms = torch.tensor(lms, device=device) + src2ws[src]", "LinearCRF(scores).argmax() assert ptags.shape == tags.shape if (tags[:, 0] == vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags =", "src2ws[src] * samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] = lms.tolist() samples[wh][i][\"pred_tags\"] = pts else: _log.info(\"Combining the", "load_src if src != main_src] if src_key_as_lang and corpus[\"lang\"] in srcs: _log.info(\"Removing %s", "to evaluate on train set at every epoch end eval_on_train = False #", "pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores = model(words, mask)", "not compute_loss: return masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf = LinearCRF(masked_scores.contiguous()) crf_z = LinearCRF(state[\"scores\"].contiguous())", "if artifacts_dir and save_samples: path = artifacts_dir / \"samples.pkl\" _log.info(\"Saving samples to %s\",", "= lms.unsqueeze(0) mask = compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True) assert mask.shape == lms.shape mask =", "s: len(s[\"words\"])) trn_iter = ShuffleIterator( BucketIterator(samples[\"train\"], lambda s: len(s[\"words\"]) // 10, batch_size), rng=_rnd", "pptx_loss = -crf.log_partitions().sum() + crf_z.log_partitions().sum() state[\"pptx_loss\"] = pptx_loss.item() state[\"size\"] = masked_scores.size(0) with torch.no_grad():", "\"geom_mean\" @ex.named_config def prag_lopw(): l2_coef = 0.062 lr = 4.7e-4 combine = \"geom_mean\"", "tag pairs mask\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert", "tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if load_src2ws_from: _log.info(\"Loading src weights from %s\", load_src2ws_from) src2ws", "= 80 # learning rate lr = 1e-5 # coefficient of L2 regularization", "= LinearCRF(state[\"scores\"].contiguous()) pptx_loss = -crf.log_partitions().sum() + crf_z.log_partitions().sum() state[\"pptx_loss\"] = pptx_loss.item() state[\"size\"] = masked_scores.size(0)", "False # exclude last position crf = LinearCRF( masked_scores.contiguous(), mask[:, :-1] ) #", "== vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags = tags[:, 1:], ptags[:, 1:] if (tags[:, -1] ==", "def compute_pptx_ambiguous_tag_pairs_mask(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN)", "acc) _run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"dev_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\",", "\"log_marginals pred_tags\".split()] for i, lms, pts in zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"] = lms samples_[wh][i][\"pred_tags\"]", "probabilities lms = rearrange(lms, \"slen nntags ntags -> slen (nntags ntags)\") lms =", "srcs in src2ws, weights won't sum to one\") _log.info(\"Sources: %s\", list(srcs)) _log.info(\"Weights: %s\",", "torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid = len(log_ntags) // 2 if", "src, path) model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating %s extended word embedding layer\", src) assert model.word_emb.embedding_dim", "main_src = \"\" # device to run on [cpu, cuda] device = \"cuda\"", "step=state[\"n_iters\"]) state[\"dev_acc\"] = acc @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state): if state[\"epoch\"] != max_epoch: return _log.info(\"Evaluating", "= torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask = torch.zeros(1, 1, 1).bool() samples[wh][i][\"pptx_mask\"] = (old_mask | pptx_mask).tolist()", "mask\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim() ==", "sequences in chart: %.1e\", math.exp(log_med)) _log.info(\"Creating optimizer\") opt = torch.optim.Adam(model.parameters(), lr=lr) finetuner =", "s in enumerate(samples_[wh]): s[\"_id\"] = i runner = Runner() runner.state[\"_ids\"] = [] if", "combine = \"geom_mean\" @ex.named_config def testrun(): seed = 12345 max_epoch = 2 corpus", "pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim() == 3 if \"pptx_mask\" in samples[wh][i]: old_mask =", "maybe_compute_loss(state): if not compute_loss: return masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf = LinearCRF(masked_scores.contiguous()) crf_z", "if not eval_on_train: return _log.info(\"Evaluating on train\") acc, pptx_loss = run_eval(model, vocab, samples[\"train\"])", "if artifacts_dir: path = artifacts_dir / \"vocab.yml\" _log.info(\"Saving vocabulary to %s\", path) path.write_text(dump(vocab),", "model(words, mask) bsz, slen = words.shape assert scores.shape == (bsz, slen - 1,", "l2_coef = 4.7e-3 lr = 2.6e-4 combine = \"geom_mean\" @ex.named_config def prag_lopw(): l2_coef", "path = artifacts_dir / \"model.yml\" _log.info(\"Saving model metadata to %s\", path) path.write_text(dump(model), encoding=\"utf8\")", "nntags ntags\", ntags=len(vocab[\"tags\"]) ) lms = lms.unsqueeze(0) mask = compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True) assert", "and save_samples: path = artifacts_dir / \"samples.pkl\" _log.info(\"Saving samples to %s\", path) with", "for s in samples[wh]) continue for i, s in enumerate(samples_[wh]): s[\"_id\"] = i", "processed and loaded\") srcs = [] else: srcs = [src for src in", "else: samples = { wh: list(read_tagging_samples(wh, max_length.get(wh))) for wh in [\"train\", \"dev\", \"test\"]", "runner.run(BucketIterator(samples_[wh], lambda s: len(s[\"words\"]), batch_size)) for x in \"pptx_masks log_marginals pred_tags\".split(): assert x", "s.pop(k) assert src == main_src _log.info(\"Main source is %s\", src) if artifacts_dir: path", "= words.numel() if compute_loss: state[\"scores\"] = scores state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def maybe_compute_loss(state):", "ValueError(f\"unknown value for combine: {combine}\") @runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state): batch = state[\"batch\"].to_array() words =", "numbers max_length = {\"train\": 60} # load source models from these directories and", "tokens _log.info(\"Read %d %s samples and %d tokens\", len(samples[wh]), wh, n_toks) kv =", "if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda s: len(s[\"words\"])) trn_iter = ShuffleIterator( BucketIterator(samples[\"train\"],", "to save the final samples as an artifact save_samples = False # load", "\"pptx_masks\" in runner.state: for i, pptx_mask in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist() else:", "or len(runner.state[x]) == len(samples_[wh]) assert len(runner.state[\"_ids\"]) == len(samples_[wh]) if \"pptx_masks\" in runner.state: for", "80 # learning rate lr = 1e-5 # coefficient of L2 regularization against", "src, src_i + 1, len(srcs)) load_from, load_params = load_src[src] path = Path(load_from) /", "enumerate(srcs): _log.info(\"Processing src %s [%d/%d]\", src, src_i + 1, len(srcs)) load_from, load_params =", "== tags.shape if (tags[:, 0] == vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags = tags[:, 1:], ptags[:,", "pts = samples[wh][i].get(\"pred_tags\", []) lms = torch.tensor(lms, device=device) + src2ws[src] * samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist())", "(old_mask | pptx_mask).tolist() if not load_samples_from and combine == \"geom_mean\": for wh in", "BucketIterator(samples[\"train\"], lambda s: len(s[\"words\"]) // 10, batch_size), rng=_rnd ) _log.info(\"Starting finetuning\") try: finetuner.run(trn_iter,", "max_epoch = 2 corpus = dict(portion=0.05) @ex.capture def run_eval(model, vocab, samples, device=\"cpu\", batch_size=16,", "src because samples are processed and loaded\") srcs = [] else: srcs =", "combine: {combine}\") @runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) mask =", "leave=False): pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim() == 3 if \"pptx_mask\" in samples[wh][i]: old_mask", "ptags[:, :-1] state[\"bcorr\"] = (ptags == tags).long().sum().item() state[\"btotal\"] = tags.numel() state[\"n_items\"] = words.numel()", "total=sum(len(s[\"words\"]) for s in samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner) origin_params = {name: p.clone().detach() for name,", "if src != main_src] if src_key_as_lang and corpus[\"lang\"] in srcs: _log.info(\"Removing %s from", "will be set to zero\") if any(src not in srcs for src in", "in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist() else: zips = [runner.state[x] for x in", "artifacts_dir = \"\" # discard train/dev/test samples with length greater than these numbers", "# load src2ws from this path load_src2ws_from = \"\" @ex.named_config def prag(): l2_coef", "on %s set\", wh) log_ntags = [] for s in tqdm(samples_[wh], unit=\"sample\", leave=False):", "i runner = Runner() runner.state[\"_ids\"] = [] if combine == \"geom_mean\": runner.state.update({\"log_marginals\": [],", "-1e9) crf = LinearCRF(masked_scores.contiguous()) crf_z = LinearCRF(state[\"scores\"].contiguous()) pptx_loss = -crf.log_partitions().sum() + crf_z.log_partitions().sum() state[\"pptx_loss\"]", "(mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config def default(): # directory to save finetuning artifacts", "list(vocab.stoi(samples[wh])) for wh in samples} path = Path(load_from) / \"model.yml\" _log.info(\"Loading %s model", "= 2.6e-4 combine = \"geom_mean\" @ex.named_config def prag_lopw(): l2_coef = 0.062 lr =", "of tag sequences in chart: %.1e\", math.exp(log_med)) assert len(samples_[wh]) == len(samples[wh]) if combine", "in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim() == 3 if \"pptx_mask\"", "log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid = len(log_ntags) // 2 if len(log_ntags) % 2: log_med =", "in chart: %.1e\", math.exp(log_med)) _log.info(\"Creating optimizer\") opt = torch.optim.Adam(model.parameters(), lr=lr) finetuner = Runner()", "python # Copyright (c) 2021 <NAME> from itertools import chain from pathlib import", "\"geom_mean\": runner.state.update({\"log_marginals\": [], \"pred_tags\": []}) elif combine == \"union\": runner.state[\"pptx_masks\"] = [] else:", "save_state_dict(\"model\", model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda s: len(s[\"words\"])) trn_iter = ShuffleIterator( BucketIterator(samples[\"train\"], lambda s: len(s[\"words\"])", "def compute_loss(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask =", "loss.item()} state[\"n_items\"] = lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run, model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state): if", "vocab: _log.info(\"Found %d %s\", len(vocab[name]), name) _log.info(\"Extending %s vocabulary with target words\", src)", "unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid =", "_log.info(\"Read %d %s samples and %d tokens\", len(samples[wh]), wh, n_toks) kv = KeyedVectors.load_word2vec_format(word_emb_path)", ":-1] ) # exclude last position from mask crf_z = LinearCRF(scores.contiguous(), mask[:, :-1])", "from callbacks import compute_l2_loss, log_grads, log_stats, save_state_dict, update_params from crf import LinearCRF from", "KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from: _log.info(\"Skipping non-main src because samples are processed and loaded\") srcs", "this path load_src2ws_from = \"\" @ex.named_config def prag(): l2_coef = 0.1 lr =", "words = torch.from_numpy(batch[\"words\"]).to(device) pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores", "samples), unit=\"tok\", leave=False).attach_on( runner ) if compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def evaluate_batch(state): batch", "= words != vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores = model(words, mask) bsz, slen = words.shape", "%s vocabulary from %s\", src, path) vocab = load(path.read_text(encoding=\"utf8\")) for name in vocab:", "cumulative prob threshold thresh = 0.95 # batch size batch_size = 80 #", "ptags = tags[:, 1:], ptags[:, 1:] if (tags[:, -1] == vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags", "2 for s in samples[wh]) # don't count BOS/EOS tokens _log.info(\"Read %d %s", "torch.optim.Adam(model.parameters(), lr=lr) finetuner = Runner() EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"]) for s in samples[\"train\"]),", "x in \"log_marginals pred_tags\".split()] for i, lms, pts in zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"] =", "== lms.size(2) # Renormalise the marginal probabilities lms = rearrange(lms, \"slen nntags ntags", "leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid = len(log_ntags)", "corpus, _log, _run, _rnd, max_length=None, load_src=None, main_src=None, load_src2ws_from=None, artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\",", "_log.info(\"Sources: %s\", list(srcs)) _log.info(\"Weights: %s\", [src2ws[src] for src in srcs]) else: src2ws =", "target words\", src) vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found %d words now\", len(vocab[\"words\"])) samples_ = {wh:", "charts combine = \"union\" # whether to evaluate on train set at every", "[] for s in tqdm(samples_[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask,", "ptags = LinearCRF(scores).argmax() assert ptags.shape == tags.shape if (tags[:, 0] == vocab[\"tags\"].index(\"<s>\")).all(): tags,", "load(path.read_text(encoding=\"utf8\")) for name in vocab: _log.info(\"Found %d %s\", len(vocab[name]), name) _log.info(\"Extending %s vocabulary", "have masking at test time\" model.eval() scores = model(words) ptags = LinearCRF(scores).argmax() assert", "log_grads, log_stats, save_state_dict, update_params from crf import LinearCRF from ingredients.corpus import ing as", "sum(len(s[\"words\"]) - 2 for s in samples[wh]) # don't count BOS/EOS tokens _log.info(\"Read", "pptx_mask.shape == scores.shape masked_scores = scores.masked_fill(~pptx_mask, -1e9) lengths = mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths -", "- max_) + math.exp(log_ntags[mid] - max_) ) - math.log(2) ) _log.info(\"Median number of", "= [] else: srcs = [src for src in load_src if src !=", "state[\"n_items\"] = words.numel() n_toks = sum(len(s[\"words\"]) for s in samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if", "slen (nntags ntags)\") lms = lms.log_softmax(dim=1) lms = rearrange( lms, \"slen (nntags ntags)", "model.word_emb.weight, vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN), ) ) model.to(device) for wh in [\"train\", \"dev\"]: if", "device=\"cpu\", combine=\"union\", thresh=0.95, batch_size=16, save_samples=False, lr=1e-5, l2_coef=1.0, eval_on_train=False, max_epoch=10, ): \"\"\"Finetune/adapt a trained", "): \"\"\"Finetune/adapt a trained tagger with PPTX.\"\"\" if max_length is None: max_length =", "pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(), } state[\"extra_stats\"] = {\"loss\": loss.item()} state[\"n_items\"] = lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt),", "ntags) -> slen nntags ntags\", ntags=len(vocab[\"tags\"]) ) lms = lms.unsqueeze(0) mask = compute_ambiguous_tag_pairs_mask(lms,", "in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): lms = samples[wh][i].get(\"log_marginals\", 0) pts = samples[wh][i].get(\"pred_tags\", []) lms", "src2ws): _log.warning(\"Too many srcs in src2ws, weights won't sum to one\") _log.info(\"Sources: %s\",", "[\"train\", \"dev\"]: _log.info(\"Computing the ambiguous tag pairs mask on %s set\", wh) for", "not found in load_src\") if artifacts_dir: artifacts_dir = Path(artifacts_dir) if load_samples_from: _log.info(\"Loading samples", "from this path load_src2ws_from = \"\" @ex.named_config def prag(): l2_coef = 0.1 lr", "_log.info(\"Processing src %s [%d/%d]\", src, src_i + 1, len(srcs)) load_from, load_params = load_src[src]", "lms.size(1) == lms.size(2) # Renormalise the marginal probabilities lms = rearrange(lms, \"slen nntags", "= {name: p.clone().detach() for name, p in model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH) def", "torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores = model(words, mask) bsz, slen", "= Runner() EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"]) for s in samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner) origin_params", "in src2ws for src in srcs): _log.warning(\"Some srcs have no weights, will be", "against initial parameters l2_coef = 1.0 # max number of epochs max_epoch =", "pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state): _log.info(\"Evaluating on dev\") acc, pptx_loss =", "lambda s: len(s[\"words\"]) // 10, batch_size), rng=_rnd ) _log.info(\"Starting finetuning\") try: finetuner.run(trn_iter, max_epoch)", "= tags[:, 1:], ptags[:, 1:] if (tags[:, -1] == vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags =", "compute_l2_loss, log_grads, log_stats, save_state_dict, update_params from crf import LinearCRF from ingredients.corpus import ing", "_log.info( \"Computing marginals and best tags for %s set with source %s\", wh,", "load_src2ws_from=None, artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\", combine=\"union\", thresh=0.95, batch_size=16, save_samples=False, lr=1e-5, l2_coef=1.0, eval_on_train=False,", "len(vocab[\"tags\"])) assert pptx_mask.shape == scores.shape masked_scores = scores.masked_fill(~pptx_mask, -1e9) lengths = mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device),", "max_length = {\"train\": 60} # load source models from these directories and parameters", "[runner.state[x] for x in \"log_marginals pred_tags\".split()] for i, lms, pts in zip(runner.state[\"_ids\"], *zips):", "= torch.tensor(lms, device=device) + src2ws[src] * samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] = lms.tolist() samples[wh][i][\"pred_tags\"] =", ") model.to(device) for wh in [\"train\", \"dev\"]: if load_samples_from: assert all(\"pptx_mask\" in s", "# coefficient of L2 regularization against initial parameters l2_coef = 1.0 # max", "= state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must", "(*.pkl) load_samples_from = \"\" # how to combine PPTX charts combine = \"union\"", "torch.from_numpy(batch[\"tags\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have masking at", "== scores.shape masked_scores = scores.masked_fill(~pptx_mask, -1e9) lengths = mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths - 1]", "Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter = apply_backspaces_and_linefeeds # Setup mongodb observer mongo_url = os.getenv(\"SACRED_MONGO_URL\") db_name", "srcs for src in src2ws): _log.warning(\"Too many srcs in src2ws, weights won't sum", "wh in [\"train\", \"dev\"]: if load_samples_from: assert all(\"pptx_mask\" in s for s in", "+ 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask = compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] = words.numel()", "it's the tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if load_src2ws_from: _log.info(\"Loading src weights from %s\",", "the marginals\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): lms = samples[wh][i].get(\"log_marginals\", 0) pts", "= 12345 max_epoch = 2 corpus = dict(portion=0.05) @ex.capture def run_eval(model, vocab, samples,", "assert src == main_src _log.info(\"Main source is %s\", src) if artifacts_dir: path =", "= i runner = Runner() runner.state[\"_ids\"] = [] if combine == \"geom_mean\": runner.state.update({\"log_marginals\":", "* state[\"l2_loss\"] state[\"loss\"] = loss state[\"stats\"] = { \"pptx_loss\": pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(), }", "- 1]] = True s[\"pptx_mask\"] = mask.tolist() for k in \"log_marginals pred_tags\".split(): s.pop(k)", "zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist() else: zips = [runner.state[x] for x in \"log_marginals", "samples_ = {wh: list(vocab.stoi(samples[wh])) for wh in samples} path = Path(load_from) / \"model.yml\"", "runner.state.update({\"log_marginals\": [], \"pred_tags\": []}) elif combine == \"union\": runner.state[\"pptx_masks\"] = [] else: raise", "bsz, slen = words.shape assert scores.shape == (bsz, slen - 1, len(vocab[\"tags\"]), len(vocab[\"tags\"]))", "src2ws = {src: 1 / len(srcs) for src in srcs} for src_i, src", "model.eval() scores = model(words) ptags = LinearCRF(scores).argmax() assert ptags.shape == tags.shape if (tags[:,", "else: zips = [runner.state[x] for x in \"log_marginals pred_tags\".split()] for i, lms, pts", "tags = torch.from_numpy(batch[\"tags\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have", "path = artifacts_dir / \"vocab.yml\" _log.info(\"Saving vocabulary to %s\", path) path.write_text(dump(vocab), encoding=\"utf8\") path", "len(srcs)) load_from, load_params = load_src[src] path = Path(load_from) / \"vocab.yml\" _log.info(\"Loading %s vocabulary", "= \"geom_mean\" @ex.named_config def testrun(): seed = 12345 max_epoch = 2 corpus =", "source %s\", wh, src ) else: _log.info( \"Computing PPTX ambiguous tag pairs mask", "math.exp(log_med)) _log.info(\"Creating optimizer\") opt = torch.optim.Adam(model.parameters(), lr=lr) finetuner = Runner() EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\",", ") _log.info(\"Median number of tag sequences in chart: %.1e\", math.exp(log_med)) assert len(samples_[wh]) ==", "from mask pptx_loss = (-crf.log_partitions().sum() + crf_z.log_partitions().sum()) / bsz loss = pptx_loss +", "samples: n_toks = sum(len(s[\"words\"]) - 2 for s in samples[wh]) # don't count", "s in samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner) origin_params = {name: p.clone().detach() for name, p in", "= {wh: list(vocab.stoi(samples[wh])) for wh in samples} path = Path(load_from) / \"model.yml\" _log.info(\"Loading", "0.1 lr = 5.9e-5 combine = \"union\" @ex.named_config def prag_gmean(): l2_coef = 4.7e-3", "= torch.from_numpy(batch[\"words\"]).to(device) pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores =", "log_ntags[mid] else: max_ = max(log_ntags[mid - 1], log_ntags[mid]) log_med = ( max_ +", "False # load samples from this file (*.pkl) load_samples_from = \"\" # how", "pred_tags\".split(): s.pop(k) assert src == main_src _log.info(\"Main source is %s\", src) if artifacts_dir:", "== tags).long().sum().item() state[\"btotal\"] = tags.numel() state[\"n_items\"] = words.numel() if compute_loss: state[\"scores\"] = scores", "samples from this file (*.pkl) load_samples_from = \"\" # how to combine PPTX", "have masking at test time\" model.eval() scores = model(words) if combine == \"geom_mean\":", "pts[j - 1]] = True s[\"pptx_mask\"] = mask.tolist() for k in \"log_marginals pred_tags\".split():", "finetuner = Runner() EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"]) for s in samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner)", "sum(len(s[\"words\"]) for s in samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if combine == \"geom_mean\": _log.info( \"Computing", "== (bsz, slen - 1, len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert pptx_mask.shape == scores.shape masked_scores =", "= state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN)", "for i, pptx_mask in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist() else: zips = [runner.state[x]", "mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid = len(log_ntags) //", "/ \"model.yml\" _log.info(\"Loading %s model from metadata %s\", src, path) model = load(path.read_text(encoding=\"utf8\"))", "in word2vec format word_emb_path = \"wiki.en.vec\" # cumulative prob threshold thresh = 0.95", "@runner.on(Event.BATCH) def evaluate_batch(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) tags = torch.from_numpy(batch[\"tags\"]).to(device) mask", "encoding=\"utf8\") path = artifacts_dir / \"model.yml\" _log.info(\"Saving model metadata to %s\", path) path.write_text(dump(model),", "if src_key_as_lang and corpus[\"lang\"] in srcs: _log.info(\"Removing %s from src parsers because it's", "%s\", wh, src ) with torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda s: len(s[\"words\"]), batch_size)) for x", "- math.log(2) ) _log.info(\"Median number of tag sequences in chart: %.1e\", math.exp(log_med)) _log.info(\"Creating", "word embedding in word2vec format word_emb_path = \"wiki.en.vec\" # cumulative prob threshold thresh", "update_params from crf import LinearCRF from ingredients.corpus import ing as corpus_ing, read_tagging_samples from", "s in samples[wh]) # don't count BOS/EOS tokens _log.info(\"Read %d %s samples and", "have no weights, will be set to zero\") if any(src not in srcs", "{ wh: list(read_tagging_samples(wh, max_length.get(wh))) for wh in [\"train\", \"dev\", \"test\"] } for wh", "scores = model(words) ptags = LinearCRF(scores).argmax() assert ptags.shape == tags.shape if (tags[:, 0]", "in zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"] = lms samples_[wh][i][\"pred_tags\"] = pts if combine != \"geom_mean\":", "every epoch end eval_on_train = False # load src2ws from this path load_src2ws_from", "src) assert model.word_emb.embedding_dim == kv.vector_size with torch.no_grad(): model.word_emb = torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight, vocab[\"words\"],", "%d %s samples and %d tokens\", len(samples[wh]), wh, n_toks) kv = KeyedVectors.load_word2vec_format(word_emb_path) if", "return _log.info(\"Evaluating on train\") acc, pptx_loss = run_eval(model, vocab, samples[\"train\"]) _log.info(\"train_acc: %.1f%%\", 100", "and corpus[\"lang\"] in srcs: _log.info(\"Removing %s from src parsers because it's the tgt\",", "from src parsers because it's the tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if load_src2ws_from: _log.info(\"Loading", "thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] = words.numel() n_toks = sum(len(s[\"words\"]) for s in samples_[wh])", "unit=\"tok\").attach_on(runner) if combine == \"geom_mean\": _log.info( \"Computing marginals and best tags for %s", "\"\"\"Finetune/adapt a trained tagger with PPTX.\"\"\" if max_length is None: max_length = {}", "_log.info(\"Evaluating on train\") acc, pptx_loss = run_eval(model, vocab, samples[\"train\"]) _log.info(\"train_acc: %.1f%%\", 100 *", "from crf import LinearCRF from ingredients.corpus import ing as corpus_ing, read_tagging_samples from serialization", "main_src] if src_key_as_lang and corpus[\"lang\"] in srcs: _log.info(\"Removing %s from src parsers because", "any(src not in src2ws for src in srcs): _log.warning(\"Some srcs have no weights,", "ambiguous tag pairs mask on %s set\", wh) for s in tqdm(samples[wh], unit=\"sample\",", "crf_z.log_partitions().sum()) / bsz loss = pptx_loss + l2_coef * state[\"l2_loss\"] state[\"loss\"] = loss", "= torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid = len(log_ntags) // 2", "as f: pickle.dump(samples, f) samples = {wh: list(vocab.stoi(samples[wh])) for wh in samples} for", "!= main_src] if src_key_as_lang and corpus[\"lang\"] in srcs: _log.info(\"Removing %s from src parsers", "1e-5 # coefficient of L2 regularization against initial parameters l2_coef = 1.0 #", "load_samples_from: assert all(\"pptx_mask\" in s for s in samples[wh]) continue for i, s", "_log.info(\"Evaluating on dev\") acc, pptx_loss = run_eval(model, vocab, samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\", 100 *", "state[\"pptx_loss\"] = pptx_loss.item() state[\"size\"] = masked_scores.size(0) with torch.no_grad(): runner.run(BucketIterator(samples, lambda s: len(s[\"words\"]), batch_size))", "1:] if (tags[:, -1] == vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags = tags[:, :-1], ptags[:, :-1]", "runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain def finetune( corpus, _log, _run, _rnd, max_length=None, load_src=None, main_src=None, load_src2ws_from=None,", "%s samples and %d tokens\", len(samples[wh]), wh, n_toks) kv = KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from:", "with open(load_samples_from, \"rb\") as f: samples = pickle.load(f) else: samples = { wh:", "on train\") acc, pptx_loss = run_eval(model, vocab, samples[\"train\"]) _log.info(\"train_acc: %.1f%%\", 100 * acc)", "of tag sequences in chart on %s set\", wh) log_ntags = [] for", "for src in srcs} for src_i, src in enumerate(srcs): _log.info(\"Processing src %s [%d/%d]\",", "model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state): if not eval_on_train: return _log.info(\"Evaluating on train\") acc,", "save_samples = False # load samples from this file (*.pkl) load_samples_from = \"\"", "_run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"]) if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda s: len(s[\"words\"])) trn_iter", ") lms = lms.unsqueeze(0) mask = compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True) assert mask.shape == lms.shape", "{} if load_src is None: load_src = {\"src\": (\"artifacts\", \"model.pth\")} main_src = \"src\"", "{src: 1 / len(srcs) for src in srcs} for src_i, src in enumerate(srcs):", "metadata to %s\", path) path.write_text(dump(model), encoding=\"utf8\") if artifacts_dir and save_samples: path = artifacts_dir", "than these numbers max_length = {\"train\": 60} # load source models from these", "scores.masked_fill(~pptx_mask, -1e9) lengths = mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths - 1] = False # exclude", "# Copyright (c) 2021 <NAME> from itertools import chain from pathlib import Path", "= state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf = LinearCRF(masked_scores.contiguous()) crf_z = LinearCRF(state[\"scores\"].contiguous()) pptx_loss = -crf.log_partitions().sum() +", "== 3 if \"pptx_mask\" in samples[wh][i]: old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask = torch.zeros(1,", "load_from, load_params = load_src[src] path = Path(load_from) / \"vocab.yml\" _log.info(\"Loading %s vocabulary from", "_run, _rnd, max_length=None, load_src=None, main_src=None, load_src2ws_from=None, artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\", combine=\"union\", thresh=0.95,", "last position from mask crf_z = LinearCRF(scores.contiguous(), mask[:, :-1]) # exclude last position", "of epochs max_epoch = 10 # whether to save the final samples as", "BOS/EOS tokens _log.info(\"Read %d %s samples and %d tokens\", len(samples[wh]), wh, n_toks) kv", "weights from %s\", load_src2ws_from) src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src not in src2ws for", "%d words now\", len(vocab[\"words\"])) samples_ = {wh: list(vocab.stoi(samples[wh])) for wh in samples} path", "if load_samples_from: assert all(\"pptx_mask\" in s for s in samples[wh]) continue for i,", "import MongoObserver from sacred.utils import apply_backspaces_and_linefeeds from text2array import BucketIterator, ShuffleIterator from tqdm", "= words.shape assert scores.shape == (bsz, slen - 1, len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert pptx_mask.shape", "import rearrange from gensim.models.keyedvectors import KeyedVectors from rnnr import Event, Runner from rnnr.attachments", "marginals and best tags for %s set with source %s\", wh, src )", "if load_src2ws_from: _log.info(\"Loading src weights from %s\", load_src2ws_from) src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src", "from einops import rearrange from gensim.models.keyedvectors import KeyedVectors from rnnr import Event, Runner", "lr = 5.9e-5 combine = \"union\" @ex.named_config def prag_gmean(): l2_coef = 4.7e-3 lr", "open(load_samples_from, \"rb\") as f: samples = pickle.load(f) else: samples = { wh: list(read_tagging_samples(wh,", "for x in \"pptx_masks log_marginals pred_tags\".split(): assert x not in runner.state or len(runner.state[x])", "db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config def default(): # directory to save finetuning artifacts artifacts_dir", "MongoObserver from sacred.utils import apply_backspaces_and_linefeeds from text2array import BucketIterator, ShuffleIterator from tqdm import", "from serialization import dump, load from utils import extend_word_embedding ex = Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing])", "_log.info(\"Evaluating on test\") acc, _ = run_eval(model, vocab, samples[\"test\"], compute_loss=False) _log.info(\"test_acc: %.1f%%\", 100", "== kv.vector_size with torch.no_grad(): model.word_emb = torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight, vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN), )", "LinearCRF( masked_scores.contiguous(), mask[:, :-1] ) # exclude last position from mask crf_z =", "\"cuda\" if torch.cuda.is_available() else \"cpu\" # path to word embedding in word2vec format", "0.95 # batch size batch_size = 80 # learning rate lr = 1e-5", "coefficient of L2 regularization against initial parameters l2_coef = 1.0 # max number", "scores = model(words) if combine == \"geom_mean\": crf = LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log())", "in samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if combine == \"geom_mean\": _log.info( \"Computing marginals and best", "rearrange( lms, \"slen (nntags ntags) -> slen nntags ntags\", ntags=len(vocab[\"tags\"]) ) lms =", "samples} for wh in [\"train\", \"dev\"]: _log.info(\"Computing median number of tag sequences in", "path load_src2ws_from = \"\" @ex.named_config def prag(): l2_coef = 0.1 lr = 5.9e-5", "\"slen (nntags ntags) -> slen nntags ntags\", ntags=len(vocab[\"tags\"]) ) lms = lms.unsqueeze(0) mask", "import chain from pathlib import Path import math import os import pickle from", "in samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner) origin_params = {name: p.clone().detach() for name, p in model.named_parameters()}", "= artifacts_dir / \"model.yml\" _log.info(\"Saving model metadata to %s\", path) path.write_text(dump(model), encoding=\"utf8\") if", "pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"] = acc @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state): if state[\"epoch\"] !=", "optimizer\") opt = torch.optim.Adam(model.parameters(), lr=lr) finetuner = Runner() EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"]) for", "crf_z = LinearCRF(state[\"scores\"].contiguous()) pptx_loss = -crf.log_partitions().sum() + crf_z.log_partitions().sum() state[\"pptx_loss\"] = pptx_loss.item() state[\"size\"] =", "not load_samples_from and combine == \"geom_mean\": for wh in [\"train\", \"dev\"]: _log.info(\"Computing the", "%s model from metadata %s\", src, path) model = load(path.read_text(encoding=\"utf8\")) path = Path(load_from)", "math.log(2) ) _log.info(\"Median number of tag sequences in chart: %.1e\", math.exp(log_med)) assert len(samples_[wh])", "old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask = torch.zeros(1, 1, 1).bool() samples[wh][i][\"pptx_mask\"] = (old_mask |", "= load_src[src] path = Path(load_from) / \"vocab.yml\" _log.info(\"Loading %s vocabulary from %s\", src,", "# discard train/dev/test samples with length greater than these numbers max_length = {\"train\":", "log_grads(_run, model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state): if not eval_on_train: return _log.info(\"Evaluating on train\")", "\"\" # how to combine PPTX charts combine = \"union\" # whether to", "1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask = compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] = words.numel() n_toks", "old_mask = torch.zeros(1, 1, 1).bool() samples[wh][i][\"pptx_mask\"] = (old_mask | pptx_mask).tolist() if not load_samples_from", "= artifacts_dir / \"samples.pkl\" _log.info(\"Saving samples to %s\", path) with open(path, \"wb\") as", "a trained tagger with PPTX.\"\"\" if max_length is None: max_length = {} if", "device=\"cpu\", batch_size=16, compute_loss=True): runner = Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for s", "cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid = len(log_ntags) // 2 if len(log_ntags)", "artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda s: len(s[\"words\"])) trn_iter = ShuffleIterator( BucketIterator(samples[\"train\"], lambda", "sacred import Experiment from sacred.observers import MongoObserver from sacred.utils import apply_backspaces_and_linefeeds from text2array", "sum to one\") _log.info(\"Sources: %s\", list(srcs)) _log.info(\"Weights: %s\", [src2ws[src] for src in srcs])", "s in tqdm(samples_[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item())", "\"geom_mean\": for wh in [\"train\", \"dev\"]: _log.info(\"Computing the ambiguous tag pairs mask on", "in srcs]) else: src2ws = {src: 1 / len(srcs) for src in srcs}", ") _log.info(\"Median number of tag sequences in chart: %.1e\", math.exp(log_med)) _log.info(\"Creating optimizer\") opt", "= model(words, mask) bsz, slen = words.shape assert scores.shape == (bsz, slen -", "Runner from rnnr.attachments import EpochTimer, MeanReducer, ProgressBar, SumReducer from sacred import Experiment from", "%s [%d/%d]\", src, src_i + 1, len(srcs)) load_from, load_params = load_src[src] path =", "%s set\", wh) log_ntags = [] for s in tqdm(samples[wh], unit=\"sample\", leave=False): mask", "not in runner.state or len(runner.state[x]) == len(samples_[wh]) assert len(runner.state[\"_ids\"]) == len(samples_[wh]) if \"pptx_masks\"", "import math import os import pickle from einops import rearrange from gensim.models.keyedvectors import", "= load(path.read_text(encoding=\"utf8\")) path = Path(load_from) / load_params _log.info(\"Loading %s model parameters from %s\",", "\"dev\"]: _log.info(\"Computing the ambiguous tag pairs mask on %s set\", wh) for s", "pptx_loss = run_eval(model, vocab, samples[\"train\"]) _log.info(\"train_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"])", "= artifacts_dir / \"vocab.yml\" _log.info(\"Saving vocabulary to %s\", path) path.write_text(dump(vocab), encoding=\"utf8\") path =", "%s\", path) path.write_text(dump(vocab), encoding=\"utf8\") path = artifacts_dir / \"model.yml\" _log.info(\"Saving model metadata to", "name in vocab: _log.info(\"Found %d %s\", len(vocab[name]), name) _log.info(\"Extending %s vocabulary with target", "batch_size=16, compute_loss=True): runner = Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for s in", "trn_iter = ShuffleIterator( BucketIterator(samples[\"train\"], lambda s: len(s[\"words\"]) // 10, batch_size), rng=_rnd ) _log.info(\"Starting", "artifacts_dir: path = artifacts_dir / \"vocab.yml\" _log.info(\"Saving vocabulary to %s\", path) path.write_text(dump(vocab), encoding=\"utf8\")", "main_src = \"src\" elif main_src not in load_src: raise ValueError(f\"{main_src} not found in", "else: srcs = [src for src in load_src if src != main_src] if", "scores state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def maybe_compute_loss(state): if not compute_loss: return masked_scores =", "ptags.shape == tags.shape if (tags[:, 0] == vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags = tags[:, 1:],", "wh) log_ntags = [] for s in tqdm(samples[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0)", "compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True) assert mask.shape == lms.shape mask = mask.squeeze(0) for pts in", "samples[wh][i][\"pred_tags\"] = pts else: _log.info(\"Combining the ambiguous tag pairs mask\") for i in", "torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid = len(log_ntags) // 2 if len(log_ntags) % 2:", "= 2 corpus = dict(portion=0.05) @ex.capture def run_eval(model, vocab, samples, device=\"cpu\", batch_size=16, compute_loss=True):", "= \"cuda\" if torch.cuda.is_available() else \"cpu\" # path to word embedding in word2vec", "\"\" @ex.named_config def prag(): l2_coef = 0.1 lr = 5.9e-5 combine = \"union\"", "runner.run(BucketIterator(samples, lambda s: len(s[\"words\"]), batch_size)) return runner.state[\"corr\"] / runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain def finetune(", "= ( max_ + math.log( math.exp(log_ntags[mid - 1] - max_) + math.exp(log_ntags[mid] -", "test time\" model.eval() scores = model(words) if combine == \"geom_mean\": crf = LinearCRF(scores)", "model.to(device) for wh in [\"train\", \"dev\"]: if load_samples_from: assert all(\"pptx_mask\" in s for", "samples_[wh][i][\"log_marginals\"] = lms samples_[wh][i][\"pred_tags\"] = pts if combine != \"geom_mean\": _log.info(\"Computing median number", "lms = rearrange( lms, \"slen (nntags ntags) -> slen nntags ntags\", ntags=len(vocab[\"tags\"]) )", "scores = model(words, mask) bsz, slen = words.shape assert scores.shape == (bsz, slen", "src %s [%d/%d]\", src, src_i + 1, len(srcs)) load_from, load_params = load_src[src] path", "tokens\", len(samples[wh]), wh, n_toks) kv = KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from: _log.info(\"Skipping non-main src because", "ntags=len(vocab[\"tags\"]) ) lms = lms.unsqueeze(0) mask = compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True) assert mask.shape ==", "= \"\" # discard train/dev/test samples with length greater than these numbers max_length", "vocab, samples[\"test\"], compute_loss=False) _log.info(\"test_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"]) if artifacts_dir:", "assert pptx_loss is not None _log.info(\"dev_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"] =", "src ) else: _log.info( \"Computing PPTX ambiguous tag pairs mask for %s set", "= loss state[\"stats\"] = { \"pptx_loss\": pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(), } state[\"extra_stats\"] = {\"loss\":", "lengths = mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths - 1] = False # exclude last position", "log_med = ( max_ + math.log( math.exp(log_ntags[mid - 1] - max_) + math.exp(log_ntags[mid]", "pptx_mask = compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] = words.numel() n_toks = sum(len(s[\"words\"]) for", "chart on %s set\", wh) log_ntags = [] for s in tqdm(samples[wh], unit=\"sample\",", "= run_eval(model, vocab, samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"]) assert", "is %s\", src) if artifacts_dir: path = artifacts_dir / \"vocab.yml\" _log.info(\"Saving vocabulary to", "None: max_length = {} if load_src is None: load_src = {\"src\": (\"artifacts\", \"model.pth\")}", "\"pptx_loss\": pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(), } state[\"extra_stats\"] = {\"loss\": loss.item()} state[\"n_items\"] = lengths.sum().item() finetuner.on(Event.BATCH,", "rearrange(lms, \"slen nntags ntags -> slen (nntags ntags)\") lms = lms.log_softmax(dim=1) lms =", "srcs = [src for src in load_src if src != main_src] if src_key_as_lang", "vocab, samples[\"train\"]) _log.info(\"train_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is", "in tqdm(samples_[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort()", "= LinearCRF( masked_scores.contiguous(), mask[:, :-1] ) # exclude last position from mask crf_z", "artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\", combine=\"union\", thresh=0.95, batch_size=16, save_samples=False, lr=1e-5, l2_coef=1.0, eval_on_train=False, max_epoch=10,", "median number of tag sequences in chart on %s set\", wh) log_ntags =", "i, lms, pts in zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"] = lms samples_[wh][i][\"pred_tags\"] = pts if", "test\") acc, _ = run_eval(model, vocab, samples[\"test\"], compute_loss=False) _log.info(\"test_acc: %.1f%%\", 100 * acc)", "import os import pickle from einops import rearrange from gensim.models.keyedvectors import KeyedVectors from", "%s\", path) path.write_text(dump(model), encoding=\"utf8\") if artifacts_dir and save_samples: path = artifacts_dir / \"samples.pkl\"", "BucketIterator, ShuffleIterator from tqdm import tqdm import torch from aatrn import compute_ambiguous_tag_pairs_mask from", "device to run on [cpu, cuda] device = \"cuda\" if torch.cuda.is_available() else \"cpu\"", "[] for s in tqdm(samples[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask,", "lms.log_softmax(dim=1) lms = rearrange( lms, \"slen (nntags ntags) -> slen nntags ntags\", ntags=len(vocab[\"tags\"])", "return runner.state[\"corr\"] / runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain def finetune( corpus, _log, _run, _rnd, max_length=None,", "from itertools import chain from pathlib import Path import math import os import", "1, pts[j], pts[j - 1]] = True s[\"pptx_mask\"] = mask.tolist() for k in", "= mask.tolist() for k in \"log_marginals pred_tags\".split(): s.pop(k) assert src == main_src _log.info(\"Main", "treat keys in load_src as lang codes src_key_as_lang = False # the main", "in tqdm(samples[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort()", "trained tagger with PPTX.\"\"\" if max_length is None: max_length = {} if load_src", "mask.long().sum(dim=1) mask[torch.arange(bsz).to(mask.device), lengths - 1] = False # exclude last position crf =", "(load_from, load_params)} load_src = {} # whether to treat keys in load_src as", "None: load_src = {\"src\": (\"artifacts\", \"model.pth\")} main_src = \"src\" elif main_src not in", "#!/usr/bin/env python # Copyright (c) 2021 <NAME> from itertools import chain from pathlib", "train\") acc, pptx_loss = run_eval(model, vocab, samples[\"train\"]) _log.info(\"train_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"train_acc\",", "src != main_src] if src_key_as_lang and corpus[\"lang\"] in srcs: _log.info(\"Removing %s from src", "\"slen nntags ntags -> slen (nntags ntags)\") lms = lms.log_softmax(dim=1) lms = rearrange(", "= torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores = model(words, mask) bsz,", "compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH) def compute_loss(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) pptx_mask =", "kv, vocab[\"words\"].index(vocab.UNK_TOKEN), ) ) model.to(device) for wh in [\"train\", \"dev\"]: if load_samples_from: assert", "# whether to save the final samples as an artifact save_samples = False", "for s in tqdm(samples_[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9)", "load_params _log.info(\"Loading %s model parameters from %s\", src, path) model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating %s", "2 corpus = dict(portion=0.05) @ex.capture def run_eval(model, vocab, samples, device=\"cpu\", batch_size=16, compute_loss=True): runner", "\"model.yml\" _log.info(\"Loading %s model from metadata %s\", src, path) model = load(path.read_text(encoding=\"utf8\")) path", "load_src = {} # whether to treat keys in load_src as lang codes", "run_eval(model, vocab, samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss", "mask[j - 1, pts[j], pts[j - 1]] = True s[\"pptx_mask\"] = mask.tolist() for", "src_key_as_lang=False, device=\"cpu\", combine=\"union\", thresh=0.95, batch_size=16, save_samples=False, lr=1e-5, l2_coef=1.0, eval_on_train=False, max_epoch=10, ): \"\"\"Finetune/adapt a", "model metadata to %s\", path) path.write_text(dump(model), encoding=\"utf8\") if artifacts_dir and save_samples: path =", "%s set with source %s\", wh, src ) with torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda s:", "= pts else: _log.info(\"Combining the ambiguous tag pairs mask\") for i in tqdm(range(len(samples_[wh])),", "path) path.write_text(dump(model), encoding=\"utf8\") if artifacts_dir and save_samples: path = artifacts_dir / \"samples.pkl\" _log.info(\"Saving", "pts[j], pts[j - 1]] = True s[\"pptx_mask\"] = mask.tolist() for k in \"log_marginals", "%s\", src, path) vocab = load(path.read_text(encoding=\"utf8\")) for name in vocab: _log.info(\"Found %d %s\",", "rng=_rnd ) _log.info(\"Starting finetuning\") try: finetuner.run(trn_iter, max_epoch) except KeyboardInterrupt: _log.info(\"Interrupt detected, training will", "= \"\" @ex.named_config def prag(): l2_coef = 0.1 lr = 5.9e-5 combine =", "compute_loss(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) pptx_mask = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() mask = words", "seed = 12345 max_epoch = 2 corpus = dict(portion=0.05) @ex.capture def run_eval(model, vocab,", "= compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] = words.numel() n_toks = sum(len(s[\"words\"]) for s", "to zero\") if any(src not in srcs for src in src2ws): _log.warning(\"Too many", "os.getenv(\"SACRED_MONGO_URL\") db_name = os.getenv(\"SACRED_DB_NAME\") if None not in (mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config", "maybe_eval_on_train(state): if not eval_on_train: return _log.info(\"Evaluating on train\") acc, pptx_loss = run_eval(model, vocab,", "\"pptx_masks log_marginals pred_tags\".split(): assert x not in runner.state or len(runner.state[x]) == len(samples_[wh]) assert", "lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run, model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state): if not eval_on_train: return", "number of tag sequences in chart: %.1e\", math.exp(log_med)) _log.info(\"Creating optimizer\") opt = torch.optim.Adam(model.parameters(),", "pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"] = acc @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state): if state[\"epoch\"] != max_epoch: return", "how to combine PPTX charts combine = \"union\" # whether to evaluate on", "import tqdm import torch from aatrn import compute_ambiguous_tag_pairs_mask from callbacks import compute_l2_loss, log_grads,", "in \"pptx_masks log_marginals pred_tags\".split(): assert x not in runner.state or len(runner.state[x]) == len(samples_[wh])", "if any(src not in srcs for src in src2ws): _log.warning(\"Too many srcs in", "acc, pptx_loss = run_eval(model, vocab, samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"dev_acc\", acc,", "combine = \"union\" # whether to evaluate on train set at every epoch", "= sum(len(s[\"words\"]) - 2 for s in samples[wh]) # don't count BOS/EOS tokens", "model.word_emb.embedding_dim == kv.vector_size with torch.no_grad(): model.word_emb = torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight, vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN),", "src_i, src in enumerate(srcs): _log.info(\"Processing src %s [%d/%d]\", src, src_i + 1, len(srcs))", "= torch.from_numpy(batch[\"tags\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have masking", "in \"log_marginals pred_tags\".split(): s.pop(k) assert src == main_src _log.info(\"Main source is %s\", src)", "= LinearCRF(scores.contiguous(), mask[:, :-1]) # exclude last position from mask pptx_loss = (-crf.log_partitions().sum()", "load samples from this file (*.pkl) load_samples_from = \"\" # how to combine", "these numbers max_length = {\"train\": 60} # load source models from these directories", "0] == vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags = tags[:, 1:], ptags[:, 1:] if (tags[:, -1]", "artifacts_dir: artifacts_dir = Path(artifacts_dir) if load_samples_from: _log.info(\"Loading samples from %s\", load_samples_from) with open(load_samples_from,", "number of tag sequences in chart: %.1e\", math.exp(log_med)) assert len(samples_[wh]) == len(samples[wh]) if", "* acc) _run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"]) if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model, under=artifacts_dir)) samples[\"train\"].sort(key=lambda s:", "%s\", load_src2ws_from) src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src not in src2ws for src in", "pptx_mask in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist() else: zips = [runner.state[x] for x", "src2ws for src in srcs): _log.warning(\"Some srcs have no weights, will be set", "path) path.write_text(dump(vocab), encoding=\"utf8\") path = artifacts_dir / \"model.yml\" _log.info(\"Saving model metadata to %s\",", "{wh: list(vocab.stoi(samples[wh])) for wh in samples} path = Path(load_from) / \"model.yml\" _log.info(\"Loading %s", "_log.info(\"Combining the marginals\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): lms = samples[wh][i].get(\"log_marginals\", 0)", "def maybe_eval_on_test(state): if state[\"epoch\"] != max_epoch: return _log.info(\"Evaluating on test\") acc, _ =", "samples = {wh: list(vocab.stoi(samples[wh])) for wh in samples} for wh in [\"train\", \"dev\"]:", "in load_src if src != main_src] if src_key_as_lang and corpus[\"lang\"] in srcs: _log.info(\"Removing", "f: pickle.dump(samples, f) samples = {wh: list(vocab.stoi(samples[wh])) for wh in samples} for wh", "layer\", src) assert model.word_emb.embedding_dim == kv.vector_size with torch.no_grad(): model.word_emb = torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight,", "pptx_loss is not None _log.info(\"dev_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"] = acc", "keys in load_src as lang codes src_key_as_lang = False # the main source", "embedding in word2vec format word_emb_path = \"wiki.en.vec\" # cumulative prob threshold thresh =", "load_params)} load_src = {} # whether to treat keys in load_src as lang", "word2vec format word_emb_path = \"wiki.en.vec\" # cumulative prob threshold thresh = 0.95 #", "samples from %s\", load_samples_from) with open(load_samples_from, \"rb\") as f: samples = pickle.load(f) else:", "mask) bsz, slen = words.shape assert scores.shape == (bsz, slen - 1, len(vocab[\"tags\"]),", "= 10 # whether to save the final samples as an artifact save_samples", "finetuning\") try: finetuner.run(trn_iter, max_epoch) except KeyboardInterrupt: _log.info(\"Interrupt detected, training will abort\") else: return", "@finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state): if state[\"epoch\"] != max_epoch: return _log.info(\"Evaluating on test\") acc, _", "None _log.info(\"dev_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"] = acc @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state):", "main_src not in load_src: raise ValueError(f\"{main_src} not found in load_src\") if artifacts_dir: artifacts_dir", "in samples), unit=\"tok\", leave=False).attach_on( runner ) if compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def evaluate_batch(state):", "= 0.062 lr = 4.7e-4 combine = \"geom_mean\" @ex.named_config def testrun(): seed =", "_ = run_eval(model, vocab, samples[\"test\"], compute_loss=False) _log.info(\"test_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"test_acc\", acc,", "be set to zero\") if any(src not in srcs for src in src2ws):", "one\") _log.info(\"Sources: %s\", list(srcs)) _log.info(\"Weights: %s\", [src2ws[src] for src in srcs]) else: src2ws", "= masked_scores.size(0) with torch.no_grad(): runner.run(BucketIterator(samples, lambda s: len(s[\"words\"]), batch_size)) return runner.state[\"corr\"] / runner.state[\"total\"],", "with open(path, \"wb\") as f: pickle.dump(samples, f) samples = {wh: list(vocab.stoi(samples[wh])) for wh", "in [\"train\", \"dev\"]: _log.info(\"Computing the ambiguous tag pairs mask on %s set\", wh)", "state[\"bcorr\"] = (ptags == tags).long().sum().item() state[\"btotal\"] = tags.numel() state[\"n_items\"] = words.numel() if compute_loss:", "1] = False # exclude last position crf = LinearCRF( masked_scores.contiguous(), mask[:, :-1]", "MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def evaluate_batch(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) tags =", "mask.all(), \"must not have masking at test time\" model.eval() scores = model(words) ptags", "kv.vector_size with torch.no_grad(): model.word_emb = torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight, vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN), ) )", "tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim() == 3 if \"pptx_mask\" in", "load_src=None, main_src=None, load_src2ws_from=None, artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\", combine=\"union\", thresh=0.95, batch_size=16, save_samples=False, lr=1e-5,", "if (tags[:, -1] == vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags = tags[:, :-1], ptags[:, :-1] state[\"bcorr\"]", "position crf = LinearCRF( masked_scores.contiguous(), mask[:, :-1] ) # exclude last position from", "lms.dim() == 3 and lms.size(1) == lms.size(2) # Renormalise the marginal probabilities lms", "{ \"pptx_loss\": pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(), } state[\"extra_stats\"] = {\"loss\": loss.item()} state[\"n_items\"] = lengths.sum().item()", "lms = lms.log_softmax(dim=1) lms = rearrange( lms, \"slen (nntags ntags) -> slen nntags", "mask.squeeze(0) for pts in s[\"pred_tags\"]: for j in range(1, len(pts)): mask[j - 1,", "x in \"pptx_masks log_marginals pred_tags\".split(): assert x not in runner.state or len(runner.state[x]) ==", "False # the main source to start finetuning from main_src = \"\" #", "pts if combine != \"geom_mean\": _log.info(\"Computing median number of tag sequences in chart", "from ingredients.corpus import ing as corpus_ing, read_tagging_samples from serialization import dump, load from", "if load_samples_from: _log.info(\"Loading samples from %s\", load_samples_from) with open(load_samples_from, \"rb\") as f: samples", "math.exp(log_med)) assert len(samples_[wh]) == len(samples[wh]) if combine == \"geom_mean\": _log.info(\"Combining the marginals\") for", "combine == \"geom_mean\": crf = LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask =", "in tqdm(samples[wh], unit=\"sample\", leave=False): lms = torch.tensor(s[\"log_marginals\"]) assert lms.dim() == 3 and lms.size(1)", "-1] == vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags = tags[:, :-1], ptags[:, :-1] state[\"bcorr\"] = (ptags", "combine == \"geom_mean\": _log.info(\"Combining the marginals\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): lms", "pptx_mask.tolist() else: zips = [runner.state[x] for x in \"log_marginals pred_tags\".split()] for i, lms,", "_log.info(\"Saving samples to %s\", path) with open(path, \"wb\") as f: pickle.dump(samples, f) samples", "= LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask = compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist())", "if any(src not in src2ws for src in srcs): _log.warning(\"Some srcs have no", "pred_tags\".split()] for i, lms, pts in zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"] = lms samples_[wh][i][\"pred_tags\"] =", "+ math.exp(log_ntags[mid] - max_) ) - math.log(2) ) _log.info(\"Median number of tag sequences", "# Renormalise the marginal probabilities lms = rearrange(lms, \"slen nntags ntags -> slen", "save_samples: path = artifacts_dir / \"samples.pkl\" _log.info(\"Saving samples to %s\", path) with open(path,", "len(log_ntags) % 2: log_med = log_ntags[mid] else: max_ = max(log_ntags[mid - 1], log_ntags[mid])", "- 2 for s in samples[wh]) # don't count BOS/EOS tokens _log.info(\"Read %d", "threshold thresh = 0.95 # batch size batch_size = 80 # learning rate", "== main_src _log.info(\"Main source is %s\", src) if artifacts_dir: path = artifacts_dir /", "pairs mask for %s set with source %s\", wh, src ) with torch.no_grad():", "len(samples_[wh]) == len(samples[wh]) if combine == \"geom_mean\": _log.info(\"Combining the marginals\") for i in", "PPTX ambiguous tag pairs mask for %s set with source %s\", wh, src", "samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not", "leave=False).attach_on( runner ) if compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def evaluate_batch(state): batch = state[\"batch\"].to_array()", "%s set\", wh) for s in tqdm(samples[wh], unit=\"sample\", leave=False): lms = torch.tensor(s[\"log_marginals\"]) assert", "l2_coef = 0.1 lr = 5.9e-5 combine = \"union\" @ex.named_config def prag_gmean(): l2_coef", "s: len(s[\"words\"]), batch_size)) for x in \"pptx_masks log_marginals pred_tags\".split(): assert x not in", "max_length=None, load_src=None, main_src=None, load_src2ws_from=None, artifacts_dir=None, load_samples_from=None, word_emb_path=\"wiki.id.vec\", src_key_as_lang=False, device=\"cpu\", combine=\"union\", thresh=0.95, batch_size=16, save_samples=False,", "finetuning artifacts artifacts_dir = \"\" # discard train/dev/test samples with length greater than", "on test\") acc, _ = run_eval(model, vocab, samples[\"test\"], compute_loss=False) _log.info(\"test_acc: %.1f%%\", 100 *", "for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim() == 3", "pairs mask\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim()", "\"src\" elif main_src not in load_src: raise ValueError(f\"{main_src} not found in load_src\") if", "corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if load_src2ws_from: _log.info(\"Loading src weights from %s\", load_src2ws_from) src2ws =", "for src_i, src in enumerate(srcs): _log.info(\"Processing src %s [%d/%d]\", src, src_i + 1,", "for src in load_src if src != main_src] if src_key_as_lang and corpus[\"lang\"] in", "pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] = lms.tolist() samples[wh][i][\"pred_tags\"] = pts else: _log.info(\"Combining the ambiguous tag pairs", "samples[wh]) # don't count BOS/EOS tokens _log.info(\"Read %d %s samples and %d tokens\",", "j in range(1, len(pts)): mask[j - 1, pts[j], pts[j - 1]] = True", "= model(words) if combine == \"geom_mean\": crf = LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax())", "[] if combine == \"geom_mean\": runner.state.update({\"log_marginals\": [], \"pred_tags\": []}) elif combine == \"union\":", "rate lr = 1e-5 # coefficient of L2 regularization against initial parameters l2_coef", "# Setup mongodb observer mongo_url = os.getenv(\"SACRED_MONGO_URL\") db_name = os.getenv(\"SACRED_DB_NAME\") if None not", "model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating %s extended word embedding layer\", src) assert model.word_emb.embedding_dim == kv.vector_size", "to treat keys in load_src as lang codes src_key_as_lang = False # the", "\"l2_loss\": state[\"l2_loss\"].item(), } state[\"extra_stats\"] = {\"loss\": loss.item()} state[\"n_items\"] = lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run,", "weights, will be set to zero\") if any(src not in srcs for src", "i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): lms = samples[wh][i].get(\"log_marginals\", 0) pts = samples[wh][i].get(\"pred_tags\", [])", "parameters from %s\", src, path) model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating %s extended word embedding layer\",", "srcs: _log.info(\"Removing %s from src parsers because it's the tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src)", "samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist() else: zips = [runner.state[x] for x in \"log_marginals pred_tags\".split()] for", "combine == \"geom_mean\": _log.info( \"Computing marginals and best tags for %s set with", "don't count BOS/EOS tokens _log.info(\"Read %d %s samples and %d tokens\", len(samples[wh]), wh,", "state[\"size\"] = masked_scores.size(0) with torch.no_grad(): runner.run(BucketIterator(samples, lambda s: len(s[\"words\"]), batch_size)) return runner.state[\"corr\"] /", "samples = pickle.load(f) else: samples = { wh: list(read_tagging_samples(wh, max_length.get(wh))) for wh in", "\"wb\") as f: pickle.dump(samples, f) samples = {wh: list(vocab.stoi(samples[wh])) for wh in samples}", "for %s set with source %s\", wh, src ) with torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda", "%s\", src) if artifacts_dir: path = artifacts_dir / \"vocab.yml\" _log.info(\"Saving vocabulary to %s\",", "return _log.info(\"Evaluating on test\") acc, _ = run_eval(model, vocab, samples[\"test\"], compute_loss=False) _log.info(\"test_acc: %.1f%%\",", "mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) model.train() scores = model(words, mask) bsz, slen =", "\"geom_mean\": crf = LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask = compute_ambiguous_tag_pairs_mask(scores, thresh)", "\"pptx_mask\" in samples[wh][i]: old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask = torch.zeros(1, 1, 1).bool() samples[wh][i][\"pptx_mask\"]", "= \"geom_mean\" @ex.named_config def prag_lopw(): l2_coef = 0.062 lr = 4.7e-4 combine =", "path = Path(load_from) / load_params _log.info(\"Loading %s model parameters from %s\", src, path)", "_log.info(\"Creating %s extended word embedding layer\", src) assert model.word_emb.embedding_dim == kv.vector_size with torch.no_grad():", "tag sequences in chart: %.1e\", math.exp(log_med)) assert len(samples_[wh]) == len(samples[wh]) if combine ==", "runner.state[\"pptx_masks\"] = [] else: raise ValueError(f\"unknown value for combine: {combine}\") @runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state):", "for src in srcs]) else: src2ws = {src: 1 / len(srcs) for src", "extend_word_embedding( model.word_emb.weight, vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN), ) ) model.to(device) for wh in [\"train\", \"dev\"]:", "epoch end eval_on_train = False # load src2ws from this path load_src2ws_from =", "if \"pptx_masks\" in runner.state: for i, pptx_mask in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"] = pptx_mask.tolist()", "for pts in s[\"pred_tags\"]: for j in range(1, len(pts)): mask[j - 1, pts[j],", "tagger with PPTX.\"\"\" if max_length is None: max_length = {} if load_src is", "srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if load_src2ws_from: _log.info(\"Loading src weights from %s\", load_src2ws_from) src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\"))", "in s for s in samples[wh]) continue for i, s in enumerate(samples_[wh]): s[\"_id\"]", "@runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) mask = words !=", "len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert pptx_mask.shape == scores.shape masked_scores = scores.masked_fill(~pptx_mask, -1e9) lengths = mask.long().sum(dim=1)", "= torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def maybe_compute_loss(state): if not compute_loss: return masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9)", "max_length is None: max_length = {} if load_src is None: load_src = {\"src\":", ") with torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda s: len(s[\"words\"]), batch_size)) for x in \"pptx_masks log_marginals", "src in enumerate(srcs): _log.info(\"Processing src %s [%d/%d]\", src, src_i + 1, len(srcs)) load_from,", "under=artifacts_dir)) samples[\"train\"].sort(key=lambda s: len(s[\"words\"])) trn_iter = ShuffleIterator( BucketIterator(samples[\"train\"], lambda s: len(s[\"words\"]) // 10,", "else: _log.info( \"Computing PPTX ambiguous tag pairs mask for %s set with source", "origin_params = {name: p.clone().detach() for name, p in model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH)", "def prag(): l2_coef = 0.1 lr = 5.9e-5 combine = \"union\" @ex.named_config def", "10, batch_size), rng=_rnd ) _log.info(\"Starting finetuning\") try: finetuner.run(trn_iter, max_epoch) except KeyboardInterrupt: _log.info(\"Interrupt detected,", "else: src2ws = {src: 1 / len(srcs) for src in srcs} for src_i,", "acc, _ = run_eval(model, vocab, samples[\"test\"], compute_loss=False) _log.info(\"test_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"test_acc\",", "in src2ws, weights won't sum to one\") _log.info(\"Sources: %s\", list(srcs)) _log.info(\"Weights: %s\", [src2ws[src]", "len(s[\"words\"]) // 10, batch_size), rng=_rnd ) _log.info(\"Starting finetuning\") try: finetuner.run(trn_iter, max_epoch) except KeyboardInterrupt:", "tags, ptags = tags[:, :-1], ptags[:, :-1] state[\"bcorr\"] = (ptags == tags).long().sum().item() state[\"btotal\"]", "train set at every epoch end eval_on_train = False # load src2ws from", "def prag_lopw(): l2_coef = 0.062 lr = 4.7e-4 combine = \"geom_mean\" @ex.named_config def", "= 0.1 lr = 5.9e-5 combine = \"union\" @ex.named_config def prag_gmean(): l2_coef =", "[src for src in load_src if src != main_src] if src_key_as_lang and corpus[\"lang\"]", "lambda s: len(s[\"words\"]), batch_size)) for x in \"pptx_masks log_marginals pred_tags\".split(): assert x not", "pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state): _log.info(\"Evaluating on dev\") acc, pptx_loss = run_eval(model, vocab,", "pptx_mask.dim() == 3 if \"pptx_mask\" in samples[wh][i]: old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask =", "_log.info(\"dev_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"dev_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None", "and parameters {key: (load_from, load_params)} load_src = {} # whether to treat keys", "= {\"train\": 60} # load source models from these directories and parameters {key:", "the final samples as an artifact save_samples = False # load samples from", "\"model.pth\")} main_src = \"src\" elif main_src not in load_src: raise ValueError(f\"{main_src} not found", "marginal probabilities lms = rearrange(lms, \"slen nntags ntags -> slen (nntags ntags)\") lms", "if (tags[:, 0] == vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags = tags[:, 1:], ptags[:, 1:] if", "load_src[src] path = Path(load_from) / \"vocab.yml\" _log.info(\"Loading %s vocabulary from %s\", src, path)", "tags, ptags = tags[:, 1:], ptags[:, 1:] if (tags[:, -1] == vocab[\"tags\"].index(\"</s>\")).all(): tags,", "pptx_mask).tolist() if not load_samples_from and combine == \"geom_mean\": for wh in [\"train\", \"dev\"]:", "won't sum to one\") _log.info(\"Sources: %s\", list(srcs)) _log.info(\"Weights: %s\", [src2ws[src] for src in", "src weights from %s\", load_src2ws_from) src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src not in src2ws", "in range(1, len(pts)): mask[j - 1, pts[j], pts[j - 1]] = True s[\"pptx_mask\"]", "\"Computing PPTX ambiguous tag pairs mask for %s set with source %s\", wh,", "and loaded\") srcs = [] else: srcs = [src for src in load_src", "(bsz, slen - 1, len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert pptx_mask.shape == scores.shape masked_scores = scores.masked_fill(~pptx_mask,", "mask.shape == lms.shape mask = mask.squeeze(0) for pts in s[\"pred_tags\"]: for j in", "len(s[\"words\"])) trn_iter = ShuffleIterator( BucketIterator(samples[\"train\"], lambda s: len(s[\"words\"]) // 10, batch_size), rng=_rnd )", "= LinearCRF(scores).argmax() assert ptags.shape == tags.shape if (tags[:, 0] == vocab[\"tags\"].index(\"<s>\")).all(): tags, ptags", "lms samples_[wh][i][\"pred_tags\"] = pts if combine != \"geom_mean\": _log.info(\"Computing median number of tag", ") - math.log(2) ) _log.info(\"Median number of tag sequences in chart: %.1e\", math.exp(log_med))", "not eval_on_train: return _log.info(\"Evaluating on train\") acc, pptx_loss = run_eval(model, vocab, samples[\"train\"]) _log.info(\"train_acc:", "src in srcs} for src_i, src in enumerate(srcs): _log.info(\"Processing src %s [%d/%d]\", src,", "in load_src: raise ValueError(f\"{main_src} not found in load_src\") if artifacts_dir: artifacts_dir = Path(artifacts_dir)", "on %s set\", wh) for s in tqdm(samples[wh], unit=\"sample\", leave=False): lms = torch.tensor(s[\"log_marginals\"])", "from tqdm import tqdm import torch from aatrn import compute_ambiguous_tag_pairs_mask from callbacks import", "= load(path.read_text(encoding=\"utf8\")) for name in vocab: _log.info(\"Found %d %s\", len(vocab[name]), name) _log.info(\"Extending %s", "set with source %s\", wh, src ) with torch.no_grad(): runner.run(BucketIterator(samples_[wh], lambda s: len(s[\"words\"]),", "import Event, Runner from rnnr.attachments import EpochTimer, MeanReducer, ProgressBar, SumReducer from sacred import", "words = torch.from_numpy(batch[\"words\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have", "if combine != \"geom_mean\": _log.info(\"Computing median number of tag sequences in chart on", "from text2array import BucketIterator, ShuffleIterator from tqdm import tqdm import torch from aatrn", "/ runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain def finetune( corpus, _log, _run, _rnd, max_length=None, load_src=None, main_src=None,", "tag pairs mask on %s set\", wh) for s in tqdm(samples[wh], unit=\"sample\", leave=False):", "src) if artifacts_dir: path = artifacts_dir / \"vocab.yml\" _log.info(\"Saving vocabulary to %s\", path)", "if not compute_loss: return masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf = LinearCRF(masked_scores.contiguous()) crf_z =", "load_src2ws_from: _log.info(\"Loading src weights from %s\", load_src2ws_from) src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src not", "== len(samples_[wh]) assert len(runner.state[\"_ids\"]) == len(samples_[wh]) if \"pptx_masks\" in runner.state: for i, pptx_mask", "assert x not in runner.state or len(runner.state[x]) == len(samples_[wh]) assert len(runner.state[\"_ids\"]) == len(samples_[wh])", "_log.info(\"Median number of tag sequences in chart: %.1e\", math.exp(log_med)) assert len(samples_[wh]) == len(samples[wh])", "wh) for s in tqdm(samples[wh], unit=\"sample\", leave=False): lms = torch.tensor(s[\"log_marginals\"]) assert lms.dim() ==", "= tags[:, :-1], ptags[:, :-1] state[\"bcorr\"] = (ptags == tags).long().sum().item() state[\"btotal\"] = tags.numel()", "no weights, will be set to zero\") if any(src not in srcs for", "%s from src parsers because it's the tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if load_src2ws_from:", "= lms.tolist() samples[wh][i][\"pred_tags\"] = pts else: _log.info(\"Combining the ambiguous tag pairs mask\") for", "4.7e-3 lr = 2.6e-4 combine = \"geom_mean\" @ex.named_config def prag_lopw(): l2_coef = 0.062", "at test time\" model.eval() scores = model(words) if combine == \"geom_mean\": crf =", "at every epoch end eval_on_train = False # load src2ws from this path", "@finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state): _log.info(\"Evaluating on dev\") acc, pptx_loss = run_eval(model, vocab, samples[\"dev\"]) _log.info(\"dev_acc:", "= sum(len(s[\"words\"]) for s in samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if combine == \"geom_mean\": _log.info(", "\"geom_mean\": _log.info( \"Computing marginals and best tags for %s set with source %s\",", "list(vocab.stoi(samples[wh])) for wh in samples} for wh in [\"train\", \"dev\"]: _log.info(\"Computing median number", "%s\", [src2ws[src] for src in srcs]) else: src2ws = {src: 1 / len(srcs)", "not have masking at test time\" model.eval() scores = model(words) if combine ==", "torch from aatrn import compute_ambiguous_tag_pairs_mask from callbacks import compute_l2_loss, log_grads, log_stats, save_state_dict, update_params", "test time\" model.eval() scores = model(words) ptags = LinearCRF(scores).argmax() assert ptags.shape == tags.shape", "= torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid = len(log_ntags) // 2 if len(log_ntags) %", "compute_loss=False) _log.info(\"test_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"]) if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\",", "found in load_src\") if artifacts_dir: artifacts_dir = Path(artifacts_dir) if load_samples_from: _log.info(\"Loading samples from", "itertools import chain from pathlib import Path import math import os import pickle", "(nntags ntags)\") lms = lms.log_softmax(dim=1) lms = rearrange( lms, \"slen (nntags ntags) ->", "+ l2_coef * state[\"l2_loss\"] state[\"loss\"] = loss state[\"stats\"] = { \"pptx_loss\": pptx_loss.item(), \"l2_loss\":", "_run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"train_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss,", "the main source to start finetuning from main_src = \"\" # device to", "_log.warning(\"Some srcs have no weights, will be set to zero\") if any(src not", "torch.tensor(s[\"log_marginals\"]) assert lms.dim() == 3 and lms.size(1) == lms.size(2) # Renormalise the marginal", "runner.state[\"corr\"] / runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain def finetune( corpus, _log, _run, _rnd, max_length=None, load_src=None,", "torch.tensor(samples_[wh][i][\"pptx_mask\"]) assert pptx_mask.dim() == 3 if \"pptx_mask\" in samples[wh][i]: old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"]) else:", "_log.info(\"Computing median number of tag sequences in chart on %s set\", wh) log_ntags", "save_samples=False, lr=1e-5, l2_coef=1.0, eval_on_train=False, max_epoch=10, ): \"\"\"Finetune/adapt a trained tagger with PPTX.\"\"\" if", "chain from pathlib import Path import math import os import pickle from einops", "n_toks = sum(len(s[\"words\"]) - 2 for s in samples[wh]) # don't count BOS/EOS", "in load_src as lang codes src_key_as_lang = False # the main source to", "crf = LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask = compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask)", "step=state[\"n_iters\"]) assert pptx_loss is not None _log.info(\"train_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED)", ") # exclude last position from mask crf_z = LinearCRF(scores.contiguous(), mask[:, :-1]) #", "as corpus_ing, read_tagging_samples from serialization import dump, load from utils import extend_word_embedding ex", "ValueError(f\"{main_src} not found in load_src\") if artifacts_dir: artifacts_dir = Path(artifacts_dir) if load_samples_from: _log.info(\"Loading", "rearrange from gensim.models.keyedvectors import KeyedVectors from rnnr import Event, Runner from rnnr.attachments import", "wh in samples: n_toks = sum(len(s[\"words\"]) - 2 for s in samples[wh]) #", "_log.info(\"Loading %s vocabulary from %s\", src, path) vocab = load(path.read_text(encoding=\"utf8\")) for name in", "path) model = load(path.read_text(encoding=\"utf8\")) path = Path(load_from) / load_params _log.info(\"Loading %s model parameters", "range(1, len(pts)): mask[j - 1, pts[j], pts[j - 1]] = True s[\"pptx_mask\"] =", "enumerate(samples_[wh]): s[\"_id\"] = i runner = Runner() runner.state[\"_ids\"] = [] if combine ==", "in enumerate(samples_[wh]): s[\"_id\"] = i runner = Runner() runner.state[\"_ids\"] = [] if combine", "Runner() runner.state[\"_ids\"] = [] if combine == \"geom_mean\": runner.state.update({\"log_marginals\": [], \"pred_tags\": []}) elif", "lr=lr) finetuner = Runner() EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"]) for s in samples[\"train\"]), unit=\"tok\"", "l2_coef = 0.062 lr = 4.7e-4 combine = \"geom_mean\" @ex.named_config def testrun(): seed", "LinearCRF(scores.contiguous(), mask[:, :-1]) # exclude last position from mask pptx_loss = (-crf.log_partitions().sum() +", "state[\"stats\"] = { \"pptx_loss\": pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(), } state[\"extra_stats\"] = {\"loss\": loss.item()} state[\"n_items\"]", "pickle from einops import rearrange from gensim.models.keyedvectors import KeyedVectors from rnnr import Event,", "list(srcs)) _log.info(\"Weights: %s\", [src2ws[src] for src in srcs]) else: src2ws = {src: 1", "discard train/dev/test samples with length greater than these numbers max_length = {\"train\": 60}", "== \"geom_mean\": runner.state.update({\"log_marginals\": [], \"pred_tags\": []}) elif combine == \"union\": runner.state[\"pptx_masks\"] = []", "== \"geom_mean\": _log.info( \"Computing marginals and best tags for %s set with source", "path) with open(path, \"wb\") as f: pickle.dump(samples, f) samples = {wh: list(vocab.stoi(samples[wh])) for", "if combine == \"geom_mean\": runner.state.update({\"log_marginals\": [], \"pred_tags\": []}) elif combine == \"union\": runner.state[\"pptx_masks\"]", "{name: p.clone().detach() for name, p in model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH) def compute_loss(state):", "from metadata %s\", src, path) model = load(path.read_text(encoding=\"utf8\")) path = Path(load_from) / load_params", "def testrun(): seed = 12345 max_epoch = 2 corpus = dict(portion=0.05) @ex.capture def", "samples with length greater than these numbers max_length = {\"train\": 60} # load", "on train set at every epoch end eval_on_train = False # load src2ws", "last position crf = LinearCRF( masked_scores.contiguous(), mask[:, :-1] ) # exclude last position", "# load source models from these directories and parameters {key: (load_from, load_params)} load_src", "s: len(s[\"words\"]), batch_size)) return runner.state[\"corr\"] / runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain def finetune( corpus, _log,", "= False # load src2ws from this path load_src2ws_from = \"\" @ex.named_config def", "load_samples_from) with open(load_samples_from, \"rb\") as f: samples = pickle.load(f) else: samples = {", "sequences in chart: %.1e\", math.exp(log_med)) assert len(samples_[wh]) == len(samples[wh]) if combine == \"geom_mean\":", "= lms samples_[wh][i][\"pred_tags\"] = pts if combine != \"geom_mean\": _log.info(\"Computing median number of", "any(src not in srcs for src in src2ws): _log.warning(\"Too many srcs in src2ws,", "combine PPTX charts combine = \"union\" # whether to evaluate on train set", "l2_coef = 1.0 # max number of epochs max_epoch = 10 # whether", "from rnnr import Event, Runner from rnnr.attachments import EpochTimer, MeanReducer, ProgressBar, SumReducer from", "= {\"src\": (\"artifacts\", \"model.pth\")} main_src = \"src\" elif main_src not in load_src: raise", "pptx_loss.item() state[\"size\"] = masked_scores.size(0) with torch.no_grad(): runner.run(BucketIterator(samples, lambda s: len(s[\"words\"]), batch_size)) return runner.state[\"corr\"]", "= torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight, vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN), ) ) model.to(device) for wh in", "= rearrange(lms, \"slen nntags ntags -> slen (nntags ntags)\") lms = lms.log_softmax(dim=1) lms", "1, len(srcs)) load_from, load_params = load_src[src] path = Path(load_from) / \"vocab.yml\" _log.info(\"Loading %s", "\"cpu\")) _log.info(\"Creating %s extended word embedding layer\", src) assert model.word_emb.embedding_dim == kv.vector_size with", "\"geom_mean\" @ex.named_config def testrun(): seed = 12345 max_epoch = 2 corpus = dict(portion=0.05)", "path) vocab = load(path.read_text(encoding=\"utf8\")) for name in vocab: _log.info(\"Found %d %s\", len(vocab[name]), name)", "assert all(\"pptx_mask\" in s for s in samples[wh]) continue for i, s in", "== \"geom_mean\": for wh in [\"train\", \"dev\"]: _log.info(\"Computing the ambiguous tag pairs mask", "lms.unsqueeze(0) mask = compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True) assert mask.shape == lms.shape mask = mask.squeeze(0)", "[src2ws[src] for src in srcs]) else: src2ws = {src: 1 / len(srcs) for", "import EpochTimer, MeanReducer, ProgressBar, SumReducer from sacred import Experiment from sacred.observers import MongoObserver", "torch.from_numpy(batch[\"words\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have masking at", "assert scores.shape == (bsz, slen - 1, len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert pptx_mask.shape == scores.shape", "%.1e\", math.exp(log_med)) _log.info(\"Creating optimizer\") opt = torch.optim.Adam(model.parameters(), lr=lr) finetuner = Runner() EpochTimer().attach_on(finetuner) ProgressBar(", "model(words) ptags = LinearCRF(scores).argmax() assert ptags.shape == tags.shape if (tags[:, 0] == vocab[\"tags\"].index(\"<s>\")).all():", "src parsers because it's the tgt\", corpus[\"lang\"]) srcs.remove(corpus[\"lang\"]) srcs.append(main_src) if load_src2ws_from: _log.info(\"Loading src", "to start finetuning from main_src = \"\" # device to run on [cpu,", "_log.info(\"Found %d words now\", len(vocab[\"words\"])) samples_ = {wh: list(vocab.stoi(samples[wh])) for wh in samples}", "from aatrn import compute_ambiguous_tag_pairs_mask from callbacks import compute_l2_loss, log_grads, log_stats, save_state_dict, update_params from", "source to start finetuning from main_src = \"\" # device to run on", "# max number of epochs max_epoch = 10 # whether to save the", "# exclude last position crf = LinearCRF( masked_scores.contiguous(), mask[:, :-1] ) # exclude", "%.1f%%\", 100 * acc) _run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"]) if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED, save_state_dict(\"model\", model, under=artifacts_dir))", "dict(portion=0.05) @ex.capture def run_eval(model, vocab, samples, device=\"cpu\", batch_size=16, compute_loss=True): runner = Runner() SumReducer(\"corr\",", "= Path(load_from) / \"vocab.yml\" _log.info(\"Loading %s vocabulary from %s\", src, path) vocab =", "_log.info(\"Median number of tag sequences in chart: %.1e\", math.exp(log_med)) _log.info(\"Creating optimizer\") opt =", "= [] else: raise ValueError(f\"unknown value for combine: {combine}\") @runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state): batch", "greater than these numbers max_length = {\"train\": 60} # load source models from", "value for combine: {combine}\") @runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device)", "ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if combine == \"geom_mean\": _log.info( \"Computing marginals and best tags for", "log_ntags = [] for s in tqdm(samples_[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores", "src2ws, weights won't sum to one\") _log.info(\"Sources: %s\", list(srcs)) _log.info(\"Weights: %s\", [src2ws[src] for", "samples as an artifact save_samples = False # load samples from this file", "if len(log_ntags) % 2: log_med = log_ntags[mid] else: max_ = max(log_ntags[mid - 1],", "ex.captured_out_filter = apply_backspaces_and_linefeeds # Setup mongodb observer mongo_url = os.getenv(\"SACRED_MONGO_URL\") db_name = os.getenv(\"SACRED_DB_NAME\")", "state[\"n_items\"] = words.numel() if compute_loss: state[\"scores\"] = scores state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def", "is None: max_length = {} if load_src is None: load_src = {\"src\": (\"artifacts\",", "s[\"pred_tags\"]: for j in range(1, len(pts)): mask[j - 1, pts[j], pts[j - 1]]", "not in load_src: raise ValueError(f\"{main_src} not found in load_src\") if artifacts_dir: artifacts_dir =", "state[\"btotal\"] = tags.numel() state[\"n_items\"] = words.numel() if compute_loss: state[\"scores\"] = scores state[\"pptx_mask\"] =", "not in (mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config def default(): # directory to save", "1).bool() samples[wh][i][\"pptx_mask\"] = (old_mask | pptx_mask).tolist() if not load_samples_from and combine == \"geom_mean\":", "%s\", src, path) model = load(path.read_text(encoding=\"utf8\")) path = Path(load_from) / load_params _log.info(\"Loading %s", "exclude last position crf = LinearCRF( masked_scores.contiguous(), mask[:, :-1] ) # exclude last", "= {} if load_src is None: load_src = {\"src\": (\"artifacts\", \"model.pth\")} main_src =", "len(vocab[\"words\"])) samples_ = {wh: list(vocab.stoi(samples[wh])) for wh in samples} path = Path(load_from) /", "s in samples_[wh]) ProgressBar(total=n_toks, unit=\"tok\").attach_on(runner) if combine == \"geom_mean\": _log.info( \"Computing marginals and", "crf = LinearCRF(masked_scores.contiguous()) crf_z = LinearCRF(state[\"scores\"].contiguous()) pptx_loss = -crf.log_partitions().sum() + crf_z.log_partitions().sum() state[\"pptx_loss\"] =", "combine = \"geom_mean\" @ex.named_config def prag_lopw(): l2_coef = 0.062 lr = 4.7e-4 combine", "\"union\" # whether to evaluate on train set at every epoch end eval_on_train", "!= \"geom_mean\": _log.info(\"Computing median number of tag sequences in chart on %s set\",", "# batch size batch_size = 80 # learning rate lr = 1e-5 #", "batch_size = 80 # learning rate lr = 1e-5 # coefficient of L2", "in (mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config def default(): # directory to save finetuning", "is not None _log.info(\"train_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state): _log.info(\"Evaluating", "from %s\", src, path) vocab = load(path.read_text(encoding=\"utf8\")) for name in vocab: _log.info(\"Found %d", "metadata %s\", src, path) model = load(path.read_text(encoding=\"utf8\")) path = Path(load_from) / load_params _log.info(\"Loading", "samples, device=\"cpu\", batch_size=16, compute_loss=True): runner = Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for", "runner.state.get(\"mean_pptx_loss\") @ex.automain def finetune( corpus, _log, _run, _rnd, max_length=None, load_src=None, main_src=None, load_src2ws_from=None, artifacts_dir=None,", "dump, load from utils import extend_word_embedding ex = Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter = apply_backspaces_and_linefeeds", "- 1] = False # exclude last position crf = LinearCRF( masked_scores.contiguous(), mask[:,", "[]) lms = torch.tensor(lms, device=device) + src2ws[src] * samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] = lms.tolist()", "compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] = words.numel() n_toks = sum(len(s[\"words\"]) for s in", "lang codes src_key_as_lang = False # the main source to start finetuning from", "LinearCRF(state[\"scores\"].contiguous()) pptx_loss = -crf.log_partitions().sum() + crf_z.log_partitions().sum() state[\"pptx_loss\"] = pptx_loss.item() state[\"size\"] = masked_scores.size(0) with", "encoding=\"utf8\") if artifacts_dir and save_samples: path = artifacts_dir / \"samples.pkl\" _log.info(\"Saving samples to", "{\"src\": (\"artifacts\", \"model.pth\")} main_src = \"src\" elif main_src not in load_src: raise ValueError(f\"{main_src}", "- 1] - max_) + math.exp(log_ntags[mid] - max_) ) - math.log(2) ) _log.info(\"Median", "lr = 4.7e-4 combine = \"geom_mean\" @ex.named_config def testrun(): seed = 12345 max_epoch", "_log.info(\"train_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state): _log.info(\"Evaluating on dev\") acc,", "file (*.pkl) load_samples_from = \"\" # how to combine PPTX charts combine =", "[\"train\", \"dev\"]: if load_samples_from: assert all(\"pptx_mask\" in s for s in samples[wh]) continue", "else: pptx_mask = compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] = words.numel() n_toks = sum(len(s[\"words\"])", "lms = lms.unsqueeze(0) mask = compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True) assert mask.shape == lms.shape mask", "samples[wh][i]: old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask = torch.zeros(1, 1, 1).bool() samples[wh][i][\"pptx_mask\"] = (old_mask", "/ load_params _log.info(\"Loading %s model parameters from %s\", src, path) model.load_state_dict(torch.load(path, \"cpu\")) _log.info(\"Creating", "value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def evaluate_batch(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) tags = torch.from_numpy(batch[\"tags\"]).to(device)", "set\", wh) log_ntags = [] for s in tqdm(samples_[wh], unit=\"sample\", leave=False): mask =", "db_name = os.getenv(\"SACRED_DB_NAME\") if None not in (mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config def", "the marginal probabilities lms = rearrange(lms, \"slen nntags ntags -> slen (nntags ntags)\")", "= Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for s in samples), unit=\"tok\", leave=False).attach_on(", "samples[wh][i][\"log_marginals\"] = lms.tolist() samples[wh][i][\"pred_tags\"] = pts else: _log.info(\"Combining the ambiguous tag pairs mask\")", "for s in tqdm(samples[wh], unit=\"sample\", leave=False): lms = torch.tensor(s[\"log_marginals\"]) assert lms.dim() == 3", "not in src2ws for src in srcs): _log.warning(\"Some srcs have no weights, will", "_log.info(\"Loading src weights from %s\", load_src2ws_from) src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src not in", "load_src2ws_from) src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if any(src not in src2ws for src in srcs):", "-1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid = len(log_ntags) // 2 if len(log_ntags) % 2: log_med", "for k in \"log_marginals pred_tags\".split(): s.pop(k) assert src == main_src _log.info(\"Main source is", "max_epoch = 10 # whether to save the final samples as an artifact", "as lang codes src_key_as_lang = False # the main source to start finetuning", "src_key_as_lang = False # the main source to start finetuning from main_src =", "zero\") if any(src not in srcs for src in src2ws): _log.warning(\"Too many srcs", "opt = torch.optim.Adam(model.parameters(), lr=lr) finetuner = Runner() EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"]) for s", "%.4f\", pptx_loss) _run.log_scalar(\"dev_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) state[\"dev_acc\"] = acc @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state): if state[\"epoch\"]", "<NAME> from itertools import chain from pathlib import Path import math import os", "torch.zeros(1, 1, 1).bool() samples[wh][i][\"pptx_mask\"] = (old_mask | pptx_mask).tolist() if not load_samples_from and combine", "ambiguous tag pairs mask for %s set with source %s\", wh, src )", "path.write_text(dump(model), encoding=\"utf8\") if artifacts_dir and save_samples: path = artifacts_dir / \"samples.pkl\" _log.info(\"Saving samples", "parameters {key: (load_from, load_params)} load_src = {} # whether to treat keys in", "vocab[\"words\"], kv, vocab[\"words\"].index(vocab.UNK_TOKEN), ) ) model.to(device) for wh in [\"train\", \"dev\"]: if load_samples_from:", "state[\"extra_stats\"] = {\"loss\": loss.item()} state[\"n_items\"] = lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run, model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED)", "import ing as corpus_ing, read_tagging_samples from serialization import dump, load from utils import", "on %s set\", wh) log_ntags = [] for s in tqdm(samples[wh], unit=\"sample\", leave=False):", "raise ValueError(f\"{main_src} not found in load_src\") if artifacts_dir: artifacts_dir = Path(artifacts_dir) if load_samples_from:", "src in load_src if src != main_src] if src_key_as_lang and corpus[\"lang\"] in srcs:", "load src2ws from this path load_src2ws_from = \"\" @ex.named_config def prag(): l2_coef =", "if torch.cuda.is_available() else \"cpu\" # path to word embedding in word2vec format word_emb_path", "= False # exclude last position crf = LinearCRF( masked_scores.contiguous(), mask[:, :-1] )", "torch.cuda.is_available() else \"cpu\" # path to word embedding in word2vec format word_emb_path =", "load_samples_from: _log.info(\"Loading samples from %s\", load_samples_from) with open(load_samples_from, \"rb\") as f: samples =", "because samples are processed and loaded\") srcs = [] else: srcs = [src", "for combine: {combine}\") @runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state): batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) mask", "_log.info(\"Skipping non-main src because samples are processed and loaded\") srcs = [] else:", "whether to treat keys in load_src as lang codes src_key_as_lang = False #", "run_eval(model, vocab, samples[\"train\"]) _log.info(\"train_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss", "= Experiment(\"xduft-pptx-tagging-testrun\", ingredients=[corpus_ing]) ex.captured_out_filter = apply_backspaces_and_linefeeds # Setup mongodb observer mongo_url = os.getenv(\"SACRED_MONGO_URL\")", "== len(samples_[wh]) if \"pptx_masks\" in runner.state: for i, pptx_mask in zip(runner.state[\"_ids\"], runner.state[\"pptx_masks\"]): samples_[wh][i][\"pptx_mask\"]", "\"must not have masking at test time\" model.eval() scores = model(words) if combine", "unit=\"sample\", leave=False): lms = samples[wh][i].get(\"log_marginals\", 0) pts = samples[wh][i].get(\"pred_tags\", []) lms = torch.tensor(lms,", "open(path, \"wb\") as f: pickle.dump(samples, f) samples = {wh: list(vocab.stoi(samples[wh])) for wh in", "tqdm(samples_[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid", "for wh in [\"train\", \"dev\", \"test\"] } for wh in samples: n_toks =", "ambiguous tag pairs mask\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): pptx_mask = torch.tensor(samples_[wh][i][\"pptx_mask\"])", "= {src: 1 / len(srcs) for src in srcs} for src_i, src in", "set\", wh) log_ntags = [] for s in tqdm(samples[wh], unit=\"sample\", leave=False): mask =", "torch.tensor(lms, device=device) + src2ws[src] * samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] = lms.tolist() samples[wh][i][\"pred_tags\"] = pts", "None not in (mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name)) @ex.config def default(): # directory to", "= log_ntags[mid] else: max_ = max(log_ntags[mid - 1], log_ntags[mid]) log_med = ( max_", "device = \"cuda\" if torch.cuda.is_available() else \"cpu\" # path to word embedding in", "+ src2ws[src] * samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] = lms.tolist() samples[wh][i][\"pred_tags\"] = pts else: _log.info(\"Combining", "p in model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH) def compute_loss(state): batch = state[\"batch\"].to_array() words", "lms = torch.tensor(lms, device=device) + src2ws[src] * samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] = lms.tolist() samples[wh][i][\"pred_tags\"]", "s in samples[wh]) continue for i, s in enumerate(samples_[wh]): s[\"_id\"] = i runner", "if \"pptx_mask\" in samples[wh][i]: old_mask = torch.tensor(samples[wh][i][\"pptx_mask\"]) else: old_mask = torch.zeros(1, 1, 1).bool()", "[] else: srcs = [src for src in load_src if src != main_src]", "state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask = compute_ambiguous_tag_pairs_mask(scores, thresh) state[\"pptx_masks\"].extend(pptx_mask) state[\"_ids\"].extend(batch[\"_id\"].tolist()) state[\"n_items\"] =", "@ex.capture def run_eval(model, vocab, samples, device=\"cpu\", batch_size=16, compute_loss=True): runner = Runner() SumReducer(\"corr\", value=\"bcorr\").attach_on(runner)", "s[\"pptx_mask\"] = mask.tolist() for k in \"log_marginals pred_tags\".split(): s.pop(k) assert src == main_src", "= { wh: list(read_tagging_samples(wh, max_length.get(wh))) for wh in [\"train\", \"dev\", \"test\"] } for", "combine=\"union\", thresh=0.95, batch_size=16, save_samples=False, lr=1e-5, l2_coef=1.0, eval_on_train=False, max_epoch=10, ): \"\"\"Finetune/adapt a trained tagger", "Renormalise the marginal probabilities lms = rearrange(lms, \"slen nntags ntags -> slen (nntags", "srcs.append(main_src) if load_src2ws_from: _log.info(\"Loading src weights from %s\", load_src2ws_from) src2ws = load(Path(load_src2ws_from).read_text(encoding=\"utf8\")) if", "import LinearCRF from ingredients.corpus import ing as corpus_ing, read_tagging_samples from serialization import dump,", "= (ptags == tags).long().sum().item() state[\"btotal\"] = tags.numel() state[\"n_items\"] = words.numel() if compute_loss: state[\"scores\"]", "eval_on_dev(state): _log.info(\"Evaluating on dev\") acc, pptx_loss = run_eval(model, vocab, samples[\"dev\"]) _log.info(\"dev_acc: %.1f%%\", 100", "try: finetuner.run(trn_iter, max_epoch) except KeyboardInterrupt: _log.info(\"Interrupt detected, training will abort\") else: return finetuner.state.get(\"dev_acc\")", "%.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state): _log.info(\"Evaluating on dev\") acc, pptx_loss", "callbacks import compute_l2_loss, log_grads, log_stats, save_state_dict, update_params from crf import LinearCRF from ingredients.corpus", "for wh in samples} path = Path(load_from) / \"model.yml\" _log.info(\"Loading %s model from", "EpochTimer().attach_on(finetuner) ProgressBar( stats=\"stats\", total=sum(len(s[\"words\"]) for s in samples[\"train\"]), unit=\"tok\" ).attach_on(finetuner) origin_params = {name:", "prag_gmean(): l2_coef = 4.7e-3 lr = 2.6e-4 combine = \"geom_mean\" @ex.named_config def prag_lopw():", "samples[\"test\"], compute_loss=False) _log.info(\"test_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"test_acc\", acc, step=state[\"n_iters\"]) if artifacts_dir: finetuner.on(Event.EPOCH_FINISHED,", "== \"geom_mean\": _log.info(\"Combining the marginals\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): lms =", "exclude last position from mask crf_z = LinearCRF(scores.contiguous(), mask[:, :-1]) # exclude last", "*zips): samples_[wh][i][\"log_marginals\"] = lms samples_[wh][i][\"pred_tags\"] = pts if combine != \"geom_mean\": _log.info(\"Computing median", "zip(runner.state[\"_ids\"], *zips): samples_[wh][i][\"log_marginals\"] = lms samples_[wh][i][\"pred_tags\"] = pts if combine != \"geom_mean\": _log.info(\"Computing", "samples_[wh][i][\"log_marginals\"] pts.append(samples_[wh][i][\"pred_tags\"].tolist()) samples[wh][i][\"log_marginals\"] = lms.tolist() samples[wh][i][\"pred_tags\"] = pts else: _log.info(\"Combining the ambiguous tag", "combine == \"union\": runner.state[\"pptx_masks\"] = [] else: raise ValueError(f\"unknown value for combine: {combine}\")", "<reponame>kmkurn/uxtspwsd<filename>run_pptx_tagging.py #!/usr/bin/env python # Copyright (c) 2021 <NAME> from itertools import chain from", "pts else: _log.info(\"Combining the ambiguous tag pairs mask\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\",", "%d tokens\", len(samples[wh]), wh, n_toks) kv = KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from: _log.info(\"Skipping non-main src", "l2_coef * state[\"l2_loss\"] state[\"loss\"] = loss state[\"stats\"] = { \"pptx_loss\": pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(),", "= { \"pptx_loss\": pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(), } state[\"extra_stats\"] = {\"loss\": loss.item()} state[\"n_items\"] =", "None _log.info(\"train_pptx_loss: %.4f\", pptx_loss) _run.log_scalar(\"train_pptx_loss\", pptx_loss, step=state[\"n_iters\"]) @finetuner.on(Event.EPOCH_FINISHED) def eval_on_dev(state): _log.info(\"Evaluating on dev\")", "[\"words\"]) _log.info(\"Found %d words now\", len(vocab[\"words\"])) samples_ = {wh: list(vocab.stoi(samples[wh])) for wh in", "math.log( math.exp(log_ntags[mid - 1] - max_) + math.exp(log_ntags[mid] - max_) ) - math.log(2)", "= False # load samples from this file (*.pkl) load_samples_from = \"\" #", "(\"artifacts\", \"model.pth\")} main_src = \"src\" elif main_src not in load_src: raise ValueError(f\"{main_src} not", "for src in srcs): _log.warning(\"Some srcs have no weights, will be set to", "s in tqdm(samples[wh], unit=\"sample\", leave=False): lms = torch.tensor(s[\"log_marginals\"]) assert lms.dim() == 3 and", "runner = Runner() runner.state[\"_ids\"] = [] if combine == \"geom_mean\": runner.state.update({\"log_marginals\": [], \"pred_tags\":", "to run on [cpu, cuda] device = \"cuda\" if torch.cuda.is_available() else \"cpu\" #", "wh in samples} for wh in [\"train\", \"dev\"]: _log.info(\"Computing median number of tag", "%s vocabulary with target words\", src) vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found %d words now\", len(vocab[\"words\"]))", "if compute_loss: state[\"scores\"] = scores state[\"pptx_mask\"] = torch.from_numpy(batch[\"pptx_mask\"]).to(device).bool() @runner.on(Event.BATCH) def maybe_compute_loss(state): if not", "tqdm(samples[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9) log_ntags.append(LinearCRF(cnt_scores).log_partitions().item()) log_ntags.sort() mid", "loss state[\"stats\"] = { \"pptx_loss\": pptx_loss.item(), \"l2_loss\": state[\"l2_loss\"].item(), } state[\"extra_stats\"] = {\"loss\": loss.item()}", "l2_coef=1.0, eval_on_train=False, max_epoch=10, ): \"\"\"Finetune/adapt a trained tagger with PPTX.\"\"\" if max_length is", "tags[:, 1:], ptags[:, 1:] if (tags[:, -1] == vocab[\"tags\"].index(\"</s>\")).all(): tags, ptags = tags[:,", "samples and %d tokens\", len(samples[wh]), wh, n_toks) kv = KeyedVectors.load_word2vec_format(word_emb_path) if load_samples_from: _log.info(\"Skipping", "in vocab: _log.info(\"Found %d %s\", len(vocab[name]), name) _log.info(\"Extending %s vocabulary with target words\",", "# exclude last position from mask crf_z = LinearCRF(scores.contiguous(), mask[:, :-1]) # exclude", ").attach_on(finetuner) origin_params = {name: p.clone().detach() for name, p in model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params))", "crf_z.log_partitions().sum() state[\"pptx_loss\"] = pptx_loss.item() state[\"size\"] = masked_scores.size(0) with torch.no_grad(): runner.run(BucketIterator(samples, lambda s: len(s[\"words\"]),", "load_samples_from: _log.info(\"Skipping non-main src because samples are processed and loaded\") srcs = []", "_log.info(\"Starting finetuning\") try: finetuner.run(trn_iter, max_epoch) except KeyboardInterrupt: _log.info(\"Interrupt detected, training will abort\") else:", "def maybe_eval_on_train(state): if not eval_on_train: return _log.info(\"Evaluating on train\") acc, pptx_loss = run_eval(model,", "= 5.9e-5 combine = \"union\" @ex.named_config def prag_gmean(): l2_coef = 4.7e-3 lr =", "max_epoch: return _log.info(\"Evaluating on test\") acc, _ = run_eval(model, vocab, samples[\"test\"], compute_loss=False) _log.info(\"test_acc:", "position from mask pptx_loss = (-crf.log_partitions().sum() + crf_z.log_partitions().sum()) / bsz loss = pptx_loss", "set at every epoch end eval_on_train = False # load src2ws from this", "assert model.word_emb.embedding_dim == kv.vector_size with torch.no_grad(): model.word_emb = torch.nn.Embedding.from_pretrained( extend_word_embedding( model.word_emb.weight, vocab[\"words\"], kv,", "samples[\"train\"]) _log.info(\"train_acc: %.1f%%\", 100 * acc) _run.log_scalar(\"train_acc\", acc, step=state[\"n_iters\"]) assert pptx_loss is not", "// 2 if len(log_ntags) % 2: log_med = log_ntags[mid] else: max_ = max(log_ntags[mid", "= words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(), \"must not have masking at test time\"", "%.1e\", math.exp(log_med)) assert len(samples_[wh]) == len(samples[wh]) if combine == \"geom_mean\": _log.info(\"Combining the marginals\")", "else: raise ValueError(f\"unknown value for combine: {combine}\") @runner.on(Event.BATCH) def compute_pptx_ambiguous_tag_pairs_mask(state): batch = state[\"batch\"].to_array()", "mask[torch.arange(bsz).to(mask.device), lengths - 1] = False # exclude last position crf = LinearCRF(", "for wh in [\"train\", \"dev\"]: _log.info(\"Computing the ambiguous tag pairs mask on %s", "src_i + 1, len(srcs)) load_from, load_params = load_src[src] path = Path(load_from) / \"vocab.yml\"", "if state[\"epoch\"] != max_epoch: return _log.info(\"Evaluating on test\") acc, _ = run_eval(model, vocab,", "max_) + math.exp(log_ntags[mid] - max_) ) - math.log(2) ) _log.info(\"Median number of tag", "== \"geom_mean\": crf = LinearCRF(scores) state[\"log_marginals\"].extend((crf.marginals() + 1e-9).log()) state[\"pred_tags\"].extend(crf.argmax()) else: pptx_mask = compute_ambiguous_tag_pairs_mask(scores,", "max_ = max(log_ntags[mid - 1], log_ntags[mid]) log_med = ( max_ + math.log( math.exp(log_ntags[mid", "Event, Runner from rnnr.attachments import EpochTimer, MeanReducer, ProgressBar, SumReducer from sacred import Experiment", "SumReducer(\"corr\", value=\"bcorr\").attach_on(runner) SumReducer(\"total\", value=\"btotal\").attach_on(runner) ProgressBar(total=sum(len(s[\"words\"]) for s in samples), unit=\"tok\", leave=False).attach_on( runner )", "_log.info(\"Combining the ambiguous tag pairs mask\") for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): pptx_mask", "read_tagging_samples from serialization import dump, load from utils import extend_word_embedding ex = Experiment(\"xduft-pptx-tagging-testrun\",", "Experiment from sacred.observers import MongoObserver from sacred.utils import apply_backspaces_and_linefeeds from text2array import BucketIterator,", "many srcs in src2ws, weights won't sum to one\") _log.info(\"Sources: %s\", list(srcs)) _log.info(\"Weights:", "@ex.named_config def prag(): l2_coef = 0.1 lr = 5.9e-5 combine = \"union\" @ex.named_config", "samples[wh]) continue for i, s in enumerate(samples_[wh]): s[\"_id\"] = i runner = Runner()", "wh in [\"train\", \"dev\"]: _log.info(\"Computing the ambiguous tag pairs mask on %s set\",", "name, p in model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH) def compute_loss(state): batch = state[\"batch\"].to_array()", "lengths - 1] = False # exclude last position crf = LinearCRF( masked_scores.contiguous(),", "= \"union\" @ex.named_config def prag_gmean(): l2_coef = 4.7e-3 lr = 2.6e-4 combine =", "L2 regularization against initial parameters l2_coef = 1.0 # max number of epochs", "\"geom_mean\": _log.info(\"Computing median number of tag sequences in chart on %s set\", wh)", "observer mongo_url = os.getenv(\"SACRED_MONGO_URL\") db_name = os.getenv(\"SACRED_DB_NAME\") if None not in (mongo_url, db_name):", "in load_src\") if artifacts_dir: artifacts_dir = Path(artifacts_dir) if load_samples_from: _log.info(\"Loading samples from %s\",", "to save finetuning artifacts artifacts_dir = \"\" # discard train/dev/test samples with length", "= ShuffleIterator( BucketIterator(samples[\"train\"], lambda s: len(s[\"words\"]) // 10, batch_size), rng=_rnd ) _log.info(\"Starting finetuning\")", "exclude last position from mask pptx_loss = (-crf.log_partitions().sum() + crf_z.log_partitions().sum()) / bsz loss", "vocabulary to %s\", path) path.write_text(dump(vocab), encoding=\"utf8\") path = artifacts_dir / \"model.yml\" _log.info(\"Saving model", "words = torch.from_numpy(batch[\"words\"]).to(device) tags = torch.from_numpy(batch[\"tags\"]).to(device) mask = words != vocab[\"words\"].index(vocab.PAD_TOKEN) assert mask.all(),", "\"dev\"]: _log.info(\"Computing median number of tag sequences in chart on %s set\", wh)", "= [] if combine == \"geom_mean\": runner.state.update({\"log_marginals\": [], \"pred_tags\": []}) elif combine ==", "= os.getenv(\"SACRED_MONGO_URL\") db_name = os.getenv(\"SACRED_DB_NAME\") if None not in (mongo_url, db_name): ex.observers.append(MongoObserver.create(url=mongo_url, db_name=db_name))", "for name, p in model.named_parameters()} finetuner.on(Event.BATCH, compute_l2_loss(model, origin_params)) @finetuner.on(Event.BATCH) def compute_loss(state): batch =", "def maybe_compute_loss(state): if not compute_loss: return masked_scores = state[\"scores\"].masked_fill(~state[\"pptx_mask\"], -1e9) crf = LinearCRF(masked_scores.contiguous())", "in chart on %s set\", wh) log_ntags = [] for s in tqdm(samples_[wh],", "1, len(vocab[\"tags\"]), len(vocab[\"tags\"])) assert pptx_mask.shape == scores.shape masked_scores = scores.masked_fill(~pptx_mask, -1e9) lengths =", "for s in tqdm(samples[wh], unit=\"sample\", leave=False): mask = torch.tensor(s[\"pptx_mask\"]).unsqueeze(0) cnt_scores = torch.zeros_like(mask).float().masked_fill(~mask, -1e9)", "for wh in samples: n_toks = sum(len(s[\"words\"]) - 2 for s in samples[wh])", "number of tag sequences in chart on %s set\", wh) log_ntags = []", "\"wiki.en.vec\" # cumulative prob threshold thresh = 0.95 # batch size batch_size =", "PPTX.\"\"\" if max_length is None: max_length = {} if load_src is None: load_src", "@ex.named_config def prag_lopw(): l2_coef = 0.062 lr = 4.7e-4 combine = \"geom_mean\" @ex.named_config", "pathlib import Path import math import os import pickle from einops import rearrange", "if artifacts_dir: artifacts_dir = Path(artifacts_dir) if load_samples_from: _log.info(\"Loading samples from %s\", load_samples_from) with", "whether to evaluate on train set at every epoch end eval_on_train = False", "= {} # whether to treat keys in load_src as lang codes src_key_as_lang", "wh: list(read_tagging_samples(wh, max_length.get(wh))) for wh in [\"train\", \"dev\", \"test\"] } for wh in", "= {\"loss\": loss.item()} state[\"n_items\"] = lengths.sum().item() finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run, model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def", "runner ) if compute_loss: MeanReducer(\"mean_pptx_loss\", value=\"pptx_loss\").attach_on(runner) @runner.on(Event.BATCH) def evaluate_batch(state): batch = state[\"batch\"].to_array() words", "mask[:, :-1]) # exclude last position from mask pptx_loss = (-crf.log_partitions().sum() + crf_z.log_partitions().sum())", "import compute_ambiguous_tag_pairs_mask from callbacks import compute_l2_loss, log_grads, log_stats, save_state_dict, update_params from crf import", "and best tags for %s set with source %s\", wh, src ) else:", "batch = state[\"batch\"].to_array() words = torch.from_numpy(batch[\"words\"]).to(device) tags = torch.from_numpy(batch[\"tags\"]).to(device) mask = words !=", "1], log_ntags[mid]) log_med = ( max_ + math.log( math.exp(log_ntags[mid - 1] - max_)", "= compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True) assert mask.shape == lms.shape mask = mask.squeeze(0) for pts", "compute_ambiguous_tag_pairs_mask from callbacks import compute_l2_loss, log_grads, log_stats, save_state_dict, update_params from crf import LinearCRF", "with target words\", src) vocab.extend(chain(*samples.values()), [\"words\"]) _log.info(\"Found %d words now\", len(vocab[\"words\"])) samples_ =", "lms.size(2) # Renormalise the marginal probabilities lms = rearrange(lms, \"slen nntags ntags ->", "= acc @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_test(state): if state[\"epoch\"] != max_epoch: return _log.info(\"Evaluating on test\")", "embedding layer\", src) assert model.word_emb.embedding_dim == kv.vector_size with torch.no_grad(): model.word_emb = torch.nn.Embedding.from_pretrained( extend_word_embedding(", "finetuner.on(Event.BATCH, [update_params(opt), log_grads(_run, model), log_stats(_run)]) @finetuner.on(Event.EPOCH_FINISHED) def maybe_eval_on_train(state): if not eval_on_train: return _log.info(\"Evaluating", "lambda s: len(s[\"words\"]), batch_size)) return runner.state[\"corr\"] / runner.state[\"total\"], runner.state.get(\"mean_pptx_loss\") @ex.automain def finetune( corpus,", "ntags\", ntags=len(vocab[\"tags\"]) ) lms = lms.unsqueeze(0) mask = compute_ambiguous_tag_pairs_mask(lms, thresh, is_log_marginals=True) assert mask.shape", "save finetuning artifacts artifacts_dir = \"\" # discard train/dev/test samples with length greater", "for i in tqdm(range(len(samples_[wh])), unit=\"sample\", leave=False): lms = samples[wh][i].get(\"log_marginals\", 0) pts = samples[wh][i].get(\"pred_tags\",", "tags).long().sum().item() state[\"btotal\"] = tags.numel() state[\"n_items\"] = words.numel() if compute_loss: state[\"scores\"] = scores state[\"pptx_mask\"]", "from pathlib import Path import math import os import pickle from einops import", "_log.info(\"Computing the ambiguous tag pairs mask on %s set\", wh) for s in", "= apply_backspaces_and_linefeeds # Setup mongodb observer mongo_url = os.getenv(\"SACRED_MONGO_URL\") db_name = os.getenv(\"SACRED_DB_NAME\") if", "def default(): # directory to save finetuning artifacts artifacts_dir = \"\" # discard", "= \"\" # how to combine PPTX charts combine = \"union\" # whether", "lr = 1e-5 # coefficient of L2 regularization against initial parameters l2_coef =", "\"rb\") as f: samples = pickle.load(f) else: samples = { wh: list(read_tagging_samples(wh, max_length.get(wh)))", "pred_tags\".split(): assert x not in runner.state or len(runner.state[x]) == len(samples_[wh]) assert len(runner.state[\"_ids\"]) ==" ]
[ "\"d\", \"nbits\": \"i\", \"nsamples\": \"i\", \"nbeams\": \"i\", \"ibeam\": \"i\", \"fch1\": \"d\", \"foff\": \"d\",", "\"i\", \"nbeams\": \"i\", \"ibeam\": \"i\", \"fch1\": \"d\", \"foff\": \"d\", \"FREQUENCY_START\": \"flag\", \"fchannel\": \"d\",", "\"d\", \"period\": \"d\", \"npuls\": \"q\", \"nbins\": \"i\", \"HEADER_END\": \"flag\", } def prep_string(string): return", "string def prep_double(name, value): return prep_string(name) + struct.pack(\"d\", float(value)) def prep_int(name, value): return", "header definitions and tools. Slightly modified version of: https://github.com/scottransom/presto/blob/master/lib/python/sigproc.py by <NAME>. <NAME>, <EMAIL>", "\"str\", \"barycentric\": \"i\", \"pulsarcentric\": \"i\", \"az_start\": \"d\", \"za_start\": \"d\", \"src_raj\": \"d\", \"src_dej\": \"d\",", "parameter and value for writing to binary file.\"\"\" if header_params[parameter] == \"d\": return", "return prep_double(parameter, value) elif header_params[parameter] == \"i\": return prep_int(parameter, value) elif header_params[parameter] ==", "\"i\", \"refdm\": \"d\", \"period\": \"d\", \"npuls\": \"q\", \"nbins\": \"i\", \"HEADER_END\": \"flag\", } def", "\"d\", \"foff\": \"d\", \"FREQUENCY_START\": \"flag\", \"fchannel\": \"d\", \"FREQUENCY_END\": \"flag\", \"nchans\": \"i\", \"nifs\": \"i\",", "\"HEADER_START\": \"flag\", \"telescope_id\": \"i\", \"machine_id\": \"i\", \"data_type\": \"i\", \"rawdatafile\": \"str\", \"source_name\": \"str\", \"barycentric\":", "\"ibeam\": \"i\", \"fch1\": \"d\", \"foff\": \"d\", \"FREQUENCY_START\": \"flag\", \"fchannel\": \"d\", \"FREQUENCY_END\": \"flag\", \"nchans\":", "\"refdm\": \"d\", \"period\": \"d\", \"npuls\": \"q\", \"nbins\": \"i\", \"HEADER_END\": \"flag\", } def prep_string(string):", "<NAME>. <NAME>, <EMAIL> \"\"\" import struct header_params = { \"HEADER_START\": \"flag\", \"telescope_id\": \"i\",", "\"rawdatafile\": \"str\", \"source_name\": \"str\", \"barycentric\": \"i\", \"pulsarcentric\": \"i\", \"az_start\": \"d\", \"za_start\": \"d\", \"src_raj\":", "value for writing to binary file.\"\"\" if header_params[parameter] == \"d\": return prep_double(parameter, value)", "\"source_name\": \"str\", \"barycentric\": \"i\", \"pulsarcentric\": \"i\", \"az_start\": \"d\", \"za_start\": \"d\", \"src_raj\": \"d\", \"src_dej\":", "int(value)) def addto_hdr(parameter, value): \"\"\"Prepare parameter and value for writing to binary file.\"\"\"", "{ \"HEADER_START\": \"flag\", \"telescope_id\": \"i\", \"machine_id\": \"i\", \"data_type\": \"i\", \"rawdatafile\": \"str\", \"source_name\": \"str\",", "\"d\", \"src_raj\": \"d\", \"src_dej\": \"d\", \"tstart\": \"d\", \"tsamp\": \"d\", \"nbits\": \"i\", \"nsamples\": \"i\",", "value): return prep_string(name) + struct.pack(\"d\", float(value)) def prep_int(name, value): return prep_string(name) + struct.pack(\"i\",", "\"HEADER_END\": \"flag\", } def prep_string(string): return struct.pack(\"i\", len(string)) + string def prep_double(name, value):", "writing to binary file.\"\"\" if header_params[parameter] == \"d\": return prep_double(parameter, value) elif header_params[parameter]", "header_params[parameter] == \"d\": return prep_double(parameter, value) elif header_params[parameter] == \"i\": return prep_int(parameter, value)", "\"d\", \"tsamp\": \"d\", \"nbits\": \"i\", \"nsamples\": \"i\", \"nbeams\": \"i\", \"ibeam\": \"i\", \"fch1\": \"d\",", "struct.pack(\"i\", int(value)) def addto_hdr(parameter, value): \"\"\"Prepare parameter and value for writing to binary", "\"src_raj\": \"d\", \"src_dej\": \"d\", \"tstart\": \"d\", \"tsamp\": \"d\", \"nbits\": \"i\", \"nsamples\": \"i\", \"nbeams\":", "return prep_string(parameter) + prep_string(value) elif header_params[parameter] == \"flag\": return prep_string(parameter) else: print(f\"WARNING key", "\"d\", \"tstart\": \"d\", \"tsamp\": \"d\", \"nbits\": \"i\", \"nsamples\": \"i\", \"nbeams\": \"i\", \"ibeam\": \"i\",", "== \"str\": return prep_string(parameter) + prep_string(value) elif header_params[parameter] == \"flag\": return prep_string(parameter) else:", "prep_double(name, value): return prep_string(name) + struct.pack(\"d\", float(value)) def prep_int(name, value): return prep_string(name) +", "\"nbeams\": \"i\", \"ibeam\": \"i\", \"fch1\": \"d\", \"foff\": \"d\", \"FREQUENCY_START\": \"flag\", \"fchannel\": \"d\", \"FREQUENCY_END\":", "\"tsamp\": \"d\", \"nbits\": \"i\", \"nsamples\": \"i\", \"nbeams\": \"i\", \"ibeam\": \"i\", \"fch1\": \"d\", \"foff\":", "= { \"HEADER_START\": \"flag\", \"telescope_id\": \"i\", \"machine_id\": \"i\", \"data_type\": \"i\", \"rawdatafile\": \"str\", \"source_name\":", "elif header_params[parameter] == \"str\": return prep_string(parameter) + prep_string(value) elif header_params[parameter] == \"flag\": return", "\"str\": return prep_string(parameter) + prep_string(value) elif header_params[parameter] == \"flag\": return prep_string(parameter) else: print(f\"WARNING", "\"FREQUENCY_START\": \"flag\", \"fchannel\": \"d\", \"FREQUENCY_END\": \"flag\", \"nchans\": \"i\", \"nifs\": \"i\", \"refdm\": \"d\", \"period\":", "\"foff\": \"d\", \"FREQUENCY_START\": \"flag\", \"fchannel\": \"d\", \"FREQUENCY_END\": \"flag\", \"nchans\": \"i\", \"nifs\": \"i\", \"refdm\":", "\"d\", \"npuls\": \"q\", \"nbins\": \"i\", \"HEADER_END\": \"flag\", } def prep_string(string): return struct.pack(\"i\", len(string))", "\"\"\" import struct header_params = { \"HEADER_START\": \"flag\", \"telescope_id\": \"i\", \"machine_id\": \"i\", \"data_type\":", "\"i\", \"nsamples\": \"i\", \"nbeams\": \"i\", \"ibeam\": \"i\", \"fch1\": \"d\", \"foff\": \"d\", \"FREQUENCY_START\": \"flag\",", "\"FREQUENCY_END\": \"flag\", \"nchans\": \"i\", \"nifs\": \"i\", \"refdm\": \"d\", \"period\": \"d\", \"npuls\": \"q\", \"nbins\":", "\"flag\", } def prep_string(string): return struct.pack(\"i\", len(string)) + string def prep_double(name, value): return", "return prep_string(name) + struct.pack(\"i\", int(value)) def addto_hdr(parameter, value): \"\"\"Prepare parameter and value for", "\"i\", \"data_type\": \"i\", \"rawdatafile\": \"str\", \"source_name\": \"str\", \"barycentric\": \"i\", \"pulsarcentric\": \"i\", \"az_start\": \"d\",", "\"i\": return prep_int(parameter, value) elif header_params[parameter] == \"str\": return prep_string(parameter) + prep_string(value) elif", "\"flag\", \"fchannel\": \"d\", \"FREQUENCY_END\": \"flag\", \"nchans\": \"i\", \"nifs\": \"i\", \"refdm\": \"d\", \"period\": \"d\",", "header_params[parameter] == \"i\": return prep_int(parameter, value) elif header_params[parameter] == \"str\": return prep_string(parameter) +", "\"i\", \"pulsarcentric\": \"i\", \"az_start\": \"d\", \"za_start\": \"d\", \"src_raj\": \"d\", \"src_dej\": \"d\", \"tstart\": \"d\",", "== \"i\": return prep_int(parameter, value) elif header_params[parameter] == \"str\": return prep_string(parameter) + prep_string(value)", "version of: https://github.com/scottransom/presto/blob/master/lib/python/sigproc.py by <NAME>. <NAME>, <EMAIL> \"\"\" import struct header_params = {", "\"az_start\": \"d\", \"za_start\": \"d\", \"src_raj\": \"d\", \"src_dej\": \"d\", \"tstart\": \"d\", \"tsamp\": \"d\", \"nbits\":", "\"d\", \"FREQUENCY_START\": \"flag\", \"fchannel\": \"d\", \"FREQUENCY_END\": \"flag\", \"nchans\": \"i\", \"nifs\": \"i\", \"refdm\": \"d\",", "modified version of: https://github.com/scottransom/presto/blob/master/lib/python/sigproc.py by <NAME>. <NAME>, <EMAIL> \"\"\" import struct header_params =", "\"i\", \"rawdatafile\": \"str\", \"source_name\": \"str\", \"barycentric\": \"i\", \"pulsarcentric\": \"i\", \"az_start\": \"d\", \"za_start\": \"d\",", "+ string def prep_double(name, value): return prep_string(name) + struct.pack(\"d\", float(value)) def prep_int(name, value):", "by <NAME>. <NAME>, <EMAIL> \"\"\" import struct header_params = { \"HEADER_START\": \"flag\", \"telescope_id\":", "value): return prep_string(name) + struct.pack(\"i\", int(value)) def addto_hdr(parameter, value): \"\"\"Prepare parameter and value", "\"nsamples\": \"i\", \"nbeams\": \"i\", \"ibeam\": \"i\", \"fch1\": \"d\", \"foff\": \"d\", \"FREQUENCY_START\": \"flag\", \"fchannel\":", "float(value)) def prep_int(name, value): return prep_string(name) + struct.pack(\"i\", int(value)) def addto_hdr(parameter, value): \"\"\"Prepare", "len(string)) + string def prep_double(name, value): return prep_string(name) + struct.pack(\"d\", float(value)) def prep_int(name,", "addto_hdr(parameter, value): \"\"\"Prepare parameter and value for writing to binary file.\"\"\" if header_params[parameter]", "} def prep_string(string): return struct.pack(\"i\", len(string)) + string def prep_double(name, value): return prep_string(name)", "\"tstart\": \"d\", \"tsamp\": \"d\", \"nbits\": \"i\", \"nsamples\": \"i\", \"nbeams\": \"i\", \"ibeam\": \"i\", \"fch1\":", "\"data_type\": \"i\", \"rawdatafile\": \"str\", \"source_name\": \"str\", \"barycentric\": \"i\", \"pulsarcentric\": \"i\", \"az_start\": \"d\", \"za_start\":", "\"\"\"Sigproc header definitions and tools. Slightly modified version of: https://github.com/scottransom/presto/blob/master/lib/python/sigproc.py by <NAME>. <NAME>,", "\"flag\", \"telescope_id\": \"i\", \"machine_id\": \"i\", \"data_type\": \"i\", \"rawdatafile\": \"str\", \"source_name\": \"str\", \"barycentric\": \"i\",", "\"d\", \"FREQUENCY_END\": \"flag\", \"nchans\": \"i\", \"nifs\": \"i\", \"refdm\": \"d\", \"period\": \"d\", \"npuls\": \"q\",", "def prep_double(name, value): return prep_string(name) + struct.pack(\"d\", float(value)) def prep_int(name, value): return prep_string(name)", "Slightly modified version of: https://github.com/scottransom/presto/blob/master/lib/python/sigproc.py by <NAME>. <NAME>, <EMAIL> \"\"\" import struct header_params", "\"i\", \"machine_id\": \"i\", \"data_type\": \"i\", \"rawdatafile\": \"str\", \"source_name\": \"str\", \"barycentric\": \"i\", \"pulsarcentric\": \"i\",", "header_params[parameter] == \"str\": return prep_string(parameter) + prep_string(value) elif header_params[parameter] == \"flag\": return prep_string(parameter)", "\"d\", \"za_start\": \"d\", \"src_raj\": \"d\", \"src_dej\": \"d\", \"tstart\": \"d\", \"tsamp\": \"d\", \"nbits\": \"i\",", "tools. Slightly modified version of: https://github.com/scottransom/presto/blob/master/lib/python/sigproc.py by <NAME>. <NAME>, <EMAIL> \"\"\" import struct", "def prep_string(string): return struct.pack(\"i\", len(string)) + string def prep_double(name, value): return prep_string(name) +", "return prep_int(parameter, value) elif header_params[parameter] == \"str\": return prep_string(parameter) + prep_string(value) elif header_params[parameter]", "\"pulsarcentric\": \"i\", \"az_start\": \"d\", \"za_start\": \"d\", \"src_raj\": \"d\", \"src_dej\": \"d\", \"tstart\": \"d\", \"tsamp\":", "prep_string(parameter) + prep_string(value) elif header_params[parameter] == \"flag\": return prep_string(parameter) else: print(f\"WARNING key '{parameter}'", "struct header_params = { \"HEADER_START\": \"flag\", \"telescope_id\": \"i\", \"machine_id\": \"i\", \"data_type\": \"i\", \"rawdatafile\":", "\"i\", \"az_start\": \"d\", \"za_start\": \"d\", \"src_raj\": \"d\", \"src_dej\": \"d\", \"tstart\": \"d\", \"tsamp\": \"d\",", "\"telescope_id\": \"i\", \"machine_id\": \"i\", \"data_type\": \"i\", \"rawdatafile\": \"str\", \"source_name\": \"str\", \"barycentric\": \"i\", \"pulsarcentric\":", "\"i\", \"HEADER_END\": \"flag\", } def prep_string(string): return struct.pack(\"i\", len(string)) + string def prep_double(name,", "if header_params[parameter] == \"d\": return prep_double(parameter, value) elif header_params[parameter] == \"i\": return prep_int(parameter,", "https://github.com/scottransom/presto/blob/master/lib/python/sigproc.py by <NAME>. <NAME>, <EMAIL> \"\"\" import struct header_params = { \"HEADER_START\": \"flag\",", "prep_string(name) + struct.pack(\"d\", float(value)) def prep_int(name, value): return prep_string(name) + struct.pack(\"i\", int(value)) def", "\"npuls\": \"q\", \"nbins\": \"i\", \"HEADER_END\": \"flag\", } def prep_string(string): return struct.pack(\"i\", len(string)) +", "+ prep_string(value) elif header_params[parameter] == \"flag\": return prep_string(parameter) else: print(f\"WARNING key '{parameter}' is", "value) elif header_params[parameter] == \"i\": return prep_int(parameter, value) elif header_params[parameter] == \"str\": return", "\"nbins\": \"i\", \"HEADER_END\": \"flag\", } def prep_string(string): return struct.pack(\"i\", len(string)) + string def", "+ struct.pack(\"d\", float(value)) def prep_int(name, value): return prep_string(name) + struct.pack(\"i\", int(value)) def addto_hdr(parameter,", "+ struct.pack(\"i\", int(value)) def addto_hdr(parameter, value): \"\"\"Prepare parameter and value for writing to", "struct.pack(\"d\", float(value)) def prep_int(name, value): return prep_string(name) + struct.pack(\"i\", int(value)) def addto_hdr(parameter, value):", "<NAME>, <EMAIL> \"\"\" import struct header_params = { \"HEADER_START\": \"flag\", \"telescope_id\": \"i\", \"machine_id\":", "prep_int(parameter, value) elif header_params[parameter] == \"str\": return prep_string(parameter) + prep_string(value) elif header_params[parameter] ==", "\"\"\"Prepare parameter and value for writing to binary file.\"\"\" if header_params[parameter] == \"d\":", "\"nifs\": \"i\", \"refdm\": \"d\", \"period\": \"d\", \"npuls\": \"q\", \"nbins\": \"i\", \"HEADER_END\": \"flag\", }", "for writing to binary file.\"\"\" if header_params[parameter] == \"d\": return prep_double(parameter, value) elif", "\"za_start\": \"d\", \"src_raj\": \"d\", \"src_dej\": \"d\", \"tstart\": \"d\", \"tsamp\": \"d\", \"nbits\": \"i\", \"nsamples\":", "\"str\", \"source_name\": \"str\", \"barycentric\": \"i\", \"pulsarcentric\": \"i\", \"az_start\": \"d\", \"za_start\": \"d\", \"src_raj\": \"d\",", "value) elif header_params[parameter] == \"str\": return prep_string(parameter) + prep_string(value) elif header_params[parameter] == \"flag\":", "\"fch1\": \"d\", \"foff\": \"d\", \"FREQUENCY_START\": \"flag\", \"fchannel\": \"d\", \"FREQUENCY_END\": \"flag\", \"nchans\": \"i\", \"nifs\":", "return struct.pack(\"i\", len(string)) + string def prep_double(name, value): return prep_string(name) + struct.pack(\"d\", float(value))", "\"fchannel\": \"d\", \"FREQUENCY_END\": \"flag\", \"nchans\": \"i\", \"nifs\": \"i\", \"refdm\": \"d\", \"period\": \"d\", \"npuls\":", "\"i\", \"fch1\": \"d\", \"foff\": \"d\", \"FREQUENCY_START\": \"flag\", \"fchannel\": \"d\", \"FREQUENCY_END\": \"flag\", \"nchans\": \"i\",", "struct.pack(\"i\", len(string)) + string def prep_double(name, value): return prep_string(name) + struct.pack(\"d\", float(value)) def", "prep_string(value) elif header_params[parameter] == \"flag\": return prep_string(parameter) else: print(f\"WARNING key '{parameter}' is unknown!\")", "\"src_dej\": \"d\", \"tstart\": \"d\", \"tsamp\": \"d\", \"nbits\": \"i\", \"nsamples\": \"i\", \"nbeams\": \"i\", \"ibeam\":", "<EMAIL> \"\"\" import struct header_params = { \"HEADER_START\": \"flag\", \"telescope_id\": \"i\", \"machine_id\": \"i\",", "header_params = { \"HEADER_START\": \"flag\", \"telescope_id\": \"i\", \"machine_id\": \"i\", \"data_type\": \"i\", \"rawdatafile\": \"str\",", "\"i\", \"nifs\": \"i\", \"refdm\": \"d\", \"period\": \"d\", \"npuls\": \"q\", \"nbins\": \"i\", \"HEADER_END\": \"flag\",", "elif header_params[parameter] == \"i\": return prep_int(parameter, value) elif header_params[parameter] == \"str\": return prep_string(parameter)", "file.\"\"\" if header_params[parameter] == \"d\": return prep_double(parameter, value) elif header_params[parameter] == \"i\": return", "prep_string(name) + struct.pack(\"i\", int(value)) def addto_hdr(parameter, value): \"\"\"Prepare parameter and value for writing", "import struct header_params = { \"HEADER_START\": \"flag\", \"telescope_id\": \"i\", \"machine_id\": \"i\", \"data_type\": \"i\",", "of: https://github.com/scottransom/presto/blob/master/lib/python/sigproc.py by <NAME>. <NAME>, <EMAIL> \"\"\" import struct header_params = { \"HEADER_START\":", "def prep_int(name, value): return prep_string(name) + struct.pack(\"i\", int(value)) def addto_hdr(parameter, value): \"\"\"Prepare parameter", "def addto_hdr(parameter, value): \"\"\"Prepare parameter and value for writing to binary file.\"\"\" if", "\"d\", \"src_dej\": \"d\", \"tstart\": \"d\", \"tsamp\": \"d\", \"nbits\": \"i\", \"nsamples\": \"i\", \"nbeams\": \"i\",", "binary file.\"\"\" if header_params[parameter] == \"d\": return prep_double(parameter, value) elif header_params[parameter] == \"i\":", "value): \"\"\"Prepare parameter and value for writing to binary file.\"\"\" if header_params[parameter] ==", "prep_double(parameter, value) elif header_params[parameter] == \"i\": return prep_int(parameter, value) elif header_params[parameter] == \"str\":", "\"nbits\": \"i\", \"nsamples\": \"i\", \"nbeams\": \"i\", \"ibeam\": \"i\", \"fch1\": \"d\", \"foff\": \"d\", \"FREQUENCY_START\":", "prep_int(name, value): return prep_string(name) + struct.pack(\"i\", int(value)) def addto_hdr(parameter, value): \"\"\"Prepare parameter and", "\"barycentric\": \"i\", \"pulsarcentric\": \"i\", \"az_start\": \"d\", \"za_start\": \"d\", \"src_raj\": \"d\", \"src_dej\": \"d\", \"tstart\":", "to binary file.\"\"\" if header_params[parameter] == \"d\": return prep_double(parameter, value) elif header_params[parameter] ==", "and tools. Slightly modified version of: https://github.com/scottransom/presto/blob/master/lib/python/sigproc.py by <NAME>. <NAME>, <EMAIL> \"\"\" import", "prep_string(string): return struct.pack(\"i\", len(string)) + string def prep_double(name, value): return prep_string(name) + struct.pack(\"d\",", "\"flag\", \"nchans\": \"i\", \"nifs\": \"i\", \"refdm\": \"d\", \"period\": \"d\", \"npuls\": \"q\", \"nbins\": \"i\",", "return prep_string(name) + struct.pack(\"d\", float(value)) def prep_int(name, value): return prep_string(name) + struct.pack(\"i\", int(value))", "\"nchans\": \"i\", \"nifs\": \"i\", \"refdm\": \"d\", \"period\": \"d\", \"npuls\": \"q\", \"nbins\": \"i\", \"HEADER_END\":", "== \"d\": return prep_double(parameter, value) elif header_params[parameter] == \"i\": return prep_int(parameter, value) elif", "\"period\": \"d\", \"npuls\": \"q\", \"nbins\": \"i\", \"HEADER_END\": \"flag\", } def prep_string(string): return struct.pack(\"i\",", "\"machine_id\": \"i\", \"data_type\": \"i\", \"rawdatafile\": \"str\", \"source_name\": \"str\", \"barycentric\": \"i\", \"pulsarcentric\": \"i\", \"az_start\":", "and value for writing to binary file.\"\"\" if header_params[parameter] == \"d\": return prep_double(parameter,", "\"q\", \"nbins\": \"i\", \"HEADER_END\": \"flag\", } def prep_string(string): return struct.pack(\"i\", len(string)) + string", "\"d\": return prep_double(parameter, value) elif header_params[parameter] == \"i\": return prep_int(parameter, value) elif header_params[parameter]", "\"i\", \"ibeam\": \"i\", \"fch1\": \"d\", \"foff\": \"d\", \"FREQUENCY_START\": \"flag\", \"fchannel\": \"d\", \"FREQUENCY_END\": \"flag\",", "definitions and tools. Slightly modified version of: https://github.com/scottransom/presto/blob/master/lib/python/sigproc.py by <NAME>. <NAME>, <EMAIL> \"\"\"" ]
[ "trainList_dvs def populateTrainList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList = []", "for im_folder, dvs_folder in zip(folderListRgb, folderListDvs): imageList = sorted(glob.glob(im_folder + '/' + '*.jpg'))", "= w st_x = 0 ed_x = h or_st_y = i or_ed_y =", "cropped_img_list = [] h,w = output_size height, width, _ = image_list[0].shape i =", "cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset): def __init__(self, folderPath, mode='train'): self.trainList = populateTrainList2Rgb(folderPath) self.mode =", "self.dvsList = populateTrainList2Dvs(dvsFolderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) print(\"# of", "np.empty((h,w), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x,", "[x[0] for x in os.walk(folderPath)] folderList = [] trainList = [] for folder", "for i in range(0, len(imageList), 9): tmp = imageList[i:i+9] if len(tmp) == 9:", "or_ed_y = i + w or_st_x = j or_ed_x = j + h", "0 ed_x = h or_st_y = i or_ed_y = i + w or_st_x", "height, width, _ = image_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h) j", "samples:\", len(self.dvsList)) def __getitem__(self, index): img_path_list = self.trainList[index] dvs_path_list = self.dvsList[index] start =", "- h) j = random.randint(0, width - w) st_y = 0 ed_y =", "= populateTrainList2(imFolderPath, dvsFolderPath) # self.dvsList = populateTrainList2Dvs(dvsFolderPath) self.mode = mode print(\"# of training", "for x in os.walk(folderPath)] trainList = [] for folder in folderList: imageList =", "output_size): cropped_img_list = [] h,w = output_size height, width, _ = image_list[0].shape i", "import os, pdb import random def populateTrainList(folderPath): folderList_pre = [x[0] for x in", "import cv2 from PIL import Image import glob import os, pdb import random", "#cv2.waitKey(0) & 0xff #brak for i in range(len(img_list)): #print(img_list[i].shape) #brak img_list[i] /= 255", "= populateTrainList2Dvs(dvsFolderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) print(\"# of dvs", "for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for dvs_path in", "training samples:\", len(self.trainList)) print(\"# of dvs samples:\", len(self.dvsList)) def __getitem__(self, index): img_path_list =", "or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset): def __init__(self, folderPath, mode='train'):", "elif h <= w: scaleX = 360 scaleY = int(360*(w/h)) img_list = []", "+ '*.png')) minLen = min(len(imageList), len(dvsList)) imageList = imageList[:minLen] dvsList = dvsList[:minLen] for", "i in range(len(img_list)): #print(img_list[i].shape) #brak img_list[i] /= 255 img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5) - 1", "+ '*.jpg')) for i in range(0, len(imageList), 12): tmp = imageList[i:i+12] if len(tmp)", "expansionLoader(data.Dataset): def __init__(self, folderPath, mode='train'): self.trainList = populateTrainList2Rgb(folderPath) self.mode = mode print(\"# of", "np import cv2 from PIL import Image import glob import os, pdb import", "= sorted(glob.glob(dvs_folder + '/' + '*.png')) minLen = min(len(imageList), len(dvsList)) imageList = imageList[:minLen]", "tmp_dvs = dvsList[i:i+12] if len(tmp_rgb) == 12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb, trainList_dvs def", "# self.dvsList = populateTrainList2Dvs(dvsFolderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) print(\"#", "dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX, scaleY)) thresh = 127 tmp = cv2.threshold(tmp,", "cv2.COLOR_BGR2GRAY), (scaleX, scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32))", "dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh = 127", "j or_ed_x = j + h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y,", "360 scaleY = int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+9]: tmp =", "or_st_y, or_ed_y) for img in image_list: new_img = np.empty((h,w,3), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y,", "cropped_img_list = [] cropped_dvs_list = [] h,w = output_size height, width, _ =", "mode='test'): self.trainList = populateTestList2(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def", "torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class dvsLoader(data.Dataset): def __init__(self,", "for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh = 127 tmp", "img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnListDvs(image_list, dvs_list, output_size): cropped_img_list", "else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0)", "= 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path", "dvs = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c) if h > w: scaleX = int(360*(h/w)) scaleY", "if len(tmp_rgb) == 12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb, trainList_dvs def populateTrainList2Rgb(folderPath): folderList =", "[] h,w = output_size height, width, _ = image_list[0].shape #print(h,w,height,width) i = random.randint(0,", "trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb, trainList_dvs def populateTrainList2Rgb(folderPath): folderList = [x[0] for x in", "folderListDvs): imageList = sorted(glob.glob(im_folder + '/' + '*.jpg')) dvsList = sorted(glob.glob(dvs_folder + '/'", "scaleX = 360 scaleY = int(360*(w/h)) img_list = [] flip = random.randint(0,1) if", "len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateTrainList2(rgbPath, dvsPath): folderListRgb = [x[0] for", "output_size height, width, _ = image_list[0].shape i = 100 j = 0 st_y", "populateTrainList2(imFolderPath, dvsFolderPath) # self.dvsList = populateTrainList2Dvs(dvsFolderPath) self.mode = mode print(\"# of training samples:\",", "folderList_pre: if folder[-3:] == '240': folderList.append(folder + \"/\" + folder.split(\"/\")[-2]) for folder in", "= 0 st_y = 0 ed_y = w st_x = 0 ed_x =", "= populateTrainList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self, index):", "= imageList[:minLen] dvsList = dvsList[:minLen] for i in range(0, len(imageList), 12): tmp_rgb =", "/= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list, cropped_dvs_list = randomCropOnListDvs(img_list, dvs_list", "#cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in range(len(img_list)): #print(img_list[i].shape) #brak img_list[i] /=", "img_list = [] dvs_list = [] flip = random.randint(0,1) if flip: for img_path", "cv2.COLOR_BGR2GRAY).shape image = cv2.imread(img_path_list[0]) dvs = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c) if h > w:", "== 12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb, trainList_dvs def populateTrainList2Rgb(folderPath): folderList = [x[0] for", "\"/\" + folder.split(\"/\")[-2]) for folder in folderList: imageList = sorted(glob.glob(folder + '/' +", "scaleX = 360 scaleY = int(360*(w/h)) img_list = [] dvs_list = [] flip", "cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp =", "360 elif h <= w: scaleX = 360 scaleY = int(360*(w/h)) img_list =", "h,w = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image = cv2.imread(img_path_list[0]) dvs = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c) if", "or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset): def __init__(self, folderPath,", "numpy as np import cv2 from PIL import Image import glob import os,", "= imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateTrainList2(rgbPath, dvsPath): folderListRgb", "scaleY = int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+2]: tmp = cv2.resize(cv2.imread(img_path),", "(scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in range(len(img_list)): #print(img_list[i].shape)", "mode='test'): self.trainList = populateValList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def", "+ '*.jpg')) for i in range(0, len(imageList), 9): tmp = imageList[i:i+9] if len(tmp)", "def populateTestList2(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList = [] for", "folderPath, mode='test'): self.trainList = populateValList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList))", "of training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index] start = 0", "trainList_dvs = [] for im_folder, dvs_folder in zip(folderListRgb, folderListDvs): imageList = sorted(glob.glob(im_folder +", "dvsList = dvsList[:minLen] for i in range(0, len(imageList), 12): tmp_rgb = imageList[i:i+12] tmp_dvs", "def populateTrainList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList = [] for", "def __getitem__(self, index): img_path_list = self.trainList[index] start = 0 h,w,c = cv2.imread(img_path_list[0]).shape image", "if len(tmp) == 9: trainList.append(imageList[i:i+9]) return trainList # def populateDvsList2(folderPath): # folderList =", "return len(self.trainList) class valLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateValList2Rgb(folderPath) self.mode =", "img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list,", "range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class", "trainList def fixedCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size height, width, _", "in range(0, len(imageList), 2): tmp = imageList[i:i+2] if len(tmp) == 2: trainList.append(imageList[i:i+2]) return", "populateTestList2(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list", "trainList.append(imageList[i:i+12]) return trainList def populateTrainList2(rgbPath, dvsPath): folderListRgb = [x[0] for x in os.walk(rgbPath)]", "image_list: new_img = np.empty((h,w,3), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y:", "range(0, len(imageList), 9): tmp = imageList[i:i+9] if len(tmp) == 9: trainList.append(imageList[i:i+9]) return trainList", "# if len(tmp) == 12: # trainList.append(imageList[i:i+12]) # return trainList def populateTestList2(folderPath): folderList", "or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnListDvs(image_list, dvs_list, output_size): cropped_img_list = [] cropped_dvs_list", "img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = randomCropOnList(img_list,(352,352)) for", "int(360*(w/h)) img_list = [] dvs_list = [] flip = random.randint(0,1) if flip: for", "# return trainList def populateTestList2(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList", "= self.dvsList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape h,w = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image", "index): img_path_list = self.trainList[index] dvs_path_list = self.dvsList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape", "j + h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img,dvs", "= output_size height, width, _ = image_list[0].shape i = 100 j = 0", "/= 0.225 cropped_img_list, cropped_dvs_list = randomCropOnListDvs(img_list, dvs_list ,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i]", "imageList[i:i+12] tmp_dvs = dvsList[i:i+12] if len(tmp_rgb) == 12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb, trainList_dvs", "def __getitem__(self, index): img_path_list = self.trainList[index] dvs_path_list = self.dvsList[index] start = random.randint(0,3) h,w,c", "cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in", "-= 0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list, cropped_dvs_list", "in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) for i in range(len(cropped_dvs_list)): cropped_dvs_list[i] =", "= image_list[0].shape i = 100 j = 0 st_y = 0 ed_y =", "return trainList_rgb, trainList_dvs def populateTrainList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList", "cv2.COLOR_BGR2GRAY) #print(h,w,c) if h > w: scaleX = int(360*(h/w)) scaleY = 360 elif", "= cv2.imread(img_path_list[0]).shape h,w = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image = cv2.imread(img_path_list[0]) dvs = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY)", "for folder in folderList_pre: if folder[-3:] == '240': folderList.append(folder + \"/\" + folder.split(\"/\")[-2])", "in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh = 127 tmp = cv2.threshold(tmp,", "cropped_img_list def __len__(self): return len(self.trainList) class testLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList =", "'*.png')) minLen = min(len(imageList), len(dvsList)) imageList = imageList[:minLen] dvsList = dvsList[:minLen] for i", "random.randint(0, width - w) st_y = 0 ed_y = w st_x = 0", "/= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = fixedCropOnList(img_list, (352, 352))", "return trainList def populateTrainList2(rgbPath, dvsPath): folderListRgb = [x[0] for x in os.walk(rgbPath)] folderListDvs", "cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY))", "ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnListDvs(image_list,", "in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList)", "import random def populateTrainList(folderPath): folderList_pre = [x[0] for x in os.walk(folderPath)] folderList =", "= i or_ed_y = i + w or_st_x = j or_ed_x = j", "img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff", "+ \"/\" + folder.split(\"/\")[-2]) for folder in folderList: imageList = sorted(glob.glob(folder + '/'", "__len__(self): return len(self.trainList) class dvsLoader(data.Dataset): def __init__(self, imFolderPath, dvsFolderPath, mode='train'): self.trainList, self.dvsList =", "= cv2.imread(img_path_list[0]) #print(h,w,c) if h > w: scaleX = int(360*(h/w)) scaleY = 360", "minLen = min(len(imageList), len(dvsList)) imageList = imageList[:minLen] dvsList = dvsList[:minLen] for i in", "st_x: ed_x] = dvs[or_st_y: or_ed_y, or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/')))", "12: # trainList.append(imageList[i:i+12]) # return trainList def populateTestList2(folderPath): folderList = [x[0] for x", "random def populateTrainList(folderPath): folderList_pre = [x[0] for x in os.walk(folderPath)] folderList = []", "folderList = [] trainList = [] for folder in folderList_pre: if folder[-3:] ==", "in folderList: imageList = sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0,", "0.225 cropped_img_list = randomCropOnList(img_list,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1)))", "= random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape h,w = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image = cv2.imread(img_path_list[0]) dvs", "pdb import random def populateTrainList(folderPath): folderList_pre = [x[0] for x in os.walk(folderPath)] folderList", "i in range(0, len(imageList), 12): tmp = imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12])", "= self.trainList[index] start = 0 h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if", "h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img in image_list:", "folderPath, mode='train'): self.trainList = populateTrainList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList))", "torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) for i in range(len(cropped_dvs_list)): cropped_dvs_list[i] = torch.from_numpy(cropped_dvs_list[i]) return cropped_img_list, cropped_dvs_list", "= 100 j = 0 st_y = 0 ed_y = w st_x =", "# trainList = [] # for folder in folderList: # imageList = sorted(glob.glob(folder", "ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list", "for img_path in img_path_list[start:start+2]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) &", "1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,", "st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img in image_list: new_img = np.empty((h,w,3),", "in os.walk(folderPath)] # trainList = [] # for folder in folderList: # imageList", "'240': folderList.append(folder + \"/\" + folder.split(\"/\")[-2]) for folder in folderList: imageList = sorted(glob.glob(folder", "for i in range(len(img_list)): #print(img_list[i].shape) #brak img_list[i] /= 255 img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5) -", "or_ed_x = j + h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y)", "#print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset): def __init__(self, folderPath, mode='train'): self.trainList = populateTrainList2Rgb(folderPath) self.mode = mode", "len(self.trainList) class testLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateTestList2(folderPath) self.mode = mode", "dvs_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h) j = random.randint(0, width -", "cropped_dvs_list = [] h,w = output_size height, width, _ = image_list[0].shape dvs_h, dvs_w", "def populateTrainList2(rgbPath, dvsPath): folderListRgb = [x[0] for x in os.walk(rgbPath)] folderListDvs = [x[0]", "9): tmp = imageList[i:i+9] if len(tmp) == 9: trainList.append(imageList[i:i+9]) return trainList # def", "for folder in folderList: imageList = sorted(glob.glob(folder + '/' + '*.jpg')) for i", "h) j = random.randint(0, width - w) st_y = 0 ed_y = w", "len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape", "/= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = randomCropOnList(img_list,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i]", "or_st_y, or_ed_y) for img,dvs in zip(image_list, dvs_list): new_img = np.empty((h,w,3), dtype=np.float32) new_dvs =", "cropped_img_list def randomCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size height, width, _", "= int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,", "in zip(folderListRgb, folderListDvs): imageList = sorted(glob.glob(im_folder + '/' + '*.jpg')) dvsList = sorted(glob.glob(dvs_folder", "cropped_img_list def randomCropOnListDvs(image_list, dvs_list, output_size): cropped_img_list = [] cropped_dvs_list = [] h,w =", "in folderList_pre: if folder[-3:] == '240': folderList.append(folder + \"/\" + folder.split(\"/\")[-2]) for folder", "-= 0.485#(img_list[i]/127.5) - 1 img_list[i][:,:,1] -= 0.456 img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0] /= 0.229", "for i in range(0, len(imageList), 12): tmp = imageList[i:i+12] if len(tmp) == 12:", "+ '/' + '*.png')) minLen = min(len(imageList), len(dvsList)) imageList = imageList[:minLen] dvsList =", "from PIL import Image import glob import os, pdb import random def populateTrainList(folderPath):", "1))) return cropped_img_list def __len__(self): return len(self.trainList) class testLoader(data.Dataset): def __init__(self, folderPath, mode='test'):", "folder.split(\"/\")[-2]) for folder in folderList: imageList = sorted(glob.glob(folder + '/' + '*.jpg')) for", "dtype=np.float32) new_dvs = np.empty((h,w), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y:", "= torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) for i in range(len(cropped_dvs_list)): cropped_dvs_list[i] = torch.from_numpy(cropped_dvs_list[i]) return cropped_img_list,", "-= 0.456 img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /=", "ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() new_dvs[st_y: ed_y, st_x: ed_x] =", "or_ed_y, or_st_x: or_ed_x, :].copy() new_dvs[st_y: ed_y, st_x: ed_x] = dvs[or_st_y: or_ed_y, or_st_x: or_ed_x].copy()", "12): tmp = imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateTrainList2(rgbPath,", "# imageList = sorted(glob.glob(folder + '/' + '*.jpg')) # for i in range(0,", "ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img,dvs in zip(image_list, dvs_list): new_img = np.empty((h,w,3),", "populateTestList2(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList = [] for folder", "mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index] start", "or_st_x: or_ed_x, :].copy() new_dvs[st_y: ed_y, st_x: ed_x] = dvs[or_st_y: or_ed_y, or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img))", "i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return", "cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in range(len(img_list)): #print(img_list[i].shape) #brak", "cv2.imread(img_path_list[0]) dvs = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c) if h > w: scaleX = int(360*(h/w))", "self.trainList, self.dvsList = populateTrainList2(imFolderPath, dvsFolderPath) # self.dvsList = populateTrainList2Dvs(dvsFolderPath) self.mode = mode print(\"#", "glob import os, pdb import random def populateTrainList(folderPath): folderList_pre = [x[0] for x", "+ '/' + '*.jpg')) for i in range(0, len(imageList), 12): tmp = imageList[i:i+12]", "if h > w: scaleX = int(360*(h/w)) scaleY = 360 elif h <=", "= imageList[i:i+9] if len(tmp) == 9: trainList.append(imageList[i:i+9]) return trainList # def populateDvsList2(folderPath): #", "trainList # def populateDvsList2(folderPath): # folderList = [x[0] for x in os.walk(folderPath)] #", "= [x[0] for x in os.walk(rgbPath)] folderListDvs = [x[0] for x in os.walk(dvsPath)]", "training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index] start = 0 h,w,c", "== 9: trainList.append(imageList[i:i+9]) return trainList # def populateDvsList2(folderPath): # folderList = [x[0] for", "= img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() new_dvs[st_y: ed_y, st_x: ed_x] = dvs[or_st_y: or_ed_y,", "else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path", "len(imageList), 2): tmp = imageList[i:i+2] if len(tmp) == 2: trainList.append(imageList[i:i+2]) return trainList def", "tmp = imageList[i:i+9] if len(tmp) == 9: trainList.append(imageList[i:i+9]) return trainList # def populateDvsList2(folderPath):", "0 st_y = 0 ed_y = w st_x = 0 ed_x = h", "populateTrainList(folderPath): folderList_pre = [x[0] for x in os.walk(folderPath)] folderList = [] trainList =", "12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb, trainList_dvs def populateTrainList2Rgb(folderPath): folderList = [x[0] for x", "len(self.trainList)) print(\"# of dvs samples:\", len(self.dvsList)) def __getitem__(self, index): img_path_list = self.trainList[index] dvs_path_list", "__getitem__(self, index): img_path_list = self.trainList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape image =", "len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateValList2Rgb(folderPath): folderList = [x[0] for x", "def __init__(self, folderPath, mode='test'): self.trainList = populateTestList2(folderPath) self.mode = mode print(\"# of training", "samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index] start = 0 h,w,c =", "= self.trainList[index] dvs_path_list = self.dvsList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape h,w =", "torch.utils.data as data import numpy as np import cv2 from PIL import Image", "dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp)", "def __getitem__(self, index): img_path_list = self.trainList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape image", "return len(self.trainList) class dvsLoader(data.Dataset): def __init__(self, imFolderPath, dvsFolderPath, mode='train'): self.trainList, self.dvsList = populateTrainList2(imFolderPath,", "0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list, cropped_dvs_list = randomCropOnListDvs(img_list, dvs_list ,(352,352)) for i in", "- w) st_y = 0 ed_y = w st_x = 0 ed_x =", "2): tmp = imageList[i:i+2] if len(tmp) == 2: trainList.append(imageList[i:i+2]) return trainList def fixedCropOnList(image_list,", "= dvs_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h) j = random.randint(0, width", "ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() new_dvs[st_y: ed_y, st_x:", "cropped_img_list = randomCropOnList(img_list,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return", "in image_list: new_img = np.empty((h,w,3), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] =", "in range(0, len(imageList), 12): tmp_rgb = imageList[i:i+12] tmp_dvs = dvsList[i:i+12] if len(tmp_rgb) ==", "img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = fixedCropOnList(img_list, (352, 352)) for i", "= [x[0] for x in os.walk(folderPath)] # trainList = [] # for folder", "tmp = imageList[i:i+2] if len(tmp) == 2: trainList.append(imageList[i:i+2]) return trainList def fixedCropOnList(image_list, output_size):", "or_ed_x, or_st_y, or_ed_y) for img in image_list: new_img = np.empty((h,w,3), dtype=np.float32) new_img.fill(128) new_img[st_y:", "len(tmp_rgb) == 12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb, trainList_dvs def populateTrainList2Rgb(folderPath): folderList = [x[0]", "cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)]", "new_img = np.empty((h,w,3), dtype=np.float32) new_dvs = np.empty((h,w), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x,", "def __len__(self): return len(self.trainList) class valLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateValList2Rgb(folderPath)", "folderList = [x[0] for x in os.walk(folderPath)] # trainList = [] # for", "trainList.append(imageList[i:i+2]) return trainList def fixedCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size height,", "dvsFolderPath) # self.dvsList = populateTrainList2Dvs(dvsFolderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList))", "= [x[0] for x in os.walk(folderPath)] folderList = [] trainList = [] for", "self.dvsList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape h,w = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image =", "in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX, scaleY)) thresh = 127 tmp =", "zip(folderListRgb, folderListDvs): imageList = sorted(glob.glob(im_folder + '/' + '*.jpg')) dvsList = sorted(glob.glob(dvs_folder +", "_ = image_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h) j = random.randint(0,", "import Image import glob import os, pdb import random def populateTrainList(folderPath): folderList_pre =", "tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp =", "ed_x = h or_st_y = i or_ed_y = i + w or_st_x =", "torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class valLoader(data.Dataset): def __init__(self,", "= cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i", "1))) for i in range(len(cropped_dvs_list)): cropped_dvs_list[i] = torch.from_numpy(cropped_dvs_list[i]) return cropped_img_list, cropped_dvs_list def __len__(self):", "new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img))", ",(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) for i in", "i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) for i in range(len(cropped_dvs_list)): cropped_dvs_list[i]", "imageList = sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0, len(imageList), 2):", "dvs_path_list = self.dvsList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape h,w = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape", "or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnListDvs(image_list, dvs_list, output_size): cropped_img_list = []", "self.mode = mode print(\"# of training samples:\", len(self.trainList)) print(\"# of dvs samples:\", len(self.dvsList))", "12): tmp = imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateValList2Rgb(folderPath):", "img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list", "img_list[i][:,:,2] /= 0.225 cropped_img_list = randomCropOnList(img_list,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2,", "start = 0 h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h >", "'*.jpg')) # for i in range(0, len(imageList), 12): # tmp = imageList[i:i+12] #", "= 360 scaleY = int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+2]: tmp", "0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = fixedCropOnList(img_list, (352, 352)) for", "== '240': folderList.append(folder + \"/\" + folder.split(\"/\")[-2]) for folder in folderList: imageList =", "= np.empty((h,w), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x:", "'*.jpg')) dvsList = sorted(glob.glob(dvs_folder + '/' + '*.png')) minLen = min(len(imageList), len(dvsList)) imageList", "trainList = [] for folder in folderList: imageList = sorted(glob.glob(folder + '/' +", "class valLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateValList2Rgb(folderPath) self.mode = mode print(\"#", "(scaleX, scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp)", "= img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnListDvs(image_list, dvs_list, output_size):", "height, width, _ = image_list[0].shape dvs_h, dvs_w = dvs_list[0].shape #print(h,w,height,width) i = random.randint(0,", "cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset): def __init__(self, folderPath, mode='train'): self.trainList =", "'/' + '*.jpg')) for i in range(0, len(imageList), 9): tmp = imageList[i:i+9] if", "<= w: scaleX = 360 scaleY = int(360*(w/h)) img_list = [] dvs_list =", "or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnList(image_list, output_size): cropped_img_list = []", "or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnListDvs(image_list, dvs_list, output_size): cropped_img_list =", "len(imageList), 12): tmp_rgb = imageList[i:i+12] tmp_dvs = dvsList[i:i+12] if len(tmp_rgb) == 12: trainList_rgb.append(imageList[i:i+12])", "#print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img,dvs in zip(image_list, dvs_list):", ":] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() new_dvs[st_y: ed_y, st_x: ed_x] = dvs[or_st_y:", "# folderList = [x[0] for x in os.walk(folderPath)] # trainList = [] #", "255 img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5) - 1 img_list[i][:,:,1] -= 0.456 img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0]", "randomCropOnList(img_list,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def", "-= 0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list =", "dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in range(len(img_list)): #print(img_list[i].shape) #brak img_list[i]", "imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateTrainList2(rgbPath, dvsPath): folderListRgb =", "[x[0] for x in os.walk(folderPath)] trainList = [] for folder in folderList: imageList", "= 360 scaleY = int(360*(w/h)) img_list = [] flip = random.randint(0,1) if flip:", "cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in range(len(img_list)):", "folderListRgb = [x[0] for x in os.walk(rgbPath)] folderListDvs = [x[0] for x in", "os.walk(rgbPath)] folderListDvs = [x[0] for x in os.walk(dvsPath)] trainList_rgb = [] trainList_dvs =", "= [x[0] for x in os.walk(folderPath)] trainList = [] for folder in folderList:", "cv2.imread(img_path_list[0]).shape h,w = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image = cv2.imread(img_path_list[0]) dvs = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c)", "populateValList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList = [] for folder", "os.walk(folderPath)] trainList = [] for folder in folderList: imageList = sorted(glob.glob(folder + '/'", "i or_ed_y = i + w or_st_x = j or_ed_x = j +", "torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class testLoader(data.Dataset): def __init__(self,", "i in range(0, len(imageList), 2): tmp = imageList[i:i+2] if len(tmp) == 2: trainList.append(imageList[i:i+2])", "or_ed_y, or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset): def __init__(self,", "fixedCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size height, width, _ = image_list[0].shape", "int(360*(h/w)) scaleY = 360 elif h <= w: scaleX = 360 scaleY =", "= 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff", "output_size): cropped_img_list = [] cropped_dvs_list = [] h,w = output_size height, width, _", "PIL import Image import glob import os, pdb import random def populateTrainList(folderPath): folderList_pre", "for folder in folderList: # imageList = sorted(glob.glob(folder + '/' + '*.jpg')) #", "1 img_list[i][:,:,1] -= 0.456 img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224", "= torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class valLoader(data.Dataset): def", "= random.randint(0,1) if flip: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1),", "folderList = [x[0] for x in os.walk(folderPath)] trainList = [] for folder in", "len(imageList), 12): tmp = imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def", "h,w = output_size height, width, _ = image_list[0].shape i = 100 j =", "0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = fixedCropOnList(img_list, (352, 352)) for i in range(len(cropped_img_list)):", "imageList[i:i+9] if len(tmp) == 9: trainList.append(imageList[i:i+9]) return trainList # def populateDvsList2(folderPath): # folderList", "12): # tmp = imageList[i:i+12] # if len(tmp) == 12: # trainList.append(imageList[i:i+12]) #", "img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh =", "len(imageList), 12): # tmp = imageList[i:i+12] # if len(tmp) == 12: # trainList.append(imageList[i:i+12])", "in os.walk(rgbPath)] folderListDvs = [x[0] for x in os.walk(dvsPath)] trainList_rgb = [] trainList_dvs", "height, width, _ = image_list[0].shape i = 100 j = 0 st_y =", "= i + w or_st_x = j or_ed_x = j + h #print(st_x,", "0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class valLoader(data.Dataset): def __init__(self, folderPath,", "cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size height,", "img,dvs in zip(image_list, dvs_list): new_img = np.empty((h,w,3), dtype=np.float32) new_dvs = np.empty((h,w), dtype=np.float32) new_img.fill(128)", "img_list[i][:,:,1] -= 0.456 img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2]", "= [] h,w = output_size height, width, _ = image_list[0].shape i = 100", "int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+2]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)]", "= dvs[or_st_y: or_ed_y, or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset):", "dvs[or_st_y: or_ed_y, or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset): def", "(352, 352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list", "0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list, cropped_dvs_list = randomCropOnListDvs(img_list, dvs_list ,(352,352))", "<= w: scaleX = 360 scaleY = int(360*(w/h)) img_list = [] flip =", "== 12: trainList.append(imageList[i:i+12]) return trainList def populateValList2Rgb(folderPath): folderList = [x[0] for x in", "= random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h > w:", "0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = randomCropOnList(img_list,(352,352)) for i in", "return cropped_img_list def randomCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size height, width,", "in img_path_list[start:start+2]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak", "img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp =", "st_x = 0 ed_x = h or_st_y = i or_ed_y = i +", "cropped_dvs_list = randomCropOnListDvs(img_list, dvs_list ,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0,", "= [] for im_folder, dvs_folder in zip(folderListRgb, folderListDvs): imageList = sorted(glob.glob(im_folder + '/'", "= 360 elif h <= w: scaleX = 360 scaleY = int(360*(w/h)) img_list", "= 0 ed_y = w st_x = 0 ed_x = h or_st_y =", "w st_x = 0 ed_x = h or_st_y = i or_ed_y = i", "= randomCropOnList(img_list,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list", "__init__(self, folderPath, mode='test'): self.trainList = populateTestList2(folderPath) self.mode = mode print(\"# of training samples:\",", "100 j = 0 st_y = 0 ed_y = w st_x = 0", "samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index] start = random.randint(0,3) h,w,c =", "= random.randint(0, width - w) st_y = 0 ed_y = w st_x =", "img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in range(len(img_list)): #print(img_list[i].shape) #brak img_list[i]", "= [] # for folder in folderList: # imageList = sorted(glob.glob(folder + '/'", "thresh = 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) &", "127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak", "sorted(glob.glob(dvs_folder + '/' + '*.png')) minLen = min(len(imageList), len(dvsList)) imageList = imageList[:minLen] dvsList", "st_y = 0 ed_y = w st_x = 0 ed_x = h or_st_y", "= self.trainList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if", "tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path,", "trainList def populateValList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList = []", "= h or_st_y = i or_ed_y = i + w or_st_x = j", "img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in", "#brak img_list[i] /= 255 img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5) - 1 img_list[i][:,:,1] -= 0.456 img_list[i][:,:,2]", "for img in image_list: new_img = np.empty((h,w,3), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x,", "range(len(img_list)): #print(img_list[i].shape) #brak img_list[i] /= 255 img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5) - 1 img_list[i][:,:,1] -=", "> w: scaleX = int(360*(h/w)) scaleY = 360 elif h <= w: scaleX", "sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0, len(imageList), 9): tmp =", "data import numpy as np import cv2 from PIL import Image import glob", "img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]:", "= cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX, scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh, 1,", "len(self.trainList) class valLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateValList2Rgb(folderPath) self.mode = mode", "randomCropOnListDvs(img_list, dvs_list ,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) for", "= [] trainList = [] for folder in folderList_pre: if folder[-3:] == '240':", "random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h > w: scaleX", "[] flip = random.randint(0,1) if flip: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path),", "- 1 img_list[i][:,:,1] -= 0.456 img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /=", "if len(tmp) == 2: trainList.append(imageList[i:i+2]) return trainList def fixedCropOnList(image_list, output_size): cropped_img_list = []", "new_img = np.empty((h,w,3), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y,", "folder in folderList: imageList = sorted(glob.glob(folder + '/' + '*.jpg')) for i in", "sorted(glob.glob(im_folder + '/' + '*.jpg')) dvsList = sorted(glob.glob(dvs_folder + '/' + '*.png')) minLen", "(scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)]", "_ = image_list[0].shape i = 100 j = 0 st_y = 0 ed_y", "= sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0, len(imageList), 12): tmp", "h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img,dvs in zip(image_list,", "width - w) st_y = 0 ed_y = w st_x = 0 ed_x", "return cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset): def __init__(self, folderPath, mode='train'): self.trainList = populateTrainList2Rgb(folderPath)", "dvsList[i:i+12] if len(tmp_rgb) == 12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb, trainList_dvs def populateTrainList2Rgb(folderPath): folderList", "new_dvs = np.empty((h,w), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y,", "image_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h) j = random.randint(0, width -", "= [] trainList_dvs = [] for im_folder, dvs_folder in zip(folderListRgb, folderListDvs): imageList =", "or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnList(image_list, output_size): cropped_img_list = [] h,w =", "360 scaleY = int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+2]: tmp =", "def __init__(self, folderPath, mode='test'): self.trainList = populateValList2Rgb(folderPath) self.mode = mode print(\"# of training", "= torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class dvsLoader(data.Dataset): def", "for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self):", "[] for im_folder, dvs_folder in zip(folderListRgb, folderListDvs): imageList = sorted(glob.glob(im_folder + '/' +", "dvsFolderPath, mode='train'): self.trainList, self.dvsList = populateTrainList2(imFolderPath, dvsFolderPath) # self.dvsList = populateTrainList2Dvs(dvsFolderPath) self.mode =", "for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path in", "/= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list, cropped_dvs_list = randomCropOnListDvs(img_list, dvs_list ,(352,352)) for i", "os.walk(folderPath)] # trainList = [] # for folder in folderList: # imageList =", "= img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnList(image_list, output_size): cropped_img_list", "torch import torch.utils.data as data import numpy as np import cv2 from PIL", "self.trainList = populateTestList2(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self,", "#print(h,w,c) if h > w: scaleX = int(360*(h/w)) scaleY = 360 elif h", "width, _ = image_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h) j =", "return trainList def fixedCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size height, width,", "h,w,c = cv2.imread(img_path_list[0]).shape h,w = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image = cv2.imread(img_path_list[0]) dvs = cv2.imread(dvs_path_list[0],", "st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def", "0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = fixedCropOnList(img_list,", "#print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img in image_list: new_img", "= imageList[i:i+2] if len(tmp) == 2: trainList.append(imageList[i:i+2]) return trainList def fixedCropOnList(image_list, output_size): cropped_img_list", "= cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image = cv2.imread(img_path_list[0]) dvs = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c) if h", "+ '/' + '*.jpg')) # for i in range(0, len(imageList), 12): # tmp", "or_ed_y) for img in image_list: new_img = np.empty((h,w,3), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x:", "0.485#(img_list[i]/127.5) - 1 img_list[i][:,:,1] -= 0.456 img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1]", "dvsList = sorted(glob.glob(dvs_folder + '/' + '*.png')) minLen = min(len(imageList), len(dvsList)) imageList =", "st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() new_dvs[st_y: ed_y, st_x: ed_x]", "class dvsLoader(data.Dataset): def __init__(self, imFolderPath, dvsFolderPath, mode='train'): self.trainList, self.dvsList = populateTrainList2(imFolderPath, dvsFolderPath) #", "cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image = cv2.imread(img_path_list[0]) dvs = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c) if h >", "= [] for folder in folderList: imageList = sorted(glob.glob(folder + '/' + '*.jpg'))", "for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX, scaleY)) thresh = 127", "folder in folderList_pre: if folder[-3:] == '240': folderList.append(folder + \"/\" + folder.split(\"/\")[-2]) for", "0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list, cropped_dvs_list =", "img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list, cropped_dvs_list = randomCropOnListDvs(img_list,", "tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX, scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh,", "len(dvsList)) imageList = imageList[:minLen] dvsList = dvsList[:minLen] for i in range(0, len(imageList), 12):", "= mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index]", "img_path_list = self.trainList[index] start = 0 h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c)", "dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for", "sorted(glob.glob(folder + '/' + '*.jpg')) # for i in range(0, len(imageList), 12): #", "return trainList # def populateDvsList2(folderPath): # folderList = [x[0] for x in os.walk(folderPath)]", "[x[0] for x in os.walk(rgbPath)] folderListDvs = [x[0] for x in os.walk(dvsPath)] trainList_rgb", "[] for folder in folderList_pre: if folder[-3:] == '240': folderList.append(folder + \"/\" +", "height - h) j = random.randint(0, width - w) st_y = 0 ed_y", "# trainList.append(imageList[i:i+12]) # return trainList def populateTestList2(folderPath): folderList = [x[0] for x in", "start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape h,w = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image = cv2.imread(img_path_list[0])", "2: trainList.append(imageList[i:i+2]) return trainList def fixedCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size", "imageList = imageList[:minLen] dvsList = dvsList[:minLen] for i in range(0, len(imageList), 12): tmp_rgb", "__getitem__(self, index): img_path_list = self.trainList[index] start = 0 h,w,c = cv2.imread(img_path_list[0]).shape image =", "trainList_rgb, trainList_dvs def populateTrainList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList =", "return cropped_img_list def __len__(self): return len(self.trainList) class dvsLoader(data.Dataset): def __init__(self, imFolderPath, dvsFolderPath, mode='train'):", "(scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh", "w: scaleX = 360 scaleY = int(360*(w/h)) img_list = [] for img_path in", "img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]:", "tmp = imageList[i:i+12] # if len(tmp) == 12: # trainList.append(imageList[i:i+12]) # return trainList", "'*.jpg')) for i in range(0, len(imageList), 9): tmp = imageList[i:i+9] if len(tmp) ==", "ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img,dvs in zip(image_list, dvs_list): new_img", "cropped_img_list, cropped_dvs_list = randomCropOnListDvs(img_list, dvs_list ,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2,", "= fixedCropOnList(img_list, (352, 352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1)))", "import torch import torch.utils.data as data import numpy as np import cv2 from", "tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path,", "in zip(image_list, dvs_list): new_img = np.empty((h,w,3), dtype=np.float32) new_dvs = np.empty((h,w), dtype=np.float32) new_img.fill(128) new_img[st_y:", "for i in range(0, len(imageList), 2): tmp = imageList[i:i+2] if len(tmp) == 2:", "tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh, 1,", "i in range(0, len(imageList), 12): tmp_rgb = imageList[i:i+12] tmp_dvs = dvsList[i:i+12] if len(tmp_rgb)", "= sorted(glob.glob(im_folder + '/' + '*.jpg')) dvsList = sorted(glob.glob(dvs_folder + '/' + '*.png'))", "in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]:", "img_path_list[start:start+2]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for", "fixedCropOnList(img_list, (352, 352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return", "self.trainList = populateValList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self,", "dvs_h, dvs_w = dvs_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h) j =", "self.dvsList = populateTrainList2(imFolderPath, dvsFolderPath) # self.dvsList = populateTrainList2Dvs(dvsFolderPath) self.mode = mode print(\"# of", "(scaleX,scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else:", "print(\"# of training samples:\", len(self.trainList)) print(\"# of dvs samples:\", len(self.dvsList)) def __getitem__(self, index):", "imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateValList2Rgb(folderPath): folderList = [x[0]", "output_size height, width, _ = image_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h)", "scaleY = 360 elif h <= w: scaleX = 360 scaleY = int(360*(w/h))", "folder[-3:] == '240': folderList.append(folder + \"/\" + folder.split(\"/\")[-2]) for folder in folderList: imageList", "in os.walk(folderPath)] folderList = [] trainList = [] for folder in folderList_pre: if", "#print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img in image_list: new_img = np.empty((h,w,3), dtype=np.float32) new_img.fill(128)", ":].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnListDvs(image_list, dvs_list, output_size): cropped_img_list = [] cropped_dvs_list =", "= cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in", "zip(image_list, dvs_list): new_img = np.empty((h,w,3), dtype=np.float32) new_dvs = np.empty((h,w), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y,", ":] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnList(image_list, output_size):", "populateTrainList2(rgbPath, dvsPath): folderListRgb = [x[0] for x in os.walk(rgbPath)] folderListDvs = [x[0] for", "+ '/' + '*.jpg')) for i in range(0, len(imageList), 9): tmp = imageList[i:i+9]", "img_list = [] flip = random.randint(0,1) if flip: for img_path in img_path_list[start:start+9]: tmp", "samples:\", len(self.trainList)) print(\"# of dvs samples:\", len(self.dvsList)) def __getitem__(self, index): img_path_list = self.trainList[index]", "= np.empty((h,w,3), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x:", "def __init__(self, imFolderPath, dvsFolderPath, mode='train'): self.trainList, self.dvsList = populateTrainList2(imFolderPath, dvsFolderPath) # self.dvsList =", "width, _ = image_list[0].shape i = 100 j = 0 st_y = 0", "+ h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img in", "[] h,w = output_size height, width, _ = image_list[0].shape i = 100 j", "12): tmp_rgb = imageList[i:i+12] tmp_dvs = dvsList[i:i+12] if len(tmp_rgb) == 12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12])", "def populateValList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList = [] for", "randomCropOnListDvs(image_list, dvs_list, output_size): cropped_img_list = [] cropped_dvs_list = [] h,w = output_size height,", "tmp = imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateValList2Rgb(folderPath): folderList", "w: scaleX = 360 scaleY = int(360*(w/h)) img_list = [] flip = random.randint(0,1)", "image = cv2.imread(img_path_list[0]) dvs = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c) if h > w: scaleX", "def randomCropOnListDvs(image_list, dvs_list, output_size): cropped_img_list = [] cropped_dvs_list = [] h,w = output_size", "dvsList[:minLen] for i in range(0, len(imageList), 12): tmp_rgb = imageList[i:i+12] tmp_dvs = dvsList[i:i+12]", "valLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateValList2Rgb(folderPath) self.mode = mode print(\"# of", "new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() new_dvs[st_y:", "ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img in image_list: new_img =", "or_ed_x, :].copy() new_dvs[st_y: ed_y, st_x: ed_x] = dvs[or_st_y: or_ed_y, or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs))", "h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h > w: scaleX =", "if len(tmp) == 12: # trainList.append(imageList[i:i+12]) # return trainList def populateTestList2(folderPath): folderList =", "= output_size height, width, _ = image_list[0].shape #print(h,w,height,width) i = random.randint(0, height -", "for x in os.walk(folderPath)] folderList = [] trainList = [] for folder in", "= 0 ed_x = h or_st_y = i or_ed_y = i + w", "def __init__(self, folderPath, mode='train'): self.trainList = populateTrainList2Rgb(folderPath) self.mode = mode print(\"# of training", "= int(360*(h/w)) scaleY = 360 elif h <= w: scaleX = 360 scaleY", "image_list[0].shape dvs_h, dvs_w = dvs_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h) j", "dvsLoader(data.Dataset): def __init__(self, imFolderPath, dvsFolderPath, mode='train'): self.trainList, self.dvsList = populateTrainList2(imFolderPath, dvsFolderPath) # self.dvsList", "__getitem__(self, index): img_path_list = self.trainList[index] dvs_path_list = self.dvsList[index] start = random.randint(0,3) h,w,c =", "= random.randint(0, height - h) j = random.randint(0, width - w) st_y =", "dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh = 127 tmp =", "sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0, len(imageList), 2): tmp =", "for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) &", "0 ed_y = w st_x = 0 ed_x = h or_st_y = i", "or_ed_y) for img,dvs in zip(image_list, dvs_list): new_img = np.empty((h,w,3), dtype=np.float32) new_dvs = np.empty((h,w),", "/= 0.225 cropped_img_list = fixedCropOnList(img_list, (352, 352)) for i in range(len(cropped_img_list)): cropped_img_list[i] =", "img_path_list = self.trainList[index] dvs_path_list = self.dvsList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape h,w", "os.walk(folderPath)] folderList = [] trainList = [] for folder in folderList_pre: if folder[-3:]", "= cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c) if h > w: scaleX = int(360*(h/w)) scaleY =", "360 scaleY = int(360*(w/h)) img_list = [] dvs_list = [] flip = random.randint(0,1)", "return trainList def populateTestList2(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList =", "0.225 cropped_img_list = fixedCropOnList(img_list, (352, 352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2,", "+ '/' + '*.jpg')) for i in range(0, len(imageList), 2): tmp = imageList[i:i+2]", "trainList def populateTrainList2(rgbPath, dvsPath): folderListRgb = [x[0] for x in os.walk(rgbPath)] folderListDvs =", "0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class testLoader(data.Dataset): def __init__(self, folderPath,", "h or_st_y = i or_ed_y = i + w or_st_x = j or_ed_x", "'/' + '*.png')) minLen = min(len(imageList), len(dvsList)) imageList = imageList[:minLen] dvsList = dvsList[:minLen]", "# for folder in folderList: # imageList = sorted(glob.glob(folder + '/' + '*.jpg'))", "trainList.append(imageList[i:i+12]) # return trainList def populateTestList2(folderPath): folderList = [x[0] for x in os.walk(folderPath)]", "def populateTrainList(folderPath): folderList_pre = [x[0] for x in os.walk(folderPath)] folderList = [] trainList", "= j + h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for", "ed_y, st_x: ed_x] = dvs[or_st_y: or_ed_y, or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list, cropped_dvs_list", "[x[0] for x in os.walk(dvsPath)] trainList_rgb = [] trainList_dvs = [] for im_folder,", "scaleY = int(360*(w/h)) img_list = [] flip = random.randint(0,1) if flip: for img_path", "range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) for i in range(len(cropped_dvs_list)): cropped_dvs_list[i] = torch.from_numpy(cropped_dvs_list[i])", "ed_x] = dvs[or_st_y: or_ed_y, or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class", "dvs_folder in zip(folderListRgb, folderListDvs): imageList = sorted(glob.glob(im_folder + '/' + '*.jpg')) dvsList =", "0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class dvsLoader(data.Dataset): def __init__(self, imFolderPath,", "img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = fixedCropOnList(img_list, (352,", "training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index] start = random.randint(0,3) h,w,c", "self.trainList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h", "img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnList(image_list, output_size): cropped_img_list =", "= randomCropOnListDvs(img_list, dvs_list ,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1)))", "output_size height, width, _ = image_list[0].shape dvs_h, dvs_w = dvs_list[0].shape #print(h,w,height,width) i =", "folderList_pre = [x[0] for x in os.walk(folderPath)] folderList = [] trainList = []", "x in os.walk(rgbPath)] folderListDvs = [x[0] for x in os.walk(dvsPath)] trainList_rgb = []", "9: trainList.append(imageList[i:i+9]) return trainList # def populateDvsList2(folderPath): # folderList = [x[0] for x", "w or_st_x = j or_ed_x = j + h #print(st_x, ed_x, st_y, ed_y)", "int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)]", "min(len(imageList), len(dvsList)) imageList = imageList[:minLen] dvsList = dvsList[:minLen] for i in range(0, len(imageList),", "_ = image_list[0].shape dvs_h, dvs_w = dvs_list[0].shape #print(h,w,height,width) i = random.randint(0, height -", "360 scaleY = int(360*(w/h)) img_list = [] flip = random.randint(0,1) if flip: for", "return cropped_img_list def __len__(self): return len(self.trainList) class valLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList", "len(tmp) == 2: trainList.append(imageList[i:i+2]) return trainList def fixedCropOnList(image_list, output_size): cropped_img_list = [] h,w", "class testLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateTestList2(folderPath) self.mode = mode print(\"#", "= [] h,w = output_size height, width, _ = image_list[0].shape #print(h,w,height,width) i =", "in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp", "cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32))", "ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnList(image_list,", "cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset): def __init__(self, folderPath, mode='train'): self.trainList = populateTrainList2Rgb(folderPath) self.mode", "0, 1))) for i in range(len(cropped_dvs_list)): cropped_dvs_list[i] = torch.from_numpy(cropped_dvs_list[i]) return cropped_img_list, cropped_dvs_list def", "= sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0, len(imageList), 2): tmp", "/= 0.225 cropped_img_list = randomCropOnList(img_list,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0,", "tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for", "cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) for i in range(len(cropped_dvs_list)): cropped_dvs_list[i] = torch.from_numpy(cropped_dvs_list[i]) return", "testLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateTestList2(folderPath) self.mode = mode print(\"# of", "scaleY = int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path),", "in range(len(img_list)): #print(img_list[i].shape) #brak img_list[i] /= 255 img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5) - 1 img_list[i][:,:,1]", "return cropped_img_list def randomCropOnListDvs(image_list, dvs_list, output_size): cropped_img_list = [] cropped_dvs_list = [] h,w", "#print(img_list[i].shape) #brak img_list[i] /= 255 img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5) - 1 img_list[i][:,:,1] -= 0.456", "imageList[i:i+12] # if len(tmp) == 12: # trainList.append(imageList[i:i+12]) # return trainList def populateTestList2(folderPath):", "[] h,w = output_size height, width, _ = image_list[0].shape dvs_h, dvs_w = dvs_list[0].shape", "1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in range(len(img_list)): #print(img_list[i].shape)", "scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in range(len(img_list)): #print(img_list[i].shape) #brak", "self.trainList[index] start = 0 h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h", "= [] for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp)", "class expansionLoader(data.Dataset): def __init__(self, folderPath, mode='train'): self.trainList = populateTrainList2Rgb(folderPath) self.mode = mode print(\"#", "+ folder.split(\"/\")[-2]) for folder in folderList: imageList = sorted(glob.glob(folder + '/' + '*.jpg'))", "/= 255 img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5) - 1 img_list[i][:,:,1] -= 0.456 img_list[i][:,:,2] -= 0.406", "imageList = sorted(glob.glob(folder + '/' + '*.jpg')) # for i in range(0, len(imageList),", "= cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path),", "= min(len(imageList), len(dvsList)) imageList = imageList[:minLen] dvsList = dvsList[:minLen] for i in range(0,", "+ '*.jpg')) # for i in range(0, len(imageList), 12): # tmp = imageList[i:i+12]", "cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnListDvs(image_list, dvs_list, output_size): cropped_img_list = [] cropped_dvs_list = []", "img_path in img_path_list[start:start+2]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff", "'/' + '*.jpg')) dvsList = sorted(glob.glob(dvs_folder + '/' + '*.png')) minLen = min(len(imageList),", "output_size): cropped_img_list = [] h,w = output_size height, width, _ = image_list[0].shape #print(h,w,height,width)", "cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,", "as data import numpy as np import cv2 from PIL import Image import", "i = random.randint(0, height - h) j = random.randint(0, width - w) st_y", "def __len__(self): return len(self.trainList) class testLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateTestList2(folderPath)", "range(0, len(imageList), 12): tmp = imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList", "imageList[:minLen] dvsList = dvsList[:minLen] for i in range(0, len(imageList), 12): tmp_rgb = imageList[i:i+12]", "/= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = fixedCropOnList(img_list, (352, 352)) for i in", "folderList.append(folder + \"/\" + folder.split(\"/\")[-2]) for folder in folderList: imageList = sorted(glob.glob(folder +", "randomCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size height, width, _ = image_list[0].shape", "img_list[i] /= 255 img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5) - 1 img_list[i][:,:,1] -= 0.456 img_list[i][:,:,2] -=", "<= w: scaleX = 360 scaleY = int(360*(w/h)) img_list = [] for img_path", "+ '*.jpg')) for i in range(0, len(imageList), 2): tmp = imageList[i:i+2] if len(tmp)", "trainList def populateTestList2(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList = []", "populateTrainList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList = [] for folder", "os.walk(dvsPath)] trainList_rgb = [] trainList_dvs = [] for im_folder, dvs_folder in zip(folderListRgb, folderListDvs):", "trainList_rgb = [] trainList_dvs = [] for im_folder, dvs_folder in zip(folderListRgb, folderListDvs): imageList", "trainList.append(imageList[i:i+12]) return trainList def populateValList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList", "in range(0, len(imageList), 12): # tmp = imageList[i:i+12] # if len(tmp) == 12:", ":].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size", "thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path),", "or_st_x = j or_ed_x = j + h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x,", "cropped_img_list def __len__(self): return len(self.trainList) class valLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList =", "ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img in image_list: new_img = np.empty((h,w,3), dtype=np.float32)", "cropped_img_list def __len__(self): return len(self.trainList) class dvsLoader(data.Dataset): def __init__(self, imFolderPath, dvsFolderPath, mode='train'): self.trainList,", "return trainList def populateValList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)] trainList =", "for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) for i in range(len(cropped_dvs_list)):", "import torch.utils.data as data import numpy as np import cv2 from PIL import", "cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX, scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1]", "if flip: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for", "return cropped_img_list def __len__(self): return len(self.trainList) class testLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList", "len(self.trainList) class dvsLoader(data.Dataset): def __init__(self, imFolderPath, dvsFolderPath, mode='train'): self.trainList, self.dvsList = populateTrainList2(imFolderPath, dvsFolderPath)", "img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp =", "populateTrainList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list", "0xff #brak for i in range(len(img_list)): #print(img_list[i].shape) #brak img_list[i] /= 255 img_list[i][:,:,0] -=", "len(imageList), 9): tmp = imageList[i:i+9] if len(tmp) == 9: trainList.append(imageList[i:i+9]) return trainList #", "== 12: trainList.append(imageList[i:i+12]) return trainList def populateTrainList2(rgbPath, dvsPath): folderListRgb = [x[0] for x", "= [] h,w = output_size height, width, _ = image_list[0].shape dvs_h, dvs_w =", "in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp", "j + h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img", "self.mode = mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list =", "flip: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for", "+ w or_st_x = j or_ed_x = j + h #print(st_x, ed_x, st_y,", "= dvsList[i:i+12] if len(tmp_rgb) == 12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb, trainList_dvs def populateTrainList2Rgb(folderPath):", "cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class testLoader(data.Dataset):", "w) st_y = 0 ed_y = w st_x = 0 ed_x = h", "j = random.randint(0, width - w) st_y = 0 ed_y = w st_x", "populateValList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list", "or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnList(image_list, output_size): cropped_img_list = [] h,w", "new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() new_dvs[st_y: ed_y,", "in os.walk(folderPath)] trainList = [] for folder in folderList: imageList = sorted(glob.glob(folder +", "dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32))", "dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX, scaleY)) thresh = 127 tmp", "= [] for img_path in img_path_list[start:start+2]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp)", "= 360 scaleY = int(360*(w/h)) img_list = [] dvs_list = [] flip =", "thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i in range(len(img_list)):", "[] dvs_list = [] flip = random.randint(0,1) if flip: for img_path in img_path_list[start:start+9]:", "= dvsList[:minLen] for i in range(0, len(imageList), 12): tmp_rgb = imageList[i:i+12] tmp_dvs =", "12: trainList.append(imageList[i:i+12]) return trainList def populateTrainList2(rgbPath, dvsPath): folderListRgb = [x[0] for x in", "x in os.walk(folderPath)] # trainList = [] # for folder in folderList: #", "scaleX = 360 scaleY = int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+9]:", "folderList: # imageList = sorted(glob.glob(folder + '/' + '*.jpg')) # for i in", "w: scaleX = 360 scaleY = int(360*(w/h)) img_list = [] dvs_list = []", "in range(0, len(imageList), 9): tmp = imageList[i:i+9] if len(tmp) == 9: trainList.append(imageList[i:i+9]) return", "dvs_list, output_size): cropped_img_list = [] cropped_dvs_list = [] h,w = output_size height, width,", "if flip: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else:", "trainList.append(imageList[i:i+9]) return trainList # def populateDvsList2(folderPath): # folderList = [x[0] for x in", "x in os.walk(dvsPath)] trainList_rgb = [] trainList_dvs = [] for im_folder, dvs_folder in", "dvs_list = [] flip = random.randint(0,1) if flip: for img_path in img_path_list[start:start+9]: tmp", "'*.jpg')) for i in range(0, len(imageList), 2): tmp = imageList[i:i+2] if len(tmp) ==", "#brak for i in range(len(img_list)): #print(img_list[i].shape) #brak img_list[i] /= 255 img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5)", "= image_list[0].shape dvs_h, dvs_w = dvs_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h)", "0.225 cropped_img_list, cropped_dvs_list = randomCropOnListDvs(img_list, dvs_list ,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] =", "random.randint(0,1) if flip: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32))", "folderPath, mode='test'): self.trainList = populateTestList2(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList))", "i in range(len(cropped_dvs_list)): cropped_dvs_list[i] = torch.from_numpy(cropped_dvs_list[i]) return cropped_img_list, cropped_dvs_list def __len__(self): return len(self.trainList)", "= [] cropped_dvs_list = [] h,w = output_size height, width, _ = image_list[0].shape", "self.trainList = populateTrainList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self,", "= sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0, len(imageList), 9): tmp", "= imageList[i:i+12] # if len(tmp) == 12: # trainList.append(imageList[i:i+12]) # return trainList def", "dvs_w = dvs_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h) j = random.randint(0,", "cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1),", "index): img_path_list = self.trainList[index] start = 0 h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0])", "imFolderPath, dvsFolderPath, mode='train'): self.trainList, self.dvsList = populateTrainList2(imFolderPath, dvsFolderPath) # self.dvsList = populateTrainList2Dvs(dvsFolderPath) self.mode", "random.randint(0, height - h) j = random.randint(0, width - w) st_y = 0", "img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX, scaleY)) thresh =", "return len(self.trainList) class testLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateTestList2(folderPath) self.mode =", "Image import glob import os, pdb import random def populateTrainList(folderPath): folderList_pre = [x[0]", "= 360 scaleY = int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+9]: tmp", "scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0)", "for i in range(0, len(imageList), 12): tmp_rgb = imageList[i:i+12] tmp_dvs = dvsList[i:i+12] if", "i in range(0, len(imageList), 9): tmp = imageList[i:i+9] if len(tmp) == 9: trainList.append(imageList[i:i+9])", "cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class dvsLoader(data.Dataset):", "i = 100 j = 0 st_y = 0 ed_y = w st_x", "img_path_list = self.trainList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c)", "mode print(\"# of training samples:\", len(self.trainList)) print(\"# of dvs samples:\", len(self.dvsList)) def __getitem__(self,", "self.trainList[index] dvs_path_list = self.dvsList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape h,w = cv2.imread(dvs_path_list[0],", "def populateDvsList2(folderPath): # folderList = [x[0] for x in os.walk(folderPath)] # trainList =", "cropped_img_list = [] h,w = output_size height, width, _ = image_list[0].shape #print(h,w,height,width) i", "tmp_rgb = imageList[i:i+12] tmp_dvs = dvsList[i:i+12] if len(tmp_rgb) == 12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return", "if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateValList2Rgb(folderPath): folderList = [x[0] for", "[] # for folder in folderList: # imageList = sorted(glob.glob(folder + '/' +", "<reponame>sha2nkt/dvs_super_slomo import torch import torch.utils.data as data import numpy as np import cv2", "import numpy as np import cv2 from PIL import Image import glob import", "for x in os.walk(rgbPath)] folderListDvs = [x[0] for x in os.walk(dvsPath)] trainList_rgb =", "of training samples:\", len(self.trainList)) print(\"# of dvs samples:\", len(self.dvsList)) def __getitem__(self, index): img_path_list", "[] trainList_dvs = [] for im_folder, dvs_folder in zip(folderListRgb, folderListDvs): imageList = sorted(glob.glob(im_folder", "0.456 img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225", "dvs_list): new_img = np.empty((h,w,3), dtype=np.float32) new_dvs = np.empty((h,w), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x:", "print(\"# of dvs samples:\", len(self.dvsList)) def __getitem__(self, index): img_path_list = self.trainList[index] dvs_path_list =", "range(0, len(imageList), 2): tmp = imageList[i:i+2] if len(tmp) == 2: trainList.append(imageList[i:i+2]) return trainList", "tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]:", "folderListDvs = [x[0] for x in os.walk(dvsPath)] trainList_rgb = [] trainList_dvs = []", ":].copy() new_dvs[st_y: ed_y, st_x: ed_x] = dvs[or_st_y: or_ed_y, or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return", "trainList = [] for folder in folderList_pre: if folder[-3:] == '240': folderList.append(folder +", "for i in range(0, len(imageList), 12): # tmp = imageList[i:i+12] # if len(tmp)", "np.empty((h,w,3), dtype=np.float32) new_dvs = np.empty((h,w), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] =", "= imageList[i:i+12] tmp_dvs = dvsList[i:i+12] if len(tmp_rgb) == 12: trainList_rgb.append(imageList[i:i+12]) trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb,", "def fixedCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size height, width, _ =", "for img,dvs in zip(image_list, dvs_list): new_img = np.empty((h,w,3), dtype=np.float32) new_dvs = np.empty((h,w), dtype=np.float32)", "#print(h,w,height,width) i = random.randint(0, height - h) j = random.randint(0, width - w)", "+ h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img,dvs in", "img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list, cropped_dvs_list = randomCropOnListDvs(img_list, dvs_list ,(352,352)) for", "for x in os.walk(dvsPath)] trainList_rgb = [] trainList_dvs = [] for im_folder, dvs_folder", "or_st_y = i or_ed_y = i + w or_st_x = j or_ed_x =", "img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for", "def randomCropOnList(image_list, output_size): cropped_img_list = [] h,w = output_size height, width, _ =", "1))) return cropped_img_list def __len__(self): return len(self.trainList) class dvsLoader(data.Dataset): def __init__(self, imFolderPath, dvsFolderPath,", "of dvs samples:\", len(self.dvsList)) def __getitem__(self, index): img_path_list = self.trainList[index] dvs_path_list = self.dvsList[index]", "/= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = randomCropOnList(img_list,(352,352)) for i", "= [] for folder in folderList_pre: if folder[-3:] == '240': folderList.append(folder + \"/\"", "len(tmp) == 9: trainList.append(imageList[i:i+9]) return trainList # def populateDvsList2(folderPath): # folderList = [x[0]", "trainList_dvs.append(dvsList[i:i+12]) return trainList_rgb, trainList_dvs def populateTrainList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)]", "img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32))", "+ '*.jpg')) dvsList = sorted(glob.glob(dvs_folder + '/' + '*.png')) minLen = min(len(imageList), len(dvsList))", "[x[0] for x in os.walk(folderPath)] # trainList = [] # for folder in", "0.406 img_list[i][:,:,0] /= 0.229 img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = randomCropOnList(img_list,(352,352))", "img_list[i][:,:,2] /= 0.225 cropped_img_list = fixedCropOnList(img_list, (352, 352)) for i in range(len(cropped_img_list)): cropped_img_list[i]", "= cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp", "'/' + '*.jpg')) for i in range(0, len(imageList), 12): tmp = imageList[i:i+12] if", "im_folder, dvs_folder in zip(folderListRgb, folderListDvs): imageList = sorted(glob.glob(im_folder + '/' + '*.jpg')) dvsList", "ed_y = w st_x = 0 ed_x = h or_st_y = i or_ed_y", "in range(0, len(imageList), 12): tmp = imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return", "h <= w: scaleX = 360 scaleY = int(360*(w/h)) img_list = [] dvs_list", "image_list[0].shape i = 100 j = 0 st_y = 0 ed_y = w", "thresh = 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for", "range(0, len(imageList), 12): # tmp = imageList[i:i+12] # if len(tmp) == 12: #", "cv2 from PIL import Image import glob import os, pdb import random def", "__len__(self): return len(self.trainList) class valLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateValList2Rgb(folderPath) self.mode", "h <= w: scaleX = 360 scaleY = int(360*(w/h)) img_list = [] flip", "new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return", "= np.empty((h,w,3), dtype=np.float32) new_dvs = np.empty((h,w), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :]", "tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak for i", "= int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+2]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,", "if folder[-3:] == '240': folderList.append(folder + \"/\" + folder.split(\"/\")[-2]) for folder in folderList:", "# for i in range(0, len(imageList), 12): # tmp = imageList[i:i+12] # if", "img_list = [] for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32))", "tmp = imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateTrainList2(rgbPath, dvsPath):", "= sorted(glob.glob(folder + '/' + '*.jpg')) # for i in range(0, len(imageList), 12):", "imageList = sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0, len(imageList), 12):", "for i in range(len(cropped_dvs_list)): cropped_dvs_list[i] = torch.from_numpy(cropped_dvs_list[i]) return cropped_img_list, cropped_dvs_list def __len__(self): return", "352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def", "== 12: # trainList.append(imageList[i:i+12]) # return trainList def populateTestList2(folderPath): folderList = [x[0] for", "= cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h > w: scaleX = int(360*(h/w))", "= cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY),", "trainList = [] # for folder in folderList: # imageList = sorted(glob.glob(folder +", "dvs samples:\", len(self.dvsList)) def __getitem__(self, index): img_path_list = self.trainList[index] dvs_path_list = self.dvsList[index] start", "cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h > w: scaleX = int(360*(h/w)) scaleY", "def __len__(self): return len(self.trainList) class dvsLoader(data.Dataset): def __init__(self, imFolderPath, dvsFolderPath, mode='train'): self.trainList, self.dvsList", "i in range(0, len(imageList), 12): # tmp = imageList[i:i+12] # if len(tmp) ==", "[] for img_path in img_path_list[start:start+2]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0)", "scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX, scaleY)) thresh", "image = cv2.imread(img_path_list[0]) #print(h,w,c) if h > w: scaleX = int(360*(h/w)) scaleY =", "img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in img_path_list[start:start+9]: tmp", "len(tmp) == 12: # trainList.append(imageList[i:i+12]) # return trainList def populateTestList2(folderPath): folderList = [x[0]", "__init__(self, folderPath, mode='test'): self.trainList = populateValList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\",", "len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index] start = 0 h,w,c = cv2.imread(img_path_list[0]).shape", "scaleX = int(360*(h/w)) scaleY = 360 elif h <= w: scaleX = 360", "img_list[i][:,:,2] /= 0.225 cropped_img_list, cropped_dvs_list = randomCropOnListDvs(img_list, dvs_list ,(352,352)) for i in range(len(cropped_img_list)):", "mode='train'): self.trainList = populateTrainList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def", "of training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index] start = random.randint(0,3)", "h,w = output_size height, width, _ = image_list[0].shape #print(h,w,height,width) i = random.randint(0, height", "print(\"# of training samples:\", len(self.trainList)) def __getitem__(self, index): img_path_list = self.trainList[index] start =", "= cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY),", "as np import cv2 from PIL import Image import glob import os, pdb", "imageList[i:i+2] if len(tmp) == 2: trainList.append(imageList[i:i+2]) return trainList def fixedCropOnList(image_list, output_size): cropped_img_list =", "# def populateDvsList2(folderPath): # folderList = [x[0] for x in os.walk(folderPath)] # trainList", "= 0 h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h > w:", "(scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX, scaleY))", "h <= w: scaleX = 360 scaleY = int(360*(w/h)) img_list = [] for", "#print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img,dvs in zip(image_list, dvs_list): new_img = np.empty((h,w,3), dtype=np.float32)", "1))) return cropped_img_list def __len__(self): return len(self.trainList) class valLoader(data.Dataset): def __init__(self, folderPath, mode='test'):", "scaleY = int(360*(w/h)) img_list = [] dvs_list = [] flip = random.randint(0,1) if", "127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1] dvs_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path in", "start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h >", "in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0) & 0xff #brak", "j = 0 st_y = 0 ed_y = w st_x = 0 ed_x", "0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = randomCropOnList(img_list,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] =", "st_y, ed_y) #print(or_st_x, or_ed_x, or_st_y, or_ed_y) for img,dvs in zip(image_list, dvs_list): new_img =", "= cv2.imread(img_path_list[0]) dvs = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c) if h > w: scaleX =", "img_list = [] for img_path in img_path_list[start:start+2]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32))", "int(360*(w/h)) img_list = [] flip = random.randint(0,1) if flip: for img_path in img_path_list[start:start+9]:", "cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class valLoader(data.Dataset):", "flip = random.randint(0,1) if flip: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)]", "[] cropped_dvs_list = [] h,w = output_size height, width, _ = image_list[0].shape dvs_h,", "import glob import os, pdb import random def populateTrainList(folderPath): folderList_pre = [x[0] for", "cv2.imread(img_path_list[0]) #print(h,w,c) if h > w: scaleX = int(360*(h/w)) scaleY = 360 elif", "np.empty((h,w,3), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x,", "__init__(self, imFolderPath, dvsFolderPath, mode='train'): self.trainList, self.dvsList = populateTrainList2(imFolderPath, dvsFolderPath) # self.dvsList = populateTrainList2Dvs(dvsFolderPath)", "'/' + '*.jpg')) for i in range(0, len(imageList), 2): tmp = imageList[i:i+2] if", "populateTrainList2Dvs(dvsFolderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) print(\"# of dvs samples:\",", "__len__(self): return len(self.trainList) class testLoader(data.Dataset): def __init__(self, folderPath, mode='test'): self.trainList = populateTestList2(folderPath) self.mode", "img_list[i][:,:,1] /= 0.224 img_list[i][:,:,2] /= 0.225 cropped_img_list = randomCropOnList(img_list,(352,352)) for i in range(len(cropped_img_list)):", "for x in os.walk(folderPath)] # trainList = [] # for folder in folderList:", "= torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) return cropped_img_list def __len__(self): return len(self.trainList) class testLoader(data.Dataset): def", "= populateTestList2(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self, index):", "cropped_img_list = fixedCropOnList(img_list, (352, 352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0,", "[] trainList = [] for folder in folderList_pre: if folder[-3:] == '240': folderList.append(folder", "= int(360*(w/h)) img_list = [] flip = random.randint(0,1) if flip: for img_path in", "# tmp = imageList[i:i+12] # if len(tmp) == 12: # trainList.append(imageList[i:i+12]) # return", "= image_list[0].shape #print(h,w,height,width) i = random.randint(0, height - h) j = random.randint(0, width", "+ '/' + '*.jpg')) dvsList = sorted(glob.glob(dvs_folder + '/' + '*.png')) minLen =", "'*.jpg')) for i in range(0, len(imageList), 12): tmp = imageList[i:i+12] if len(tmp) ==", "= [] dvs_list = [] flip = random.randint(0,1) if flip: for img_path in", ":] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) return cropped_img_list def randomCropOnListDvs(image_list, dvs_list,", "[] for folder in folderList: imageList = sorted(glob.glob(folder + '/' + '*.jpg')) for", "cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list, cropped_dvs_list #print(len(populateTrainList('/home/user/data/nfs/'))) class expansionLoader(data.Dataset): def __init__(self, folderPath, mode='train'): self.trainList", "range(0, len(imageList), 12): tmp_rgb = imageList[i:i+12] tmp_dvs = dvsList[i:i+12] if len(tmp_rgb) == 12:", "random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape h,w = cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY).shape image = cv2.imread(img_path_list[0]) dvs =", "0 h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0]) #print(h,w,c) if h > w: scaleX", "dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh,", "'/' + '*.jpg')) # for i in range(0, len(imageList), 12): # tmp =", "x in os.walk(folderPath)] folderList = [] trainList = [] for folder in folderList_pre:", "= [] flip = random.randint(0,1) if flip: for img_path in img_path_list[start:start+9]: tmp =", "= [x[0] for x in os.walk(dvsPath)] trainList_rgb = [] trainList_dvs = [] for", "w: scaleX = int(360*(h/w)) scaleY = 360 elif h <= w: scaleX =", "or_ed_x, or_st_y, or_ed_y) for img,dvs in zip(image_list, dvs_list): new_img = np.empty((h,w,3), dtype=np.float32) new_dvs", "img_list[i][:,:,0] -= 0.485#(img_list[i]/127.5) - 1 img_list[i][:,:,1] -= 0.456 img_list[i][:,:,2] -= 0.406 img_list[i][:,:,0] /=", "= mode print(\"# of training samples:\", len(self.trainList)) print(\"# of dvs samples:\", len(self.dvsList)) def", "sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0, len(imageList), 12): tmp =", "img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy() new_dvs[st_y: ed_y, st_x: ed_x] = dvs[or_st_y: or_ed_y, or_st_x:", "= int(360*(w/h)) img_list = [] dvs_list = [] flip = random.randint(0,1) if flip:", "imageList = sorted(glob.glob(im_folder + '/' + '*.jpg')) dvsList = sorted(glob.glob(dvs_folder + '/' +", "cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) for dvs_path in dvs_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,", "in os.walk(dvsPath)] trainList_rgb = [] trainList_dvs = [] for im_folder, dvs_folder in zip(folderListRgb,", "== 2: trainList.append(imageList[i:i+2]) return trainList def fixedCropOnList(image_list, output_size): cropped_img_list = [] h,w =", "& 0xff #brak for i in range(len(img_list)): #print(img_list[i].shape) #brak img_list[i] /= 255 img_list[i][:,:,0]", "= output_size height, width, _ = image_list[0].shape dvs_h, dvs_w = dvs_list[0].shape #print(h,w,height,width) i", "h,w = output_size height, width, _ = image_list[0].shape dvs_h, dvs_w = dvs_list[0].shape #print(h,w,height,width)", "h > w: scaleX = int(360*(h/w)) scaleY = 360 elif h <= w:", "os, pdb import random def populateTrainList(folderPath): folderList_pre = [x[0] for x in os.walk(folderPath)]", "len(self.dvsList)) def __getitem__(self, index): img_path_list = self.trainList[index] dvs_path_list = self.dvsList[index] start = random.randint(0,3)", "x in os.walk(folderPath)] trainList = [] for folder in folderList: imageList = sorted(glob.glob(folder", "mode='train'): self.trainList, self.dvsList = populateTrainList2(imFolderPath, dvsFolderPath) # self.dvsList = populateTrainList2Dvs(dvsFolderPath) self.mode = mode", "= imageList[i:i+12] if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateValList2Rgb(folderPath): folderList =", "dvs_list ,(352,352)) for i in range(len(cropped_img_list)): cropped_img_list[i] = torch.from_numpy(cropped_img_list[i].transpose((2, 0, 1))) for i", "= cv2.resize(cv2.imread(dvs_path, cv2.COLOR_BGR2GRAY), (scaleX,scaleY)) thresh = 127 tmp = cv2.threshold(tmp, thresh, 1, cv2.THRESH_BINARY)[1]", "cv2.imread(dvs_path_list[0], cv2.COLOR_BGR2GRAY) #print(h,w,c) if h > w: scaleX = int(360*(h/w)) scaleY = 360", "__init__(self, folderPath, mode='train'): self.trainList = populateTrainList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\",", "for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) else: for img_path", "in folderList: # imageList = sorted(glob.glob(folder + '/' + '*.jpg')) # for i", "scaleX = 360 scaleY = int(360*(w/h)) img_list = [] for img_path in img_path_list[start:start+2]:", "[] for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX, scaleY))[:,:,(2,1,0)] img_list.append(np.array(tmp,dtype=np.float32)) #cv2.imshow(\"j\",tmp) #cv2.waitKey(0)", "populateDvsList2(folderPath): # folderList = [x[0] for x in os.walk(folderPath)] # trainList = []", "= populateValList2Rgb(folderPath) self.mode = mode print(\"# of training samples:\", len(self.trainList)) def __getitem__(self, index):", "if len(tmp) == 12: trainList.append(imageList[i:i+12]) return trainList def populateTrainList2(rgbPath, dvsPath): folderListRgb = [x[0]", "folder in folderList: # imageList = sorted(glob.glob(folder + '/' + '*.jpg')) # for", "new_dvs[st_y: ed_y, st_x: ed_x] = dvs[or_st_y: or_ed_y, or_st_x: or_ed_x].copy() cropped_img_list.append(np.ascontiguousarray(new_img)) cropped_dvs_list.append(np.ascontiguousarray(new_dvs)) return cropped_img_list,", "folderList: imageList = sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0, len(imageList),", "img in image_list: new_img = np.empty((h,w,3), dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :]", "flip: for img_path in img_path_list[start:start+9]: tmp = cv2.resize(cv2.imread(img_path), (scaleX,scaleY))[:,:,(2,1,0)] img_list.append(np.array(cv2.flip(tmp,1), dtype=np.float32)) for dvs_path", "dtype=np.float32) new_img.fill(128) new_img[st_y: ed_y, st_x: ed_x, :] = img[or_st_y: or_ed_y, or_st_x: or_ed_x, :].copy()", "index): img_path_list = self.trainList[index] start = random.randint(0,3) h,w,c = cv2.imread(img_path_list[0]).shape image = cv2.imread(img_path_list[0])", "dvsPath): folderListRgb = [x[0] for x in os.walk(rgbPath)] folderListDvs = [x[0] for x", "imageList = sorted(glob.glob(folder + '/' + '*.jpg')) for i in range(0, len(imageList), 9):", "i + w or_st_x = j or_ed_x = j + h #print(st_x, ed_x,", "12: trainList.append(imageList[i:i+12]) return trainList def populateValList2Rgb(folderPath): folderList = [x[0] for x in os.walk(folderPath)]", "= j or_ed_x = j + h #print(st_x, ed_x, st_y, ed_y) #print(or_st_x, or_ed_x,", "width, _ = image_list[0].shape dvs_h, dvs_w = dvs_list[0].shape #print(h,w,height,width) i = random.randint(0, height" ]
[ "be necessary if there is a bias in the distribution of the score,", "print('file name {}'.format(file_name)) print('=====Arguments====\\n') csv_column_names = ['seed', 'learn_rate', 'model_type', 'train_pairs', 'dev_pairs', 'test_pairs', 'epoch_num',", "args.file_name def main(argv): epoch_num, batch_size, train_type, train_percent, dev_percent, learn_rate, model_type, device, seed, file_name", "pref[1]: pref = [1, 0] elif pref[0] < pref[1]: pref = [1, 0]", "'pcc_p_train', 'tau_train', 'tau_p_train', 'rho_train_global', 'pcc_train_global', 'tau_train_global', 'rho_dev', 'rho_p_dev', 'pcc_dev', 'pcc_p_dev', 'tau_dev', 'tau_p_dev', 'rho_dev_global',", "device, seed, file_name = parse_args( argv[1:]) print('\\n=====Arguments====') print('epoch num {}'.format(epoch_num)) print('batch size {}'.format(batch_size))", "summ_entry[sum_id_j] = 0 else: summ_entry[sum_id_i] = 0 summ_entry[sum_id_j] = 1 human_pair_scores[article_id] = summ_entry", "pref == [1, 0]: summ_entry[sum_id_i] = 1 summ_entry[sum_id_j] = 0 else: summ_entry[sum_id_i] =", "pref in the reverse order by chance. this might be necessary if there", "import copy from tqdm import tqdm import pickle from scorer.data_helper.json_reader import read_sorted_scores, read_pair_anno_scores,", "summary text to last summary id with that text. that's the one we", "train_ids: train[article_id] = entry elif article_id in dev_ids: dev[article_id] = entry else: test[article_id]", "'rho_p_test', 'pcc_test', 'pcc_p_test', 'tau_test', 'tau_p_test', 'rho_test_global', 'pcc_test_global', 'tau_test_global'] # check if csv_file exists", "model_type: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, 1), ) else: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length", "{} if article_id in human_pair_scores: if pref == [1, 0]: if sum_id_i in", "we get a unique key, so that (sys_summ0,sys_summ1) and (sys_summ1,sys_summ0) are the same", "can be done more efficiently, but who cares... # rand = random.random() all[article_id]", "change this to 768 if you use bert-base deep_model, optimiser = build_model(model_type, BERT_VEC_LENGTH", "{} all = {} topic_count = 0 article_ids = list(sorted_scores.keys()) random.shuffle(article_ids) num_articles =", "kendalltau import math from torchvision import models from resources import MODEL_WEIGHT_DIR from resources", "size {}'.format(batch_size)) print('train type {}'.format(train_type)) print('train percent {}'.format(train_percent)) print('dev percent {}'.format(dev_percent)) print('learn rate", "dev_percent) train, dev, test, all = parse_split_data_balanced(sorted_scores, train_percent, dev_percent) # without majority preferences", "entries: entry = entries[article_id] summ_ids = list(entry.keys()) # really iterate over all pairs.", "sid][0] temp_entry['sys_summ' + repr(sid)] = s_text # save in dictionary entries_text[article_id] = temp_entry", "device: input = input.to('cuda') value_variables = deep_model(input) # print(value_variables) softmax_layer = torch.nn.Softmax(dim=1) pred", "the total pref vector of the specific summary pair. create a new entry", "pair_anno_scores) # test_pairs = build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores) # build human pair scores for", "preferences # train_pairs = build_pairs(train) # dev_pairs = build_pairs(dev) # test_pairs = build_pairs(test)", "'tau_p_train', 'rho_train_global', 'pcc_train_global', 'tau_train_global', 'rho_dev', 'rho_p_dev', 'pcc_dev', 'pcc_p_dev', 'tau_dev', 'tau_p_dev', 'rho_dev_global', 'pcc_dev_global', 'tau_dev_global',", "bert vectors with open('data/doc_summ_bert_vectors.pkl', 'rb') as ff: all_vec_dic = pickle.load(ff) pcc_list = []", "torch.nn.Linear(int(vec_length / 2), 1), ) if learn_rate is not None: optimiser = torch.optim.Adam(deep_model.parameters(),", "= [] for ii in range(epoch_num + 1): print('\\n=====EPOCH {}====='.format(ii)) if ii ==", "np.array(summ_vec).shape) concat_vecs.append(article_vec + summ_vec) # print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all += true_scores #", "data used for dev', default=.16) ap.add_argument('-lr', '--learn_rate', type=float, help='learning rate', default=3e-4) ap.add_argument('-mt', '--model_type',", "entries: entry = entries[article_id] summ_ids = list(entry.keys()) # mapping from summary text to", "# pred_scores_all = [] for article_id in human_scores: entry = human_scores[article_id] summ_ids =", "summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) # print(pair_list) return pair_list", "= summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) # print(pair_list) return pair_list def", "not None: fig, ax = plt.subplots() # true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all) unique = np.sort(np.unique(true_scores_all))", "in unique] # bw_methods determines how soft the distribution curve will be. lower", "dev_anno = build_human_pair_scores(dev_pairs) test_anno = build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs), len(test_pairs)) # read bert vectors", "as plt import csv def parse_split_data(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev", "'--dev_percent', type=float, help='how many data used for dev', default=.16) ap.add_argument('-lr', '--learn_rate', type=float, help='learning", "{}'.format(batch_size)) print('train type {}'.format(train_type)) print('train percent {}'.format(train_percent)) print('dev percent {}'.format(dev_percent)) print('learn rate {}'.format(learn_rate))", "if yes skip if i == j or text_i == text_j: # print(\"DUPLICATE", "for i in range(len(summ_ids)): for j in range(len(summ_ids)): # run through dictionary containing", "bert-base deep_model, optimiser = build_model(model_type, BERT_VEC_LENGTH * 2, learn_rate) if 'gpu' in device:", "loss_train, loss_dev, loss_test) # Train-Data only print(\"==Train==\") # results_train = test_rewarder(all_vec_dic, train, deep_model,", "get the unique summ ids unique_summ_id_pair = [summ2id[text_i], summ2id[text_j]] # some debug output", "= entries[article_id] summ_ids = list(entry.keys()) # mapping from summary text to last summary", "type=int, help='random seed number', default='1') ap.add_argument('-fn', '--file_name', type=str, help='file name for csv output',", "np.argmax(pcc_list) best_result = pcc_list[idx] print('\\n======Best results come from epoch no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern", "# print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all += true_scores # add scores for topic to list", "device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTest.pdf')) test_rewarder(all_vec_dic, train, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTrain.pdf'))", "0.5] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) # print(pair_list) topic_count += 1 summ_count = summ_count", "epoch 1 on, receive the data and learn from it. the loss is", "for ee in target_batch] if loss_only: loss = deep_pair_train_loss_only(vec_batch, target_batch, deep_model, optimiser, device)", "ax.set_ylabel('predicted scores') xticklabels = true_scores_all ax.set_xticks(true_scores_all) print(\"violin plot written to: %s\" % plot_file)", "id with that text. that's the one we will use summ2id = {entries_text[article_id][summ_id]:", "majority preferences and pair anno # train_pairs = build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores) # dev_pairs", "[0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref = [1, 0] pair_list.append((article_id,", "help='deep/linear', default='linear') ap.add_argument('-dv', '--device', type=str, help='cpu/gpu', default='gpu') ap.add_argument('-se', '--seed', type=int, help='random seed number',", "= input.to('cuda') value_variables = deep_model(input) # print(value_variables) softmax_layer = torch.nn.Softmax(dim=1) pred = softmax_layer(value_variables)", "vec_length, learn_rate=None): if 'linear' in model_type: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, 1), ) else:", "pred_scores) pcc, pcc_p = pearsonr(true_scores, pred_scores) tau, tau_p = kendalltau(true_scores, pred_scores) if not", "= [] weights_list = [] for ii in range(epoch_num + 1): print('\\n=====EPOCH {}====='.format(ii))", "summ_ids[i], summ_ids[j], pref)) continue elif pair['summ_id_j'] == int(entry_keys[i][8]) and pair['summ_id_i'] == int(entry_keys[j][8]): if", "pred_scores_all.shape[0]), pred_scores_all, marker=\".\", s=3, alpha=0.5) ax.set_title('Comparison and distributions of true values to predicted", "fed with the training examples loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, False, batch_size,", "train_percent, dev_percent, learn_rate, model_type, device, seed, file_name = parse_args( argv[1:]) print('\\n=====Arguments====') print('epoch num", "human_pair_scores[article_id][sum_id_j] = 1 else: if pref == [1, 0]: summ_entry[sum_id_i] = 1 summ_entry[sum_id_j]", "loss = deep_pair_train(vec_batch, target_batch, deep_model, optimiser, device) loss_list.append(loss) return np.mean(loss_list) def test_rewarder(vec_list, human_scores,", "dev_percent: dev[article_id] = entry else: test[article_id] = entry topic_count += 1 print(\"topics in", "os import path import argparse import random import copy from tqdm import tqdm", "our case, we learn f(s0)=pref[0] and f(s1)=pref[1], so this should be set to", "['seed', 'learn_rate', 'model_type', 'train_pairs', 'dev_pairs', 'test_pairs', 'epoch_num', 'loss_train', 'loss_dev', 'loss_test', 'rho_train', 'rho_p_train', 'pcc_train',", "2), 1), ) if learn_rate is not None: optimiser = torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return", "for article_id in entries: entry = entries[article_id] summ_ids = list(entry.keys()) # really iterate", "# some debug output # noinspection PyUnreachableCode if False: print(\"%s vs. %s (IDs", "= list(vecs[aid][sid2]) pair_vec_list.append([article_vec + s1_vec, article_vec + s2_vec]) return pair_vec_list def pair_train_rewarder(vec_dic, pairs,", "from epoch 1 on, receive the data and learn from it. the loss", "j in range(len(summ_ids)): # run through dictionary containing summ_ids and matching text #", "[s['sys_summ'] for s in scores_list if s['summ_id'] == sid][0] temp_entry['sys_summ' + repr(sid)] =", "loss is still the loss before fed with the training examples loss_train =", "= build_pair_vecs(vec_dic, shuffled_pairs) # print('total number of pairs built: {}'.format(len(vec_pairs))) for pointer in", "= spearmanr(true_scores_all, pred_scores_all)[0] pcc = pearsonr(true_scores_all, pred_scores_all)[0] tau = kendalltau(true_scores_all, pred_scores_all)[0] if not", "just evaluate the performance of the randomly initialized model (sanity check and baseline)", "return train, dev, test, all def parse_split_data_balanced(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {}", "or regression', default='pairwise') ap.add_argument('-tp', '--train_percent', type=float, help='how many data used for training', default=.64)", "csv def parse_split_data(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev = {} test", "j: continue if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0] elif entry[summ_ids[i]] <", "the unique summ ids unique_summ_id_pair = [summ2id[text_i], summ2id[text_j]] # some debug output #", "deep_model, device) results_test = test_rewarder(all_vec_dic, test_anno, deep_model, device) for metric in results_test: print('{}\\t{}'.format(metric,", "pref)) continue else: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue topic_count", "# train_pairs = build_pairs(train) # dev_pairs = build_pairs(dev) # test_pairs = build_pairs(test) #", "pref[1]: pref = [1, 0] else: pref = [0.5, 0.5] # skip if", "output_pattern + '_onTest.pdf')) test_rewarder(all_vec_dic, train, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTrain.pdf')) test_rewarder(all_vec_dic, dev,", "device) loss_dev = pair_train_rewarder(all_vec_dic, dev_pairs, deep_model, optimiser, True, batch_size, device) loss_test = pair_train_rewarder(all_vec_dic,", "human_scores: entry = human_scores[article_id] summ_ids = list(entry.keys()) if len(summ_ids) < 2: continue concat_vecs", "build_anno_pairs(entries, pair_anno_scores): pair_list = [] topic_count = 0 summ_count = 0 for article_id", "== sid][ 0] # that can be done more efficiently, but who cares...", "# print(input) # print(input.shape) # print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape) pred_scores = model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all", "train_anno = build_human_pair_scores(train_pairs) dev_anno = build_human_pair_scores(dev_pairs) test_anno = build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs), len(test_pairs)) #", "a tie and you want to ignore ties if pref[0] != 0.5 or", "# dev_pairs = build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores) # test_pairs = build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores) #", "pair_anno_scores) # with majority preferences # train_pairs = build_pairs_majority_preferences(train, sorted_scores) # dev_pairs =", "human_pair_scores[article_id][sum_id_j] + 1 else: human_pair_scores[article_id][sum_id_j] = 1 else: if pref == [1, 0]:", "0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue topic_count += 1 summ_count = summ_count +", "pair_train_rewarder(all_vec_dic, test_pairs, deep_model, optimiser, True, batch_size, device) csv_row = [seed, learn_rate, model_type, len(train_pairs),", "summ_ids[j], pref)) # print(pair_list) topic_count += 1 summ_count = summ_count + len(summ_ids) print(\"topics\",", "= [ee[-1] for ee in target_batch] if loss_only: loss = deep_pair_train_loss_only(vec_batch, target_batch, deep_model,", "to the total pref vector of the specific summary pair. create a new", "0]: summ_entry[sum_id_i] = 1 summ_entry[sum_id_j] = 0 else: summ_entry[sum_id_i] = 0 summ_entry[sum_id_j] =", "majority preferences but with pair anno train_pairs = build_anno_pairs(train, pair_anno_scores) dev_pairs = build_anno_pairs(dev,", "%s\" % plot_file) plt.savefig(plot_file) return results def parse_args(argv): ap = argparse.ArgumentParser(\"arguments for summary", "for article_id, scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids = [s['summ_id'] for s", "is not None: fig, ax = plt.subplots() # true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all) unique =", "'tau_dev', 'tau_p_dev', 'rho_dev_global', 'pcc_dev_global', 'tau_dev_global', 'rho_test', 'rho_p_test', 'pcc_test', 'pcc_p_test', 'tau_test', 'tau_p_test', 'rho_test_global', 'pcc_test_global',", "(math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau) if plot_file is not None:", "learn f(s0)=pref[0] and f(s1)=pref[1], so this should be set to False def build_pairs_majority_preferences(entries,", "read_pair_anno_scores, read_articles, \\ read_processed_scores, read_scores from scipy.stats import spearmanr, pearsonr, kendalltau import math", "> entry[unique_summ_id_pair[1]]: # pref = [0, 1] # else: # # todo we", "pcc_list = [] weights_list = [] for ii in range(epoch_num + 1): print('\\n=====EPOCH", "'pcc_p': [], 'tau': [], 'tau_p': [], 'rho_global': [], 'pcc_global': [], 'tau_global': []} true_scores_all", "optimiser, loss_only, batch_size=32, device='cpu'): loss_list = [] shuffled_pairs = pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs =", "is solved otherwise for i in range(len(summ_ids)): for j in range(len(summ_ids)): if i", "= list(entry.keys()) # really iterate over all pairs. there was an error here", "# print(human_scores) # pred_scores_all = [] for article_id in human_scores: entry = human_scores[article_id]", "# include the pref two times, once in one direction and once in", "number', default='1') ap.add_argument('-fn', '--file_name', type=str, help='file name for csv output', default='BetterRewardsStatistics_test.csv') args =", "1 on, receive the data and learn from it. the loss is still", "in results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx = np.argmax(pcc_list) best_result =", "np.sort(np.unique(true_scores_all)) data_to_plot = [pred_scores_all[true_score == true_scores_all] for true_score in unique] # bw_methods determines", "if ii == 0: # do not train in epoch 0, just evaluate", "def parse_split_data(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev = {} test =", "article_ids[int(train_percent * num_articles):int((train_percent + dev_percent) * num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id, scores_list in", "dictionary entry_keys = list(entry.keys()) # get pair preference from pair_anno_scores for pair in", "= summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) return pair_list def build_anno_pairs(entries, pair_anno_scores):", "= {} topic_count = 0 for article_id, scores_list in tqdm(sorted_scores.items()): entry = {}", "OUTPUTS_DIR from matplotlib import pyplot as plt import csv def parse_split_data(sorted_scores, train_percent, dev_percent,", "not hashable for the dict unique_summ_id_pair = tuple(unique_summ_id_pair) # add up the pref", "pickle from scorer.data_helper.json_reader import read_sorted_scores, read_pair_anno_scores, read_articles, \\ read_processed_scores, read_scores from scipy.stats import", "entry[unique_summ_id_pair[1]]: # pref = [0, 1] # else: # # todo we could", "= argparse.ArgumentParser(\"arguments for summary sampler\") ap.add_argument('-e', '--epoch_num', type=int, default=50) ap.add_argument('-b', '--batch_size', type=int, default=32)", "pair_anno_scores) dev_pairs = build_anno_pairs(dev, pair_anno_scores) test_pairs = build_anno_pairs(test, pair_anno_scores) # with majority preferences", "+ pref[1])).tolist() if target_type == 'binary': if pref[0] > pref[1]: pref = [1,", "args.learn_rate, args.model_type, args.device, args.seed, args.file_name def main(argv): epoch_num, batch_size, train_type, train_percent, dev_percent, learn_rate,", "pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, True, batch_size, device) else: # from epoch 1 on,", "input.to('cuda') value_variables = deep_model(input) # print(value_variables) softmax_layer = torch.nn.Softmax(dim=1) pred = softmax_layer(value_variables) #", "args = ap.parse_args(argv) return args.epoch_num, args.batch_size, args.train_type, args.train_percent, args.dev_percent, args.learn_rate, args.model_type, args.device, args.seed,", "new csv_file is generated, write column names if csv_exists is False: writer.writerow(csv_column_names) np.random.seed(seed=seed)", "entry[summ_ids[j]]: pref = [0, 1] else: pref = [0.5, 0.5] # if entry[unique_summ_id_pair[0]]", "'--seed', type=int, help='random seed number', default='1') ap.add_argument('-fn', '--file_name', type=str, help='file name for csv", "randomize_pref_order=False, double_prefs=False): pair_list = [] topic_count = 0 anno_count = 0 summ_count =", "+ summ_vec) # print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all += true_scores # add scores", "with score %s (%s) vs.\" % ( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\" system %s", "if csv_file exists if path.exists(file_name): csv_exists = True else: csv_exists = False with", "continue elif pair['summ_id_j'] == int(entry_keys[i][8]) and pair['summ_id_i'] == int(entry_keys[j][8]): if pair['pref'] == 1:", "learns f(s0,s1)=pref. in our case, we learn f(s0)=pref[0] and f(s1)=pref[1], so this should", "run through all pairs # really iterate over all pairs. there was an", "softmax_layer(value_variables) # print(pred) # print(np.array(target).shape, np.array(target).reshape(-1, 2, 1).shape) target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1)", "deep_model, optimiser, device) loss_list.append(loss) return np.mean(loss_list) def test_rewarder(vec_list, human_scores, model, device, plot_file=None): results", "written to: %s\" % plot_file) plt.savefig(plot_file) return results def parse_args(argv): ap = argparse.ArgumentParser(\"arguments", "{}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type, train_percent, seed, learn_rate, model_type, epoch_num )", "sum_id_j = str(entry[2]) pref = entry[3] summ_entry = {} if article_id in human_pair_scores:", "scorer.data_helper.json_reader import read_sorted_scores, read_pair_anno_scores, read_articles, \\ read_processed_scores, read_scores from scipy.stats import spearmanr, pearsonr,", "summ_ids[i], summ_ids[j], pref)) continue else: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref))", "{} # still run through all pairs # really iterate over all pairs.", "1) # print(target_variables) if 'gpu' in device: target_variables = target_variables.to('cuda') loss_fn = torch.nn.BCELoss()", "dev data percentage is {}! Make sure the sum is below 1.0!'.format( train_percent", "was a vielfaches of 32, then there was a last batch with []", "training examples loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, False, batch_size, device) loss_dev =", "once in the other direction if double_prefs: pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0],", "build_model(model_type, vec_length, learn_rate=None): if 'linear' in model_type: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, 1), )", "if s['summ_id'] == sid][0] temp_entry['sys_summ' + repr(sid)] = s_text # save in dictionary", "%s with score %s (%s)\" % ( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print( \" \\\"%s...\\\"", "summ_id in summ_ids} # put here the prefs for this article article_prefs =", "are more sharp ax.violinplot(data_to_plot, showmeans=True, showmedians=True, bw_method=0.2) ax.scatter(true_scores_all + np.random.normal(0, 0.1, pred_scores_all.shape[0]), pred_scores_all,", "with pair anno train_pairs = build_anno_pairs(train, pair_anno_scores) dev_pairs = build_anno_pairs(dev, pair_anno_scores) test_pairs =", "loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) return loss.cpu().item() def build_pairs(entries):", "this article article_prefs = {} # still run through all pairs # really", "import torch from torch.autograd import Variable import numpy as np import os from", "# text_j = value text_i = entries_text[article_id][summ_ids[i]] text_j = entries_text[article_id][summ_ids[j]] # check if", "loss_test) # Train-Data only print(\"==Train==\") # results_train = test_rewarder(all_vec_dic, train, deep_model, device) results_train", "or math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p) rho = spearmanr(true_scores_all, pred_scores_all)[0] pcc", "= Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1) # print(target_variables) if 'gpu' in device: target_variables = target_variables.to('cuda')", "pair_list def build_pair_vecs(vecs, pairs): pair_vec_list = [] for aid, sid1, sid2, _ in", "for s in scores_list] for sid in summ_ids: # get summary text s_text", "topic_count += 1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) return", "open('data/doc_summ_bert_vectors.pkl', 'rb') as ff: all_vec_dic = pickle.load(ff) pcc_list = [] weights_list = []", "continue else: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue elif pair['summ_id_j']", "(sys_summ1,sys_summ0) are the same if unique_summ_id_pair[1] < unique_summ_id_pair[0]: unique_summ_id_pair = unique_summ_id_pair[::-1] pref =", "noinspection PyUnreachableCode if False: print(\"%s vs. %s (IDs %s vs. %s)\" % (", "train, dev, test, all def parse_split_data_balanced(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev", "from torchvision import models from resources import MODEL_WEIGHT_DIR from resources import OUTPUTS_DIR from", "/ batch_size) + 1): # there was a bug here. when len(pairs) was", "batch_size] target_batch = shuffled_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch = [ee[-1]", "s in scores_list] for sid in summ_ids: # get summary text s_text =", "pair['pref'] == 1: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else:", "math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p) rho = spearmanr(true_scores_all, pred_scores_all)[0] pcc =", "list(vecs[aid][sid1]) s2_vec = list(vecs[aid][sid2]) pair_vec_list.append([article_vec + s1_vec, article_vec + s2_vec]) return pair_vec_list def", "False # read human scores and vectors for summaries/docs, and split the train/dev/test", "rho, rho_p = spearmanr(true_scores, pred_scores) pcc, pcc_p = pearsonr(true_scores, pred_scores) tau, tau_p =", "pref[0] < pref[1]: pref = [1, 0] else: pref = [0.5, 0.5] #", "in the reverse order by chance. this might be necessary if there is", "sid2, _ in pairs: article_vec = list(vecs[aid]['article']) s1_vec = list(vecs[aid][sid1]) s2_vec = list(vecs[aid][sid2])", "dev_anno, deep_model, device) for metric in results: print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) # Test-Data only", "reverse order by chance. this might be necessary if there is a bias", "summ_ids} # put here the prefs for this article article_prefs = {} #", "batch_size, device) loss_dev = pair_train_rewarder(all_vec_dic, dev_pairs, deep_model, optimiser, True, batch_size, device) loss_test =", "train_anno, deep_model, device) for metric in results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") # results", "s in scores_list if s['summ_id'] == sid][ 0] # that can be done", "os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest model weight saved to: {}'.format(os.path.join(MODEL_WEIGHT_DIR, model_weight_name))) if __name__ == '__main__':", "= sorted_scores[article_id] print(\" system %s with score %s (%s) vs.\" % ( full_entry[i]['sys_name'],", "print(np.array(true_scores).shape) # print(input) # print(input.shape) # print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape) pred_scores = model(input).data.cpu().numpy().reshape(1, -1)[0]", "distribution curve will be. lower values are more sharp ax.violinplot(data_to_plot, showmeans=True, showmedians=True, bw_method=0.2)", "batch_size, train_type, train_percent, seed, learn_rate, model_type, epoch_num ) test_results = test_rewarder(all_vec_dic, test, deep_model,", "int(entry_keys[i][8]) and pair['summ_id_j'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref = [1, 0]", "and double_prefs are only relevant if the learning function learns f(s0,s1)=pref. in our", "list(vecs[aid]['article']) s1_vec = list(vecs[aid][sid1]) s2_vec = list(vecs[aid][sid2]) pair_vec_list.append([article_vec + s1_vec, article_vec + s2_vec])", "return deep_model, optimiser else: return deep_model def deep_pair_train(vec_list, target, deep_model, optimiser, device): #", "'rho_test', 'rho_p_test', 'pcc_test', 'pcc_p_test', 'tau_test', 'tau_p_test', 'rho_test_global', 'pcc_test_global', 'tau_test_global'] # check if csv_file", "build_pairs_majority_preferences(entries, sorted_scores, target_type='graded', ignore_ties=False, randomize_pref_order=False, double_prefs=False): pair_list = [] topic_count = 0 anno_count", "all pairs # really iterate over all pairs. there was an error here", "this also lead to i,j=x,0 never be chosen the situation i=j is solved", "# rand = random.random() all[article_id] = entry if article_id in train_ids: train[article_id] =", "device='cpu'): loss_list = [] shuffled_pairs = pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs = build_pair_vecs(vec_dic, shuffled_pairs) #", "prompt='structure'): train = {} dev = {} test = {} all = {}", "in summ_ids: # get summary text s_text = [s['sys_summ'] for s in scores_list", "names if csv_exists is False: writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed) if train_percent +", "if 'gpu' in device: input = input.to('cuda') value_variables = deep_model(input) # print(value_variables) softmax_layer", "list(entry.keys()) # mapping from summary text to last summary id with that text.", "input = input.to('cuda') model.eval() with torch.no_grad(): # print(true_scores) # print(np.array(true_scores).shape) # print(input) #", "train_type, train_percent, dev_percent, learn_rate, model_type, device, seed, file_name = parse_args( argv[1:]) print('\\n=====Arguments====') print('epoch", "all_vec_dic = pickle.load(ff) pcc_list = [] weights_list = [] for ii in range(epoch_num", "* num_articles)] dev_ids = article_ids[int(train_percent * num_articles):int((train_percent + dev_percent) * num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):]", "baseline) loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, True, batch_size, device) else: # from", "summ_ids and matching text # for key, value in entries_text[article_id].items(): # get text", "batch_size=32, device='cpu'): loss_list = [] shuffled_pairs = pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs = build_pair_vecs(vec_dic, shuffled_pairs)", "[1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue topic_count += 1 summ_count = summ_count", "[], 'pcc_p': [], 'tau': [], 'tau_p': [], 'rho_global': [], 'pcc_global': [], 'tau_global': []}", "binary target, or graded one pref = (pref / (pref[0] + pref[1])).tolist() if", "article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair, np.array([0, 0])) + np.array(pref) # transform to target for unique_summ_id_pair,", "for the dict unique_summ_id_pair = tuple(unique_summ_id_pair) # add up the pref to the", "0.5] # skip if it is a tie and you want to ignore", "optimiser, True, batch_size, device) loss_test = pair_train_rewarder(all_vec_dic, test_pairs, deep_model, optimiser, True, batch_size, device)", "summ_ids[i], summ_ids[j], pref)) continue topic_count += 1 summ_count = summ_count + len(summ_ids) print(\"topics\",", "model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num, batch_size, train_type, train_percent, learn_rate, model_type", "temp_entry['sys_summ' + repr(sid)] = s_text # save in dictionary entries_text[article_id] = temp_entry for", "print('=====Arguments====\\n') csv_column_names = ['seed', 'learn_rate', 'model_type', 'train_pairs', 'dev_pairs', 'test_pairs', 'epoch_num', 'loss_train', 'loss_dev', 'loss_test',", "for s in scores_list] for sid in summ_ids: entry['sys_summ' + repr(sid)] = [s['scores'][prompt]", "# print(\"DUPLICATE FOUND: TEXT i\", text_i, \"TEXT j\", text_i) continue # get the", "= build_human_pair_scores(train_pairs) dev_anno = build_human_pair_scores(dev_pairs) test_anno = build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs), len(test_pairs)) # read", "range(len(summ_ids)): # run through dictionary containing summ_ids and matching text # for key,", "results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p) rho = spearmanr(true_scores_all, pred_scores_all)[0] pcc = pearsonr(true_scores_all, pred_scores_all)[0] tau", "BERT_VEC_LENGTH = 1024 # change this to 768 if you use bert-base deep_model,", "'_onDev.pdf')) print('Its performance on the test set is:') for metric in test_results: print('{}\\t{}'.format(metric,", "\"TEXT j\", text_i) continue # get the unique summ ids unique_summ_id_pair = [summ2id[text_i],", "= model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all = np.concatenate((pred_scores_all, pred_scores), axis=0) # pred_scores_all += pred_scores.tolist() rho,", "sorted_scores) # dev_pairs = build_pairs_majority_preferences(dev, sorted_scores) # test_pairs = build_pairs_majority_preferences(test, sorted_scores) # with", "summ_vec) # print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all += true_scores # add scores for", "if pair['pref'] == 1: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue", "ids so that we get a unique key, so that (sys_summ0,sys_summ1) and (sys_summ1,sys_summ0)", "print('\\n=====EPOCH {}====='.format(ii)) if ii == 0: # do not train in epoch 0,", "list(vecs[aid][sid2]) pair_vec_list.append([article_vec + s1_vec, article_vec + s2_vec]) return pair_vec_list def pair_train_rewarder(vec_dic, pairs, deep_model,", "entry if not existing article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair, np.array([0, 0])) + np.array(pref) # transform", "= parse_args( argv[1:]) print('\\n=====Arguments====') print('epoch num {}'.format(epoch_num)) print('batch size {}'.format(batch_size)) print('train type {}'.format(train_type))", "j started from 1, to prevent i,j=0,0. but this also lead to i,j=x,0", "output_pattern + '_onTrain.pdf')) test_rewarder(all_vec_dic, dev, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onDev.pdf')) print('Its performance", "models from resources import MODEL_WEIGHT_DIR from resources import OUTPUTS_DIR from matplotlib import pyplot", "int(entry_keys[j][8]): if pair['pref'] == 1: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref))", "if 'gpu' in device: input = input.to('cuda') model.eval() with torch.no_grad(): # print(true_scores) #", "import csv def parse_split_data(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev = {}", "{}'.format(train_type)) print('train percent {}'.format(train_percent)) print('dev percent {}'.format(dev_percent)) print('learn rate {}'.format(learn_rate)) print('model type {}'.format(model_type))", "continue else: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue topic_count +=", "dev_percent >= 1.: print('ERROR! Train data percentage plus dev data percentage is {}!", "results_test = test_rewarder(all_vec_dic, test, deep_model, device) results_test = test_rewarder(all_vec_dic, test_anno, deep_model, device) for", "use bert-base deep_model, optimiser = build_model(model_type, BERT_VEC_LENGTH * 2, learn_rate) if 'gpu' in", "pred_scores) if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau)", "print(\"summ\", summ_count) return pair_list def build_anno_pairs(entries, pair_anno_scores): pair_list = [] topic_count = 0", "entry[unique_summ_id_pair[1]]: # pref = [1, 0] # elif entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref", "= [] pred_scores_all = np.array([]) # print(human_scores) # pred_scores_all = [] for article_id", "pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j],", "+= 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num, batch_size, train_type, train_percent, learn_rate, model_type ) torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name))", "+= true_scores # add scores for topic to list of all scores input", "train_percent + dev_percent)) exit(1) BERT_VEC_LENGTH = 1024 # change this to 768 if", "you want to ignore ties if pref[0] != 0.5 or not ignore_ties: #", "len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) # print(pair_list) return pair_list def build_human_pair_scores(pair_list): human_pair_scores =", "int(entry_keys[j][8]): if pair['pref'] == 1: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref))", "print( \" \\\"%s...\\\" vs. \\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort() if entry[summ_ids[i]] >", "= deep_pair_train(vec_batch, target_batch, deep_model, optimiser, device) loss_list.append(loss) return np.mean(loss_list) def test_rewarder(vec_list, human_scores, model,", "help='file name for csv output', default='BetterRewardsStatistics_test.csv') args = ap.parse_args(argv) return args.epoch_num, args.batch_size, args.train_type,", "[] for aid, sid1, sid2, _ in pairs: article_vec = list(vecs[aid]['article']) s1_vec =", "transform to target for unique_summ_id_pair, pref in article_prefs.items(): # depending on the mode,", "pair_list = [] topic_count = 0 summ_count = 0 for article_id in entries:", "output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type, train_percent, seed, learn_rate, model_type, epoch_num ) test_results =", "pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) else: # include the pref", "= build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores) # build human pair scores for pairs train_anno =", "torch.no_grad(): # print(true_scores) # print(np.array(true_scores).shape) # print(input) # print(input.shape) # print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape)", "error here before since j started from 1, to prevent i,j=0,0. but this", "all = parse_split_data(sorted_scores, train_percent, dev_percent) train, dev, test, all = parse_split_data_balanced(sorted_scores, train_percent, dev_percent)", "= True else: csv_exists = False with open(file_name, 'a', newline='') as csv_file: writer", "type=str, help='deep/linear', default='linear') ap.add_argument('-dv', '--device', type=str, help='cpu/gpu', default='gpu') ap.add_argument('-se', '--seed', type=int, help='random seed", "dev_percent, prompt='structure'): train = {} dev = {} test = {} all =", "score, e.g. if they are ordered if randomize_pref_order and bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0],", "entry = entries[article_id] summ_ids = list(entry.keys()) # mapping from summary text to last", "plt import csv def parse_split_data(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev =", "[summ2id[text_i], summ2id[text_j]] # some debug output # noinspection PyUnreachableCode if False: print(\"%s vs.", "torch.backends.cudnn.benchmark = False # read human scores and vectors for summaries/docs, and split", "output_pattern + '_onDev.pdf')) print('Its performance on the test set is:') for metric in", "from resources import MODEL_WEIGHT_DIR from resources import OUTPUTS_DIR from matplotlib import pyplot as", "'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num, batch_size, train_type, train_percent, learn_rate, model_type ) torch.save(weights_list[idx],", "in tqdm(sorted_scores.items()): temp_entry = {} summ_ids = [s['summ_id'] for s in scores_list] for", "# get summary text and matching id for article_id, scores_list in tqdm(sorted_scores.items()): temp_entry", "+ 1) * batch_size] target_batch = [ee[-1] for ee in target_batch] if loss_only:", "torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest model weight saved to: {}'.format(os.path.join(MODEL_WEIGHT_DIR, model_weight_name))) if __name__ ==", "{}'.format(learn_rate)) print('model type {}'.format(model_type)) print('device {}'.format(device)) print('seed {}'.format(seed)) print('file name {}'.format(file_name)) print('=====Arguments====\\n') csv_column_names", "test_rewarder(all_vec_dic, test, deep_model, device) results_test = test_rewarder(all_vec_dic, test_anno, deep_model, device) for metric in", "entry[summ_ids[j]]: pref = [0, 1] else: pref = [0.5, 0.5] pair_list.append((article_id, summ_ids[i], summ_ids[j],", "= str(entry[2]) pref = entry[3] summ_entry = {} if article_id in human_pair_scores: if", "f(s0,s1)=pref. in our case, we learn f(s0)=pref[0] and f(s1)=pref[1], so this should be", "list(entry.keys()) # get pair preference from pair_anno_scores for pair in pair_anno_scores[article_id]: if pair['summ_id_i']", "= entry[3] summ_entry = {} if article_id in human_pair_scores: if pref == [1,", "efficiently, but who cares... # rand = random.random() all[article_id] = entry if article_id", "1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue elif pair['summ_id_j'] == int(entry_keys[i][8]) and pair['summ_id_i'] ==", "of pairs built: {}'.format(len(vec_pairs))) for pointer in range(int((len( pairs) - 1) / batch_size)", "in parse_split_data\", topic_count) return train, dev, test, all def build_model(model_type, vec_length, learn_rate=None): if", "loss = deep_pair_train_loss_only(vec_batch, target_batch, deep_model, optimiser, device) else: loss = deep_pair_train(vec_batch, target_batch, deep_model,", "if i == j: continue if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0]", "mode, use binary target, or graded one pref = (pref / (pref[0] +", "print('--> losses (train,dev,test)', loss_train, loss_dev, loss_test) # Train-Data only print(\"==Train==\") # results_train =", "for key, value in entries_text[article_id].items(): # get text for current summaries i and", "in human_scores: entry = human_scores[article_id] summ_ids = list(entry.keys()) if len(summ_ids) < 2: continue", "'binary': if pref[0] > pref[1]: pref = [1, 0] elif pref[0] < pref[1]:", "pref = [0, 1] else: pref = [0.5, 0.5] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref))", "target_batch = [ee[-1] for ee in target_batch] if loss_only: loss = deep_pair_train_loss_only(vec_batch, target_batch,", "there was an error here before since j started from 1, to prevent", "ap = argparse.ArgumentParser(\"arguments for summary sampler\") ap.add_argument('-e', '--epoch_num', type=int, default=50) ap.add_argument('-b', '--batch_size', type=int,", "csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx = np.argmax(pcc_list) best_result = pcc_list[idx] print('\\n======Best results come", "else: if sum_id_j in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] + 1 else: human_pair_scores[article_id][sum_id_j] = 1 else:", "low prio # pref = [0.5, 0.5] # sort the ids so that", "= build_pairs(train) # dev_pairs = build_pairs(dev) # test_pairs = build_pairs(test) # without majority", "in scores_list] for sid in summ_ids: entry['sys_summ' + repr(sid)] = [s['scores'][prompt] for s", "sorted_scores) # with majority preferences and pair anno # train_pairs = build_anno_pairs_majority_preferences(train, sorted_scores,", "= {} test = {} all = {} topic_count = 0 article_ids =", "entry[summ_ids[i]])) print(\" system %s with score %s (%s)\" % ( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]]))", "device: input = input.to('cuda') model.eval() with torch.no_grad(): # print(true_scores) # print(np.array(true_scores).shape) # print(input)", "'rho_global': [], 'pcc_global': [], 'tau_global': []} true_scores_all = [] pred_scores_all = np.array([]) #", "loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) optimiser.zero_grad() loss.backward() optimiser.step() return", "num_articles):int((train_percent + dev_percent) * num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id, scores_list in tqdm(sorted_scores.items()): entry", "ordered if randomize_pref_order and bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) else: pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1],", "1), ) else: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length / 2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length /", "entry if rand < train_percent: train[article_id] = entry elif rand < train_percent +", "true values to predicted score') ax.set_xlabel('true scores') ax.set_ylabel('predicted scores') xticklabels = true_scores_all ax.set_xticks(true_scores_all)", "{} for entry in pair_list: article_id = str(entry[0]) sum_id_i = str(entry[1]) sum_id_j =", "model_type ) torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest model weight saved to: {}'.format(os.path.join(MODEL_WEIGHT_DIR, model_weight_name))) if", "= [] for aid, sid1, sid2, _ in pairs: article_vec = list(vecs[aid]['article']) s1_vec", "article article_prefs = {} # still run through all pairs # really iterate", "'linear' in model_type: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, 1), ) else: deep_model = torch.nn.Sequential(", "summ_entry = {} if article_id in human_pair_scores: if pref == [1, 0]: if", "pref vector of the specific summary pair. create a new entry if not", "'model_type', 'train_pairs', 'dev_pairs', 'test_pairs', 'epoch_num', 'loss_train', 'loss_dev', 'loss_test', 'rho_train', 'rho_p_train', 'pcc_train', 'pcc_p_train', 'tau_train',", "chance. this might be necessary if there is a bias in the distribution", "otherwise for i in range(len(summ_ids)): for j in range(len(summ_ids)): if i == j:", "really iterate over all pairs. there was an error here before since j", "summaries/docs, and split the train/dev/test set sorted_scores = read_sorted_scores() # read pair anno", "was an error here before since j started from 1, to prevent i,j=0,0.", "plot_file is not None: fig, ax = plt.subplots() # true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all) unique", "= test_rewarder(all_vec_dic, test_anno, deep_model, device) for metric in results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row)", "check and baseline) loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, True, batch_size, device) else:", "before since j started from 1, to prevent i,j=0,0. but this also lead", "s in scores_list] for sid in summ_ids: entry['sys_summ' + repr(sid)] = [s['scores'][prompt] for", "softmax_layer = torch.nn.Softmax(dim=1) pred = softmax_layer(value_variables) # print(pred) # print(np.array(target).shape, np.array(target).reshape(-1, 2, 1).shape)", "len(pair_list)) return pair_list def build_pair_vecs(vecs, pairs): pair_vec_list = [] for aid, sid1, sid2,", "= Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if 'gpu' in device: input = input.to('cuda') value_variables =", "plot_file=None): results = {'rho': [], 'rho_p': [], 'pcc': [], 'pcc_p': [], 'tau': [],", "train, deep_model, device) results_train = test_rewarder(all_vec_dic, train_anno, deep_model, device) for metric in results_train:", "for article_id in entries: entry = entries[article_id] summ_ids = list(entry.keys()) # mapping from", "else: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue elif pair['summ_id_j'] ==", "device) results_train = test_rewarder(all_vec_dic, train_anno, deep_model, device) for metric in results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric])))", "and pair['summ_id_j'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref = [1, 0] pair_list.append((article_id,", "sorted_scores, target_type='graded', ignore_ties=False, randomize_pref_order=False, double_prefs=False): pair_list = [] topic_count = 0 anno_count =", "pair_vec_list def pair_train_rewarder(vec_dic, pairs, deep_model, optimiser, loss_only, batch_size=32, device='cpu'): loss_list = [] shuffled_pairs", "deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onDev.pdf')) print('Its performance on the test set is:')", "percent {}'.format(train_percent)) print('dev percent {}'.format(dev_percent)) print('learn rate {}'.format(learn_rate)) print('model type {}'.format(model_type)) print('device {}'.format(device))", "'loss_dev', 'loss_test', 'rho_train', 'rho_p_train', 'pcc_train', 'pcc_p_train', 'tau_train', 'tau_p_train', 'rho_train_global', 'pcc_train_global', 'tau_train_global', 'rho_dev', 'rho_p_dev',", "train, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTrain.pdf')) test_rewarder(all_vec_dic, dev, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern", "once in one direction and once in the other direction if double_prefs: pair_list.append((article_id,", "+ 1): print('\\n=====EPOCH {}====='.format(ii)) if ii == 0: # do not train in", "csv_file exists if path.exists(file_name): csv_exists = True else: csv_exists = False with open(file_name,", "summ_entry[sum_id_i] = 1 summ_entry[sum_id_j] = 0 else: summ_entry[sum_id_i] = 0 summ_entry[sum_id_j] = 1", "pcc = pearsonr(true_scores_all, pred_scores_all)[0] tau = kendalltau(true_scores_all, pred_scores_all)[0] if not (math.isnan(rho) or math.isnan(pcc)", "tuple(unique_summ_id_pair) # add up the pref to the total pref vector of the", "topic_count) return train, dev, test, all def parse_split_data_balanced(sorted_scores, train_percent, dev_percent, prompt='structure'): train =", "shuffled_pairs) # print('total number of pairs built: {}'.format(len(vec_pairs))) for pointer in range(int((len( pairs)", "text to last summary id with that text. that's the one we will", "summary text s_text = [s['sys_summ'] for s in scores_list if s['summ_id'] == sid][0]", "preferences and pair anno # train_pairs = build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores) # dev_pairs =", "unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) else: pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) topic_count += 1 anno_count +=", "# really iterate over all pairs. there was an error here before since", "results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p) rho = spearmanr(true_scores_all, pred_scores_all)[0] pcc = pearsonr(true_scores_all, pred_scores_all)[0] tau =", "get a unique key, so that (sys_summ0,sys_summ1) and (sys_summ1,sys_summ0) are the same if", "shuffled_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch = [ee[-1] for ee in", "tau = kendalltau(true_scores_all, pred_scores_all)[0] if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc)", "import numpy as np import os from os import path import argparse import", "print('device {}'.format(device)) print('seed {}'.format(seed)) print('file name {}'.format(file_name)) print('=====Arguments====\\n') csv_column_names = ['seed', 'learn_rate', 'model_type',", "build_human_pair_scores(dev_pairs) test_anno = build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs), len(test_pairs)) # read bert vectors with open('data/doc_summ_bert_vectors.pkl',", "i=j is solved otherwise for i in range(len(summ_ids)): for j in range(len(summ_ids)): if", "list(sorted_scores.keys()) random.shuffle(article_ids) num_articles = len(article_ids) train_ids = article_ids[0:int(train_percent * num_articles)] dev_ids = article_ids[int(train_percent", "axis=0) # pred_scores_all += pred_scores.tolist() rho, rho_p = spearmanr(true_scores, pred_scores) pcc, pcc_p =", "help='pairwise or regression', default='pairwise') ap.add_argument('-tp', '--train_percent', type=float, help='how many data used for training',", "entry else: test[article_id] = entry topic_count += 1 print(\"topics in parse_split_data\", topic_count) return", "pref = [0.5, 0.5] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) # print(pair_list) topic_count += 1", "value in entries_text[article_id].items(): # get text for current summaries i and j #", "times, once in one direction and once in the other direction if double_prefs:", "when len(pairs) was a vielfaches of 32, then there was a last batch", "build_pairs_majority_preferences(dev, sorted_scores) # test_pairs = build_pairs_majority_preferences(test, sorted_scores) # with majority preferences and pair", "print(loss) optimiser.zero_grad() loss.backward() optimiser.step() return loss.cpu().item() def deep_pair_train_loss_only(vec_list, target, deep_model, optimiser, device): #", "np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec + summ_vec) # print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all += true_scores", "learn_rate) if 'gpu' in device: deep_model.to('cuda') torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False #", "in parse_split_data\", topic_count) return train, dev, test, all def parse_split_data_balanced(sorted_scores, train_percent, dev_percent, prompt='structure'):", "train_pairs, deep_model, optimiser, False, batch_size, device) loss_dev = pair_train_rewarder(all_vec_dic, dev_pairs, deep_model, optimiser, True,", "import MODEL_WEIGHT_DIR from resources import OUTPUTS_DIR from matplotlib import pyplot as plt import", "for sid in summ_ids: # get summary text s_text = [s['sys_summ'] for s", "plot written to: %s\" % plot_file) plt.savefig(plot_file) return results def parse_args(argv): ap =", "scores for pairs train_anno = build_human_pair_scores(train_pairs) dev_anno = build_human_pair_scores(dev_pairs) test_anno = build_human_pair_scores(test_pairs) print(len(train_pairs),", "# todo we could completely ignore ties. doesnt change much. low prio #", "read pair anno scores pair_anno_scores = read_pair_anno_scores() # train, dev, test, all =", "[1, 0]: if sum_id_i in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] + 1 else: human_pair_scores[article_id][sum_id_i] = 1", "= len(article_ids) train_ids = article_ids[0:int(train_percent * num_articles)] dev_ids = article_ids[int(train_percent * num_articles):int((train_percent +", "= [0.5, 0.5] # skip if it is a tie and you want", "results_train = test_rewarder(all_vec_dic, train, deep_model, device) results_train = test_rewarder(all_vec_dic, train_anno, deep_model, device) for", "Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if 'gpu' in device: input = input.to('cuda') value_variables = deep_model(input)", "scores_list if s['summ_id'] == sid][0] temp_entry['sys_summ' + repr(sid)] = s_text # save in", "if len(summ_ids) < 2: continue concat_vecs = [] true_scores = [] for i", "+= 1 print(\"topics in parse_split_data\", topic_count) return train, dev, test, all def build_model(model_type,", "tqdm(sorted_scores.items()): temp_entry = {} summ_ids = [s['summ_id'] for s in scores_list] for sid", "summ_ids[j], pref)) continue else: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue", "true_score in unique] # bw_methods determines how soft the distribution curve will be.", "get summary text and matching id for article_id, scores_list in tqdm(sorted_scores.items()): temp_entry =", "== summ_ids[j]: # text_j = value text_i = entries_text[article_id][summ_ids[i]] text_j = entries_text[article_id][summ_ids[j]] #", "False, batch_size, device) loss_dev = pair_train_rewarder(all_vec_dic, dev_pairs, deep_model, optimiser, True, batch_size, device) loss_test", "not None: optimiser = torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return deep_model, optimiser else: return deep_model def", "key, so that (sys_summ0,sys_summ1) and (sys_summ1,sys_summ0) are the same if unique_summ_id_pair[1] < unique_summ_id_pair[0]:", "they are ordered if randomize_pref_order and bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) else: pair_list.append((article_id,", "train_pairs, deep_model, optimiser, True, batch_size, device) else: # from epoch 1 on, receive", "= article_ids[0:int(train_percent * num_articles)] dev_ids = article_ids[int(train_percent * num_articles):int((train_percent + dev_percent) * num_articles)]", "many data used for dev', default=.16) ap.add_argument('-lr', '--learn_rate', type=float, help='learning rate', default=3e-4) ap.add_argument('-mt',", "for j in range(len(summ_ids)): if i == j: continue # get keys from", "not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau) if plot_file is not", "the test set is:') for metric in test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc']))", "pref)) topic_count += 1 anno_count += len(summ_ids) summ_count += len(summ2id) print(\"topics\", topic_count) print(\"annotations\",", "for pair in pair_anno_scores[article_id]: if pair['summ_id_i'] == int(entry_keys[i][8]) and pair['summ_id_j'] == int(entry_keys[j][8]): if", "loss_train, loss_dev, loss_test] print('--> losses (train,dev,test)', loss_train, loss_dev, loss_test) # Train-Data only print(\"==Train==\")", "+ s1_vec, article_vec + s2_vec]) return pair_vec_list def pair_train_rewarder(vec_dic, pairs, deep_model, optimiser, loss_only,", "dev_pairs = build_pairs(dev) # test_pairs = build_pairs(test) # without majority preferences but with", "i in range(len(summ_ids)): for j in range(len(summ_ids)): if i == j: continue if", "get keys from dictionary entry_keys = list(entry.keys()) # get pair preference from pair_anno_scores", "scores_list in tqdm(sorted_scores.items()): temp_entry = {} summ_ids = [s['summ_id'] for s in scores_list]", "batch_size] target_batch = [ee[-1] for ee in target_batch] if loss_only: loss = deep_pair_train_loss_only(vec_batch,", "'--epoch_num', type=int, default=50) ap.add_argument('-b', '--batch_size', type=int, default=32) ap.add_argument('-tt', '--train_type', type=str, help='pairwise or regression',", "mapping from summary text to last summary id with that text. that's the", "{} dev = {} test = {} all = {} topic_count = 0", "# that can be done more efficiently, but who cares... rand = random.random()", "(%s)\" % ( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print( \" \\\"%s...\\\" vs. \\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20],", "direction if double_prefs: pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) else: #", "for s in scores_list if s['summ_id'] == sid][0] temp_entry['sys_summ' + repr(sid)] = s_text", "pair_vec_list.append([article_vec + s1_vec, article_vec + s2_vec]) return pair_vec_list def pair_train_rewarder(vec_dic, pairs, deep_model, optimiser,", "scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids = [s['summ_id'] for s in scores_list]", "if pref == [1, 0]: summ_entry[sum_id_i] = 1 summ_entry[sum_id_j] = 0 else: summ_entry[sum_id_i]", "!= 0.5 or not ignore_ties: # include the pref two times, once in", "this might be necessary if there is a bias in the distribution of", "device: deep_model.to('cuda') torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # read human scores and", "use summ2id = {entries_text[article_id][summ_id]: summ_id for summ_id in summ_ids} # put here the", "< unique_summ_id_pair[0]: unique_summ_id_pair = unique_summ_id_pair[::-1] pref = pref[::-1] # convert to tuple, otherwise", "list of all scores input = Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu' in device: input =", "if 'linear' in model_type: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, 1), ) else: deep_model =", "0, just evaluate the performance of the randomly initialized model (sanity check and", "for i in range(len(summ_ids)): for j in range(len(summ_ids)): if i == j: continue", "summ_count = 0 entries_text = {} # get summary text and matching id", "topic_count = 0 anno_count = 0 summ_count = 0 entries_text = {} #", "return pair_list def build_anno_pairs(entries, pair_anno_scores): pair_list = [] topic_count = 0 summ_count =", "write column names if csv_exists is False: writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed) if", "print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) # Test-Data only print(\"==Test==\") # results_test = test_rewarder(all_vec_dic, test, deep_model,", "[0.5, 0.5] # sort the ids so that we get a unique key,", "parse_split_data\", topic_count) return train, dev, test, all def parse_split_data_balanced(sorted_scores, train_percent, dev_percent, prompt='structure'): train", "return results def parse_args(argv): ap = argparse.ArgumentParser(\"arguments for summary sampler\") ap.add_argument('-e', '--epoch_num', type=int,", "text for current summaries i and j # if key == summ_ids[i]: #", "ap.add_argument('-tp', '--train_percent', type=float, help='how many data used for training', default=.64) ap.add_argument('-dp', '--dev_percent', type=float,", "len(summ_ids) summ_count += len(summ2id) print(\"topics\", topic_count) print(\"annotations\", anno_count) print(\"summ\", summ_count) print(\"summ pairs\", len(pair_list))", "summaries i and j # if key == summ_ids[i]: # text_i = value", "len(article_ids) train_ids = article_ids[0:int(train_percent * num_articles)] dev_ids = article_ids[int(train_percent * num_articles):int((train_percent + dev_percent)", "return pair_list def build_human_pair_scores(pair_list): human_pair_scores = {} for entry in pair_list: article_id =", "that text. that's the one we will use summ2id = {entries_text[article_id][summ_id]: summ_id for", "pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, False, batch_size, device) loss_dev = pair_train_rewarder(all_vec_dic, dev_pairs, deep_model, optimiser,", "unique_summ_id_pair[1])) full_entry = sorted_scores[article_id] print(\" system %s with score %s (%s) vs.\" %", "build_model(model_type, BERT_VEC_LENGTH * 2, learn_rate) if 'gpu' in device: deep_model.to('cuda') torch.backends.cudnn.deterministic = True", "for metric in test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed,", "this should be set to False def build_pairs_majority_preferences(entries, sorted_scores, target_type='graded', ignore_ties=False, randomize_pref_order=False, double_prefs=False):", "1] else: pref = [0.5, 0.5] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) # print(pair_list) topic_count", "# train_pairs = build_pairs_majority_preferences(train, sorted_scores) # dev_pairs = build_pairs_majority_preferences(dev, sorted_scores) # test_pairs =", "= test_rewarder(all_vec_dic, train_anno, deep_model, device) for metric in results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\")", "article_prefs = {} # still run through all pairs # really iterate over", "# read pair anno scores pair_anno_scores = read_pair_anno_scores() # train, dev, test, all", "% (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort() if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0]", "torch.nn.Softmax(dim=1) pred = softmax_layer(value_variables) # print(pred) # print(np.array(target).shape, np.array(target).reshape(-1, 2, 1).shape) target_variables =", "test = {} all = {} topic_count = 0 for article_id, scores_list in", "{} summ_ids = [s['summ_id'] for s in scores_list] for sid in summ_ids: entry['sys_summ'", "type {}'.format(train_type)) print('train percent {}'.format(train_percent)) print('dev percent {}'.format(dev_percent)) print('learn rate {}'.format(learn_rate)) print('model type", "dev_percent)) exit(1) BERT_VEC_LENGTH = 1024 # change this to 768 if you use", "'learn_rate', 'model_type', 'train_pairs', 'dev_pairs', 'test_pairs', 'epoch_num', 'loss_train', 'loss_dev', 'loss_test', 'rho_train', 'rho_p_train', 'pcc_train', 'pcc_p_train',", "+ '_onDev.pdf')) print('Its performance on the test set is:') for metric in test_results:", "batch_size, device) csv_row = [seed, learn_rate, model_type, len(train_pairs), len(dev_pairs), len(test_pairs), ii, loss_train, loss_dev,", "text_i, \"TEXT j\", text_i) continue # get the unique summ ids unique_summ_id_pair =", "= build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores) # test_pairs = build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores) # build human", "= {entries_text[article_id][summ_id]: summ_id for summ_id in summ_ids} # put here the prefs for", "+ dev_percent)) exit(1) BERT_VEC_LENGTH = 1024 # change this to 768 if you", "here before since j started from 1, to prevent i,j=0,0. but this also", "unique_summ_id_pair.sort() if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0] elif entry[summ_ids[i]] < entry[summ_ids[j]]:", "in range(int((len( pairs) - 1) / batch_size) + 1): # there was a", "unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry = sorted_scores[article_id] print(\" system %s with score %s (%s) vs.\"", "target_type='graded', ignore_ties=False, randomize_pref_order=False, double_prefs=False): pair_list = [] topic_count = 0 anno_count = 0", "1 print(\"topics in parse_split_data\", topic_count) return train, dev, test, all def parse_split_data_balanced(sorted_scores, train_percent,", "+= pred_scores.tolist() rho, rho_p = spearmanr(true_scores, pred_scores) pcc, pcc_p = pearsonr(true_scores, pred_scores) tau,", "pyplot as plt import csv def parse_split_data(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {}", "true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all) unique = np.sort(np.unique(true_scores_all)) data_to_plot = [pred_scores_all[true_score == true_scores_all] for true_score", "= 0 anno_count = 0 summ_count = 0 entries_text = {} # get", "pair['pref'] == 1: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else:", "= torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length / 2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length / 2), 1), ) if", "# elif key == summ_ids[j]: # text_j = value text_i = entries_text[article_id][summ_ids[i]] text_j", "entries[article_id] summ_ids = list(entry.keys()) # really iterate over all pairs. there was an", "print(\"%s vs. %s (IDs %s vs. %s)\" % ( summ_ids[i], summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1]))", "completely ignore ties. doesnt change much. low prio # pref = [0.5, 0.5]", "are the same if unique_summ_id_pair[1] < unique_summ_id_pair[0]: unique_summ_id_pair = unique_summ_id_pair[::-1] pref = pref[::-1]", "loss_only: loss = deep_pair_train_loss_only(vec_batch, target_batch, deep_model, optimiser, device) else: loss = deep_pair_train(vec_batch, target_batch,", "# Test-Data only print(\"==Test==\") # results_test = test_rewarder(all_vec_dic, test, deep_model, device) results_test =", "help='random seed number', default='1') ap.add_argument('-fn', '--file_name', type=str, help='file name for csv output', default='BetterRewardsStatistics_test.csv')", "deep_model, optimiser, loss_only, batch_size=32, device='cpu'): loss_list = [] shuffled_pairs = pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs", "= [seed, learn_rate, model_type, len(train_pairs), len(dev_pairs), len(test_pairs), ii, loss_train, loss_dev, loss_test] print('--> losses", "train_pairs = build_anno_pairs(train, pair_anno_scores) dev_pairs = build_anno_pairs(dev, pair_anno_scores) test_pairs = build_anno_pairs(test, pair_anno_scores) #", "many data used for training', default=.64) ap.add_argument('-dp', '--dev_percent', type=float, help='how many data used", "+ len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) # print(pair_list) return pair_list def build_human_pair_scores(pair_list): human_pair_scores", "return pair_vec_list def pair_train_rewarder(vec_dic, pairs, deep_model, optimiser, loss_only, batch_size=32, device='cpu'): loss_list = []", "pair_vec_list = [] for aid, sid1, sid2, _ in pairs: article_vec = list(vecs[aid]['article'])", "2: continue concat_vecs = [] true_scores = [] for i in range(len(summ_ids)): article_vec", "device) csv_row = [seed, learn_rate, model_type, len(train_pairs), len(dev_pairs), len(test_pairs), ii, loss_train, loss_dev, loss_test]", "= list(vecs[aid]['article']) s1_vec = list(vecs[aid][sid1]) s2_vec = list(vecs[aid][sid2]) pair_vec_list.append([article_vec + s1_vec, article_vec +", "all[article_id] = entry if article_id in train_ids: train[article_id] = entry elif article_id in", "Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1) # print(target_variables) if 'gpu' in device: target_variables = target_variables.to('cuda') loss_fn", "'pcc_p_dev', 'tau_dev', 'tau_p_dev', 'rho_dev_global', 'pcc_dev_global', 'tau_dev_global', 'rho_test', 'rho_p_test', 'pcc_test', 'pcc_p_test', 'tau_test', 'tau_p_test', 'rho_test_global',", "default='pairwise') ap.add_argument('-tp', '--train_percent', type=float, help='how many data used for training', default=.64) ap.add_argument('-dp', '--dev_percent',", "print('learn rate {}'.format(learn_rate)) print('model type {}'.format(model_type)) print('device {}'.format(device)) print('seed {}'.format(seed)) print('file name {}'.format(file_name))", "pearsonr(true_scores_all, pred_scores_all)[0] tau = kendalltau(true_scores_all, pred_scores_all)[0] if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)):", "vec_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch = shuffled_pairs[pointer * batch_size:(pointer +", "print(loss) return loss.cpu().item() def build_pairs(entries): pair_list = [] topic_count = 0 summ_count =", "{}'.format(train_percent)) print('dev percent {}'.format(dev_percent)) print('learn rate {}'.format(learn_rate)) print('model type {}'.format(model_type)) print('device {}'.format(device)) print('seed", "topic_count) print(\"annotations\", anno_count) print(\"summ\", summ_count) print(\"summ pairs\", len(pair_list)) return pair_list def build_pair_vecs(vecs, pairs):", "* batch_size:(pointer + 1) * batch_size] target_batch = [ee[-1] for ee in target_batch]", "device) else: # from epoch 1 on, receive the data and learn from", "'tau_train', 'tau_p_train', 'rho_train_global', 'pcc_train_global', 'tau_train_global', 'rho_dev', 'rho_p_dev', 'pcc_dev', 'pcc_p_dev', 'tau_dev', 'tau_p_dev', 'rho_dev_global', 'pcc_dev_global',", "train_percent, dev_percent, prompt='structure'): train = {} dev = {} test = {} all", "entries[article_id] summ_ids = list(entry.keys()) # mapping from summary text to last summary id", "# print(loss) optimiser.zero_grad() loss.backward() optimiser.step() return loss.cpu().item() def deep_pair_train_loss_only(vec_list, target, deep_model, optimiser, device):", "that (sys_summ0,sys_summ1) and (sys_summ1,sys_summ0) are the same if unique_summ_id_pair[1] < unique_summ_id_pair[0]: unique_summ_id_pair =", "vectors for summaries/docs, and split the train/dev/test set sorted_scores = read_sorted_scores() # read", "results['pcc_global'].append(pcc) results['tau_global'].append(tau) if plot_file is not None: fig, ax = plt.subplots() # true_scores_all=np.array(true_scores_all)", "spearmanr(true_scores, pred_scores) pcc, pcc_p = pearsonr(true_scores, pred_scores) tau, tau_p = kendalltau(true_scores, pred_scores) if", "'_onTrain.pdf')) test_rewarder(all_vec_dic, dev, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onDev.pdf')) print('Its performance on the", "train/dev/test set sorted_scores = read_sorted_scores() # read pair anno scores pair_anno_scores = read_pair_anno_scores()", "results = {'rho': [], 'rho_p': [], 'pcc': [], 'pcc_p': [], 'tau': [], 'tau_p':", "pref[0] != 0.5 or not ignore_ties: # include the pref two times, once", "for topic to list of all scores input = Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu' in", "== summ_ids[i]: # text_i = value # elif key == summ_ids[j]: # text_j", "# print(true_scores) # print(np.array(true_scores).shape) # print(input) # print(input.shape) # print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape) pred_scores", "test, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTest.pdf')) test_rewarder(all_vec_dic, train, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern", "to list of all scores input = Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu' in device: input", "get summary text s_text = [s['sys_summ'] for s in scores_list if s['summ_id'] ==", "article_id in entries: entry = entries[article_id] summ_ids = list(entry.keys()) # really iterate over", "# read human scores and vectors for summaries/docs, and split the train/dev/test set", "sampler\") ap.add_argument('-e', '--epoch_num', type=int, default=50) ap.add_argument('-b', '--batch_size', type=int, default=32) ap.add_argument('-tt', '--train_type', type=str, help='pairwise", "double_prefs=False): pair_list = [] topic_count = 0 anno_count = 0 summ_count = 0", "the score, e.g. if they are ordered if randomize_pref_order and bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1],", "os.path.join(OUTPUTS_DIR, output_pattern + '_onTrain.pdf')) test_rewarder(all_vec_dic, dev, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onDev.pdf')) print('Its", "if there is a bias in the distribution of the score, e.g. if", "= kendalltau(true_scores, pred_scores) if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc)", "pearsonr(true_scores, pred_scores) tau, tau_p = kendalltau(true_scores, pred_scores) if not (math.isnan(rho) or math.isnan(pcc) or", "= kendalltau(true_scores_all, pred_scores_all)[0] if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau)", "print(\"==Dev==\") # results = test_rewarder(all_vec_dic, dev, deep_model, device) results = test_rewarder(all_vec_dic, dev_anno, deep_model,", "optimiser.step() return loss.cpu().item() def deep_pair_train_loss_only(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input =", "if 'gpu' in device: target_variables = target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss = loss_fn(pred,", "lead to i,j=x,0 never be chosen the situation i=j is solved otherwise for", "and you want to ignore ties if pref[0] != 0.5 or not ignore_ties:", "range(int((len( pairs) - 1) / batch_size) + 1): # there was a bug", "continue # get the unique summ ids unique_summ_id_pair = [summ2id[text_i], summ2id[text_j]] # some", "here. when len(pairs) was a vielfaches of 32, then there was a last", "target_batch = shuffled_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch = [ee[-1] for", "= entries[article_id] summ_ids = list(entry.keys()) # really iterate over all pairs. there was", "'epoch_num', 'loss_train', 'loss_dev', 'loss_test', 'rho_train', 'rho_p_train', 'pcc_train', 'pcc_p_train', 'tau_train', 'tau_p_train', 'rho_train_global', 'pcc_train_global', 'tau_train_global',", "torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) optimiser.zero_grad() loss.backward() optimiser.step() return loss.cpu().item() def", "# pref = [0, 1] # else: # # todo we could completely", "target_variables) # print(loss) return loss.cpu().item() def build_pairs(entries): pair_list = [] topic_count = 0", "human pair scores for pairs train_anno = build_human_pair_scores(train_pairs) dev_anno = build_human_pair_scores(dev_pairs) test_anno =", "case, we learn f(s0)=pref[0] and f(s1)=pref[1], so this should be set to False", "keys from dictionary entry_keys = list(entry.keys()) # get pair preference from pair_anno_scores for", "true_scores_all ax.set_xticks(true_scores_all) print(\"violin plot written to: %s\" % plot_file) plt.savefig(plot_file) return results def", "include the pref two times, once in one direction and once in the", "+ dev_percent: dev[article_id] = entry else: test[article_id] = entry topic_count += 1 print(\"topics", "deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTest.pdf')) test_rewarder(all_vec_dic, train, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern +", "pref = [0.5, 0.5] # if entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [1,", "-1)[0] pred_scores_all = np.concatenate((pred_scores_all, pred_scores), axis=0) # pred_scores_all += pred_scores.tolist() rho, rho_p =", "# from epoch 1 on, receive the data and learn from it. the", "loss = loss_fn(pred, target_variables) # print(loss) optimiser.zero_grad() loss.backward() optimiser.step() return loss.cpu().item() def deep_pair_train_loss_only(vec_list,", "sys import torch from torch.autograd import Variable import numpy as np import os", "is:') for metric in test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format(", "on the mode, use binary target, or graded one pref = (pref /", "seed, learn_rate, model_type, epoch_num ) test_results = test_rewarder(all_vec_dic, test, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern", "> pref[1]: pref = [1, 0] elif pref[0] < pref[1]: pref = [1,", "print('epoch num {}'.format(epoch_num)) print('batch size {}'.format(batch_size)) print('train type {}'.format(train_type)) print('train percent {}'.format(train_percent)) print('dev", "loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, True, batch_size, device) else: # from epoch", "device) results = test_rewarder(all_vec_dic, dev_anno, deep_model, device) for metric in results: print('{}\\t{}'.format(metric, np.mean(results[metric])))", "help='learning rate', default=3e-4) ap.add_argument('-mt', '--model_type', type=str, help='deep/linear', default='linear') ap.add_argument('-dv', '--device', type=str, help='cpu/gpu', default='gpu')", "1] # else: # # todo we could completely ignore ties. doesnt change", "2, learn_rate) if 'gpu' in device: deep_model.to('cuda') torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False", "pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue elif pair['summ_id_j'] == int(entry_keys[i][8])", "s in scores_list if s['summ_id'] == sid][0] temp_entry['sys_summ' + repr(sid)] = s_text #", "torch.autograd import Variable import numpy as np import os from os import path", "preference from pair_anno_scores for pair in pair_anno_scores[article_id]: if pair['summ_id_i'] == int(entry_keys[i][8]) and pair['summ_id_j']", "so that we get a unique key, so that (sys_summ0,sys_summ1) and (sys_summ1,sys_summ0) are", "from torch.autograd import Variable import numpy as np import os from os import", "unique key, so that (sys_summ0,sys_summ1) and (sys_summ1,sys_summ0) are the same if unique_summ_id_pair[1] <", "pair. create a new entry if not existing article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair, np.array([0, 0]))", "pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) topic_count += 1 anno_count += len(summ_ids) summ_count += len(summ2id)", "over all pairs. there was an error here before since j started from", "results_train = test_rewarder(all_vec_dic, train_anno, deep_model, device) for metric in results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric]))", "print('train type {}'.format(train_type)) print('train percent {}'.format(train_percent)) print('dev percent {}'.format(dev_percent)) print('learn rate {}'.format(learn_rate)) print('model", "[s['scores'][prompt] for s in scores_list if s['summ_id'] == sid][ 0] # that can", "cares... rand = random.random() all[article_id] = entry if rand < train_percent: train[article_id] =", "[], 'pcc_global': [], 'tau_global': []} true_scores_all = [] pred_scores_all = np.array([]) # print(human_scores)", "[] for ii in range(epoch_num + 1): print('\\n=====EPOCH {}====='.format(ii)) if ii == 0:", "summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry = sorted_scores[article_id] print(\" system %s with score %s (%s)", "'rho_train_global', 'pcc_train_global', 'tau_train_global', 'rho_dev', 'rho_p_dev', 'pcc_dev', 'pcc_p_dev', 'tau_dev', 'tau_p_dev', 'rho_dev_global', 'pcc_dev_global', 'tau_dev_global', 'rho_test',", "= build_anno_pairs(test, pair_anno_scores) # with majority preferences # train_pairs = build_pairs_majority_preferences(train, sorted_scores) #", "= np.array([]) # print(human_scores) # pred_scores_all = [] for article_id in human_scores: entry", "or math.isnan(pcc) or math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p) rho = spearmanr(true_scores_all,", "parse_split_data\", topic_count) return train, dev, test, all def build_model(model_type, vec_length, learn_rate=None): if 'linear'", "help='how many data used for dev', default=.16) ap.add_argument('-lr', '--learn_rate', type=float, help='learning rate', default=3e-4)", "'rho_p_train', 'pcc_train', 'pcc_p_train', 'tau_train', 'tau_p_train', 'rho_train_global', 'pcc_train_global', 'tau_train_global', 'rho_dev', 'rho_p_dev', 'pcc_dev', 'pcc_p_dev', 'tau_dev',", "= csv.writer(csv_file) # if a new csv_file is generated, write column names if", "dev_pairs = build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores) # test_pairs = build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores) # build", "should be set to False def build_pairs_majority_preferences(entries, sorted_scores, target_type='graded', ignore_ties=False, randomize_pref_order=False, double_prefs=False): pair_list", "human_pair_scores[article_id][sum_id_i] + 1 else: human_pair_scores[article_id][sum_id_i] = 1 else: if sum_id_j in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j]", "there was a bug here. when len(pairs) was a vielfaches of 32, then", "pair preference from pair_anno_scores for pair in pair_anno_scores[article_id]: if pair['summ_id_i'] == int(entry_keys[i][8]) and", "* batch_size:(pointer + 1) * batch_size] target_batch = shuffled_pairs[pointer * batch_size:(pointer + 1)", "os.path.join(OUTPUTS_DIR, output_pattern + '_onTest.pdf')) test_rewarder(all_vec_dic, train, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTrain.pdf')) test_rewarder(all_vec_dic,", "return np.mean(loss_list) def test_rewarder(vec_list, human_scores, model, device, plot_file=None): results = {'rho': [], 'rho_p':", "ii == 0: # do not train in epoch 0, just evaluate the", "1 human_pair_scores[article_id] = summ_entry return human_pair_scores # randomize_pref_order and double_prefs are only relevant", "optimiser.zero_grad() loss.backward() optimiser.step() return loss.cpu().item() def deep_pair_train_loss_only(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape)", "below 1.0!'.format( train_percent + dev_percent)) exit(1) BERT_VEC_LENGTH = 1024 # change this to", "results['tau_p'].append(tau_p) rho = spearmanr(true_scores_all, pred_scores_all)[0] pcc = pearsonr(true_scores_all, pred_scores_all)[0] tau = kendalltau(true_scores_all, pred_scores_all)[0]", "False def build_pairs_majority_preferences(entries, sorted_scores, target_type='graded', ignore_ties=False, randomize_pref_order=False, double_prefs=False): pair_list = [] topic_count =", "pair_list: article_id = str(entry[0]) sum_id_i = str(entry[1]) sum_id_j = str(entry[2]) pref = entry[3]", "pref[1])).tolist() if target_type == 'binary': if pref[0] > pref[1]: pref = [1, 0]", "= deep_pair_train_loss_only(vec_batch, target_batch, deep_model, optimiser, device) else: loss = deep_pair_train(vec_batch, target_batch, deep_model, optimiser,", "rand = random.random() all[article_id] = entry if article_id in train_ids: train[article_id] = entry", "in range(len(summ_ids)): # run through dictionary containing summ_ids and matching text # for", "= {} for entry in pair_list: article_id = str(entry[0]) sum_id_i = str(entry[1]) sum_id_j", "# with majority preferences # train_pairs = build_pairs_majority_preferences(train, sorted_scores) # dev_pairs = build_pairs_majority_preferences(dev,", "'tau_dev_global', 'rho_test', 'rho_p_test', 'pcc_test', 'pcc_p_test', 'tau_test', 'tau_p_test', 'rho_test_global', 'pcc_test_global', 'tau_test_global'] # check if", "print(\"summ\", summ_count) print(\"summ pairs\", len(pair_list)) return pair_list def build_pair_vecs(vecs, pairs): pair_vec_list = []", "last batch with [] causing an exception vec_batch = vec_pairs[pointer * batch_size:(pointer +", "def parse_args(argv): ap = argparse.ArgumentParser(\"arguments for summary sampler\") ap.add_argument('-e', '--epoch_num', type=int, default=50) ap.add_argument('-b',", "args.seed, args.file_name def main(argv): epoch_num, batch_size, train_type, train_percent, dev_percent, learn_rate, model_type, device, seed,", "'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type, train_percent, seed, learn_rate, model_type, epoch_num ) test_results = test_rewarder(all_vec_dic, test,", "'pcc_test', 'pcc_p_test', 'tau_test', 'tau_p_test', 'rho_test_global', 'pcc_test_global', 'tau_test_global'] # check if csv_file exists if", "num_articles)] dev_ids = article_ids[int(train_percent * num_articles):int((train_percent + dev_percent) * num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for", "doesnt change much. low prio # pref = [0.5, 0.5] # sort the", "True else: csv_exists = False with open(file_name, 'a', newline='') as csv_file: writer =", "epoch 0, just evaluate the performance of the randomly initialized model (sanity check", "# there was a bug here. when len(pairs) was a vielfaches of 32,", "else: test[article_id] = entry topic_count += 1 print(\"topics in parse_split_data\", topic_count) return train,", "with that text. that's the one we will use summ2id = {entries_text[article_id][summ_id]: summ_id", "= [s['scores'][prompt] for s in scores_list if s['summ_id'] == sid][ 0] # that", "device) results_test = test_rewarder(all_vec_dic, test_anno, deep_model, device) for metric in results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric])))", "path import argparse import random import copy from tqdm import tqdm import pickle", "pcc_p = pearsonr(true_scores, pred_scores) tau, tau_p = kendalltau(true_scores, pred_scores) if not (math.isnan(rho) or", "if randomize_pref_order and bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) else: pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref))", "1 anno_count += len(summ_ids) summ_count += len(summ2id) print(\"topics\", topic_count) print(\"annotations\", anno_count) print(\"summ\", summ_count)", "import tqdm import pickle from scorer.data_helper.json_reader import read_sorted_scores, read_pair_anno_scores, read_articles, \\ read_processed_scores, read_scores", "else: csv_exists = False with open(file_name, 'a', newline='') as csv_file: writer = csv.writer(csv_file)", "we will use summ2id = {entries_text[article_id][summ_id]: summ_id for summ_id in summ_ids} # put", "pair_anno_scores) # build human pair scores for pairs train_anno = build_human_pair_scores(train_pairs) dev_anno =", "range(epoch_num + 1): print('\\n=====EPOCH {}====='.format(ii)) if ii == 0: # do not train", "and baseline) loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, True, batch_size, device) else: #", "temp_entry = {} summ_ids = [s['summ_id'] for s in scores_list] for sid in", "vs.\" % ( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\" system %s with score %s (%s)\"", "pair['summ_id_j'] == int(entry_keys[i][8]) and pair['summ_id_i'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref =", ") torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest model weight saved to: {}'.format(os.path.join(MODEL_WEIGHT_DIR, model_weight_name))) if __name__", "s['summ_id'] == sid][ 0] # that can be done more efficiently, but who", "return loss.cpu().item() def deep_pair_train_loss_only(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float())", "{} # get summary text and matching id for article_id, scores_list in tqdm(sorted_scores.items()):", "np.concatenate((pred_scores_all, pred_scores), axis=0) # pred_scores_all += pred_scores.tolist() rho, rho_p = spearmanr(true_scores, pred_scores) pcc,", "from scipy.stats import spearmanr, pearsonr, kendalltau import math from torchvision import models from", "Train-Data only print(\"==Train==\") # results_train = test_rewarder(all_vec_dic, train, deep_model, device) results_train = test_rewarder(all_vec_dic,", "False: writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed) if train_percent + dev_percent >= 1.: print('ERROR!", "deep_model.to('cuda') torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # read human scores and vectors", "ap.parse_args(argv) return args.epoch_num, args.batch_size, args.train_type, args.train_percent, args.dev_percent, args.learn_rate, args.model_type, args.device, args.seed, args.file_name def", "ap.add_argument('-dp', '--dev_percent', type=float, help='how many data used for dev', default=.16) ap.add_argument('-lr', '--learn_rate', type=float,", "results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p) rho = spearmanr(true_scores_all, pred_scores_all)[0] pcc = pearsonr(true_scores_all, pred_scores_all)[0]", "{entries_text[article_id][summ_id]: summ_id for summ_id in summ_ids} # put here the prefs for this", "learn_rate=None): if 'linear' in model_type: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, 1), ) else: deep_model", "from tqdm import tqdm import pickle from scorer.data_helper.json_reader import read_sorted_scores, read_pair_anno_scores, read_articles, \\", "data_to_plot = [pred_scores_all[true_score == true_scores_all] for true_score in unique] # bw_methods determines how", "optimiser else: return deep_model def deep_pair_train(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input", "dict unique_summ_id_pair = tuple(unique_summ_id_pair) # add up the pref to the total pref", "deep_model.load_state_dict(weights_list[idx]) output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type, train_percent, seed, learn_rate, model_type, epoch_num ) test_results", "the data and learn from it. the loss is still the loss before", "else: human_pair_scores[article_id][sum_id_i] = 1 else: if sum_id_j in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] + 1 else:", "summ_count) print(\"summ pairs\", len(pair_list)) return pair_list def build_pair_vecs(vecs, pairs): pair_vec_list = [] for", "= {} all = {} topic_count = 0 article_ids = list(sorted_scores.keys()) random.shuffle(article_ids) num_articles", "else: pref = [0.5, 0.5] # skip if it is a tie and", "print(human_scores) # pred_scores_all = [] for article_id in human_scores: entry = human_scores[article_id] summ_ids", "in dev_ids: dev[article_id] = entry else: test[article_id] = entry topic_count += 1 print(\"topics", "test, all = parse_split_data(sorted_scores, train_percent, dev_percent) train, dev, test, all = parse_split_data_balanced(sorted_scores, train_percent,", "shuffled_pairs = pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs = build_pair_vecs(vec_dic, shuffled_pairs) # print('total number of pairs", "summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) return pair_list def build_anno_pairs(entries, pair_anno_scores): pair_list", "deep_model(input) # print(value_variables) softmax_layer = torch.nn.Softmax(dim=1) pred = softmax_layer(value_variables) # print(pred) # print(np.array(target).shape,", "parse_args( argv[1:]) print('\\n=====Arguments====') print('epoch num {}'.format(epoch_num)) print('batch size {}'.format(batch_size)) print('train type {}'.format(train_type)) print('train", "# noinspection PyUnreachableCode if False: print(\"%s vs. %s (IDs %s vs. %s)\" %", "= torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) optimiser.zero_grad() loss.backward() optimiser.step() return loss.cpu().item()", "optimiser, True, batch_size, device) csv_row = [seed, learn_rate, model_type, len(train_pairs), len(dev_pairs), len(test_pairs), ii,", "1024 # change this to 768 if you use bert-base deep_model, optimiser =", "input = input.to('cuda') value_variables = deep_model(input) # print(value_variables) softmax_layer = torch.nn.Softmax(dim=1) pred =", "= list(entry.keys()) # mapping from summary text to last summary id with that", "[0.5, 0.5] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) # print(pair_list) topic_count += 1 summ_count =", "be done more efficiently, but who cares... # rand = random.random() all[article_id] =", "pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx = np.argmax(pcc_list) best_result = pcc_list[idx] print('\\n======Best results come from epoch", "ax.set_xlabel('true scores') ax.set_ylabel('predicted scores') xticklabels = true_scores_all ax.set_xticks(true_scores_all) print(\"violin plot written to: %s\"", "in entries: entry = entries[article_id] summ_ids = list(entry.keys()) # really iterate over all", "= [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue topic_count += 1 summ_count =", "import random import copy from tqdm import tqdm import pickle from scorer.data_helper.json_reader import", "== 1: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref", "full_entry = sorted_scores[article_id] print(\" system %s with score %s (%s) vs.\" % (", "identical, if yes skip if i == j or text_i == text_j: #", "unique summ ids unique_summ_id_pair = [summ2id[text_i], summ2id[text_j]] # some debug output # noinspection", "str(entry[0]) sum_id_i = str(entry[1]) sum_id_j = str(entry[2]) pref = entry[3] summ_entry = {}", "1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) # print(pair_list) return", "unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) topic_count += 1 anno_count += len(summ_ids) summ_count += len(summ2id) print(\"topics\",", "1 summ_entry[sum_id_j] = 0 else: summ_entry[sum_id_i] = 0 summ_entry[sum_id_j] = 1 human_pair_scores[article_id] =", "== [1, 0]: summ_entry[sum_id_i] = 1 summ_entry[sum_id_j] = 0 else: summ_entry[sum_id_i] = 0", "+ len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) return pair_list def build_anno_pairs(entries, pair_anno_scores): pair_list =", "iterate over all pairs. there was an error here before since j started", "ax = plt.subplots() # true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all) unique = np.sort(np.unique(true_scores_all)) data_to_plot = [pred_scores_all[true_score", "for s in scores_list if s['summ_id'] == sid][ 0] # that can be", "if text is identical, if yes skip if i == j or text_i", "evaluate the performance of the randomly initialized model (sanity check and baseline) loss_train", "[ee[-1] for ee in target_batch] if loss_only: loss = deep_pair_train_loss_only(vec_batch, target_batch, deep_model, optimiser,", "device, os.path.join(OUTPUTS_DIR, output_pattern + '_onDev.pdf')) print('Its performance on the test set is:') for", "of true values to predicted score') ax.set_xlabel('true scores') ax.set_ylabel('predicted scores') xticklabels = true_scores_all", "majority preferences # train_pairs = build_pairs(train) # dev_pairs = build_pairs(dev) # test_pairs =", "== j: continue # get keys from dictionary entry_keys = list(entry.keys()) # get", "[1, 0]: summ_entry[sum_id_i] = 1 summ_entry[sum_id_j] = 0 else: summ_entry[sum_id_i] = 0 summ_entry[sum_id_j]", "'test_pairs', 'epoch_num', 'loss_train', 'loss_dev', 'loss_test', 'rho_train', 'rho_p_train', 'pcc_train', 'pcc_p_train', 'tau_train', 'tau_p_train', 'rho_train_global', 'pcc_train_global',", "entry['sys_summ' + repr(sid)] = [s['scores'][prompt] for s in scores_list if s['summ_id'] == sid][", "the situation i=j is solved otherwise for i in range(len(summ_ids)): for j in", "loss_test] print('--> losses (train,dev,test)', loss_train, loss_dev, loss_test) # Train-Data only print(\"==Train==\") # results_train", "there is a bias in the distribution of the score, e.g. if they", "pair['summ_id_i'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref = [0, 1] pair_list.append((article_id, summ_ids[i],", "# for key, value in entries_text[article_id].items(): # get text for current summaries i", "pred_scores.tolist() rho, rho_p = spearmanr(true_scores, pred_scores) pcc, pcc_p = pearsonr(true_scores, pred_scores) tau, tau_p", "print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all += true_scores # add scores for topic to list of", "in range(len(summ_ids)): for j in range(len(summ_ids)): if i == j: continue # get", "preferences but with pair anno train_pairs = build_anno_pairs(train, pair_anno_scores) dev_pairs = build_anno_pairs(dev, pair_anno_scores)", "# Train-Data only print(\"==Train==\") # results_train = test_rewarder(all_vec_dic, train, deep_model, device) results_train =", "anno_count) print(\"summ\", summ_count) print(\"summ pairs\", len(pair_list)) return pair_list def build_pair_vecs(vecs, pairs): pair_vec_list =", "tqdm(sorted_scores.items()): entry = {} summ_ids = [s['summ_id'] for s in scores_list] for sid", "test_rewarder(all_vec_dic, train_anno, deep_model, device) for metric in results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") #", "one pref = (pref / (pref[0] + pref[1])).tolist() if target_type == 'binary': if", "import OUTPUTS_DIR from matplotlib import pyplot as plt import csv def parse_split_data(sorted_scores, train_percent,", "from resources import OUTPUTS_DIR from matplotlib import pyplot as plt import csv def", "target_variables) # print(loss) optimiser.zero_grad() loss.backward() optimiser.step() return loss.cpu().item() def deep_pair_train_loss_only(vec_list, target, deep_model, optimiser,", "print(\"topics\", topic_count) print(\"annotations\", anno_count) print(\"summ\", summ_count) print(\"summ pairs\", len(pair_list)) return pair_list def build_pair_vecs(vecs,", "{} topic_count = 0 article_ids = list(sorted_scores.keys()) random.shuffle(article_ids) num_articles = len(article_ids) train_ids =", "and once in the other direction if double_prefs: pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id,", "/ (pref[0] + pref[1])).tolist() if target_type == 'binary': if pref[0] > pref[1]: pref", "= deep_model(input) # print(value_variables) softmax_layer = torch.nn.Softmax(dim=1) pred = softmax_layer(value_variables) # print(pred) #", "random.shuffle(article_ids) num_articles = len(article_ids) train_ids = article_ids[0:int(train_percent * num_articles)] dev_ids = article_ids[int(train_percent *", "optimiser = torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return deep_model, optimiser else: return deep_model def deep_pair_train(vec_list, target,", "def build_pair_vecs(vecs, pairs): pair_vec_list = [] for aid, sid1, sid2, _ in pairs:", "pair_anno_scores) test_pairs = build_anno_pairs(test, pair_anno_scores) # with majority preferences # train_pairs = build_pairs_majority_preferences(train,", "values to predicted score') ax.set_xlabel('true scores') ax.set_ylabel('predicted scores') xticklabels = true_scores_all ax.set_xticks(true_scores_all) print(\"violin", "dev_pairs = build_anno_pairs(dev, pair_anno_scores) test_pairs = build_anno_pairs(test, pair_anno_scores) # with majority preferences #", "if loss_only: loss = deep_pair_train_loss_only(vec_batch, target_batch, deep_model, optimiser, device) else: loss = deep_pair_train(vec_batch,", "ap.add_argument('-e', '--epoch_num', type=int, default=50) ap.add_argument('-b', '--batch_size', type=int, default=32) ap.add_argument('-tt', '--train_type', type=str, help='pairwise or", "'pcc_test_global', 'tau_test_global'] # check if csv_file exists if path.exists(file_name): csv_exists = True else:", "'_onTest.pdf')) test_rewarder(all_vec_dic, train, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTrain.pdf')) test_rewarder(all_vec_dic, dev, deep_model, device,", "torch.nn.Linear(vec_length, 1), ) else: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length / 2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length", "pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) # print(pair_list) topic_count += 1 summ_count = summ_count +", "is identical, if yes skip if i == j or text_i == text_j:", "in range(len(summ_ids)): for j in range(len(summ_ids)): if i == j: continue if entry[summ_ids[i]]", "# if entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [1, 0] # elif entry[unique_summ_id_pair[0]]", "(pref / (pref[0] + pref[1])).tolist() if target_type == 'binary': if pref[0] > pref[1]:", "1.: print('ERROR! Train data percentage plus dev data percentage is {}! Make sure", "type=float, help='how many data used for dev', default=.16) ap.add_argument('-lr', '--learn_rate', type=float, help='learning rate',", "Test-Data only print(\"==Test==\") # results_test = test_rewarder(all_vec_dic, test, deep_model, device) results_test = test_rewarder(all_vec_dic,", "= 1 else: if pref == [1, 0]: summ_entry[sum_id_i] = 1 summ_entry[sum_id_j] =", "pair_train_rewarder(all_vec_dic, dev_pairs, deep_model, optimiser, True, batch_size, device) loss_test = pair_train_rewarder(all_vec_dic, test_pairs, deep_model, optimiser,", "read bert vectors with open('data/doc_summ_bert_vectors.pkl', 'rb') as ff: all_vec_dic = pickle.load(ff) pcc_list =", "'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num, batch_size, train_type, train_percent, learn_rate, model_type ) torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest", "1).shape) target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1) # print(target_variables) if 'gpu' in device: target_variables", "1 else: if pref == [1, 0]: summ_entry[sum_id_i] = 1 summ_entry[sum_id_j] = 0", "for sid in summ_ids: entry['sys_summ' + repr(sid)] = [s['scores'][prompt] for s in scores_list", "pref = [0.5, 0.5] # sort the ids so that we get a", "will be. lower values are more sharp ax.violinplot(data_to_plot, showmeans=True, showmedians=True, bw_method=0.2) ax.scatter(true_scores_all +", "# without majority preferences # train_pairs = build_pairs(train) # dev_pairs = build_pairs(dev) #", "(math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p) rho =", "# print(target_variables) if 'gpu' in device: target_variables = target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss", "dev, test, all = parse_split_data(sorted_scores, train_percent, dev_percent) train, dev, test, all = parse_split_data_balanced(sorted_scores,", "# dev_pairs = build_pairs_majority_preferences(dev, sorted_scores) # test_pairs = build_pairs_majority_preferences(test, sorted_scores) # with majority", "= np.argmax(pcc_list) best_result = pcc_list[idx] print('\\n======Best results come from epoch no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx])", "# train_pairs = build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores) # dev_pairs = build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores) #", "print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec + summ_vec) # print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all +=", "= False with open(file_name, 'a', newline='') as csv_file: writer = csv.writer(csv_file) # if", "pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) else: # include the pref in the reverse", "+ '_onTrain.pdf')) test_rewarder(all_vec_dic, dev, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onDev.pdf')) print('Its performance on", "# mapping from summary text to last summary id with that text. that's", "= entry else: test[article_id] = entry topic_count += 1 print(\"topics in parse_split_data\", topic_count)", "entry = entries[article_id] summ_ids = list(entry.keys()) # really iterate over all pairs. there", "pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue topic_count += 1 summ_count = summ_count + len(summ_ids)", "summ_count) # print(pair_list) return pair_list def build_human_pair_scores(pair_list): human_pair_scores = {} for entry in", "default=3e-4) ap.add_argument('-mt', '--model_type', type=str, help='deep/linear', default='linear') ap.add_argument('-dv', '--device', type=str, help='cpu/gpu', default='gpu') ap.add_argument('-se', '--seed',", "optimiser, device) else: loss = deep_pair_train(vec_batch, target_batch, deep_model, optimiser, device) loss_list.append(loss) return np.mean(loss_list)", "'dev_pairs', 'test_pairs', 'epoch_num', 'loss_train', 'loss_dev', 'loss_test', 'rho_train', 'rho_p_train', 'pcc_train', 'pcc_p_train', 'tau_train', 'tau_p_train', 'rho_train_global',", "pref = [0, 1] else: pref = [0.5, 0.5] # if entry[unique_summ_id_pair[0]] >", "if a new csv_file is generated, write column names if csv_exists is False:", "else: summ_entry[sum_id_i] = 0 summ_entry[sum_id_j] = 1 human_pair_scores[article_id] = summ_entry return human_pair_scores #", "s=3, alpha=0.5) ax.set_title('Comparison and distributions of true values to predicted score') ax.set_xlabel('true scores')", "list(entry.keys()) if len(summ_ids) < 2: continue concat_vecs = [] true_scores = [] for", "print(\"==Test==\") # results_test = test_rewarder(all_vec_dic, test, deep_model, device) results_test = test_rewarder(all_vec_dic, test_anno, deep_model,", "ids unique_summ_id_pair = [summ2id[text_i], summ2id[text_j]] # some debug output # noinspection PyUnreachableCode if", "performance of the randomly initialized model (sanity check and baseline) loss_train = pair_train_rewarder(all_vec_dic,", "be set to False def build_pairs_majority_preferences(entries, sorted_scores, target_type='graded', ignore_ties=False, randomize_pref_order=False, double_prefs=False): pair_list =", "train_percent, dev_percent) train, dev, test, all = parse_split_data_balanced(sorted_scores, train_percent, dev_percent) # without majority", "= softmax_layer(value_variables) # print(pred) # print(np.array(target).shape, np.array(target).reshape(-1, 2, 1).shape) target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2,", "data percentage is {}! Make sure the sum is below 1.0!'.format( train_percent +", "'rho_train', 'rho_p_train', 'pcc_train', 'pcc_p_train', 'tau_train', 'tau_p_train', 'rho_train_global', 'pcc_train_global', 'tau_train_global', 'rho_dev', 'rho_p_dev', 'pcc_dev', 'pcc_p_dev',", "return deep_model def deep_pair_train(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float())", "import argparse import random import copy from tqdm import tqdm import pickle from", "learn_rate, model_type, device, seed, file_name = parse_args( argv[1:]) print('\\n=====Arguments====') print('epoch num {}'.format(epoch_num)) print('batch", "dev[article_id] = entry else: test[article_id] = entry topic_count += 1 print(\"topics in parse_split_data\",", "print(pair_list) return pair_list def build_human_pair_scores(pair_list): human_pair_scores = {} for entry in pair_list: article_id", "anno_count += len(summ_ids) summ_count += len(summ2id) print(\"topics\", topic_count) print(\"annotations\", anno_count) print(\"summ\", summ_count) print(\"summ", "def deep_pair_train_loss_only(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input)", "list(entry.keys()) # really iterate over all pairs. there was an error here before", "= str(entry[0]) sum_id_i = str(entry[1]) sum_id_j = str(entry[2]) pref = entry[3] summ_entry =", "model_type, epoch_num ) test_results = test_rewarder(all_vec_dic, test, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTest.pdf'))", "train_ids = article_ids[0:int(train_percent * num_articles)] dev_ids = article_ids[int(train_percent * num_articles):int((train_percent + dev_percent) *", "csv_row = [seed, learn_rate, model_type, len(train_pairs), len(dev_pairs), len(test_pairs), ii, loss_train, loss_dev, loss_test] print('-->", "np.array(pref) # transform to target for unique_summ_id_pair, pref in article_prefs.items(): # depending on", "read_articles, \\ read_processed_scores, read_scores from scipy.stats import spearmanr, pearsonr, kendalltau import math from", "pref)) continue elif pair['summ_id_j'] == int(entry_keys[i][8]) and pair['summ_id_i'] == int(entry_keys[j][8]): if pair['pref'] ==", "full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print( \" \\\"%s...\\\" vs. \\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort()", "for training', default=.64) ap.add_argument('-dp', '--dev_percent', type=float, help='how many data used for dev', default=.16)", "{} all = {} topic_count = 0 for article_id, scores_list in tqdm(sorted_scores.items()): entry", "s1_vec = list(vecs[aid][sid1]) s2_vec = list(vecs[aid][sid2]) pair_vec_list.append([article_vec + s1_vec, article_vec + s2_vec]) return", "batch with [] causing an exception vec_batch = vec_pairs[pointer * batch_size:(pointer + 1)", "function learns f(s0,s1)=pref. in our case, we learn f(s0)=pref[0] and f(s1)=pref[1], so this", "# convert to tuple, otherwise its not hashable for the dict unique_summ_id_pair =", "batch_size, device) else: # from epoch 1 on, receive the data and learn", "entry elif article_id in dev_ids: dev[article_id] = entry else: test[article_id] = entry topic_count", "from summary text to last summary id with that text. that's the one", "repr(sid)] = [s['scores'][prompt] for s in scores_list if s['summ_id'] == sid][ 0] #", "sorted_scores = read_sorted_scores() # read pair anno scores pair_anno_scores = read_pair_anno_scores() # train,", "[] weights_list = [] for ii in range(epoch_num + 1): print('\\n=====EPOCH {}====='.format(ii)) if", "topic_count) print(\"summ\", summ_count) return pair_list def build_anno_pairs(entries, pair_anno_scores): pair_list = [] topic_count =", "containing summ_ids and matching text # for key, value in entries_text[article_id].items(): # get", "None: fig, ax = plt.subplots() # true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all) unique = np.sort(np.unique(true_scores_all)) data_to_plot", "torch from torch.autograd import Variable import numpy as np import os from os", "(sys_summ0,sys_summ1) and (sys_summ1,sys_summ0) are the same if unique_summ_id_pair[1] < unique_summ_id_pair[0]: unique_summ_id_pair = unique_summ_id_pair[::-1]", "in entries_text[article_id].items(): # get text for current summaries i and j # if", "key == summ_ids[j]: # text_j = value text_i = entries_text[article_id][summ_ids[i]] text_j = entries_text[article_id][summ_ids[j]]", "else: loss = deep_pair_train(vec_batch, target_batch, deep_model, optimiser, device) loss_list.append(loss) return np.mean(loss_list) def test_rewarder(vec_list,", "s2_vec = list(vecs[aid][sid2]) pair_vec_list.append([article_vec + s1_vec, article_vec + s2_vec]) return pair_vec_list def pair_train_rewarder(vec_dic,", "unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) else: # include the pref in", "pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) else: # include the pref in the reverse order", "# print(pred) # print(np.array(target).shape, np.array(target).reshape(-1, 2, 1).shape) target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1) #", "to last summary id with that text. that's the one we will use", "input.to('cuda') model.eval() with torch.no_grad(): # print(true_scores) # print(np.array(true_scores).shape) # print(input) # print(input.shape) #", "pair in pair_anno_scores[article_id]: if pair['summ_id_i'] == int(entry_keys[i][8]) and pair['summ_id_j'] == int(entry_keys[j][8]): if pair['pref']", "return pair_list def build_pair_vecs(vecs, pairs): pair_vec_list = [] for aid, sid1, sid2, _", "[], 'tau': [], 'tau_p': [], 'rho_global': [], 'pcc_global': [], 'tau_global': []} true_scores_all =", "percent {}'.format(dev_percent)) print('learn rate {}'.format(learn_rate)) print('model type {}'.format(model_type)) print('device {}'.format(device)) print('seed {}'.format(seed)) print('file", "also lead to i,j=x,0 never be chosen the situation i=j is solved otherwise", "batch_size) + 1): # there was a bug here. when len(pairs) was a", "summ_ids[i], summ_ids[j], pref)) continue else: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref))", "can be done more efficiently, but who cares... rand = random.random() all[article_id] =", "article_id = str(entry[0]) sum_id_i = str(entry[1]) sum_id_j = str(entry[2]) pref = entry[3] summ_entry", "[0, 1] # else: # # todo we could completely ignore ties. doesnt", "# read bert vectors with open('data/doc_summ_bert_vectors.pkl', 'rb') as ff: all_vec_dic = pickle.load(ff) pcc_list", "True, batch_size, device) loss_test = pair_train_rewarder(all_vec_dic, test_pairs, deep_model, optimiser, True, batch_size, device) csv_row", "% plot_file) plt.savefig(plot_file) return results def parse_args(argv): ap = argparse.ArgumentParser(\"arguments for summary sampler\")", "in range(epoch_num + 1): print('\\n=====EPOCH {}====='.format(ii)) if ii == 0: # do not", "ee in target_batch] if loss_only: loss = deep_pair_train_loss_only(vec_batch, target_batch, deep_model, optimiser, device) else:", "and f(s1)=pref[1], so this should be set to False def build_pairs_majority_preferences(entries, sorted_scores, target_type='graded',", "that can be done more efficiently, but who cares... rand = random.random() all[article_id]", "might be necessary if there is a bias in the distribution of the", "parse_split_data(sorted_scores, train_percent, dev_percent) train, dev, test, all = parse_split_data_balanced(sorted_scores, train_percent, dev_percent) # without", "the distribution curve will be. lower values are more sharp ax.violinplot(data_to_plot, showmeans=True, showmedians=True,", "if rand < train_percent: train[article_id] = entry elif rand < train_percent + dev_percent:", "Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu' in device: input = input.to('cuda') model.eval() with torch.no_grad(): # print(true_scores)", "unique_summ_id_pair[::-1] pref = pref[::-1] # convert to tuple, otherwise its not hashable for", "+ 1): # there was a bug here. when len(pairs) was a vielfaches", "768 if you use bert-base deep_model, optimiser = build_model(model_type, BERT_VEC_LENGTH * 2, learn_rate)", "deep_pair_train(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if", "i,j=x,0 never be chosen the situation i=j is solved otherwise for i in", "if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0] elif entry[summ_ids[i]] < entry[summ_ids[j]]: pref", "# print(pair_list) topic_count += 1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\",", "test_rewarder(all_vec_dic, test, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTest.pdf')) test_rewarder(all_vec_dic, train, deep_model, device, os.path.join(OUTPUTS_DIR,", "np.array([0, 0])) + np.array(pref) # transform to target for unique_summ_id_pair, pref in article_prefs.items():", "[] shuffled_pairs = pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs = build_pair_vecs(vec_dic, shuffled_pairs) # print('total number of", "test_anno = build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs), len(test_pairs)) # read bert vectors with open('data/doc_summ_bert_vectors.pkl', 'rb')", "f(s1)=pref[1], so this should be set to False def build_pairs_majority_preferences(entries, sorted_scores, target_type='graded', ignore_ties=False,", "from epoch no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type, train_percent, seed, learn_rate,", "'--train_type', type=str, help='pairwise or regression', default='pairwise') ap.add_argument('-tp', '--train_percent', type=float, help='how many data used", "results['tau_global'].append(tau) if plot_file is not None: fig, ax = plt.subplots() # true_scores_all=np.array(true_scores_all) #", "csv_file: writer = csv.writer(csv_file) # if a new csv_file is generated, write column", "test_rewarder(all_vec_dic, train, deep_model, device) results_train = test_rewarder(all_vec_dic, train_anno, deep_model, device) for metric in", "= Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu' in device: input = input.to('cuda') model.eval() with torch.no_grad(): #", "percentage plus dev data percentage is {}! Make sure the sum is below", "do not train in epoch 0, just evaluate the performance of the randomly", "import math from torchvision import models from resources import MODEL_WEIGHT_DIR from resources import", "= 0 summ_count = 0 for article_id in entries: entry = entries[article_id] summ_ids", "all def parse_split_data_balanced(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev = {} test", "== 0: # do not train in epoch 0, just evaluate the performance", "os.path.join(OUTPUTS_DIR, output_pattern + '_onDev.pdf')) print('Its performance on the test set is:') for metric", "one direction and once in the other direction if double_prefs: pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0],", "learn_rate, model_type, epoch_num ) test_results = test_rewarder(all_vec_dic, test, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern +", "loss_list.append(loss) return np.mean(loss_list) def test_rewarder(vec_list, human_scores, model, device, plot_file=None): results = {'rho': [],", "test_pairs = build_anno_pairs(test, pair_anno_scores) # with majority preferences # train_pairs = build_pairs_majority_preferences(train, sorted_scores)", "is below 1.0!'.format( train_percent + dev_percent)) exit(1) BERT_VEC_LENGTH = 1024 # change this", "print(pred) # print(np.array(target).shape, np.array(target).reshape(-1, 2, 1).shape) target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1) # print(target_variables)", "= value text_i = entries_text[article_id][summ_ids[i]] text_j = entries_text[article_id][summ_ids[j]] # check if text is", "# test_pairs = build_pairs(test) # without majority preferences but with pair anno train_pairs", "print(\"violin plot written to: %s\" % plot_file) plt.savefig(plot_file) return results def parse_args(argv): ap", "bw_methods determines how soft the distribution curve will be. lower values are more", "* batch_size] target_batch = shuffled_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch =", "deep_model, device) for metric in results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") # results =", "# run through dictionary containing summ_ids and matching text # for key, value", "a new csv_file is generated, write column names if csv_exists is False: writer.writerow(csv_column_names)", "pref[0] > pref[1]: pref = [1, 0] elif pref[0] < pref[1]: pref =", "train_percent, learn_rate, model_type ) torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest model weight saved to: {}'.format(os.path.join(MODEL_WEIGHT_DIR,", "# pref = [1, 0] # elif entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref =", "pref[::-1] # convert to tuple, otherwise its not hashable for the dict unique_summ_id_pair", "open(file_name, 'a', newline='') as csv_file: writer = csv.writer(csv_file) # if a new csv_file", "yes skip if i == j or text_i == text_j: # print(\"DUPLICATE FOUND:", "len(train_pairs), len(dev_pairs), len(test_pairs), ii, loss_train, loss_dev, loss_test] print('--> losses (train,dev,test)', loss_train, loss_dev, loss_test)", "pair_train_rewarder(vec_dic, pairs, deep_model, optimiser, loss_only, batch_size=32, device='cpu'): loss_list = [] shuffled_pairs = pairs[:]", "= list(vec_list[article_id]['article']) summ_vec = list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec + summ_vec) #", "np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) # Test-Data only print(\"==Test==\") # results_test = test_rewarder(all_vec_dic, test, deep_model, device)", "entries_text[article_id] = temp_entry for article_id in entries: entry = entries[article_id] summ_ids = list(entry.keys())", "the same if unique_summ_id_pair[1] < unique_summ_id_pair[0]: unique_summ_id_pair = unique_summ_id_pair[::-1] pref = pref[::-1] #", "majority preferences # train_pairs = build_pairs_majority_preferences(train, sorted_scores) # dev_pairs = build_pairs_majority_preferences(dev, sorted_scores) #", "otherwise for i in range(len(summ_ids)): for j in range(len(summ_ids)): # run through dictionary", "[] causing an exception vec_batch = vec_pairs[pointer * batch_size:(pointer + 1) * batch_size]", "true_scores = [] for i in range(len(summ_ids)): article_vec = list(vec_list[article_id]['article']) summ_vec = list(vec_list[article_id][summ_ids[i]])", "scores and vectors for summaries/docs, and split the train/dev/test set sorted_scores = read_sorted_scores()", "spearmanr, pearsonr, kendalltau import math from torchvision import models from resources import MODEL_WEIGHT_DIR", "= shuffled_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch = [ee[-1] for ee", "print('\\n=====Arguments====') print('epoch num {}'.format(epoch_num)) print('batch size {}'.format(batch_size)) print('train type {}'.format(train_type)) print('train percent {}'.format(train_percent))", "is generated, write column names if csv_exists is False: writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed)", "tau_p = kendalltau(true_scores, pred_scores) if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p)", "pairs): pair_vec_list = [] for aid, sid1, sid2, _ in pairs: article_vec =", "'tau_p': [], 'rho_global': [], 'pcc_global': [], 'tau_global': []} true_scores_all = [] pred_scores_all =", "numpy as np import os from os import path import argparse import random", "is a tie and you want to ignore ties if pref[0] != 0.5", "path.exists(file_name): csv_exists = True else: csv_exists = False with open(file_name, 'a', newline='') as", "in device: input = input.to('cuda') model.eval() with torch.no_grad(): # print(true_scores) # print(np.array(true_scores).shape) #", "def main(argv): epoch_num, batch_size, train_type, train_percent, dev_percent, learn_rate, model_type, device, seed, file_name =", "+ dev_percent) * num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id, scores_list in tqdm(sorted_scores.items()): entry =", "1 else: if sum_id_j in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] + 1 else: human_pair_scores[article_id][sum_id_j] = 1", "csv_file is generated, write column names if csv_exists is False: writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed)", "test[article_id] = entry topic_count += 1 print(\"topics in parse_split_data\", topic_count) return train, dev,", "print('model type {}'.format(model_type)) print('device {}'.format(device)) print('seed {}'.format(seed)) print('file name {}'.format(file_name)) print('=====Arguments====\\n') csv_column_names =", "build_anno_pairs(train, pair_anno_scores) dev_pairs = build_anno_pairs(dev, pair_anno_scores) test_pairs = build_anno_pairs(test, pair_anno_scores) # with majority", "in pair_list: article_id = str(entry[0]) sum_id_i = str(entry[1]) sum_id_j = str(entry[2]) pref =", "for article_id, scores_list in tqdm(sorted_scores.items()): temp_entry = {} summ_ids = [s['summ_id'] for s", "from matplotlib import pyplot as plt import csv def parse_split_data(sorted_scores, train_percent, dev_percent, prompt='structure'):", "in dictionary entries_text[article_id] = temp_entry for article_id in entries: entry = entries[article_id] summ_ids", "tau, tau_p = kendalltau(true_scores, pred_scores) if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho'].append(rho)", "up the pref to the total pref vector of the specific summary pair.", "print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num, batch_size, train_type, train_percent,", "print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx = np.argmax(pcc_list) best_result = pcc_list[idx] print('\\n======Best", "article_ids[0:int(train_percent * num_articles)] dev_ids = article_ids[int(train_percent * num_articles):int((train_percent + dev_percent) * num_articles)] #", "score') ax.set_xlabel('true scores') ax.set_ylabel('predicted scores') xticklabels = true_scores_all ax.set_xticks(true_scores_all) print(\"violin plot written to:", "deep_model, optimiser, False, batch_size, device) loss_dev = pair_train_rewarder(all_vec_dic, dev_pairs, deep_model, optimiser, True, batch_size,", "or math.isnan(pcc) or math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau) if plot_file is not None: fig,", "human_pair_scores[article_id] = summ_entry return human_pair_scores # randomize_pref_order and double_prefs are only relevant if", "1) / batch_size) + 1): # there was a bug here. when len(pairs)", "deep_model, device) for metric in results: print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) # Test-Data only print(\"==Test==\")", "+= 1 print(\"topics in parse_split_data\", topic_count) return train, dev, test, all def parse_split_data_balanced(sorted_scores,", "text_i = value # elif key == summ_ids[j]: # text_j = value text_i", "0 summ_count = 0 for article_id in entries: entry = entries[article_id] summ_ids =", "# if key == summ_ids[i]: # text_i = value # elif key ==", "0 article_ids = list(sorted_scores.keys()) random.shuffle(article_ids) num_articles = len(article_ids) train_ids = article_ids[0:int(train_percent * num_articles)]", "= test_rewarder(all_vec_dic, dev, deep_model, device) results = test_rewarder(all_vec_dic, dev_anno, deep_model, device) for metric", "and pair['summ_id_i'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref = [0, 1] pair_list.append((article_id,", "+ np.random.normal(0, 0.1, pred_scores_all.shape[0]), pred_scores_all, marker=\".\", s=3, alpha=0.5) ax.set_title('Comparison and distributions of true", "pref = [0.5, 0.5] # skip if it is a tie and you", "{}'.format(epoch_num)) print('batch size {}'.format(batch_size)) print('train type {}'.format(train_type)) print('train percent {}'.format(train_percent)) print('dev percent {}'.format(dev_percent))", "unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) else: # include the pref in the", "be done more efficiently, but who cares... rand = random.random() all[article_id] = entry", "generated, write column names if csv_exists is False: writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed)", "i in range(len(summ_ids)): article_vec = list(vec_list[article_id]['article']) summ_vec = list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape)", "is still the loss before fed with the training examples loss_train = pair_train_rewarder(all_vec_dic,", "= entry elif article_id in dev_ids: dev[article_id] = entry else: test[article_id] = entry", "concat_vecs = [] true_scores = [] for i in range(len(summ_ids)): article_vec = list(vec_list[article_id]['article'])", "for ii in range(epoch_num + 1): print('\\n=====EPOCH {}====='.format(ii)) if ii == 0: #", "only print(\"==Test==\") # results_test = test_rewarder(all_vec_dic, test, deep_model, device) results_test = test_rewarder(all_vec_dic, test_anno,", "topic_count += 1 print(\"topics in parse_split_data\", topic_count) return train, dev, test, all def", "< 2: continue concat_vecs = [] true_scores = [] for i in range(len(summ_ids)):", "= [] for i in range(len(summ_ids)): article_vec = list(vec_list[article_id]['article']) summ_vec = list(vec_list[article_id][summ_ids[i]]) #", "results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") # results = test_rewarder(all_vec_dic, dev, deep_model, device) results", "== [1, 0]: if sum_id_i in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] + 1 else: human_pair_scores[article_id][sum_id_i] =", "who cares... rand = random.random() all[article_id] = entry if rand < train_percent: train[article_id]", "pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j],", "test_rewarder(all_vec_dic, dev, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onDev.pdf')) print('Its performance on the test", "str(entry[1]) sum_id_j = str(entry[2]) pref = entry[3] summ_entry = {} if article_id in", "the training examples loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, False, batch_size, device) loss_dev", "'gpu' in device: deep_model.to('cuda') torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # read human", "import pickle from scorer.data_helper.json_reader import read_sorted_scores, read_pair_anno_scores, read_articles, \\ read_processed_scores, read_scores from scipy.stats", "False: print(\"%s vs. %s (IDs %s vs. %s)\" % ( summ_ids[i], summ_ids[j], unique_summ_id_pair[0],", "ff: all_vec_dic = pickle.load(ff) pcc_list = [] weights_list = [] for ii in", "last summary id with that text. that's the one we will use summ2id", "the loss is still the loss before fed with the training examples loss_train", "only print(\"==Train==\") # results_train = test_rewarder(all_vec_dic, train, deep_model, device) results_train = test_rewarder(all_vec_dic, train_anno,", "[0.5, 0.5] # if entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [1, 0] #", "cares... # rand = random.random() all[article_id] = entry if article_id in train_ids: train[article_id]", "target_type == 'binary': if pref[0] > pref[1]: pref = [1, 0] elif pref[0]", "in range(len(summ_ids)): for j in range(len(summ_ids)): # run through dictionary containing summ_ids and", "summ_ids = list(entry.keys()) # really iterate over all pairs. there was an error", "range(len(summ_ids)): if i == j: continue # get keys from dictionary entry_keys =", "unique_summ_id_pair[1], pref)) topic_count += 1 anno_count += len(summ_ids) summ_count += len(summ2id) print(\"topics\", topic_count)", "sorted_scores, pair_anno_scores) # build human pair scores for pairs train_anno = build_human_pair_scores(train_pairs) dev_anno", "pairs. there was an error here before since j started from 1, to", "include the pref in the reverse order by chance. this might be necessary", "= read_pair_anno_scores() # train, dev, test, all = parse_split_data(sorted_scores, train_percent, dev_percent) train, dev,", "1: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref =", "= [1, 0] elif entry[summ_ids[i]] < entry[summ_ids[j]]: pref = [0, 1] else: pref", "[1, 0] elif pref[0] < pref[1]: pref = [1, 0] else: pref =", "main(argv): epoch_num, batch_size, train_type, train_percent, dev_percent, learn_rate, model_type, device, seed, file_name = parse_args(", "resources import OUTPUTS_DIR from matplotlib import pyplot as plt import csv def parse_split_data(sorted_scores,", "# test_pairs = build_pairs_majority_preferences(test, sorted_scores) # with majority preferences and pair anno #", "= pearsonr(true_scores_all, pred_scores_all)[0] tau = kendalltau(true_scores_all, pred_scores_all)[0] if not (math.isnan(rho) or math.isnan(pcc) or", "of 32, then there was a last batch with [] causing an exception", "os from os import path import argparse import random import copy from tqdm", "this to 768 if you use bert-base deep_model, optimiser = build_model(model_type, BERT_VEC_LENGTH *", "BERT_VEC_LENGTH * 2, learn_rate) if 'gpu' in device: deep_model.to('cuda') torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark", "sid][ 0] # that can be done more efficiently, but who cares... #", "and bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) else: pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) topic_count +=", "summ_entry[sum_id_i] = 0 summ_entry[sum_id_j] = 1 human_pair_scores[article_id] = summ_entry return human_pair_scores # randomize_pref_order", "or graded one pref = (pref / (pref[0] + pref[1])).tolist() if target_type ==", "unique_summ_id_pair[0], pref[::-1])) else: pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) topic_count += 1 anno_count += len(summ_ids)", "= entry topic_count += 1 print(\"topics in parse_split_data\", topic_count) return train, dev, test,", "loss_fn(pred, target_variables) # print(loss) return loss.cpu().item() def build_pairs(entries): pair_list = [] topic_count =", "summary pair. create a new entry if not existing article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair, np.array([0,", "alpha=0.5) ax.set_title('Comparison and distributions of true values to predicted score') ax.set_xlabel('true scores') ax.set_ylabel('predicted", "summary text and matching id for article_id, scores_list in tqdm(sorted_scores.items()): temp_entry = {}", "< train_percent: train[article_id] = entry elif rand < train_percent + dev_percent: dev[article_id] =", "pref in article_prefs.items(): # depending on the mode, use binary target, or graded", "loss before fed with the training examples loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser,", "ax.scatter(true_scores_all + np.random.normal(0, 0.1, pred_scores_all.shape[0]), pred_scores_all, marker=\".\", s=3, alpha=0.5) ax.set_title('Comparison and distributions of", "in summ_ids: entry['sys_summ' + repr(sid)] = [s['scores'][prompt] for s in scores_list if s['summ_id']", "but who cares... rand = random.random() all[article_id] = entry if rand < train_percent:", "summ_ids[i]: # text_i = value # elif key == summ_ids[j]: # text_j =", "'tau_global': []} true_scores_all = [] pred_scores_all = np.array([]) # print(human_scores) # pred_scores_all =", "all = {} topic_count = 0 article_ids = list(sorted_scores.keys()) random.shuffle(article_ids) num_articles = len(article_ids)", "print(np.array(target).shape, np.array(target).reshape(-1, 2, 1).shape) target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1) # print(target_variables) if 'gpu'", "return train, dev, test, all def build_model(model_type, vec_length, learn_rate=None): if 'linear' in model_type:", "< train_percent + dev_percent: dev[article_id] = entry else: test[article_id] = entry topic_count +=", "test_pairs, deep_model, optimiser, True, batch_size, device) csv_row = [seed, learn_rate, model_type, len(train_pairs), len(dev_pairs),", "# print('total number of pairs built: {}'.format(len(vec_pairs))) for pointer in range(int((len( pairs) -", "other direction if double_prefs: pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) else:", "without majority preferences but with pair anno train_pairs = build_anno_pairs(train, pair_anno_scores) dev_pairs =", "built: {}'.format(len(vec_pairs))) for pointer in range(int((len( pairs) - 1) / batch_size) + 1):", "args.train_type, args.train_percent, args.dev_percent, args.learn_rate, args.model_type, args.device, args.seed, args.file_name def main(argv): epoch_num, batch_size, train_type,", "the pref in the reverse order by chance. this might be necessary if", "anno # train_pairs = build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores) # dev_pairs = build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores)", "# results = test_rewarder(all_vec_dic, dev, deep_model, device) results = test_rewarder(all_vec_dic, dev_anno, deep_model, device)", "type=int, default=50) ap.add_argument('-b', '--batch_size', type=int, default=32) ap.add_argument('-tt', '--train_type', type=str, help='pairwise or regression', default='pairwise')", "since j started from 1, to prevent i,j=0,0. but this also lead to", "train_type, train_percent, seed, learn_rate, model_type, epoch_num ) test_results = test_rewarder(all_vec_dic, test, deep_model, device,", "num {}'.format(epoch_num)) print('batch size {}'.format(batch_size)) print('train type {}'.format(train_type)) print('train percent {}'.format(train_percent)) print('dev percent", "be. lower values are more sharp ax.violinplot(data_to_plot, showmeans=True, showmedians=True, bw_method=0.2) ax.scatter(true_scores_all + np.random.normal(0,", "in scores_list] for sid in summ_ids: # get summary text s_text = [s['sys_summ']", "device) for metric in results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") # results = test_rewarder(all_vec_dic,", "tuple, otherwise its not hashable for the dict unique_summ_id_pair = tuple(unique_summ_id_pair) # add", "sum_id_i in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] + 1 else: human_pair_scores[article_id][sum_id_i] = 1 else: if sum_id_j", "if entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [1, 0] # elif entry[unique_summ_id_pair[0]] >", "1 else: human_pair_scores[article_id][sum_id_i] = 1 else: if sum_id_j in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] + 1", "default='linear') ap.add_argument('-dv', '--device', type=str, help='cpu/gpu', default='gpu') ap.add_argument('-se', '--seed', type=int, help='random seed number', default='1')", "= [] shuffled_pairs = pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs = build_pair_vecs(vec_dic, shuffled_pairs) # print('total number", "optimiser, True, batch_size, device) else: # from epoch 1 on, receive the data", "summ_ids: entry['sys_summ' + repr(sid)] = [s['scores'][prompt] for s in scores_list if s['summ_id'] ==", "% ( summ_ids[i], summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry = sorted_scores[article_id] print(\" system %s with", "all = {} topic_count = 0 for article_id, scores_list in tqdm(sorted_scores.items()): entry =", "the loss before fed with the training examples loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model,", "results: print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) # Test-Data only print(\"==Test==\") # results_test = test_rewarder(all_vec_dic, test,", "if path.exists(file_name): csv_exists = True else: csv_exists = False with open(file_name, 'a', newline='')", "plus dev data percentage is {}! Make sure the sum is below 1.0!'.format(", "randomly initialized model (sanity check and baseline) loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser,", "input = Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu' in device: input = input.to('cuda') model.eval() with torch.no_grad():", "plt.subplots() # true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all) unique = np.sort(np.unique(true_scores_all)) data_to_plot = [pred_scores_all[true_score == true_scores_all]", "article_id in train_ids: train[article_id] = entry elif article_id in dev_ids: dev[article_id] = entry", "= pref[::-1] # convert to tuple, otherwise its not hashable for the dict", "pref = [1, 0] elif pref[0] < pref[1]: pref = [1, 0] else:", "np.array(target).reshape(-1, 2, 1).shape) target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1) # print(target_variables) if 'gpu' in", "= torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) return loss.cpu().item() def build_pairs(entries): pair_list", "of the score, e.g. if they are ordered if randomize_pref_order and bool(random.getrandbits(1)): pair_list.append((article_id,", "learn_rate, model_type ) torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest model weight saved to: {}'.format(os.path.join(MODEL_WEIGHT_DIR, model_weight_name)))", "== int(entry_keys[j][8]): if pair['pref'] == 1: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j],", "- 1) / batch_size) + 1): # there was a bug here. when", "deep_model, device) for metric in results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx", "< entry[summ_ids[j]]: pref = [0, 1] else: pref = [0.5, 0.5] pair_list.append((article_id, summ_ids[i],", "test_rewarder(vec_list, human_scores, model, device, plot_file=None): results = {'rho': [], 'rho_p': [], 'pcc': [],", "ties if pref[0] != 0.5 or not ignore_ties: # include the pref two", "parse_split_data_balanced(sorted_scores, train_percent, dev_percent) # without majority preferences # train_pairs = build_pairs(train) # dev_pairs", "= [0.5, 0.5] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) # print(pair_list) topic_count += 1 summ_count", "rate', default=3e-4) ap.add_argument('-mt', '--model_type', type=str, help='deep/linear', default='linear') ap.add_argument('-dv', '--device', type=str, help='cpu/gpu', default='gpu') ap.add_argument('-se',", "who cares... # rand = random.random() all[article_id] = entry if article_id in train_ids:", "pref = entry[3] summ_entry = {} if article_id in human_pair_scores: if pref ==", "put here the prefs for this article article_prefs = {} # still run", "target_variables = target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) return", "more efficiently, but who cares... # rand = random.random() all[article_id] = entry if", "MODEL_WEIGHT_DIR from resources import OUTPUTS_DIR from matplotlib import pyplot as plt import csv", "range(len(summ_ids)): for j in range(len(summ_ids)): if i == j: continue if entry[summ_ids[i]] >", "score %s (%s)\" % ( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print( \" \\\"%s...\\\" vs. \\\"%s...\\\"\"", "idx = np.argmax(pcc_list) best_result = pcc_list[idx] print('\\n======Best results come from epoch no. {}====='.format(idx))", "summ_ids = [s['summ_id'] for s in scores_list] for sid in summ_ids: entry['sys_summ' +", "and matching text # for key, value in entries_text[article_id].items(): # get text for", "if pair['pref'] == 1: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue", "summ_count) return pair_list def build_anno_pairs(entries, pair_anno_scores): pair_list = [] topic_count = 0 summ_count", "if unique_summ_id_pair[1] < unique_summ_id_pair[0]: unique_summ_id_pair = unique_summ_id_pair[::-1] pref = pref[::-1] # convert to", "test, deep_model, device) results_test = test_rewarder(all_vec_dic, test_anno, deep_model, device) for metric in results_test:", "build_pair_vecs(vecs, pairs): pair_vec_list = [] for aid, sid1, sid2, _ in pairs: article_vec", "torchvision import models from resources import MODEL_WEIGHT_DIR from resources import OUTPUTS_DIR from matplotlib", "= loss_fn(pred, target_variables) # print(loss) return loss.cpu().item() def build_pairs(entries): pair_list = [] topic_count", "same if unique_summ_id_pair[1] < unique_summ_id_pair[0]: unique_summ_id_pair = unique_summ_id_pair[::-1] pref = pref[::-1] # convert", "metric in results: print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) # Test-Data only print(\"==Test==\") # results_test =", "argv[1:]) print('\\n=====Arguments====') print('epoch num {}'.format(epoch_num)) print('batch size {}'.format(batch_size)) print('train type {}'.format(train_type)) print('train percent", "= read_sorted_scores() # read pair anno scores pair_anno_scores = read_pair_anno_scores() # train, dev,", "# with majority preferences and pair anno # train_pairs = build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores)", "print('\\n======Best results come from epoch no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type,", "entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [0, 1] # else: # # todo", "seed, file_name = parse_args( argv[1:]) print('\\n=====Arguments====') print('epoch num {}'.format(epoch_num)) print('batch size {}'.format(batch_size)) print('train", "for summary sampler\") ap.add_argument('-e', '--epoch_num', type=int, default=50) ap.add_argument('-b', '--batch_size', type=int, default=32) ap.add_argument('-tt', '--train_type',", "sorted_scores) # test_pairs = build_pairs_majority_preferences(test, sorted_scores) # with majority preferences and pair anno", "np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed) if train_percent + dev_percent >= 1.: print('ERROR! Train data", "pref)) continue topic_count += 1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\",", "= [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref = [1, 0]", "and vectors for summaries/docs, and split the train/dev/test set sorted_scores = read_sorted_scores() #", "all[article_id] = entry if rand < train_percent: train[article_id] = entry elif rand <", "summ2id = {entries_text[article_id][summ_id]: summ_id for summ_id in summ_ids} # put here the prefs", "%s vs. %s)\" % ( summ_ids[i], summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry = sorted_scores[article_id] print(\"", "print(model(input).data.cpu().numpy().shape) pred_scores = model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all = np.concatenate((pred_scores_all, pred_scores), axis=0) # pred_scores_all +=", "in human_pair_scores: if pref == [1, 0]: if sum_id_i in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] +", "* batch_size] target_batch = [ee[-1] for ee in target_batch] if loss_only: loss =", "topic_count = 0 summ_count = 0 for article_id in entries: entry = entries[article_id]", "prefs for this article article_prefs = {} # still run through all pairs", "exit(1) BERT_VEC_LENGTH = 1024 # change this to 768 if you use bert-base", "args.train_percent, args.dev_percent, args.learn_rate, args.model_type, args.device, args.seed, args.file_name def main(argv): epoch_num, batch_size, train_type, train_percent,", "are only relevant if the learning function learns f(s0,s1)=pref. in our case, we", "relevant if the learning function learns f(s0,s1)=pref. in our case, we learn f(s0)=pref[0]", "torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length / 2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length / 2), 1), ) if learn_rate", "results = test_rewarder(all_vec_dic, dev, deep_model, device) results = test_rewarder(all_vec_dic, dev_anno, deep_model, device) for", "the other direction if double_prefs: pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref))", "scores pair_anno_scores = read_pair_anno_scores() # train, dev, test, all = parse_split_data(sorted_scores, train_percent, dev_percent)", "'loss_train', 'loss_dev', 'loss_test', 'rho_train', 'rho_p_train', 'pcc_train', 'pcc_p_train', 'tau_train', 'tau_p_train', 'rho_train_global', 'pcc_train_global', 'tau_train_global', 'rho_dev',", "= [0.5, 0.5] # if entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [1, 0]", "unique_summ_id_pair[0]: unique_summ_id_pair = unique_summ_id_pair[::-1] pref = pref[::-1] # convert to tuple, otherwise its", "xticklabels = true_scores_all ax.set_xticks(true_scores_all) print(\"violin plot written to: %s\" % plot_file) plt.savefig(plot_file) return", "'rho_dev_global', 'pcc_dev_global', 'tau_dev_global', 'rho_test', 'rho_p_test', 'pcc_test', 'pcc_p_test', 'tau_test', 'tau_p_test', 'rho_test_global', 'pcc_test_global', 'tau_test_global'] #", "%s (%s)\" % ( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print( \" \\\"%s...\\\" vs. \\\"%s...\\\"\" %", "in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] + 1 else: human_pair_scores[article_id][sum_id_i] = 1 else: if sum_id_j in", "pref = [0, 1] # else: # # todo we could completely ignore", "math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau) if plot_file is not None: fig, ax = plt.subplots()", "elif pref[0] < pref[1]: pref = [1, 0] else: pref = [0.5, 0.5]", "topic_count += 1 anno_count += len(summ_ids) summ_count += len(summ2id) print(\"topics\", topic_count) print(\"annotations\", anno_count)", "spearmanr(true_scores_all, pred_scores_all)[0] pcc = pearsonr(true_scores_all, pred_scores_all)[0] tau = kendalltau(true_scores_all, pred_scores_all)[0] if not (math.isnan(rho)", "np.random.normal(0, 0.1, pred_scores_all.shape[0]), pred_scores_all, marker=\".\", s=3, alpha=0.5) ax.set_title('Comparison and distributions of true values", "add up the pref to the total pref vector of the specific summary", "* num_articles):int((train_percent + dev_percent) * num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id, scores_list in tqdm(sorted_scores.items()):", "type=int, default=32) ap.add_argument('-tt', '--train_type', type=str, help='pairwise or regression', default='pairwise') ap.add_argument('-tp', '--train_percent', type=float, help='how", "deep_model, optimiser, True, batch_size, device) csv_row = [seed, learn_rate, model_type, len(train_pairs), len(dev_pairs), len(test_pairs),", "Variable import numpy as np import os from os import path import argparse", "== 'binary': if pref[0] > pref[1]: pref = [1, 0] elif pref[0] <", "= tuple(unique_summ_id_pair) # add up the pref to the total pref vector of", "learn_rate is not None: optimiser = torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return deep_model, optimiser else: return", "system %s with score %s (%s)\" % ( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print( \"", "= [1, 0] elif pref[0] < pref[1]: pref = [1, 0] else: pref", "pairs\", len(pair_list)) return pair_list def build_pair_vecs(vecs, pairs): pair_vec_list = [] for aid, sid1,", ">= 1.: print('ERROR! Train data percentage plus dev data percentage is {}! Make", "come from epoch no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type, train_percent, seed,", "range(len(summ_ids)): article_vec = list(vec_list[article_id]['article']) summ_vec = list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec +", "ax.set_title('Comparison and distributions of true values to predicted score') ax.set_xlabel('true scores') ax.set_ylabel('predicted scores')", "== j: continue if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0] elif entry[summ_ids[i]]", "'--train_percent', type=float, help='how many data used for training', default=.64) ap.add_argument('-dp', '--dev_percent', type=float, help='how", "and pair anno # train_pairs = build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores) # dev_pairs = build_anno_pairs_majority_preferences(dev,", "matching text # for key, value in entries_text[article_id].items(): # get text for current", "# print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec + summ_vec) # print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all", "= target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) optimiser.zero_grad() loss.backward()", "device) for metric in results: print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) # Test-Data only print(\"==Test==\") #", "[0.5, 0.5] # skip if it is a tie and you want to", "print(\"summ pairs\", len(pair_list)) return pair_list def build_pair_vecs(vecs, pairs): pair_vec_list = [] for aid,", "= 0 for article_id in entries: entry = entries[article_id] summ_ids = list(entry.keys()) #", "test, all = parse_split_data_balanced(sorted_scores, train_percent, dev_percent) # without majority preferences # train_pairs =", "randomize_pref_order and bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) else: pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) topic_count", "deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTrain.pdf')) test_rewarder(all_vec_dic, dev, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern +", "test_rewarder(all_vec_dic, dev, deep_model, device) results = test_rewarder(all_vec_dic, dev_anno, deep_model, device) for metric in", "but with pair anno train_pairs = build_anno_pairs(train, pair_anno_scores) dev_pairs = build_anno_pairs(dev, pair_anno_scores) test_pairs", "np.mean(test_results[metric]))) model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num, batch_size, train_type, train_percent, learn_rate,", "train in epoch 0, just evaluate the performance of the randomly initialized model", "name {}'.format(file_name)) print('=====Arguments====\\n') csv_column_names = ['seed', 'learn_rate', 'model_type', 'train_pairs', 'dev_pairs', 'test_pairs', 'epoch_num', 'loss_train',", "dev, test, all def build_model(model_type, vec_length, learn_rate=None): if 'linear' in model_type: deep_model =", "deep_pair_train(vec_batch, target_batch, deep_model, optimiser, device) loss_list.append(loss) return np.mean(loss_list) def test_rewarder(vec_list, human_scores, model, device,", "deep_model, optimiser = build_model(model_type, BERT_VEC_LENGTH * 2, learn_rate) if 'gpu' in device: deep_model.to('cuda')", "j\", text_i) continue # get the unique summ ids unique_summ_id_pair = [summ2id[text_i], summ2id[text_j]]", "= 0 article_ids = list(sorted_scores.keys()) random.shuffle(article_ids) num_articles = len(article_ids) train_ids = article_ids[0:int(train_percent *", "= test_rewarder(all_vec_dic, dev_anno, deep_model, device) for metric in results: print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) #", "pair_anno_scores[article_id]: if pair['summ_id_i'] == int(entry_keys[i][8]) and pair['summ_id_j'] == int(entry_keys[j][8]): if pair['pref'] == 1:", "as csv_file: writer = csv.writer(csv_file) # if a new csv_file is generated, write", "argparse import random import copy from tqdm import tqdm import pickle from scorer.data_helper.json_reader", "# save in dictionary entries_text[article_id] = temp_entry for article_id in entries: entry =", "{} test = {} all = {} topic_count = 0 article_ids = list(sorted_scores.keys())", "%s (IDs %s vs. %s)\" % ( summ_ids[i], summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry =", "deep_model, optimiser, True, batch_size, device) loss_test = pair_train_rewarder(all_vec_dic, test_pairs, deep_model, optimiser, True, batch_size,", "def test_rewarder(vec_list, human_scores, model, device, plot_file=None): results = {'rho': [], 'rho_p': [], 'pcc':", "print('seed {}'.format(seed)) print('file name {}'.format(file_name)) print('=====Arguments====\\n') csv_column_names = ['seed', 'learn_rate', 'model_type', 'train_pairs', 'dev_pairs',", "'tau': [], 'tau_p': [], 'rho_global': [], 'pcc_global': [], 'tau_global': []} true_scores_all = []", "curve will be. lower values are more sharp ax.violinplot(data_to_plot, showmeans=True, showmedians=True, bw_method=0.2) ax.scatter(true_scores_all", "= [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref = [0, 1]", "set to False def build_pairs_majority_preferences(entries, sorted_scores, target_type='graded', ignore_ties=False, randomize_pref_order=False, double_prefs=False): pair_list = []", "tqdm import pickle from scorer.data_helper.json_reader import read_sorted_scores, read_pair_anno_scores, read_articles, \\ read_processed_scores, read_scores from", "vielfaches of 32, then there was a last batch with [] causing an", "was a bug here. when len(pairs) was a vielfaches of 32, then there", "summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) return pair_list def build_anno_pairs(entries,", "csv_exists = True else: csv_exists = False with open(file_name, 'a', newline='') as csv_file:", "text is identical, if yes skip if i == j or text_i ==", "train_pairs = build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores) # dev_pairs = build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores) # test_pairs", "device: target_variables = target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss)", "else: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length / 2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length / 2), 1),", "if pref[0] > pref[1]: pref = [1, 0] elif pref[0] < pref[1]: pref", "get text for current summaries i and j # if key == summ_ids[i]:", "deep_model, device) results_train = test_rewarder(all_vec_dic, train_anno, deep_model, device) for metric in results_train: print('{}\\t{}'.format(metric,", "create a new entry if not existing article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair, np.array([0, 0])) +", "results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p) rho = spearmanr(true_scores_all, pred_scores_all)[0] pcc = pearsonr(true_scores_all,", "summ_ids[i], summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry = sorted_scores[article_id] print(\" system %s with score %s", "= [] true_scores = [] for i in range(len(summ_ids)): article_vec = list(vec_list[article_id]['article']) summ_vec", "default='1') ap.add_argument('-fn', '--file_name', type=str, help='file name for csv output', default='BetterRewardsStatistics_test.csv') args = ap.parse_args(argv)", "in pair_anno_scores[article_id]: if pair['summ_id_i'] == int(entry_keys[i][8]) and pair['summ_id_j'] == int(entry_keys[j][8]): if pair['pref'] ==", "args.dev_percent, args.learn_rate, args.model_type, args.device, args.seed, args.file_name def main(argv): epoch_num, batch_size, train_type, train_percent, dev_percent,", "random.random() all[article_id] = entry if article_id in train_ids: train[article_id] = entry elif article_id", "more efficiently, but who cares... rand = random.random() all[article_id] = entry if rand", "entries_text[article_id][summ_ids[j]] # check if text is identical, if yes skip if i ==", "e.g. if they are ordered if randomize_pref_order and bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1]))", "specific summary pair. create a new entry if not existing article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair,", "def build_human_pair_scores(pair_list): human_pair_scores = {} for entry in pair_list: article_id = str(entry[0]) sum_id_i", "TEXT i\", text_i, \"TEXT j\", text_i) continue # get the unique summ ids", "unique_summ_id_pair, pref in article_prefs.items(): # depending on the mode, use binary target, or", "= {} dev = {} test = {} all = {} topic_count =", "entry[summ_ids[j]]: pref = [1, 0] elif entry[summ_ids[i]] < entry[summ_ids[j]]: pref = [0, 1]", "[] for i in range(len(summ_ids)): article_vec = list(vec_list[article_id]['article']) summ_vec = list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape,", "i in range(len(summ_ids)): for j in range(len(summ_ids)): if i == j: continue #", "pointer in range(int((len( pairs) - 1) / batch_size) + 1): # there was", "= test_rewarder(all_vec_dic, train, deep_model, device) results_train = test_rewarder(all_vec_dic, train_anno, deep_model, device) for metric", "'--file_name', type=str, help='file name for csv output', default='BetterRewardsStatistics_test.csv') args = ap.parse_args(argv) return args.epoch_num,", "pred_scores_all)[0] if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau) if plot_file", "article_vec + s2_vec]) return pair_vec_list def pair_train_rewarder(vec_dic, pairs, deep_model, optimiser, loss_only, batch_size=32, device='cpu'):", "'tau_train_global', 'rho_dev', 'rho_p_dev', 'pcc_dev', 'pcc_p_dev', 'tau_dev', 'tau_p_dev', 'rho_dev_global', 'pcc_dev_global', 'tau_dev_global', 'rho_test', 'rho_p_test', 'pcc_test',", "device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTrain.pdf')) test_rewarder(all_vec_dic, dev, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onDev.pdf'))", "data used for training', default=.64) ap.add_argument('-dp', '--dev_percent', type=float, help='how many data used for", "plt.savefig(plot_file) return results def parse_args(argv): ap = argparse.ArgumentParser(\"arguments for summary sampler\") ap.add_argument('-e', '--epoch_num',", "in tqdm(sorted_scores.items()): entry = {} summ_ids = [s['summ_id'] for s in scores_list] for", "not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p) rho", "loss_test = pair_train_rewarder(all_vec_dic, test_pairs, deep_model, optimiser, True, batch_size, device) csv_row = [seed, learn_rate,", "print(\"topics in parse_split_data\", topic_count) return train, dev, test, all def parse_split_data_balanced(sorted_scores, train_percent, dev_percent,", "seed, epoch_num, batch_size, train_type, train_percent, learn_rate, model_type ) torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest model", "type {}'.format(model_type)) print('device {}'.format(device)) print('seed {}'.format(seed)) print('file name {}'.format(file_name)) print('=====Arguments====\\n') csv_column_names = ['seed',", "with torch.no_grad(): # print(true_scores) # print(np.array(true_scores).shape) # print(input) # print(input.shape) # print(model(input).data.cpu().numpy()) #", "= list(sorted_scores.keys()) random.shuffle(article_ids) num_articles = len(article_ids) train_ids = article_ids[0:int(train_percent * num_articles)] dev_ids =", "np.mean(loss_list) def test_rewarder(vec_list, human_scores, model, device, plot_file=None): results = {'rho': [], 'rho_p': [],", "not train in epoch 0, just evaluate the performance of the randomly initialized", "= {} test = {} all = {} topic_count = 0 for article_id,", "to prevent i,j=0,0. but this also lead to i,j=x,0 never be chosen the", "# depending on the mode, use binary target, or graded one pref =", "elif entry[summ_ids[i]] < entry[summ_ids[j]]: pref = [0, 1] else: pref = [0.5, 0.5]", "column names if csv_exists is False: writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed) if train_percent", "loss = loss_fn(pred, target_variables) # print(loss) return loss.cpu().item() def build_pairs(entries): pair_list = []", "'pcc_train_global', 'tau_train_global', 'rho_dev', 'rho_p_dev', 'pcc_dev', 'pcc_p_dev', 'tau_dev', 'tau_p_dev', 'rho_dev_global', 'pcc_dev_global', 'tau_dev_global', 'rho_test', 'rho_p_test',", "= build_pairs_majority_preferences(train, sorted_scores) # dev_pairs = build_pairs_majority_preferences(dev, sorted_scores) # test_pairs = build_pairs_majority_preferences(test, sorted_scores)", "print(\"annotations\", anno_count) print(\"summ\", summ_count) print(\"summ pairs\", len(pair_list)) return pair_list def build_pair_vecs(vecs, pairs): pair_vec_list", "[] true_scores = [] for i in range(len(summ_ids)): article_vec = list(vec_list[article_id]['article']) summ_vec =", "training', default=.64) ap.add_argument('-dp', '--dev_percent', type=float, help='how many data used for dev', default=.16) ap.add_argument('-lr',", "= build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores) # dev_pairs = build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores) # test_pairs =", "pair_anno_scores for pair in pair_anno_scores[article_id]: if pair['summ_id_i'] == int(entry_keys[i][8]) and pair['summ_id_j'] == int(entry_keys[j][8]):", "if the learning function learns f(s0,s1)=pref. in our case, we learn f(s0)=pref[0] and", "id for article_id, scores_list in tqdm(sorted_scores.items()): temp_entry = {} summ_ids = [s['summ_id'] for", "= [pred_scores_all[true_score == true_scores_all] for true_score in unique] # bw_methods determines how soft", "'loss_test', 'rho_train', 'rho_p_train', 'pcc_train', 'pcc_p_train', 'tau_train', 'tau_p_train', 'rho_train_global', 'pcc_train_global', 'tau_train_global', 'rho_dev', 'rho_p_dev', 'pcc_dev',", ") test_results = test_rewarder(all_vec_dic, test, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTest.pdf')) test_rewarder(all_vec_dic, train,", "= [0, 1] else: pref = [0.5, 0.5] # if entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]:", "int(vec_length / 2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length / 2), 1), ) if learn_rate is not", "train_type, train_percent, learn_rate, model_type ) torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest model weight saved to:", "[], 'rho_global': [], 'pcc_global': [], 'tau_global': []} true_scores_all = [] pred_scores_all = np.array([])", "loss_list = [] shuffled_pairs = pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs = build_pair_vecs(vec_dic, shuffled_pairs) # print('total", "in entries: entry = entries[article_id] summ_ids = list(entry.keys()) # mapping from summary text", "pair_list = [] topic_count = 0 anno_count = 0 summ_count = 0 entries_text", "# get pair preference from pair_anno_scores for pair in pair_anno_scores[article_id]: if pair['summ_id_i'] ==", "causing an exception vec_batch = vec_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch", "train = {} dev = {} test = {} all = {} topic_count", "article_id in human_scores: entry = human_scores[article_id] summ_ids = list(entry.keys()) if len(summ_ids) < 2:", "the distribution of the score, e.g. if they are ordered if randomize_pref_order and", "value # elif key == summ_ids[j]: # text_j = value text_i = entries_text[article_id][summ_ids[i]]", "pred_scores = model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all = np.concatenate((pred_scores_all, pred_scores), axis=0) # pred_scores_all += pred_scores.tolist()", "random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed) if train_percent + dev_percent >= 1.: print('ERROR! Train data percentage", "'rho_test_global', 'pcc_test_global', 'tau_test_global'] # check if csv_file exists if path.exists(file_name): csv_exists = True", "torch.manual_seed(seed) if train_percent + dev_percent >= 1.: print('ERROR! Train data percentage plus dev", "= 1 human_pair_scores[article_id] = summ_entry return human_pair_scores # randomize_pref_order and double_prefs are only", "read_sorted_scores() # read pair anno scores pair_anno_scores = read_pair_anno_scores() # train, dev, test,", "torch.nn.Sequential( torch.nn.Linear(vec_length, 1), ) else: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length / 2)), torch.nn.ReLU(),", "# check if text is identical, if yes skip if i == j", "entries_text[article_id][summ_ids[i]] text_j = entries_text[article_id][summ_ids[j]] # check if text is identical, if yes skip", "pred_scores) tau, tau_p = kendalltau(true_scores, pred_scores) if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)):", "elif key == summ_ids[j]: # text_j = value text_i = entries_text[article_id][summ_ids[i]] text_j =", "article_ids = list(sorted_scores.keys()) random.shuffle(article_ids) num_articles = len(article_ids) train_ids = article_ids[0:int(train_percent * num_articles)] dev_ids", "read_processed_scores, read_scores from scipy.stats import spearmanr, pearsonr, kendalltau import math from torchvision import", "# that can be done more efficiently, but who cares... # rand =", "a vielfaches of 32, then there was a last batch with [] causing", "1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) return pair_list def", "ax.violinplot(data_to_plot, showmeans=True, showmedians=True, bw_method=0.2) ax.scatter(true_scores_all + np.random.normal(0, 0.1, pred_scores_all.shape[0]), pred_scores_all, marker=\".\", s=3, alpha=0.5)", "summ_count = 0 for article_id in entries: entry = entries[article_id] summ_ids = list(entry.keys())", "Train data percentage plus dev data percentage is {}! Make sure the sum", "unique = np.sort(np.unique(true_scores_all)) data_to_plot = [pred_scores_all[true_score == true_scores_all] for true_score in unique] #", "sum_id_j in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] + 1 else: human_pair_scores[article_id][sum_id_j] = 1 else: if pref", "0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref = [0, 1] pair_list.append((article_id, summ_ids[i],", "output', default='BetterRewardsStatistics_test.csv') args = ap.parse_args(argv) return args.epoch_num, args.batch_size, args.train_type, args.train_percent, args.dev_percent, args.learn_rate, args.model_type,", "= entries_text[article_id][summ_ids[j]] # check if text is identical, if yes skip if i", "with majority preferences # train_pairs = build_pairs_majority_preferences(train, sorted_scores) # dev_pairs = build_pairs_majority_preferences(dev, sorted_scores)", "pairs train_anno = build_human_pair_scores(train_pairs) dev_anno = build_human_pair_scores(dev_pairs) test_anno = build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs), len(test_pairs))", "started from 1, to prevent i,j=0,0. but this also lead to i,j=x,0 never", "= [] topic_count = 0 anno_count = 0 summ_count = 0 entries_text =", "0 summ_entry[sum_id_j] = 1 human_pair_scores[article_id] = summ_entry return human_pair_scores # randomize_pref_order and double_prefs", "through dictionary containing summ_ids and matching text # for key, value in entries_text[article_id].items():", "elif rand < train_percent + dev_percent: dev[article_id] = entry else: test[article_id] = entry", ") if learn_rate is not None: optimiser = torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return deep_model, optimiser", "full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\" system %s with score %s (%s)\" % ( full_entry[j]['sys_name'],", "= build_human_pair_scores(dev_pairs) test_anno = build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs), len(test_pairs)) # read bert vectors with", "if pair['summ_id_i'] == int(entry_keys[i][8]) and pair['summ_id_j'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref", "help='cpu/gpu', default='gpu') ap.add_argument('-se', '--seed', type=int, help='random seed number', default='1') ap.add_argument('-fn', '--file_name', type=str, help='file", "test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num, batch_size, train_type,", "set is:') for metric in test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name +=", "0] elif pref[0] < pref[1]: pref = [1, 0] else: pref = [0.5,", "loss.cpu().item() def deep_pair_train_loss_only(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) #", "not existing article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair, np.array([0, 0])) + np.array(pref) # transform to target", "0.5] # sort the ids so that we get a unique key, so", "is False: writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed) if train_percent + dev_percent >= 1.:", "dev_percent) * num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id, scores_list in tqdm(sorted_scores.items()): entry = {}", "human_pair_scores[article_id][sum_id_i] = 1 else: if sum_id_j in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] + 1 else: human_pair_scores[article_id][sum_id_j]", "train_percent: train[article_id] = entry elif rand < train_percent + dev_percent: dev[article_id] = entry", "if csv_exists is False: writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed) if train_percent + dev_percent", "len(summ_ids) < 2: continue concat_vecs = [] true_scores = [] for i in", "for pairs train_anno = build_human_pair_scores(train_pairs) dev_anno = build_human_pair_scores(dev_pairs) test_anno = build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs),", "unique_summ_id_pair = [summ2id[text_i], summ2id[text_j]] # some debug output # noinspection PyUnreachableCode if False:", "solved otherwise for i in range(len(summ_ids)): for j in range(len(summ_ids)): if i ==", "train, dev, test, all def build_model(model_type, vec_length, learn_rate=None): if 'linear' in model_type: deep_model", "pred_scores_all += pred_scores.tolist() rho, rho_p = spearmanr(true_scores, pred_scores) pcc, pcc_p = pearsonr(true_scores, pred_scores)", "[1, 0] # elif entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [0, 1] #", "chosen the situation i=j is solved otherwise for i in range(len(summ_ids)): for j", "default=50) ap.add_argument('-b', '--batch_size', type=int, default=32) ap.add_argument('-tt', '--train_type', type=str, help='pairwise or regression', default='pairwise') ap.add_argument('-tp',", "ap.add_argument('-tt', '--train_type', type=str, help='pairwise or regression', default='pairwise') ap.add_argument('-tp', '--train_percent', type=float, help='how many data", "torch.nn.Linear(vec_length, int(vec_length / 2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length / 2), 1), ) if learn_rate is", "== true_scores_all] for true_score in unique] # bw_methods determines how soft the distribution", "predicted score') ax.set_xlabel('true scores') ax.set_ylabel('predicted scores') xticklabels = true_scores_all ax.set_xticks(true_scores_all) print(\"violin plot written", "model_type, device, seed, file_name = parse_args( argv[1:]) print('\\n=====Arguments====') print('epoch num {}'.format(epoch_num)) print('batch size", "= 0 for article_id, scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids = [s['summ_id']", "skip if it is a tie and you want to ignore ties if", "dev_pairs = build_pairs_majority_preferences(dev, sorted_scores) # test_pairs = build_pairs_majority_preferences(test, sorted_scores) # with majority preferences", "writer = csv.writer(csv_file) # if a new csv_file is generated, write column names", "= temp_entry for article_id in entries: entry = entries[article_id] summ_ids = list(entry.keys()) #", "== 1: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref", "(train,dev,test)', loss_train, loss_dev, loss_test) # Train-Data only print(\"==Train==\") # results_train = test_rewarder(all_vec_dic, train,", "== int(entry_keys[j][8]): if pair['pref'] == 1: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j],", "dev_percent, learn_rate, model_type, device, seed, file_name = parse_args( argv[1:]) print('\\n=====Arguments====') print('epoch num {}'.format(epoch_num))", "torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return deep_model, optimiser else: return deep_model def deep_pair_train(vec_list, target, deep_model, optimiser,", "if pref == [1, 0]: if sum_id_i in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] + 1 else:", "# put here the prefs for this article article_prefs = {} # still", "'pcc': [], 'pcc_p': [], 'tau': [], 'tau_p': [], 'rho_global': [], 'pcc_global': [], 'tau_global':", "file_name = parse_args( argv[1:]) print('\\n=====Arguments====') print('epoch num {}'.format(epoch_num)) print('batch size {}'.format(batch_size)) print('train type", "summ_vec = list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec + summ_vec) # print(np.array(concat_vecs).shape) #", "args.device, args.seed, args.file_name def main(argv): epoch_num, batch_size, train_type, train_percent, dev_percent, learn_rate, model_type, device,", "Make sure the sum is below 1.0!'.format( train_percent + dev_percent)) exit(1) BERT_VEC_LENGTH =", "[0, 1] else: pref = [0.5, 0.5] # if entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: #", "{}'.format(dev_percent)) print('learn rate {}'.format(learn_rate)) print('model type {}'.format(model_type)) print('device {}'.format(device)) print('seed {}'.format(seed)) print('file name", "+ np.array(pref) # transform to target for unique_summ_id_pair, pref in article_prefs.items(): # depending", "if i == j: continue # get keys from dictionary entry_keys = list(entry.keys())", "text_j = value text_i = entries_text[article_id][summ_ids[i]] text_j = entries_text[article_id][summ_ids[j]] # check if text", "bug here. when len(pairs) was a vielfaches of 32, then there was a", "'pcc_dev', 'pcc_p_dev', 'tau_dev', 'tau_p_dev', 'rho_dev_global', 'pcc_dev_global', 'tau_dev_global', 'rho_test', 'rho_p_test', 'pcc_test', 'pcc_p_test', 'tau_test', 'tau_p_test',", "learning function learns f(s0,s1)=pref. in our case, we learn f(s0)=pref[0] and f(s1)=pref[1], so", "optimiser, False, batch_size, device) loss_dev = pair_train_rewarder(all_vec_dic, dev_pairs, deep_model, optimiser, True, batch_size, device)", "if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau) if plot_file is", "loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, False, batch_size, device) loss_dev = pair_train_rewarder(all_vec_dic, dev_pairs,", "still the loss before fed with the training examples loss_train = pair_train_rewarder(all_vec_dic, train_pairs,", "import models from resources import MODEL_WEIGHT_DIR from resources import OUTPUTS_DIR from matplotlib import", "in epoch 0, just evaluate the performance of the randomly initialized model (sanity", "= {} # get summary text and matching id for article_id, scores_list in", "in device: deep_model.to('cuda') torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # read human scores", "summ_ids[j], pref)) continue else: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue", "= ap.parse_args(argv) return args.epoch_num, args.batch_size, args.train_type, args.train_percent, args.dev_percent, args.learn_rate, args.model_type, args.device, args.seed, args.file_name", "train_pairs = build_pairs(train) # dev_pairs = build_pairs(dev) # test_pairs = build_pairs(test) # without", "math.isnan(pcc) or math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p) rho = spearmanr(true_scores_all, pred_scores_all)[0]", "in our case, we learn f(s0)=pref[0] and f(s1)=pref[1], so this should be set", "dev_ids = article_ids[int(train_percent * num_articles):int((train_percent + dev_percent) * num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id,", "value text_i = entries_text[article_id][summ_ids[i]] text_j = entries_text[article_id][summ_ids[j]] # check if text is identical,", "= [0, 1] else: pref = [0.5, 0.5] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) #", "optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if 'gpu' in device:", "list(vec_list[article_id]['article']) summ_vec = list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec + summ_vec) # print(np.array(concat_vecs).shape)", "not ignore_ties: # include the pref two times, once in one direction and", "\\\"%s...\\\" vs. \\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort() if entry[summ_ids[i]] > entry[summ_ids[j]]: pref", "sid1, sid2, _ in pairs: article_vec = list(vecs[aid]['article']) s1_vec = list(vecs[aid][sid1]) s2_vec =", "_ in pairs: article_vec = list(vecs[aid]['article']) s1_vec = list(vecs[aid][sid1]) s2_vec = list(vecs[aid][sid2]) pair_vec_list.append([article_vec", "# results_test = test_rewarder(all_vec_dic, test, deep_model, device) results_test = test_rewarder(all_vec_dic, test_anno, deep_model, device)", "np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") # results = test_rewarder(all_vec_dic, dev, deep_model, device) results = test_rewarder(all_vec_dic,", "for dev', default=.16) ap.add_argument('-lr', '--learn_rate', type=float, help='learning rate', default=3e-4) ap.add_argument('-mt', '--model_type', type=str, help='deep/linear',", "dev, test, all def parse_split_data_balanced(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev =", "print(target_variables) if 'gpu' in device: target_variables = target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss =", "default=.16) ap.add_argument('-lr', '--learn_rate', type=float, help='learning rate', default=3e-4) ap.add_argument('-mt', '--model_type', type=str, help='deep/linear', default='linear') ap.add_argument('-dv',", "a bias in the distribution of the score, e.g. if they are ordered", "distributions of true values to predicted score') ax.set_xlabel('true scores') ax.set_ylabel('predicted scores') xticklabels =", "import Variable import numpy as np import os from os import path import", "pair['summ_id_i'] == int(entry_keys[i][8]) and pair['summ_id_j'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref =", "for pointer in range(int((len( pairs) - 1) / batch_size) + 1): # there", "[pred_scores_all[true_score == true_scores_all] for true_score in unique] # bw_methods determines how soft the", "matching id for article_id, scores_list in tqdm(sorted_scores.items()): temp_entry = {} summ_ids = [s['summ_id']", "train, dev, test, all = parse_split_data(sorted_scores, train_percent, dev_percent) train, dev, test, all =", "to i,j=x,0 never be chosen the situation i=j is solved otherwise for i", "print('dev percent {}'.format(dev_percent)) print('learn rate {}'.format(learn_rate)) print('model type {}'.format(model_type)) print('device {}'.format(device)) print('seed {}'.format(seed))", "+= len(summ_ids) summ_count += len(summ2id) print(\"topics\", topic_count) print(\"annotations\", anno_count) print(\"summ\", summ_count) print(\"summ pairs\",", "# get text for current summaries i and j # if key ==", "vectors with open('data/doc_summ_bert_vectors.pkl', 'rb') as ff: all_vec_dic = pickle.load(ff) pcc_list = [] weights_list", "soft the distribution curve will be. lower values are more sharp ax.violinplot(data_to_plot, showmeans=True,", "i == j: continue if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0] elif", "train_percent, dev_percent) # without majority preferences # train_pairs = build_pairs(train) # dev_pairs =", "and matching id for article_id, scores_list in tqdm(sorted_scores.items()): temp_entry = {} summ_ids =", "sum is below 1.0!'.format( train_percent + dev_percent)) exit(1) BERT_VEC_LENGTH = 1024 # change", "rho_p = spearmanr(true_scores, pred_scores) pcc, pcc_p = pearsonr(true_scores, pred_scores) tau, tau_p = kendalltau(true_scores,", "1: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref =", "= 0 summ_entry[sum_id_j] = 1 human_pair_scores[article_id] = summ_entry return human_pair_scores # randomize_pref_order and", "= 1024 # change this to 768 if you use bert-base deep_model, optimiser", "+ dev_percent >= 1.: print('ERROR! Train data percentage plus dev data percentage is", "= build_anno_pairs(dev, pair_anno_scores) test_pairs = build_anno_pairs(test, pair_anno_scores) # with majority preferences # train_pairs", "topic_count) print(\"summ\", summ_count) # print(pair_list) return pair_list def build_human_pair_scores(pair_list): human_pair_scores = {} for", "direction and once in the other direction if double_prefs: pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1]))", "optimiser, device) loss_list.append(loss) return np.mean(loss_list) def test_rewarder(vec_list, human_scores, model, device, plot_file=None): results =", "{} test = {} all = {} topic_count = 0 for article_id, scores_list", "pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref = [0,", "number of pairs built: {}'.format(len(vec_pairs))) for pointer in range(int((len( pairs) - 1) /", "pickle.load(ff) pcc_list = [] weights_list = [] for ii in range(epoch_num + 1):", "vs. %s)\" % ( summ_ids[i], summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry = sorted_scores[article_id] print(\" system", "pref = [1, 0] # elif entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [0,", "build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs), len(test_pairs)) # read bert vectors with open('data/doc_summ_bert_vectors.pkl', 'rb') as ff:", "bias in the distribution of the score, e.g. if they are ordered if", "deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length / 2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length / 2), 1), )", "= entry if article_id in train_ids: train[article_id] = entry elif article_id in dev_ids:", "the ids so that we get a unique key, so that (sys_summ0,sys_summ1) and", "torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) return loss.cpu().item() def build_pairs(entries): pair_list =", "{} topic_count = 0 for article_id, scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids", "loss_only, batch_size=32, device='cpu'): loss_list = [] shuffled_pairs = pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs = build_pair_vecs(vec_dic,", "a bug here. when len(pairs) was a vielfaches of 32, then there was", "of the specific summary pair. create a new entry if not existing article_prefs[unique_summ_id_pair]", "0] # that can be done more efficiently, but who cares... # rand", "you use bert-base deep_model, optimiser = build_model(model_type, BERT_VEC_LENGTH * 2, learn_rate) if 'gpu'", "convert to tuple, otherwise its not hashable for the dict unique_summ_id_pair = tuple(unique_summ_id_pair)", "# text_i = value # elif key == summ_ids[j]: # text_j = value", "entry[summ_ids[i]] < entry[summ_ids[j]]: pref = [0, 1] else: pref = [0.5, 0.5] pair_list.append((article_id,", "entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [1, 0] # elif entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]:", "scores_list if s['summ_id'] == sid][ 0] # that can be done more efficiently,", "model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num, batch_size, train_type, train_percent, learn_rate, model_type ) torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR,", "results come from epoch no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type, train_percent,", "# print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape) pred_scores = model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all = np.concatenate((pred_scores_all, pred_scores), axis=0)", "the pref two times, once in one direction and once in the other", "{} summ_ids = [s['summ_id'] for s in scores_list] for sid in summ_ids: #", "sid in summ_ids: # get summary text s_text = [s['sys_summ'] for s in", "target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) optimiser.zero_grad() loss.backward() optimiser.step()", "text_i) continue # get the unique summ ids unique_summ_id_pair = [summ2id[text_i], summ2id[text_j]] #", "entry[summ_ids[j]])) print( \" \\\"%s...\\\" vs. \\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort() if entry[summ_ids[i]]", "loss_dev, loss_test] print('--> losses (train,dev,test)', loss_train, loss_dev, loss_test) # Train-Data only print(\"==Train==\") #", "'rho_p_dev', 'pcc_dev', 'pcc_p_dev', 'tau_dev', 'tau_p_dev', 'rho_dev_global', 'pcc_dev_global', 'tau_dev_global', 'rho_test', 'rho_p_test', 'pcc_test', 'pcc_p_test', 'tau_test',", "# print(np.array(true_scores).shape) # print(input) # print(input.shape) # print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape) pred_scores = model(input).data.cpu().numpy().reshape(1,", "in train_ids: train[article_id] = entry elif article_id in dev_ids: dev[article_id] = entry else:", "skip if i == j or text_i == text_j: # print(\"DUPLICATE FOUND: TEXT", "target_batch] if loss_only: loss = deep_pair_train_loss_only(vec_batch, target_batch, deep_model, optimiser, device) else: loss =", "if it is a tie and you want to ignore ties if pref[0]", "pair_list def build_anno_pairs(entries, pair_anno_scores): pair_list = [] topic_count = 0 summ_count = 0", "if train_percent + dev_percent >= 1.: print('ERROR! Train data percentage plus dev data", "print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if 'gpu' in device: input = input.to('cuda')", "a new entry if not existing article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair, np.array([0, 0])) + np.array(pref)", "unique_summ_id_pair[1] < unique_summ_id_pair[0]: unique_summ_id_pair = unique_summ_id_pair[::-1] pref = pref[::-1] # convert to tuple,", "pref to the total pref vector of the specific summary pair. create a", "read_scores from scipy.stats import spearmanr, pearsonr, kendalltau import math from torchvision import models", "in range(len(summ_ids)): if i == j: continue if entry[summ_ids[i]] > entry[summ_ids[j]]: pref =", "import sys import torch from torch.autograd import Variable import numpy as np import", "summary sampler\") ap.add_argument('-e', '--epoch_num', type=int, default=50) ap.add_argument('-b', '--batch_size', type=int, default=32) ap.add_argument('-tt', '--train_type', type=str,", "# elif entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [0, 1] # else: #", "type=float, help='how many data used for training', default=.64) ap.add_argument('-dp', '--dev_percent', type=float, help='how many", "pair anno scores pair_anno_scores = read_pair_anno_scores() # train, dev, test, all = parse_split_data(sorted_scores,", "= article_prefs.get(unique_summ_id_pair, np.array([0, 0])) + np.array(pref) # transform to target for unique_summ_id_pair, pref", "# include the pref in the reverse order by chance. this might be", "summ_id for summ_id in summ_ids} # put here the prefs for this article", "continue if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0] elif entry[summ_ids[i]] < entry[summ_ids[j]]:", "j in range(len(summ_ids)): if i == j: continue if entry[summ_ids[i]] > entry[summ_ids[j]]: pref", "examples loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, False, batch_size, device) loss_dev = pair_train_rewarder(all_vec_dic,", "receive the data and learn from it. the loss is still the loss", "dev_ids: dev[article_id] = entry else: test[article_id] = entry topic_count += 1 print(\"topics in", "print(input.shape) # print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape) pred_scores = model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all = np.concatenate((pred_scores_all, pred_scores),", "to ignore ties if pref[0] != 0.5 or not ignore_ties: # include the", "results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx = np.argmax(pcc_list) best_result = pcc_list[idx]", "= [s['sys_summ'] for s in scores_list if s['summ_id'] == sid][0] temp_entry['sys_summ' + repr(sid)]", "(%s) vs.\" % ( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\" system %s with score %s", "pair_anno_scores) # dev_pairs = build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores) # test_pairs = build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores)", "# print(pair_list) return pair_list def build_human_pair_scores(pair_list): human_pair_scores = {} for entry in pair_list:", "j in range(len(summ_ids)): if i == j: continue # get keys from dictionary", "pref)) continue else: pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue elif", "if article_id in human_pair_scores: if pref == [1, 0]: if sum_id_i in human_pair_scores[article_id]:", "= summ_entry return human_pair_scores # randomize_pref_order and double_prefs are only relevant if the", "for true_score in unique] # bw_methods determines how soft the distribution curve will", "used for dev', default=.16) ap.add_argument('-lr', '--learn_rate', type=float, help='learning rate', default=3e-4) ap.add_argument('-mt', '--model_type', type=str,", "pairs # really iterate over all pairs. there was an error here before", "if i == j or text_i == text_j: # print(\"DUPLICATE FOUND: TEXT i\",", "full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print( \" \\\"%s...\\\" vs. \\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort() if", "want to ignore ties if pref[0] != 0.5 or not ignore_ties: # include", "+= len(summ2id) print(\"topics\", topic_count) print(\"annotations\", anno_count) print(\"summ\", summ_count) print(\"summ pairs\", len(pair_list)) return pair_list", "existing article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair, np.array([0, 0])) + np.array(pref) # transform to target for", "= build_model(model_type, BERT_VEC_LENGTH * 2, learn_rate) if 'gpu' in device: deep_model.to('cuda') torch.backends.cudnn.deterministic =", "(full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort() if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0] elif", "train_percent, seed, learn_rate, model_type, epoch_num ) test_results = test_rewarder(all_vec_dic, test, deep_model, device, os.path.join(OUTPUTS_DIR,", "plot_file) plt.savefig(plot_file) return results def parse_args(argv): ap = argparse.ArgumentParser(\"arguments for summary sampler\") ap.add_argument('-e',", "in scores_list if s['summ_id'] == sid][ 0] # that can be done more", "i=j is solved otherwise for i in range(len(summ_ids)): for j in range(len(summ_ids)): #", "so that (sys_summ0,sys_summ1) and (sys_summ1,sys_summ0) are the same if unique_summ_id_pair[1] < unique_summ_id_pair[0]: unique_summ_id_pair", "csv output', default='BetterRewardsStatistics_test.csv') args = ap.parse_args(argv) return args.epoch_num, args.batch_size, args.train_type, args.train_percent, args.dev_percent, args.learn_rate,", "newline='') as csv_file: writer = csv.writer(csv_file) # if a new csv_file is generated,", "on the test set is:') for metric in test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name =", "train[article_id] = entry elif rand < train_percent + dev_percent: dev[article_id] = entry else:", "its not hashable for the dict unique_summ_id_pair = tuple(unique_summ_id_pair) # add up the", "writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed) if train_percent + dev_percent >= 1.: print('ERROR! Train", "in range(len(summ_ids)): if i == j: continue # get keys from dictionary entry_keys", "text. that's the one we will use summ2id = {entries_text[article_id][summ_id]: summ_id for summ_id", "kendalltau(true_scores, pred_scores) if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p)", "def deep_pair_train(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input)", "train_pairs = build_pairs_majority_preferences(train, sorted_scores) # dev_pairs = build_pairs_majority_preferences(dev, sorted_scores) # test_pairs = build_pairs_majority_preferences(test,", "sid][ 0] # that can be done more efficiently, but who cares... rand", "def parse_split_data_balanced(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev = {} test =", "before fed with the training examples loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, False,", "i\", text_i, \"TEXT j\", text_i) continue # get the unique summ ids unique_summ_id_pair", "pairs, deep_model, optimiser, loss_only, batch_size=32, device='cpu'): loss_list = [] shuffled_pairs = pairs[:] np.random.shuffle(shuffled_pairs)", "build_pair_vecs(vec_dic, shuffled_pairs) # print('total number of pairs built: {}'.format(len(vec_pairs))) for pointer in range(int((len(", "article_id in entries: entry = entries[article_id] summ_ids = list(entry.keys()) # mapping from summary", "temp_entry for article_id in entries: entry = entries[article_id] summ_ids = list(entry.keys()) # mapping", "be chosen the situation i=j is solved otherwise for i in range(len(summ_ids)): for", "used for training', default=.64) ap.add_argument('-dp', '--dev_percent', type=float, help='how many data used for dev',", "'a', newline='') as csv_file: writer = csv.writer(csv_file) # if a new csv_file is", "% ( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\" system %s with score %s (%s)\" %", "double_prefs: pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) else: # include the", "entry = {} summ_ids = [s['summ_id'] for s in scores_list] for sid in", "set sorted_scores = read_sorted_scores() # read pair anno scores pair_anno_scores = read_pair_anno_scores() #", "print(\"topics\", topic_count) print(\"summ\", summ_count) # print(pair_list) return pair_list def build_human_pair_scores(pair_list): human_pair_scores = {}", "1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref = [1, 0] pair_list.append((article_id, summ_ids[i],", "[0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue elif pair['summ_id_j'] == int(entry_keys[i][8]) and pair['summ_id_i']", "concat_vecs.append(article_vec + summ_vec) # print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all += true_scores # add", "prio # pref = [0.5, 0.5] # sort the ids so that we", "and learn from it. the loss is still the loss before fed with", "range(len(summ_ids)): if i == j: continue if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1,", "the mode, use binary target, or graded one pref = (pref / (pref[0]", "the learning function learns f(s0,s1)=pref. in our case, we learn f(s0)=pref[0] and f(s1)=pref[1],", "the dict unique_summ_id_pair = tuple(unique_summ_id_pair) # add up the pref to the total", "+ 1 else: human_pair_scores[article_id][sum_id_j] = 1 else: if pref == [1, 0]: summ_entry[sum_id_i]", "return human_pair_scores # randomize_pref_order and double_prefs are only relevant if the learning function", "{}'.format(len(vec_pairs))) for pointer in range(int((len( pairs) - 1) / batch_size) + 1): #", "dictionary containing summ_ids and matching text # for key, value in entries_text[article_id].items(): #", "dev, test, all = parse_split_data_balanced(sorted_scores, train_percent, dev_percent) # without majority preferences # train_pairs", "= build_anno_pairs(train, pair_anno_scores) dev_pairs = build_anno_pairs(dev, pair_anno_scores) test_pairs = build_anno_pairs(test, pair_anno_scores) # with", "pred_scores_all = [] for article_id in human_scores: entry = human_scores[article_id] summ_ids = list(entry.keys())", "= 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type, train_percent, seed, learn_rate, model_type, epoch_num ) test_results = test_rewarder(all_vec_dic,", "= pearsonr(true_scores, pred_scores) tau, tau_p = kendalltau(true_scores, pred_scores) if not (math.isnan(rho) or math.isnan(pcc)", "values are more sharp ax.violinplot(data_to_plot, showmeans=True, showmedians=True, bw_method=0.2) ax.scatter(true_scores_all + np.random.normal(0, 0.1, pred_scores_all.shape[0]),", "current summaries i and j # if key == summ_ids[i]: # text_i =", "that's the one we will use summ2id = {entries_text[article_id][summ_id]: summ_id for summ_id in", "model.eval() with torch.no_grad(): # print(true_scores) # print(np.array(true_scores).shape) # print(input) # print(input.shape) # print(model(input).data.cpu().numpy())", "todo we could completely ignore ties. doesnt change much. low prio # pref", "deep_model, optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if 'gpu' in", "type=float, help='learning rate', default=3e-4) ap.add_argument('-mt', '--model_type', type=str, help='deep/linear', default='linear') ap.add_argument('-dv', '--device', type=str, help='cpu/gpu',", "determines how soft the distribution curve will be. lower values are more sharp", "# add scores for topic to list of all scores input = Variable(torch.from_numpy(np.array(concat_vecs)).float())", "= [] topic_count = 0 summ_count = 0 for article_id in entries: entry", "repr(sid)] = s_text # save in dictionary entries_text[article_id] = temp_entry for article_id in", "j or text_i == text_j: # print(\"DUPLICATE FOUND: TEXT i\", text_i, \"TEXT j\",", "help='how many data used for training', default=.64) ap.add_argument('-dp', '--dev_percent', type=float, help='how many data", "if key == summ_ids[i]: # text_i = value # elif key == summ_ids[j]:", "loss_dev = pair_train_rewarder(all_vec_dic, dev_pairs, deep_model, optimiser, True, batch_size, device) loss_test = pair_train_rewarder(all_vec_dic, test_pairs,", "elif article_id in dev_ids: dev[article_id] = entry else: test[article_id] = entry topic_count +=", "csv_row.append(np.mean(results[metric])) # Test-Data only print(\"==Test==\") # results_test = test_rewarder(all_vec_dic, test, deep_model, device) results_test", "for metric in results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx = np.argmax(pcc_list)", "[] pred_scores_all = np.array([]) # print(human_scores) # pred_scores_all = [] for article_id in", "= input.to('cuda') model.eval() with torch.no_grad(): # print(true_scores) # print(np.array(true_scores).shape) # print(input) # print(input.shape)", "metric in test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num,", "to target for unique_summ_id_pair, pref in article_prefs.items(): # depending on the mode, use", "continue concat_vecs = [] true_scores = [] for i in range(len(summ_ids)): article_vec =", "debug output # noinspection PyUnreachableCode if False: print(\"%s vs. %s (IDs %s vs.", "2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length / 2), 1), ) if learn_rate is not None: optimiser", "0 anno_count = 0 summ_count = 0 entries_text = {} # get summary", "1), ) if learn_rate is not None: optimiser = torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return deep_model,", "test_pairs = build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores) # build human pair scores for pairs train_anno", "pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue elif pair['summ_id_j'] == int(entry_keys[i][8]) and pair['summ_id_i'] == int(entry_keys[j][8]):", "is {}! Make sure the sum is below 1.0!'.format( train_percent + dev_percent)) exit(1)", "all scores input = Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu' in device: input = input.to('cuda') model.eval()", "output # noinspection PyUnreachableCode if False: print(\"%s vs. %s (IDs %s vs. %s)\"", "pref == [1, 0]: if sum_id_i in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] + 1 else: human_pair_scores[article_id][sum_id_i]", "= torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return deep_model, optimiser else: return deep_model def deep_pair_train(vec_list, target, deep_model,", "pair anno train_pairs = build_anno_pairs(train, pair_anno_scores) dev_pairs = build_anno_pairs(dev, pair_anno_scores) test_pairs = build_anno_pairs(test,", "epoch_num ) test_results = test_rewarder(all_vec_dic, test, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTest.pdf')) test_rewarder(all_vec_dic,", "args.epoch_num, args.batch_size, args.train_type, args.train_percent, args.dev_percent, args.learn_rate, args.model_type, args.device, args.seed, args.file_name def main(argv): epoch_num,", "for metric in results: print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) # Test-Data only print(\"==Test==\") # results_test", "to predicted score') ax.set_xlabel('true scores') ax.set_ylabel('predicted scores') xticklabels = true_scores_all ax.set_xticks(true_scores_all) print(\"violin plot", "weights_list = [] for ii in range(epoch_num + 1): print('\\n=====EPOCH {}====='.format(ii)) if ii", "build_pairs(entries): pair_list = [] topic_count = 0 summ_count = 0 for article_id in", "for summaries/docs, and split the train/dev/test set sorted_scores = read_sorted_scores() # read pair", "pairs built: {}'.format(len(vec_pairs))) for pointer in range(int((len( pairs) - 1) / batch_size) +", "= {'rho': [], 'rho_p': [], 'pcc': [], 'pcc_p': [], 'tau': [], 'tau_p': [],", "deep_model, device) results = test_rewarder(all_vec_dic, dev_anno, deep_model, device) for metric in results: print('{}\\t{}'.format(metric,", "the reverse order by chance. this might be necessary if there is a", "the pref to the total pref vector of the specific summary pair. create", "an exception vec_batch = vec_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch =", "ignore ties if pref[0] != 0.5 or not ignore_ties: # include the pref", "human_pair_scores: if pref == [1, 0]: if sum_id_i in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] + 1", "+= 1 anno_count += len(summ_ids) summ_count += len(summ2id) print(\"topics\", topic_count) print(\"annotations\", anno_count) print(\"summ\",", "# print(model(input).data.cpu().numpy().shape) pred_scores = model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all = np.concatenate((pred_scores_all, pred_scores), axis=0) # pred_scores_all", "[], 'tau_p': [], 'rho_global': [], 'pcc_global': [], 'tau_global': []} true_scores_all = [] pred_scores_all", "test_pairs = build_pairs_majority_preferences(test, sorted_scores) # with majority preferences and pair anno # train_pairs", "continue topic_count += 1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count)", "showmeans=True, showmedians=True, bw_method=0.2) ax.scatter(true_scores_all + np.random.normal(0, 0.1, pred_scores_all.shape[0]), pred_scores_all, marker=\".\", s=3, alpha=0.5) ax.set_title('Comparison", "len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) return pair_list def build_anno_pairs(entries, pair_anno_scores): pair_list = []", "sorted_scores, pair_anno_scores) # test_pairs = build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores) # build human pair scores", "done more efficiently, but who cares... # rand = random.random() all[article_id] = entry", "regression', default='pairwise') ap.add_argument('-tp', '--train_percent', type=float, help='how many data used for training', default=.64) ap.add_argument('-dp',", "batch_size, device) loss_test = pair_train_rewarder(all_vec_dic, test_pairs, deep_model, optimiser, True, batch_size, device) csv_row =", "full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\" system %s with score %s (%s)\" % ( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'],", "# true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all) unique = np.sort(np.unique(true_scores_all)) data_to_plot = [pred_scores_all[true_score == true_scores_all] for", "for current summaries i and j # if key == summ_ids[i]: # text_i", "build human pair scores for pairs train_anno = build_human_pair_scores(train_pairs) dev_anno = build_human_pair_scores(dev_pairs) test_anno", "entry = human_scores[article_id] summ_ids = list(entry.keys()) if len(summ_ids) < 2: continue concat_vecs =", "data and learn from it. the loss is still the loss before fed", "target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if 'gpu'", "print(len(train_pairs), len(dev_pairs), len(test_pairs)) # read bert vectors with open('data/doc_summ_bert_vectors.pkl', 'rb') as ff: all_vec_dic", "vs. %s (IDs %s vs. %s)\" % ( summ_ids[i], summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry", "print('batch size {}'.format(batch_size)) print('train type {}'.format(train_type)) print('train percent {}'.format(train_percent)) print('dev percent {}'.format(dev_percent)) print('learn", "if pref[0] != 0.5 or not ignore_ties: # include the pref two times,", "results def parse_args(argv): ap = argparse.ArgumentParser(\"arguments for summary sampler\") ap.add_argument('-e', '--epoch_num', type=int, default=50)", "# transform to target for unique_summ_id_pair, pref in article_prefs.items(): # depending on the", "distribution of the score, e.g. if they are ordered if randomize_pref_order and bool(random.getrandbits(1)):", "args.model_type, args.device, args.seed, args.file_name def main(argv): epoch_num, batch_size, train_type, train_percent, dev_percent, learn_rate, model_type,", "True torch.backends.cudnn.benchmark = False # read human scores and vectors for summaries/docs, and", "= pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, False, batch_size, device) loss_dev = pair_train_rewarder(all_vec_dic, dev_pairs, deep_model,", "topic_count += 1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) #", "topic_count) return train, dev, test, all def build_model(model_type, vec_length, learn_rate=None): if 'linear' in", "print(\" system %s with score %s (%s)\" % ( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print(", "None: optimiser = torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return deep_model, optimiser else: return deep_model def deep_pair_train(vec_list,", "losses (train,dev,test)', loss_train, loss_dev, loss_test) # Train-Data only print(\"==Train==\") # results_train = test_rewarder(all_vec_dic,", "+ repr(sid)] = [s['scores'][prompt] for s in scores_list if s['summ_id'] == sid][ 0]", "build_pairs(dev) # test_pairs = build_pairs(test) # without majority preferences but with pair anno", "i == j or text_i == text_j: # print(\"DUPLICATE FOUND: TEXT i\", text_i,", "with open(file_name, 'a', newline='') as csv_file: writer = csv.writer(csv_file) # if a new", "if they are ordered if randomize_pref_order and bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) else:", "pair scores for pairs train_anno = build_human_pair_scores(train_pairs) dev_anno = build_human_pair_scores(dev_pairs) test_anno = build_human_pair_scores(test_pairs)", "model, device, plot_file=None): results = {'rho': [], 'rho_p': [], 'pcc': [], 'pcc_p': [],", "summ_ids: # get summary text s_text = [s['sys_summ'] for s in scores_list if", "pred_scores_all = np.concatenate((pred_scores_all, pred_scores), axis=0) # pred_scores_all += pred_scores.tolist() rho, rho_p = spearmanr(true_scores,", "= pcc_list[idx] print('\\n======Best results come from epoch no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format(", "{}'.format(model_type)) print('device {}'.format(device)) print('seed {}'.format(seed)) print('file name {}'.format(file_name)) print('=====Arguments====\\n') csv_column_names = ['seed', 'learn_rate',", "build_pairs(train) # dev_pairs = build_pairs(dev) # test_pairs = build_pairs(test) # without majority preferences", "never be chosen the situation i=j is solved otherwise for i in range(len(summ_ids)):", "human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] + 1 else: human_pair_scores[article_id][sum_id_j] = 1 else: if pref == [1,", "== sid][0] temp_entry['sys_summ' + repr(sid)] = s_text # save in dictionary entries_text[article_id] =", "= {} all = {} topic_count = 0 for article_id, scores_list in tqdm(sorted_scores.items()):", "for metric in results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") # results = test_rewarder(all_vec_dic, dev,", "= human_scores[article_id] summ_ids = list(entry.keys()) if len(summ_ids) < 2: continue concat_vecs = []", "weights_list.append(copy.deepcopy(deep_model.state_dict())) idx = np.argmax(pcc_list) best_result = pcc_list[idx] print('\\n======Best results come from epoch no.", "= [0.5, 0.5] # sort the ids so that we get a unique", "test_rewarder(all_vec_dic, test_anno, deep_model, device) for metric in results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc']))", "== text_j: # print(\"DUPLICATE FOUND: TEXT i\", text_i, \"TEXT j\", text_i) continue #", "j: continue # get keys from dictionary entry_keys = list(entry.keys()) # get pair", "# print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all += true_scores # add scores for topic", "< entry[summ_ids[j]]: pref = [0, 1] else: pref = [0.5, 0.5] # if", "[] topic_count = 0 summ_count = 0 for article_id in entries: entry =", "in target_batch] if loss_only: loss = deep_pair_train_loss_only(vec_batch, target_batch, deep_model, optimiser, device) else: loss", "= loss_fn(pred, target_variables) # print(loss) optimiser.zero_grad() loss.backward() optimiser.step() return loss.cpu().item() def deep_pair_train_loss_only(vec_list, target,", "len(dev_pairs), len(test_pairs)) # read bert vectors with open('data/doc_summ_bert_vectors.pkl', 'rb') as ff: all_vec_dic =", "anno train_pairs = build_anno_pairs(train, pair_anno_scores) dev_pairs = build_anno_pairs(dev, pair_anno_scores) test_pairs = build_anno_pairs(test, pair_anno_scores)", "topic_count = 0 article_ids = list(sorted_scores.keys()) random.shuffle(article_ids) num_articles = len(article_ids) train_ids = article_ids[0:int(train_percent", "< pref[1]: pref = [1, 0] else: pref = [0.5, 0.5] # skip", "{}'.format(seed)) print('file name {}'.format(file_name)) print('=====Arguments====\\n') csv_column_names = ['seed', 'learn_rate', 'model_type', 'train_pairs', 'dev_pairs', 'test_pairs',", "the prefs for this article article_prefs = {} # still run through all", "dev', default=.16) ap.add_argument('-lr', '--learn_rate', type=float, help='learning rate', default=3e-4) ap.add_argument('-mt', '--model_type', type=str, help='deep/linear', default='linear')", "are ordered if randomize_pref_order and bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) else: pair_list.append((article_id, unique_summ_id_pair[0],", "a last batch with [] causing an exception vec_batch = vec_pairs[pointer * batch_size:(pointer", "on, receive the data and learn from it. the loss is still the", "len(dev_pairs), len(test_pairs), ii, loss_train, loss_dev, loss_test] print('--> losses (train,dev,test)', loss_train, loss_dev, loss_test) #", "= value # elif key == summ_ids[j]: # text_j = value text_i =", "def build_anno_pairs(entries, pair_anno_scores): pair_list = [] topic_count = 0 summ_count = 0 for", "percentage is {}! Make sure the sum is below 1.0!'.format( train_percent + dev_percent))", "# test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id, scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids = [s['summ_id']", "pair anno # train_pairs = build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores) # dev_pairs = build_anno_pairs_majority_preferences(dev, sorted_scores,", "= list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec + summ_vec) # print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]])", "with score %s (%s)\" % ( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print( \" \\\"%s...\\\" vs.", "only relevant if the learning function learns f(s0,s1)=pref. in our case, we learn", "= [summ2id[text_i], summ2id[text_j]] # some debug output # noinspection PyUnreachableCode if False: print(\"%s", "ii, loss_train, loss_dev, loss_test] print('--> losses (train,dev,test)', loss_train, loss_dev, loss_test) # Train-Data only", "0] else: pref = [0.5, 0.5] # skip if it is a tie", "import os from os import path import argparse import random import copy from", "train, dev, test, all = parse_split_data_balanced(sorted_scores, train_percent, dev_percent) # without majority preferences #", "pred = softmax_layer(value_variables) # print(pred) # print(np.array(target).shape, np.array(target).reshape(-1, 2, 1).shape) target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1,", "device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if 'gpu' in device: input", "batch_size:(pointer + 1) * batch_size] target_batch = shuffled_pairs[pointer * batch_size:(pointer + 1) *", "math.isnan(pcc) or math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau) if plot_file is not None: fig, ax", "{}====='.format(ii)) if ii == 0: # do not train in epoch 0, just", "is solved otherwise for i in range(len(summ_ids)): for j in range(len(summ_ids)): # run", "= {} summ_ids = [s['summ_id'] for s in scores_list] for sid in summ_ids:", "+ repr(sid)] = s_text # save in dictionary entries_text[article_id] = temp_entry for article_id", "human_scores, model, device, plot_file=None): results = {'rho': [], 'rho_p': [], 'pcc': [], 'pcc_p':", "return args.epoch_num, args.batch_size, args.train_type, args.train_percent, args.dev_percent, args.learn_rate, args.model_type, args.device, args.seed, args.file_name def main(argv):", "= False # read human scores and vectors for summaries/docs, and split the", "summ_ids[j]: # text_j = value text_i = entries_text[article_id][summ_ids[i]] text_j = entries_text[article_id][summ_ids[j]] # check", "argparse.ArgumentParser(\"arguments for summary sampler\") ap.add_argument('-e', '--epoch_num', type=int, default=50) ap.add_argument('-b', '--batch_size', type=int, default=32) ap.add_argument('-tt',", "2, 1) # print(target_variables) if 'gpu' in device: target_variables = target_variables.to('cuda') loss_fn =", "print(input) if 'gpu' in device: input = input.to('cuda') value_variables = deep_model(input) # print(value_variables)", "range(len(summ_ids)): for j in range(len(summ_ids)): if i == j: continue # get keys", "situation i=j is solved otherwise for i in range(len(summ_ids)): for j in range(len(summ_ids)):", "1) * batch_size] target_batch = [ee[-1] for ee in target_batch] if loss_only: loss", "'pcc_p_test', 'tau_test', 'tau_p_test', 'rho_test_global', 'pcc_test_global', 'tau_test_global'] # check if csv_file exists if path.exists(file_name):", "% ( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print( \" \\\"%s...\\\" vs. \\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20]))", "'--learn_rate', type=float, help='learning rate', default=3e-4) ap.add_argument('-mt', '--model_type', type=str, help='deep/linear', default='linear') ap.add_argument('-dv', '--device', type=str,", "exception vec_batch = vec_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch = shuffled_pairs[pointer", "in test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num, batch_size,", "true_scores_all] for true_score in unique] # bw_methods determines how soft the distribution curve", "text s_text = [s['sys_summ'] for s in scores_list if s['summ_id'] == sid][0] temp_entry['sys_summ'", "'gpu' in device: input = input.to('cuda') model.eval() with torch.no_grad(): # print(true_scores) # print(np.array(true_scores).shape)", "if article_id in train_ids: train[article_id] = entry elif article_id in dev_ids: dev[article_id] =", "pair_anno_scores): pair_list = [] topic_count = 0 summ_count = 0 for article_id in", "0 entries_text = {} # get summary text and matching id for article_id,", "random.random() all[article_id] = entry if rand < train_percent: train[article_id] = entry elif rand", "0] elif entry[summ_ids[i]] < entry[summ_ids[j]]: pref = [0, 1] else: pref = [0.5,", "= [1, 0] else: pref = [0.5, 0.5] # skip if it is", "vs. \\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort() if entry[summ_ids[i]] > entry[summ_ids[j]]: pref =", "two times, once in one direction and once in the other direction if", "deep_model def deep_pair_train(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) #", "build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores) # test_pairs = build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores) # build human pair", "0 for article_id in entries: entry = entries[article_id] summ_ids = list(entry.keys()) # really", "no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type, train_percent, seed, learn_rate, model_type, epoch_num", "pref)) # print(pair_list) topic_count += 1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count)", "return loss.cpu().item() def build_pairs(entries): pair_list = [] topic_count = 0 summ_count = 0", "'gpu' in device: target_variables = target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables)", "type=str, help='cpu/gpu', default='gpu') ap.add_argument('-se', '--seed', type=int, help='random seed number', default='1') ap.add_argument('-fn', '--file_name', type=str,", "= entries_text[article_id][summ_ids[i]] text_j = entries_text[article_id][summ_ids[j]] # check if text is identical, if yes", "in pairs: article_vec = list(vecs[aid]['article']) s1_vec = list(vecs[aid][sid1]) s2_vec = list(vecs[aid][sid2]) pair_vec_list.append([article_vec +", "else: pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue topic_count += 1", "dev, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onDev.pdf')) print('Its performance on the test set", "article_id in human_pair_scores: if pref == [1, 0]: if sum_id_i in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i]", "len(pairs) was a vielfaches of 32, then there was a last batch with", "= pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, True, batch_size, device) else: # from epoch 1", "more sharp ax.violinplot(data_to_plot, showmeans=True, showmedians=True, bw_method=0.2) ax.scatter(true_scores_all + np.random.normal(0, 0.1, pred_scores_all.shape[0]), pred_scores_all, marker=\".\",", "entry topic_count += 1 print(\"topics in parse_split_data\", topic_count) return train, dev, test, all", "= 1 summ_entry[sum_id_j] = 0 else: summ_entry[sum_id_i] = 0 summ_entry[sum_id_j] = 1 human_pair_scores[article_id]", "= torch.nn.Sequential( torch.nn.Linear(vec_length, 1), ) else: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length / 2)),", "article_id, scores_list in tqdm(sorted_scores.items()): temp_entry = {} summ_ids = [s['summ_id'] for s in", "bw_method=0.2) ax.scatter(true_scores_all + np.random.normal(0, 0.1, pred_scores_all.shape[0]), pred_scores_all, marker=\".\", s=3, alpha=0.5) ax.set_title('Comparison and distributions", "build_anno_pairs(dev, pair_anno_scores) test_pairs = build_anno_pairs(test, pair_anno_scores) # with majority preferences # train_pairs =", "pref = (pref / (pref[0] + pref[1])).tolist() if target_type == 'binary': if pref[0]", "= 0 entries_text = {} # get summary text and matching id for", "from dictionary entry_keys = list(entry.keys()) # get pair preference from pair_anno_scores for pair", "the performance of the randomly initialized model (sanity check and baseline) loss_train =", "unique_summ_id_pair = unique_summ_id_pair[::-1] pref = pref[::-1] # convert to tuple, otherwise its not", "for csv output', default='BetterRewardsStatistics_test.csv') args = ap.parse_args(argv) return args.epoch_num, args.batch_size, args.train_type, args.train_percent, args.dev_percent,", "and split the train/dev/test set sorted_scores = read_sorted_scores() # read pair anno scores", "read human scores and vectors for summaries/docs, and split the train/dev/test set sorted_scores", "it. the loss is still the loss before fed with the training examples", "pair_anno_scores = read_pair_anno_scores() # train, dev, test, all = parse_split_data(sorted_scores, train_percent, dev_percent) train,", "# do not train in epoch 0, just evaluate the performance of the", "device) for metric in results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx =", "matplotlib import pyplot as plt import csv def parse_split_data(sorted_scores, train_percent, dev_percent, prompt='structure'): train", "import spearmanr, pearsonr, kendalltau import math from torchvision import models from resources import", "and j # if key == summ_ids[i]: # text_i = value # elif", "32, then there was a last batch with [] causing an exception vec_batch", "much. low prio # pref = [0.5, 0.5] # sort the ids so", "# check if csv_file exists if path.exists(file_name): csv_exists = True else: csv_exists =", "np import os from os import path import argparse import random import copy", "# dev_pairs = build_pairs(dev) # test_pairs = build_pairs(test) # without majority preferences but", "use binary target, or graded one pref = (pref / (pref[0] + pref[1])).tolist()", "else: pref = [0.5, 0.5] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) # print(pair_list) topic_count +=", "system %s with score %s (%s) vs.\" % ( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\"", "\" \\\"%s...\\\" vs. \\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort() if entry[summ_ids[i]] > entry[summ_ids[j]]:", "> entry[unique_summ_id_pair[1]]: # pref = [1, 0] # elif entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: #", "# randomize_pref_order and double_prefs are only relevant if the learning function learns f(s0,s1)=pref.", "= 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name += 'seed{}_epoch{}_batch{}_{}_trainPercent{}_lrate{}_{}.model'.format( seed, epoch_num, batch_size, train_type, train_percent, learn_rate, model_type )", "for i in range(len(summ_ids)): article_vec = list(vec_list[article_id]['article']) summ_vec = list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape, np.array(article_vec).shape,", "is a bias in the distribution of the score, e.g. if they are", "article_id in dev_ids: dev[article_id] = entry else: test[article_id] = entry topic_count += 1", "# get summary text s_text = [s['sys_summ'] for s in scores_list if s['summ_id']", "sum_id_i = str(entry[1]) sum_id_j = str(entry[2]) pref = entry[3] summ_entry = {} if", "human_pair_scores = {} for entry in pair_list: article_id = str(entry[0]) sum_id_i = str(entry[1])", "through all pairs # really iterate over all pairs. there was an error", "# if a new csv_file is generated, write column names if csv_exists is", "rand < train_percent + dev_percent: dev[article_id] = entry else: test[article_id] = entry topic_count", "dev_pairs, deep_model, optimiser, True, batch_size, device) loss_test = pair_train_rewarder(all_vec_dic, test_pairs, deep_model, optimiser, True,", "= [] for article_id in human_scores: entry = human_scores[article_id] summ_ids = list(entry.keys()) if", "if False: print(\"%s vs. %s (IDs %s vs. %s)\" % ( summ_ids[i], summ_ids[j],", "import path import argparse import random import copy from tqdm import tqdm import", "human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] + 1 else: human_pair_scores[article_id][sum_id_i] = 1 else: if sum_id_j in human_pair_scores[article_id]:", "else: return deep_model def deep_pair_train(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input =", "print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") # results = test_rewarder(all_vec_dic, dev, deep_model, device) results =", "change much. low prio # pref = [0.5, 0.5] # sort the ids", "otherwise its not hashable for the dict unique_summ_id_pair = tuple(unique_summ_id_pair) # add up", "target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1) # print(target_variables) if 'gpu' in device: target_variables =", "deep_model, optimiser, True, batch_size, device) else: # from epoch 1 on, receive the", "from 1, to prevent i,j=0,0. but this also lead to i,j=x,0 never be", "'train_pairs', 'dev_pairs', 'test_pairs', 'epoch_num', 'loss_train', 'loss_dev', 'loss_test', 'rho_train', 'rho_p_train', 'pcc_train', 'pcc_p_train', 'tau_train', 'tau_p_train',", "i in range(len(summ_ids)): for j in range(len(summ_ids)): # run through dictionary containing summ_ids", "'tau_test', 'tau_p_test', 'rho_test_global', 'pcc_test_global', 'tau_test_global'] # check if csv_file exists if path.exists(file_name): csv_exists", "list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec + summ_vec) # print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]])", "scores_list] for sid in summ_ids: entry['sys_summ' + repr(sid)] = [s['scores'][prompt] for s in", "optimiser = build_model(model_type, BERT_VEC_LENGTH * 2, learn_rate) if 'gpu' in device: deep_model.to('cuda') torch.backends.cudnn.deterministic", "= test_rewarder(all_vec_dic, test, deep_model, device) results_test = test_rewarder(all_vec_dic, test_anno, deep_model, device) for metric", "pref two times, once in one direction and once in the other direction", "if learn_rate is not None: optimiser = torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return deep_model, optimiser else:", "results = test_rewarder(all_vec_dic, dev_anno, deep_model, device) for metric in results: print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric]))", "order by chance. this might be necessary if there is a bias in", "> entry[summ_ids[j]]: pref = [1, 0] elif entry[summ_ids[i]] < entry[summ_ids[j]]: pref = [0,", "True, batch_size, device) csv_row = [seed, learn_rate, model_type, len(train_pairs), len(dev_pairs), len(test_pairs), ii, loss_train,", "[0, 1] else: pref = [0.5, 0.5] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) # print(pair_list)", "pref = [1, 0] else: pref = [0.5, 0.5] # skip if it", "+= 1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) # print(pair_list)", "sure the sum is below 1.0!'.format( train_percent + dev_percent)) exit(1) BERT_VEC_LENGTH = 1024", "test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id, scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids = [s['summ_id'] for", "pred_scores_all = np.array([]) # print(human_scores) # pred_scores_all = [] for article_id in human_scores:", "dev = {} test = {} all = {} topic_count = 0 for", "build_pairs_majority_preferences(train, sorted_scores) # dev_pairs = build_pairs_majority_preferences(dev, sorted_scores) # test_pairs = build_pairs_majority_preferences(test, sorted_scores) #", "save in dictionary entries_text[article_id] = temp_entry for article_id in entries: entry = entries[article_id]", "of the randomly initialized model (sanity check and baseline) loss_train = pair_train_rewarder(all_vec_dic, train_pairs,", "from pair_anno_scores for pair in pair_anno_scores[article_id]: if pair['summ_id_i'] == int(entry_keys[i][8]) and pair['summ_id_j'] ==", "# test_pairs = build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores) # build human pair scores for pairs", "loss_fn(pred, target_variables) # print(loss) optimiser.zero_grad() loss.backward() optimiser.step() return loss.cpu().item() def deep_pair_train_loss_only(vec_list, target, deep_model,", "all pairs. there was an error here before since j started from 1,", "could completely ignore ties. doesnt change much. low prio # pref = [0.5,", "pairs) - 1) / batch_size) + 1): # there was a bug here.", "ignore_ties=False, randomize_pref_order=False, double_prefs=False): pair_list = [] topic_count = 0 anno_count = 0 summ_count", "train_percent + dev_percent: dev[article_id] = entry else: test[article_id] = entry topic_count += 1", "done more efficiently, but who cares... rand = random.random() all[article_id] = entry if", "def build_model(model_type, vec_length, learn_rate=None): if 'linear' in model_type: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, 1),", "# train, dev, test, all = parse_split_data(sorted_scores, train_percent, dev_percent) train, dev, test, all", "1 print(\"topics in parse_split_data\", topic_count) return train, dev, test, all def build_model(model_type, vec_length,", "'rho_p': [], 'pcc': [], 'pcc_p': [], 'tau': [], 'tau_p': [], 'rho_global': [], 'pcc_global':", "for aid, sid1, sid2, _ in pairs: article_vec = list(vecs[aid]['article']) s1_vec = list(vecs[aid][sid1])", "= build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs), len(test_pairs)) # read bert vectors with open('data/doc_summ_bert_vectors.pkl', 'rb') as", "read_sorted_scores, read_pair_anno_scores, read_articles, \\ read_processed_scores, read_scores from scipy.stats import spearmanr, pearsonr, kendalltau import", "split the train/dev/test set sorted_scores = read_sorted_scores() # read pair anno scores pair_anno_scores", "default=.64) ap.add_argument('-dp', '--dev_percent', type=float, help='how many data used for dev', default=.16) ap.add_argument('-lr', '--learn_rate',", "num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id, scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids =", "'rb') as ff: all_vec_dic = pickle.load(ff) pcc_list = [] weights_list = [] for", "test_anno, deep_model, device) for metric in results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict()))", "= parse_split_data(sorted_scores, train_percent, dev_percent) train, dev, test, all = parse_split_data_balanced(sorted_scores, train_percent, dev_percent) #", "build_pairs_majority_preferences(test, sorted_scores) # with majority preferences and pair anno # train_pairs = build_anno_pairs_majority_preferences(train,", "for summ_id in summ_ids} # put here the prefs for this article article_prefs", "# print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if 'gpu' in device: input =", "the one we will use summ2id = {entries_text[article_id][summ_id]: summ_id for summ_id in summ_ids}", "j # if key == summ_ids[i]: # text_i = value # elif key", "in article_prefs.items(): # depending on the mode, use binary target, or graded one", "deep_pair_train_loss_only(vec_batch, target_batch, deep_model, optimiser, device) else: loss = deep_pair_train(vec_batch, target_batch, deep_model, optimiser, device)", "[1, 0] else: pref = [0.5, 0.5] # skip if it is a", "(IDs %s vs. %s)\" % ( summ_ids[i], summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry = sorted_scores[article_id]", "pred_scores_all, marker=\".\", s=3, alpha=0.5) ax.set_title('Comparison and distributions of true values to predicted score')", "sharp ax.violinplot(data_to_plot, showmeans=True, showmedians=True, bw_method=0.2) ax.scatter(true_scores_all + np.random.normal(0, 0.1, pred_scores_all.shape[0]), pred_scores_all, marker=\".\", s=3,", "i,j=0,0. but this also lead to i,j=x,0 never be chosen the situation i=j", "'--device', type=str, help='cpu/gpu', default='gpu') ap.add_argument('-se', '--seed', type=int, help='random seed number', default='1') ap.add_argument('-fn', '--file_name',", "target_variables = target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) optimiser.zero_grad()", "default='gpu') ap.add_argument('-se', '--seed', type=int, help='random seed number', default='1') ap.add_argument('-fn', '--file_name', type=str, help='file name", "or math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau) if plot_file is not None: fig, ax =", "performance on the test set is:') for metric in test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name", "if sum_id_i in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] + 1 else: human_pair_scores[article_id][sum_id_i] = 1 else: if", "all = parse_split_data_balanced(sorted_scores, train_percent, dev_percent) # without majority preferences # train_pairs = build_pairs(train)", "that we get a unique key, so that (sys_summ0,sys_summ1) and (sys_summ1,sys_summ0) are the", "0.5 or not ignore_ties: # include the pref two times, once in one", "from it. the loss is still the loss before fed with the training", "# print(np.array(target).shape, np.array(target).reshape(-1, 2, 1).shape) target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1) # print(target_variables) if", "= plt.subplots() # true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all) unique = np.sort(np.unique(true_scores_all)) data_to_plot = [pred_scores_all[true_score ==", "# unique_summ_id_pair.sort() if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0] elif entry[summ_ids[i]] <", "text_j = entries_text[article_id][summ_ids[j]] # check if text is identical, if yes skip if", "test_rewarder(all_vec_dic, train, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTrain.pdf')) test_rewarder(all_vec_dic, dev, deep_model, device, os.path.join(OUTPUTS_DIR,", "or text_i == text_j: # print(\"DUPLICATE FOUND: TEXT i\", text_i, \"TEXT j\", text_i)", "run through dictionary containing summ_ids and matching text # for key, value in", "sid in summ_ids: entry['sys_summ' + repr(sid)] = [s['scores'][prompt] for s in scores_list if", "1): print('\\n=====EPOCH {}====='.format(ii)) if ii == 0: # do not train in epoch", "was a last batch with [] causing an exception vec_batch = vec_pairs[pointer *", "print(\"topics\", topic_count) print(\"summ\", summ_count) return pair_list def build_anno_pairs(entries, pair_anno_scores): pair_list = [] topic_count", "summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) # print(pair_list) return pair_list def build_human_pair_scores(pair_list):", "== int(entry_keys[i][8]) and pair['summ_id_j'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref = [1,", "print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape) pred_scores = model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all = np.concatenate((pred_scores_all, pred_scores), axis=0) #", "best_result = pcc_list[idx] print('\\n======Best results come from epoch no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern =", "to: %s\" % plot_file) plt.savefig(plot_file) return results def parse_args(argv): ap = argparse.ArgumentParser(\"arguments for", "[1, 0] elif entry[summ_ids[i]] < entry[summ_ids[j]]: pref = [0, 1] else: pref =", "pref)) else: # include the pref in the reverse order by chance. this", "scores_list] for sid in summ_ids: # get summary text s_text = [s['sys_summ'] for", "= list(entry.keys()) if len(summ_ids) < 2: continue concat_vecs = [] true_scores = []", "test = {} all = {} topic_count = 0 article_ids = list(sorted_scores.keys()) random.shuffle(article_ids)", "anno_count = 0 summ_count = 0 entries_text = {} # get summary text", "text_i = entries_text[article_id][summ_ids[i]] text_j = entries_text[article_id][summ_ids[j]] # check if text is identical, if", "fig, ax = plt.subplots() # true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all) unique = np.sort(np.unique(true_scores_all)) data_to_plot =", "0.5] # if entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [1, 0] # elif", "check if csv_file exists if path.exists(file_name): csv_exists = True else: csv_exists = False", "0.1, pred_scores_all.shape[0]), pred_scores_all, marker=\".\", s=3, alpha=0.5) ax.set_title('Comparison and distributions of true values to", "0 summ_count = 0 entries_text = {} # get summary text and matching", "print('train percent {}'.format(train_percent)) print('dev percent {}'.format(dev_percent)) print('learn rate {}'.format(learn_rate)) print('model type {}'.format(model_type)) print('device", "input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if 'gpu' in device: input = input.to('cuda') value_variables", "( summ_ids[i], summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry = sorted_scores[article_id] print(\" system %s with score", "hashable for the dict unique_summ_id_pair = tuple(unique_summ_id_pair) # add up the pref to", "parse_split_data(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev = {} test = {}", "print(true_scores) # print(np.array(true_scores).shape) # print(input) # print(input.shape) # print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape) pred_scores =", "np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx = np.argmax(pcc_list) best_result = pcc_list[idx] print('\\n======Best results", "= True torch.backends.cudnn.benchmark = False # read human scores and vectors for summaries/docs,", "all def build_model(model_type, vec_length, learn_rate=None): if 'linear' in model_type: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length,", "s1_vec, article_vec + s2_vec]) return pair_vec_list def pair_train_rewarder(vec_dic, pairs, deep_model, optimiser, loss_only, batch_size=32,", "= [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue elif pair['summ_id_j'] == int(entry_keys[i][8]) and", "= list(vecs[aid][sid1]) s2_vec = list(vecs[aid][sid2]) pair_vec_list.append([article_vec + s1_vec, article_vec + s2_vec]) return pair_vec_list", "= [0, 1] # else: # # todo we could completely ignore ties.", "the randomly initialized model (sanity check and baseline) loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model,", "= build_pairs_majority_preferences(test, sorted_scores) # with majority preferences and pair anno # train_pairs =", "loss.cpu().item() def build_pairs(entries): pair_list = [] topic_count = 0 summ_count = 0 for", "s2_vec]) return pair_vec_list def pair_train_rewarder(vec_dic, pairs, deep_model, optimiser, loss_only, batch_size=32, device='cpu'): loss_list =", "rate {}'.format(learn_rate)) print('model type {}'.format(model_type)) print('device {}'.format(device)) print('seed {}'.format(seed)) print('file name {}'.format(file_name)) print('=====Arguments====\\n')", "device, plot_file=None): results = {'rho': [], 'rho_p': [], 'pcc': [], 'pcc_p': [], 'tau':", "0] # elif entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [0, 1] # else:", "ignore ties. doesnt change much. low prio # pref = [0.5, 0.5] #", "= np.concatenate((pred_scores_all, pred_scores), axis=0) # pred_scores_all += pred_scores.tolist() rho, rho_p = spearmanr(true_scores, pred_scores)", "true_scores # add scores for topic to list of all scores input =", "score %s (%s) vs.\" % ( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\" system %s with", "we learn f(s0)=pref[0] and f(s1)=pref[1], so this should be set to False def", "torch.random.manual_seed(seed) torch.manual_seed(seed) if train_percent + dev_percent >= 1.: print('ERROR! Train data percentage plus", "model_type, len(train_pairs), len(dev_pairs), len(test_pairs), ii, loss_train, loss_dev, loss_test] print('--> losses (train,dev,test)', loss_train, loss_dev,", "[] topic_count = 0 anno_count = 0 summ_count = 0 entries_text = {}", "/ 2), 1), ) if learn_rate is not None: optimiser = torch.optim.Adam(deep_model.parameters(), lr=learn_rate)", "for entry in pair_list: article_id = str(entry[0]) sum_id_i = str(entry[1]) sum_id_j = str(entry[2])", "the sum is below 1.0!'.format( train_percent + dev_percent)) exit(1) BERT_VEC_LENGTH = 1024 #", "print('Its performance on the test set is:') for metric in test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric])))", "of all scores input = Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu' in device: input = input.to('cuda')", "'tau_p_dev', 'rho_dev_global', 'pcc_dev_global', 'tau_dev_global', 'rho_test', 'rho_p_test', 'pcc_test', 'pcc_p_test', 'tau_test', 'tau_p_test', 'rho_test_global', 'pcc_test_global', 'tau_test_global']", "s_text # save in dictionary entries_text[article_id] = temp_entry for article_id in entries: entry", "= (pref / (pref[0] + pref[1])).tolist() if target_type == 'binary': if pref[0] >", "print(\"==Train==\") # results_train = test_rewarder(all_vec_dic, train, deep_model, device) results_train = test_rewarder(all_vec_dic, train_anno, deep_model,", "if double_prefs: pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) else: # include", "target_batch, deep_model, optimiser, device) loss_list.append(loss) return np.mean(loss_list) def test_rewarder(vec_list, human_scores, model, device, plot_file=None):", "pred_scores), axis=0) # pred_scores_all += pred_scores.tolist() rho, rho_p = spearmanr(true_scores, pred_scores) pcc, pcc_p", "entry[summ_ids[i]] < entry[summ_ids[j]]: pref = [0, 1] else: pref = [0.5, 0.5] #", "elif entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [0, 1] # else: # #", "depending on the mode, use binary target, or graded one pref = (pref", "epoch_num, batch_size, train_type, train_percent, dev_percent, learn_rate, model_type, device, seed, file_name = parse_args( argv[1:])", "lr=learn_rate) return deep_model, optimiser else: return deep_model def deep_pair_train(vec_list, target, deep_model, optimiser, device):", "/ 2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length / 2), 1), ) if learn_rate is not None:", "epoch no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size, train_type, train_percent, seed, learn_rate, model_type,", "== int(entry_keys[i][8]) and pair['summ_id_i'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref = [0,", "scores') ax.set_ylabel('predicted scores') xticklabels = true_scores_all ax.set_xticks(true_scores_all) print(\"violin plot written to: %s\" %", "{}! Make sure the sum is below 1.0!'.format( train_percent + dev_percent)) exit(1) BERT_VEC_LENGTH", "print(pair_list) topic_count += 1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count)", "unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) else: # include the pref in the reverse order by", "an error here before since j started from 1, to prevent i,j=0,0. but", "article_prefs.items(): # depending on the mode, use binary target, or graded one pref", "pcc, pcc_p = pearsonr(true_scores, pred_scores) tau, tau_p = kendalltau(true_scores, pred_scores) if not (math.isnan(rho)", "print(\"summ\", summ_count) # print(pair_list) return pair_list def build_human_pair_scores(pair_list): human_pair_scores = {} for entry", "to False def build_pairs_majority_preferences(entries, sorted_scores, target_type='graded', ignore_ties=False, randomize_pref_order=False, double_prefs=False): pair_list = [] topic_count", "FOUND: TEXT i\", text_i, \"TEXT j\", text_i) continue # get the unique summ", ") else: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length / 2)), torch.nn.ReLU(), torch.nn.Linear(int(vec_length / 2),", "vector of the specific summary pair. create a new entry if not existing", "csv_exists is False: writer.writerow(csv_column_names) np.random.seed(seed=seed) random.seed(seed) torch.random.manual_seed(seed) torch.manual_seed(seed) if train_percent + dev_percent >=", "summ_ids[j], pref)) continue elif pair['summ_id_j'] == int(entry_keys[i][8]) and pair['summ_id_i'] == int(entry_keys[j][8]): if pair['pref']", "int(entry_keys[i][8]) and pair['summ_id_i'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref = [0, 1]", "if not existing article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair, np.array([0, 0])) + np.array(pref) # transform to", "1) * batch_size] target_batch = shuffled_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch", "batch_size:(pointer + 1) * batch_size] target_batch = [ee[-1] for ee in target_batch] if", "the specific summary pair. create a new entry if not existing article_prefs[unique_summ_id_pair] =", "# print(value_variables) softmax_layer = torch.nn.Softmax(dim=1) pred = softmax_layer(value_variables) # print(pred) # print(np.array(target).shape, np.array(target).reshape(-1,", "writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx = np.argmax(pcc_list) best_result = pcc_list[idx] print('\\n======Best results come from", "read_pair_anno_scores() # train, dev, test, all = parse_split_data(sorted_scores, train_percent, dev_percent) train, dev, test,", "ignore_ties: # include the pref two times, once in one direction and once", "text_i == text_j: # print(\"DUPLICATE FOUND: TEXT i\", text_i, \"TEXT j\", text_i) continue", "= str(entry[1]) sum_id_j = str(entry[2]) pref = entry[3] summ_entry = {} if article_id", "unique_summ_id_pair[1], pref)) else: # include the pref in the reverse order by chance.", "else: # from epoch 1 on, receive the data and learn from it.", "deep_model, optimiser else: return deep_model def deep_pair_train(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape)", "else: if pref == [1, 0]: summ_entry[sum_id_i] = 1 summ_entry[sum_id_j] = 0 else:", "article_vec = list(vecs[aid]['article']) s1_vec = list(vecs[aid][sid1]) s2_vec = list(vecs[aid][sid2]) pair_vec_list.append([article_vec + s1_vec, article_vec", "to tuple, otherwise its not hashable for the dict unique_summ_id_pair = tuple(unique_summ_id_pair) #", "double_prefs are only relevant if the learning function learns f(s0,s1)=pref. in our case,", "range(len(summ_ids)): for j in range(len(summ_ids)): # run through dictionary containing summ_ids and matching", "seed number', default='1') ap.add_argument('-fn', '--file_name', type=str, help='file name for csv output', default='BetterRewardsStatistics_test.csv') args", "if you use bert-base deep_model, optimiser = build_model(model_type, BERT_VEC_LENGTH * 2, learn_rate) if", "test, all def build_model(model_type, vec_length, learn_rate=None): if 'linear' in model_type: deep_model = torch.nn.Sequential(", "[1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref = [0, 1] pair_list.append((article_id,", "str(entry[2]) pref = entry[3] summ_entry = {} if article_id in human_pair_scores: if pref", "batch_size, train_type, train_percent, dev_percent, learn_rate, model_type, device, seed, file_name = parse_args( argv[1:]) print('\\n=====Arguments====')", "# get the unique summ ids unique_summ_id_pair = [summ2id[text_i], summ2id[text_j]] # some debug", "human_scores[article_id] summ_ids = list(entry.keys()) if len(summ_ids) < 2: continue concat_vecs = [] true_scores", "then there was a last batch with [] causing an exception vec_batch =", "loss_dev, loss_test) # Train-Data only print(\"==Train==\") # results_train = test_rewarder(all_vec_dic, train, deep_model, device)", "import read_sorted_scores, read_pair_anno_scores, read_articles, \\ read_processed_scores, read_scores from scipy.stats import spearmanr, pearsonr, kendalltau", "def pair_train_rewarder(vec_dic, pairs, deep_model, optimiser, loss_only, batch_size=32, device='cpu'): loss_list = [] shuffled_pairs =", "# skip if it is a tie and you want to ignore ties", "[], 'rho_p': [], 'pcc': [], 'pcc_p': [], 'tau': [], 'tau_p': [], 'rho_global': [],", "and distributions of true values to predicted score') ax.set_xlabel('true scores') ax.set_ylabel('predicted scores') xticklabels", "but this also lead to i,j=x,0 never be chosen the situation i=j is", "args.batch_size, args.train_type, args.train_percent, args.dev_percent, args.learn_rate, args.model_type, args.device, args.seed, args.file_name def main(argv): epoch_num, batch_size,", "aid, sid1, sid2, _ in pairs: article_vec = list(vecs[aid]['article']) s1_vec = list(vecs[aid][sid1]) s2_vec", "entry_keys = list(entry.keys()) # get pair preference from pair_anno_scores for pair in pair_anno_scores[article_id]:", "tie and you want to ignore ties if pref[0] != 0.5 or not", "test_pairs = build_pairs(test) # without majority preferences but with pair anno train_pairs =", "# results_train = test_rewarder(all_vec_dic, train, deep_model, device) results_train = test_rewarder(all_vec_dic, train_anno, deep_model, device)", "sorted_scores, pair_anno_scores) # dev_pairs = build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores) # test_pairs = build_anno_pairs_majority_preferences(test, sorted_scores,", "{'rho': [], 'rho_p': [], 'pcc': [], 'pcc_p': [], 'tau': [], 'tau_p': [], 'rho_global':", "kendalltau(true_scores_all, pred_scores_all)[0] if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau) if", "marker=\".\", s=3, alpha=0.5) ax.set_title('Comparison and distributions of true values to predicted score') ax.set_xlabel('true", "from scorer.data_helper.json_reader import read_sorted_scores, read_pair_anno_scores, read_articles, \\ read_processed_scores, read_scores from scipy.stats import spearmanr,", "for unique_summ_id_pair, pref in article_prefs.items(): # depending on the mode, use binary target,", "key == summ_ids[i]: # text_i = value # elif key == summ_ids[j]: #", "prevent i,j=0,0. but this also lead to i,j=x,0 never be chosen the situation", "learn_rate, model_type, len(train_pairs), len(dev_pairs), len(test_pairs), ii, loss_train, loss_dev, loss_test] print('--> losses (train,dev,test)', loss_train,", "{}'.format(device)) print('seed {}'.format(seed)) print('file name {}'.format(file_name)) print('=====Arguments====\\n') csv_column_names = ['seed', 'learn_rate', 'model_type', 'train_pairs',", "or not ignore_ties: # include the pref two times, once in one direction", "PyUnreachableCode if False: print(\"%s vs. %s (IDs %s vs. %s)\" % ( summ_ids[i],", "bool(random.getrandbits(1)): pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) else: pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) topic_count += 1", "target, or graded one pref = (pref / (pref[0] + pref[1])).tolist() if target_type", "in device: input = input.to('cuda') value_variables = deep_model(input) # print(value_variables) softmax_layer = torch.nn.Softmax(dim=1)", "else: human_pair_scores[article_id][sum_id_j] = 1 else: if pref == [1, 0]: summ_entry[sum_id_i] = 1", "s_text = [s['sys_summ'] for s in scores_list if s['summ_id'] == sid][0] temp_entry['sys_summ' +", "%s)\" % ( summ_ids[i], summ_ids[j], unique_summ_id_pair[0], unique_summ_id_pair[1])) full_entry = sorted_scores[article_id] print(\" system %s", "showmedians=True, bw_method=0.2) ax.scatter(true_scores_all + np.random.normal(0, 0.1, pred_scores_all.shape[0]), pred_scores_all, marker=\".\", s=3, alpha=0.5) ax.set_title('Comparison and", "entry if article_id in train_ids: train[article_id] = entry elif article_id in dev_ids: dev[article_id]", "unique] # bw_methods determines how soft the distribution curve will be. lower values", "def build_pairs(entries): pair_list = [] topic_count = 0 summ_count = 0 for article_id", "pref = [0, 1] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue else: pref = [1,", "in the distribution of the score, e.g. if they are ordered if randomize_pref_order", "name for csv output', default='BetterRewardsStatistics_test.csv') args = ap.parse_args(argv) return args.epoch_num, args.batch_size, args.train_type, args.train_percent,", "else: pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) topic_count += 1 anno_count += len(summ_ids) summ_count +=", "topic_count = 0 for article_id, scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids =", "summary id with that text. that's the one we will use summ2id =", "resources import MODEL_WEIGHT_DIR from resources import OUTPUTS_DIR from matplotlib import pyplot as plt", "( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\" system %s with score %s (%s)\" % (", "new entry if not existing article_prefs[unique_summ_id_pair] = article_prefs.get(unique_summ_id_pair, np.array([0, 0])) + np.array(pref) #", "a unique key, so that (sys_summ0,sys_summ1) and (sys_summ1,sys_summ0) are the same if unique_summ_id_pair[1]", "epoch_num, batch_size, train_type, train_percent, learn_rate, model_type ) torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest model weight", "target for unique_summ_id_pair, pref in article_prefs.items(): # depending on the mode, use binary", "print(\"topics in parse_split_data\", topic_count) return train, dev, test, all def build_model(model_type, vec_length, learn_rate=None):", "learn from it. the loss is still the loss before fed with the", "deep_model, optimiser, device) else: loss = deep_pair_train(vec_batch, target_batch, deep_model, optimiser, device) loss_list.append(loss) return", "{}'.format(file_name)) print('=====Arguments====\\n') csv_column_names = ['seed', 'learn_rate', 'model_type', 'train_pairs', 'dev_pairs', 'test_pairs', 'epoch_num', 'loss_train', 'loss_dev',", "%s with score %s (%s) vs.\" % ( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\" system", "print(\"DUPLICATE FOUND: TEXT i\", text_i, \"TEXT j\", text_i) continue # get the unique", "1 else: human_pair_scores[article_id][sum_id_j] = 1 else: if pref == [1, 0]: summ_entry[sum_id_i] =", "+ 1 else: human_pair_scores[article_id][sum_id_i] = 1 else: if sum_id_j in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] +", "# pred_scores_all += pred_scores.tolist() rho, rho_p = spearmanr(true_scores, pred_scores) pcc, pcc_p = pearsonr(true_scores,", "print('total number of pairs built: {}'.format(len(vec_pairs))) for pointer in range(int((len( pairs) - 1)", "tqdm import tqdm import pickle from scorer.data_helper.json_reader import read_sorted_scores, read_pair_anno_scores, read_articles, \\ read_processed_scores,", "the train/dev/test set sorted_scores = read_sorted_scores() # read pair anno scores pair_anno_scores =", "[]} true_scores_all = [] pred_scores_all = np.array([]) # print(human_scores) # pred_scores_all = []", "[], 'tau_global': []} true_scores_all = [] pred_scores_all = np.array([]) # print(human_scores) # pred_scores_all", "csv_column_names = ['seed', 'learn_rate', 'model_type', 'train_pairs', 'dev_pairs', 'test_pairs', 'epoch_num', 'loss_train', 'loss_dev', 'loss_test', 'rho_train',", "+ '_onTest.pdf')) test_rewarder(all_vec_dic, train, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTrain.pdf')) test_rewarder(all_vec_dic, dev, deep_model,", "summ_entry return human_pair_scores # randomize_pref_order and double_prefs are only relevant if the learning", "= parse_split_data_balanced(sorted_scores, train_percent, dev_percent) # without majority preferences # train_pairs = build_pairs(train) #", "import pyplot as plt import csv def parse_split_data(sorted_scores, train_percent, dev_percent, prompt='structure'): train =", "type=str, help='file name for csv output', default='BetterRewardsStatistics_test.csv') args = ap.parse_args(argv) return args.epoch_num, args.batch_size,", "# sort the ids so that we get a unique key, so that", "scores') xticklabels = true_scores_all ax.set_xticks(true_scores_all) print(\"violin plot written to: %s\" % plot_file) plt.savefig(plot_file)", "'pcc_global': [], 'tau_global': []} true_scores_all = [] pred_scores_all = np.array([]) # print(human_scores) #", "csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") # results = test_rewarder(all_vec_dic, dev, deep_model, device) results = test_rewarder(all_vec_dic, dev_anno,", "0: # do not train in epoch 0, just evaluate the performance of", "pred_scores_all=np.array(pred_scores_all) unique = np.sort(np.unique(true_scores_all)) data_to_plot = [pred_scores_all[true_score == true_scores_all] for true_score in unique]", "results['rho_global'].append(rho) results['pcc_global'].append(pcc) results['tau_global'].append(tau) if plot_file is not None: fig, ax = plt.subplots() #", "= build_pairs(dev) # test_pairs = build_pairs(test) # without majority preferences but with pair", "elif pair['summ_id_j'] == int(entry_keys[i][8]) and pair['summ_id_i'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref", "dev = {} test = {} all = {} topic_count = 0 article_ids", "preferences # train_pairs = build_pairs_majority_preferences(train, sorted_scores) # dev_pairs = build_pairs_majority_preferences(dev, sorted_scores) # test_pairs", "batch_size, train_type, train_percent, learn_rate, model_type ) torch.save(weights_list[idx], os.path.join(MODEL_WEIGHT_DIR, model_weight_name)) print('\\nbest model weight saved", "metric in results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric])) writer.writerow(csv_row) pcc_list.append(np.mean(results['pcc'])) weights_list.append(copy.deepcopy(deep_model.state_dict())) idx = np.argmax(pcc_list) best_result", "vec_batch = vec_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch = shuffled_pairs[pointer *", "= spearmanr(true_scores, pred_scores) pcc, pcc_p = pearsonr(true_scores, pred_scores) tau, tau_p = kendalltau(true_scores, pred_scores)", "build_anno_pairs(test, pair_anno_scores) # with majority preferences # train_pairs = build_pairs_majority_preferences(train, sorted_scores) # dev_pairs", "if sum_id_j in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] + 1 else: human_pair_scores[article_id][sum_id_j] = 1 else: if", "pairs: article_vec = list(vecs[aid]['article']) s1_vec = list(vecs[aid][sid1]) s2_vec = list(vecs[aid][sid2]) pair_vec_list.append([article_vec + s1_vec,", "== j or text_i == text_j: # print(\"DUPLICATE FOUND: TEXT i\", text_i, \"TEXT", "lower values are more sharp ax.violinplot(data_to_plot, showmeans=True, showmedians=True, bw_method=0.2) ax.scatter(true_scores_all + np.random.normal(0, 0.1,", "without majority preferences # train_pairs = build_pairs(train) # dev_pairs = build_pairs(dev) # test_pairs", "for j in range(len(summ_ids)): if i == j: continue if entry[summ_ids[i]] > entry[summ_ids[j]]:", "pred_scores_all)[0] pcc = pearsonr(true_scores_all, pred_scores_all)[0] tau = kendalltau(true_scores_all, pred_scores_all)[0] if not (math.isnan(rho) or", "= entry elif rand < train_percent + dev_percent: dev[article_id] = entry else: test[article_id]", "rand = random.random() all[article_id] = entry if rand < train_percent: train[article_id] = entry", "= build_pairs(test) # without majority preferences but with pair anno train_pairs = build_anno_pairs(train,", "and (sys_summ1,sys_summ0) are the same if unique_summ_id_pair[1] < unique_summ_id_pair[0]: unique_summ_id_pair = unique_summ_id_pair[::-1] pref", "train_percent + dev_percent >= 1.: print('ERROR! Train data percentage plus dev data percentage", "results_test = test_rewarder(all_vec_dic, test_anno, deep_model, device) for metric in results_test: print('{}\\t{}'.format(metric, np.mean(results_test[metric]))) csv_row.append(np.mean(results_test[metric]))", "summ_ids = [s['summ_id'] for s in scores_list] for sid in summ_ids: # get", "= vec_pairs[pointer * batch_size:(pointer + 1) * batch_size] target_batch = shuffled_pairs[pointer * batch_size:(pointer", "f(s0)=pref[0] and f(s1)=pref[1], so this should be set to False def build_pairs_majority_preferences(entries, sorted_scores,", "full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort() if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0] elif entry[summ_ids[i]]", "0])) + np.array(pref) # transform to target for unique_summ_id_pair, pref in article_prefs.items(): #", "scores for topic to list of all scores input = Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu'", "i == j: continue # get keys from dictionary entry_keys = list(entry.keys()) #", "ii in range(epoch_num + 1): print('\\n=====EPOCH {}====='.format(ii)) if ii == 0: # do", "by chance. this might be necessary if there is a bias in the", "num_articles = len(article_ids) train_ids = article_ids[0:int(train_percent * num_articles)] dev_ids = article_ids[int(train_percent * num_articles):int((train_percent", "in device: target_variables = target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables) #", "* 2, learn_rate) if 'gpu' in device: deep_model.to('cuda') torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark =", "# change this to 768 if you use bert-base deep_model, optimiser = build_model(model_type,", "ap.add_argument('-fn', '--file_name', type=str, help='file name for csv output', default='BetterRewardsStatistics_test.csv') args = ap.parse_args(argv) return", "0]: if sum_id_i in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_i] + 1 else: human_pair_scores[article_id][sum_id_i] = 1 else:", "default=32) ap.add_argument('-tt', '--train_type', type=str, help='pairwise or regression', default='pairwise') ap.add_argument('-tp', '--train_percent', type=float, help='how many", "type=str, help='pairwise or regression', default='pairwise') ap.add_argument('-tp', '--train_percent', type=float, help='how many data used for", "%s (%s) vs.\" % ( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]])) print(\" system %s with score", "true_scores_all += true_scores # add scores for topic to list of all scores", "randomize_pref_order and double_prefs are only relevant if the learning function learns f(s0,s1)=pref. in", "how soft the distribution curve will be. lower values are more sharp ax.violinplot(data_to_plot,", "= true_scores_all ax.set_xticks(true_scores_all) print(\"violin plot written to: %s\" % plot_file) plt.savefig(plot_file) return results", "= {} if article_id in human_pair_scores: if pref == [1, 0]: if sum_id_i", "= ['seed', 'learn_rate', 'model_type', 'train_pairs', 'dev_pairs', 'test_pairs', 'epoch_num', 'loss_train', 'loss_dev', 'loss_test', 'rho_train', 'rho_p_train',", "ties. doesnt change much. low prio # pref = [0.5, 0.5] # sort", "build_human_pair_scores(train_pairs) dev_anno = build_human_pair_scores(dev_pairs) test_anno = build_human_pair_scores(test_pairs) print(len(train_pairs), len(dev_pairs), len(test_pairs)) # read bert", "for j in range(len(summ_ids)): # run through dictionary containing summ_ids and matching text", "ap.add_argument('-b', '--batch_size', type=int, default=32) ap.add_argument('-tt', '--train_type', type=str, help='pairwise or regression', default='pairwise') ap.add_argument('-tp', '--train_percent',", "pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) else: pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) topic_count += 1 anno_count", "print(value_variables) softmax_layer = torch.nn.Softmax(dim=1) pred = softmax_layer(value_variables) # print(pred) # print(np.array(target).shape, np.array(target).reshape(-1, 2,", "pref = pref[::-1] # convert to tuple, otherwise its not hashable for the", "= {} # still run through all pairs # really iterate over all", "test, all def parse_split_data_balanced(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev = {}", "= [1, 0] # elif entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref = [0, 1]", "True, batch_size, device) else: # from epoch 1 on, receive the data and", "2, 1).shape) target_variables = Variable(torch.from_numpy(np.array(target)).float()).view(-1, 2, 1) # print(target_variables) if 'gpu' in device:", "efficiently, but who cares... rand = random.random() all[article_id] = entry if rand <", "= [s['summ_id'] for s in scores_list] for sid in summ_ids: # get summary", "= 1 else: if sum_id_j in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] + 1 else: human_pair_scores[article_id][sum_id_j] =", "else: pref = [0.5, 0.5] # if entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref =", "# print(input.shape) # print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape) pred_scores = model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all = np.concatenate((pred_scores_all,", "[], 'pcc': [], 'pcc_p': [], 'tau': [], 'tau_p': [], 'rho_global': [], 'pcc_global': [],", "print(\" system %s with score %s (%s) vs.\" % ( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'], entry[summ_ids[i]]))", "= s_text # save in dictionary entries_text[article_id] = temp_entry for article_id in entries:", "dictionary entries_text[article_id] = temp_entry for article_id in entries: entry = entries[article_id] summ_ids =", "'rho_dev', 'rho_p_dev', 'pcc_dev', 'pcc_p_dev', 'tau_dev', 'tau_p_dev', 'rho_dev_global', 'pcc_dev_global', 'tau_dev_global', 'rho_test', 'rho_p_test', 'pcc_test', 'pcc_p_test',", "summ_ids = list(entry.keys()) if len(summ_ids) < 2: continue concat_vecs = [] true_scores =", "= pickle.load(ff) pcc_list = [] weights_list = [] for ii in range(epoch_num +", "solved otherwise for i in range(len(summ_ids)): for j in range(len(summ_ids)): # run through", "print(np.array(concat_vecs).shape) # print(entry[summ_ids[i]]) true_scores.append(entry[summ_ids[i]]) true_scores_all += true_scores # add scores for topic to", "model (sanity check and baseline) loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, True, batch_size,", "(sanity check and baseline) loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, True, batch_size, device)", "print(input) # print(input.shape) # print(model(input).data.cpu().numpy()) # print(model(input).data.cpu().numpy().shape) pred_scores = model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all =", "if plot_file is not None: fig, ax = plt.subplots() # true_scores_all=np.array(true_scores_all) # pred_scores_all=np.array(pred_scores_all)", "'tau_test_global'] # check if csv_file exists if path.exists(file_name): csv_exists = True else: csv_exists", "in summ_ids} # put here the prefs for this article article_prefs = {}", "# print(input) if 'gpu' in device: input = input.to('cuda') value_variables = deep_model(input) #", "'--batch_size', type=int, default=32) ap.add_argument('-tt', '--train_type', type=str, help='pairwise or regression', default='pairwise') ap.add_argument('-tp', '--train_percent', type=float,", "= torch.nn.Softmax(dim=1) pred = softmax_layer(value_variables) # print(pred) # print(np.array(target).shape, np.array(target).reshape(-1, 2, 1).shape) target_variables", "in human_pair_scores[article_id]: human_pair_scores[article_id][sum_id_j] + 1 else: human_pair_scores[article_id][sum_id_j] = 1 else: if pref ==", "summ_entry[sum_id_j] = 1 human_pair_scores[article_id] = summ_entry return human_pair_scores # randomize_pref_order and double_prefs are", "model_weight_name)) print('\\nbest model weight saved to: {}'.format(os.path.join(MODEL_WEIGHT_DIR, model_weight_name))) if __name__ == '__main__': main(sys.argv)", "# build human pair scores for pairs train_anno = build_human_pair_scores(train_pairs) dev_anno = build_human_pair_scores(dev_pairs)", "we could completely ignore ties. doesnt change much. low prio # pref =", "test set is:') for metric in test_results: print('{}\\t{}'.format(metric, np.mean(test_results[metric]))) model_weight_name = 'pcc{0:.4f}_'.format(np.mean(test_results['pcc'])) model_weight_name", "'--model_type', type=str, help='deep/linear', default='linear') ap.add_argument('-dv', '--device', type=str, help='cpu/gpu', default='gpu') ap.add_argument('-se', '--seed', type=int, help='random", "entry elif rand < train_percent + dev_percent: dev[article_id] = entry else: test[article_id] =", "check if text is identical, if yes skip if i == j or", "# add up the pref to the total pref vector of the specific", "sorted_scores[article_id] print(\" system %s with score %s (%s) vs.\" % ( full_entry[i]['sys_name'], full_entry[i]['scores']['redundancy'],", "( full_entry[j]['sys_name'], full_entry[j]['scores']['redundancy'], entry[summ_ids[j]])) print( \" \\\"%s...\\\" vs. \\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) #", "in range(len(summ_ids)): article_vec = list(vec_list[article_id]['article']) summ_vec = list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec", "in model_type: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, 1), ) else: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length,", "1, to prevent i,j=0,0. but this also lead to i,j=x,0 never be chosen", "from os import path import argparse import random import copy from tqdm import", "total pref vector of the specific summary pair. create a new entry if", "summ_ids = list(entry.keys()) # mapping from summary text to last summary id with", "False with open(file_name, 'a', newline='') as csv_file: writer = csv.writer(csv_file) # if a", "entries_text = {} # get summary text and matching id for article_id, scores_list", "continue # get keys from dictionary entry_keys = list(entry.keys()) # get pair preference", "still run through all pairs # really iterate over all pairs. there was", "entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1, 0] elif entry[summ_ids[i]] < entry[summ_ids[j]]: pref =", "there was a last batch with [] causing an exception vec_batch = vec_pairs[pointer", "\\ read_processed_scores, read_scores from scipy.stats import spearmanr, pearsonr, kendalltau import math from torchvision", "= 0 summ_count = 0 entries_text = {} # get summary text and", "initialized model (sanity check and baseline) loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, True,", "human scores and vectors for summaries/docs, and split the train/dev/test set sorted_scores =", "is not None: optimiser = torch.optim.Adam(deep_model.parameters(), lr=learn_rate) return deep_model, optimiser else: return deep_model", "it is a tie and you want to ignore ties if pref[0] !=", "= random.random() all[article_id] = entry if article_id in train_ids: train[article_id] = entry elif", "graded one pref = (pref / (pref[0] + pref[1])).tolist() if target_type == 'binary':", "print('ERROR! Train data percentage plus dev data percentage is {}! Make sure the", "np.array([]) # print(human_scores) # pred_scores_all = [] for article_id in human_scores: entry =", "= entry if rand < train_percent: train[article_id] = entry elif rand < train_percent", "add scores for topic to list of all scores input = Variable(torch.from_numpy(np.array(concat_vecs)).float()) if", "device) loss_test = pair_train_rewarder(all_vec_dic, test_pairs, deep_model, optimiser, True, batch_size, device) csv_row = [seed,", "pref = [1, 0] elif entry[summ_ids[i]] < entry[summ_ids[j]]: pref = [0, 1] else:", "# still run through all pairs # really iterate over all pairs. there", "[] for article_id in human_scores: entry = human_scores[article_id] summ_ids = list(entry.keys()) if len(summ_ids)", "pcc_list[idx] print('\\n======Best results come from epoch no. {}====='.format(idx)) deep_model.load_state_dict(weights_list[idx]) output_pattern = 'batch{}_{}_trainPercent{}_seed{}_lrate{}_{}_epoch{}'.format( batch_size,", "+ s2_vec]) return pair_vec_list def pair_train_rewarder(vec_dic, pairs, deep_model, optimiser, loss_only, batch_size=32, device='cpu'): loss_list", "pref[::-1])) else: pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1], pref)) topic_count += 1 anno_count += len(summ_ids) summ_count", "ax.set_xticks(true_scores_all) print(\"violin plot written to: %s\" % plot_file) plt.savefig(plot_file) return results def parse_args(argv):", "in the other direction if double_prefs: pair_list.append((article_id, unique_summ_id_pair[1], unique_summ_id_pair[0], pref[::-1])) pair_list.append((article_id, unique_summ_id_pair[0], unique_summ_id_pair[1],", "data percentage plus dev data percentage is {}! Make sure the sum is", "key, value in entries_text[article_id].items(): # get text for current summaries i and j", "'pcc_dev_global', 'tau_dev_global', 'rho_test', 'rho_p_test', 'pcc_test', 'pcc_p_test', 'tau_test', 'tau_p_test', 'rho_test_global', 'pcc_test_global', 'tau_test_global'] # check", "that can be done more efficiently, but who cares... # rand = random.random()", "with the training examples loss_train = pair_train_rewarder(all_vec_dic, train_pairs, deep_model, optimiser, False, batch_size, device)", "# pref = [0.5, 0.5] # sort the ids so that we get", "# else: # # todo we could completely ignore ties. doesnt change much.", "device) loss_list.append(loss) return np.mean(loss_list) def test_rewarder(vec_list, human_scores, model, device, plot_file=None): results = {'rho':", "i and j # if key == summ_ids[i]: # text_i = value #", "= test_rewarder(all_vec_dic, test, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTest.pdf')) test_rewarder(all_vec_dic, train, deep_model, device,", "1): # there was a bug here. when len(pairs) was a vielfaches of", "loss.backward() optimiser.step() return loss.cpu().item() def deep_pair_train_loss_only(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input", "value_variables = deep_model(input) # print(value_variables) softmax_layer = torch.nn.Softmax(dim=1) pred = softmax_layer(value_variables) # print(pred)", "text and matching id for article_id, scores_list in tqdm(sorted_scores.items()): temp_entry = {} summ_ids", "# get keys from dictionary entry_keys = list(entry.keys()) # get pair preference from", "0 else: summ_entry[sum_id_i] = 0 summ_entry[sum_id_j] = 1 human_pair_scores[article_id] = summ_entry return human_pair_scores", "= build_pairs_majority_preferences(dev, sorted_scores) # test_pairs = build_pairs_majority_preferences(test, sorted_scores) # with majority preferences and", "= target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) return loss.cpu().item()", "here the prefs for this article article_prefs = {} # still run through", "entry in pair_list: article_id = str(entry[0]) sum_id_i = str(entry[1]) sum_id_j = str(entry[2]) pref", "1.0!'.format( train_percent + dev_percent)) exit(1) BERT_VEC_LENGTH = 1024 # change this to 768", "= unique_summ_id_pair[::-1] pref = pref[::-1] # convert to tuple, otherwise its not hashable", "necessary if there is a bias in the distribution of the score, e.g.", "'pcc_train', 'pcc_p_train', 'tau_train', 'tau_p_train', 'rho_train_global', 'pcc_train_global', 'tau_train_global', 'rho_dev', 'rho_p_dev', 'pcc_dev', 'pcc_p_dev', 'tau_dev', 'tau_p_dev',", "# without majority preferences but with pair anno train_pairs = build_anno_pairs(train, pair_anno_scores) dev_pairs", "in one direction and once in the other direction if double_prefs: pair_list.append((article_id, unique_summ_id_pair[1],", "ap.add_argument('-mt', '--model_type', type=str, help='deep/linear', default='linear') ap.add_argument('-dv', '--device', type=str, help='cpu/gpu', default='gpu') ap.add_argument('-se', '--seed', type=int,", "unique_summ_id_pair = tuple(unique_summ_id_pair) # add up the pref to the total pref vector", "to 768 if you use bert-base deep_model, optimiser = build_model(model_type, BERT_VEC_LENGTH * 2,", "torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # read human scores and vectors for", "summ_ids[i], summ_ids[j], pref)) # print(pair_list) topic_count += 1 summ_count = summ_count + len(summ_ids)", "else: # include the pref in the reverse order by chance. this might", "(pref[0] + pref[1])).tolist() if target_type == 'binary': if pref[0] > pref[1]: pref =", "if s['summ_id'] == sid][ 0] # that can be done more efficiently, but", "scores input = Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu' in device: input = input.to('cuda') model.eval() with", "results['tau'].append(tau) results['tau_p'].append(tau_p) rho = spearmanr(true_scores_all, pred_scores_all)[0] pcc = pearsonr(true_scores_all, pred_scores_all)[0] tau = kendalltau(true_scores_all,", "* num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id, scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids", "if target_type == 'binary': if pref[0] > pref[1]: pref = [1, 0] elif", "len(test_pairs)) # read bert vectors with open('data/doc_summ_bert_vectors.pkl', 'rb') as ff: all_vec_dic = pickle.load(ff)", "article_vec = list(vec_list[article_id]['article']) summ_vec = list(vec_list[article_id][summ_ids[i]]) # print(np.array(concat_vecs).shape, np.array(article_vec).shape, np.array(summ_vec).shape) concat_vecs.append(article_vec + summ_vec)", "build_anno_pairs_majority_preferences(test, sorted_scores, pair_anno_scores) # build human pair scores for pairs train_anno = build_human_pair_scores(train_pairs)", "test_results = test_rewarder(all_vec_dic, test, deep_model, device, os.path.join(OUTPUTS_DIR, output_pattern + '_onTest.pdf')) test_rewarder(all_vec_dic, train, deep_model,", "# pred_scores_all=np.array(pred_scores_all) unique = np.sort(np.unique(true_scores_all)) data_to_plot = [pred_scores_all[true_score == true_scores_all] for true_score in", "entries_text[article_id].items(): # get text for current summaries i and j # if key", "deep_pair_train_loss_only(vec_list, target, deep_model, optimiser, device): # print(np.array(vec_list).shape) input = Variable(torch.from_numpy(np.array(vec_list)).float()) # print(input) if", "topic to list of all scores input = Variable(torch.from_numpy(np.array(concat_vecs)).float()) if 'gpu' in device:", "summ ids unique_summ_id_pair = [summ2id[text_i], summ2id[text_j]] # some debug output # noinspection PyUnreachableCode", "rand < train_percent: train[article_id] = entry elif rand < train_percent + dev_percent: dev[article_id]", "= [s['summ_id'] for s in scores_list] for sid in summ_ids: entry['sys_summ' + repr(sid)]", "true_scores.append(entry[summ_ids[i]]) true_scores_all += true_scores # add scores for topic to list of all", "if 'gpu' in device: deep_model.to('cuda') torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # read", "in results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") # results = test_rewarder(all_vec_dic, dev, deep_model, device)", "= list(entry.keys()) # get pair preference from pair_anno_scores for pair in pair_anno_scores[article_id]: if", "if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho'].append(rho) results['rho_p'].append(rho_p) results['pcc'].append(pcc) results['pcc_p'].append(pcc_p) results['tau'].append(tau) results['tau_p'].append(tau_p)", "# print(loss) return loss.cpu().item() def build_pairs(entries): pair_list = [] topic_count = 0 summ_count", "parse_args(argv): ap = argparse.ArgumentParser(\"arguments for summary sampler\") ap.add_argument('-e', '--epoch_num', type=int, default=50) ap.add_argument('-b', '--batch_size',", "human_pair_scores # randomize_pref_order and double_prefs are only relevant if the learning function learns", "parse_split_data_balanced(sorted_scores, train_percent, dev_percent, prompt='structure'): train = {} dev = {} test = {}", "summ_ids[j], pref)) continue topic_count += 1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count)", "= np.sort(np.unique(true_scores_all)) data_to_plot = [pred_scores_all[true_score == true_scores_all] for true_score in unique] # bw_methods", "summ_count += len(summ2id) print(\"topics\", topic_count) print(\"annotations\", anno_count) print(\"summ\", summ_count) print(\"summ pairs\", len(pair_list)) return", "article_id, scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids = [s['summ_id'] for s in", "= pair_train_rewarder(all_vec_dic, dev_pairs, deep_model, optimiser, True, batch_size, device) loss_test = pair_train_rewarder(all_vec_dic, test_pairs, deep_model,", "train[article_id] = entry elif article_id in dev_ids: dev[article_id] = entry else: test[article_id] =", "sort the ids so that we get a unique key, so that (sys_summ0,sys_summ1)", "# bw_methods determines how soft the distribution curve will be. lower values are", "model(input).data.cpu().numpy().reshape(1, -1)[0] pred_scores_all = np.concatenate((pred_scores_all, pred_scores), axis=0) # pred_scores_all += pred_scores.tolist() rho, rho_p", "random import copy from tqdm import tqdm import pickle from scorer.data_helper.json_reader import read_sorted_scores,", "entry[3] summ_entry = {} if article_id in human_pair_scores: if pref == [1, 0]:", "ap.add_argument('-se', '--seed', type=int, help='random seed number', default='1') ap.add_argument('-fn', '--file_name', type=str, help='file name for", "ap.add_argument('-dv', '--device', type=str, help='cpu/gpu', default='gpu') ap.add_argument('-se', '--seed', type=int, help='random seed number', default='1') ap.add_argument('-fn',", "\\\"%s...\\\"\" % (full_entry[i]['sys_summ'][:20], full_entry[j]['sys_summ'][:20])) # unique_summ_id_pair.sort() if entry[summ_ids[i]] > entry[summ_ids[j]]: pref = [1,", "dev_percent) # without majority preferences # train_pairs = build_pairs(train) # dev_pairs = build_pairs(dev)", "text # for key, value in entries_text[article_id].items(): # get text for current summaries", "pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs = build_pair_vecs(vec_dic, shuffled_pairs) # print('total number of pairs built: {}'.format(len(vec_pairs)))", "dev, deep_model, device) results = test_rewarder(all_vec_dic, dev_anno, deep_model, device) for metric in results:", "np.random.shuffle(shuffled_pairs) vec_pairs = build_pair_vecs(vec_dic, shuffled_pairs) # print('total number of pairs built: {}'.format(len(vec_pairs))) for", "vec_pairs = build_pair_vecs(vec_dic, shuffled_pairs) # print('total number of pairs built: {}'.format(len(vec_pairs))) for pointer", "len(test_pairs), ii, loss_train, loss_dev, loss_test] print('--> losses (train,dev,test)', loss_train, loss_dev, loss_test) # Train-Data", "exists if path.exists(file_name): csv_exists = True else: csv_exists = False with open(file_name, 'a',", "for article_id in human_scores: entry = human_scores[article_id] summ_ids = list(entry.keys()) if len(summ_ids) <", "= pairs[:] np.random.shuffle(shuffled_pairs) vec_pairs = build_pair_vecs(vec_dic, shuffled_pairs) # print('total number of pairs built:", "text_j: # print(\"DUPLICATE FOUND: TEXT i\", text_i, \"TEXT j\", text_i) continue # get", "target_batch, deep_model, optimiser, device) else: loss = deep_pair_train(vec_batch, target_batch, deep_model, optimiser, device) loss_list.append(loss)", "s['summ_id'] == sid][0] temp_entry['sys_summ' + repr(sid)] = s_text # save in dictionary entries_text[article_id]", "scipy.stats import spearmanr, pearsonr, kendalltau import math from torchvision import models from resources", "metric in results_train: print('{}\\t{}'.format(metric, np.mean(results_train[metric]))) csv_row.append(np.mean(results_train[metric])) print(\"==Dev==\") # results = test_rewarder(all_vec_dic, dev, deep_model,", "one we will use summ2id = {entries_text[article_id][summ_id]: summ_id for summ_id in summ_ids} #", "csv.writer(csv_file) # if a new csv_file is generated, write column names if csv_exists", "def build_pairs_majority_preferences(entries, sorted_scores, target_type='graded', ignore_ties=False, randomize_pref_order=False, double_prefs=False): pair_list = [] topic_count = 0", "= article_ids[int(train_percent * num_articles):int((train_percent + dev_percent) * num_articles)] # test_ids=article_ids[int((train_percent+dev_percent)*num_articles):] for article_id, scores_list", "build_pairs(test) # without majority preferences but with pair anno train_pairs = build_anno_pairs(train, pair_anno_scores)", "build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores) # dev_pairs = build_anno_pairs_majority_preferences(dev, sorted_scores, pair_anno_scores) # test_pairs = build_anno_pairs_majority_preferences(test,", "default='BetterRewardsStatistics_test.csv') args = ap.parse_args(argv) return args.epoch_num, args.batch_size, args.train_type, args.train_percent, args.dev_percent, args.learn_rate, args.model_type, args.device,", "device) else: loss = deep_pair_train(vec_batch, target_batch, deep_model, optimiser, device) loss_list.append(loss) return np.mean(loss_list) def", "some debug output # noinspection PyUnreachableCode if False: print(\"%s vs. %s (IDs %s", "# # todo we could completely ignore ties. doesnt change much. low prio", "pred_scores_all)[0] tau = kendalltau(true_scores_all, pred_scores_all)[0] if not (math.isnan(rho) or math.isnan(pcc) or math.isnan(tau)): results['rho_global'].append(rho)", "target_variables.to('cuda') loss_fn = torch.nn.BCELoss() loss = loss_fn(pred, target_variables) # print(loss) return loss.cpu().item() def", "= {} topic_count = 0 article_ids = list(sorted_scores.keys()) random.shuffle(article_ids) num_articles = len(article_ids) train_ids", "'gpu' in device: input = input.to('cuda') value_variables = deep_model(input) # print(value_variables) softmax_layer =", "[s['summ_id'] for s in scores_list] for sid in summ_ids: # get summary text", "get pair preference from pair_anno_scores for pair in pair_anno_scores[article_id]: if pair['summ_id_i'] == int(entry_keys[i][8])", "[s['summ_id'] for s in scores_list] for sid in summ_ids: entry['sys_summ' + repr(sid)] =", "math from torchvision import models from resources import MODEL_WEIGHT_DIR from resources import OUTPUTS_DIR", "in scores_list if s['summ_id'] == sid][0] temp_entry['sys_summ' + repr(sid)] = s_text # save", "'tau_p_test', 'rho_test_global', 'pcc_test_global', 'tau_test_global'] # check if csv_file exists if path.exists(file_name): csv_exists =", "as np import os from os import path import argparse import random import", "deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, 1), ) else: deep_model = torch.nn.Sequential( torch.nn.Linear(vec_length, int(vec_length /", "pearsonr, kendalltau import math from torchvision import models from resources import MODEL_WEIGHT_DIR from", "else: # # todo we could completely ignore ties. doesnt change much. low", "test_rewarder(all_vec_dic, dev_anno, deep_model, device) for metric in results: print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) # Test-Data", "anno scores pair_anno_scores = read_pair_anno_scores() # train, dev, test, all = parse_split_data(sorted_scores, train_percent,", "csv_exists = False with open(file_name, 'a', newline='') as csv_file: writer = csv.writer(csv_file) #", "in results: print('{}\\t{}'.format(metric, np.mean(results[metric]))) csv_row.append(np.mean(results[metric])) # Test-Data only print(\"==Test==\") # results_test = test_rewarder(all_vec_dic,", "with majority preferences and pair anno # train_pairs = build_anno_pairs_majority_preferences(train, sorted_scores, pair_anno_scores) #", "pref = [1, 0] pair_list.append((article_id, summ_ids[i], summ_ids[j], pref)) continue topic_count += 1 summ_count", "+ 1) * batch_size] target_batch = shuffled_pairs[pointer * batch_size:(pointer + 1) * batch_size]", "copy from tqdm import tqdm import pickle from scorer.data_helper.json_reader import read_sorted_scores, read_pair_anno_scores, read_articles,", "= pair_train_rewarder(all_vec_dic, test_pairs, deep_model, optimiser, True, batch_size, device) csv_row = [seed, learn_rate, model_type,", "with open('data/doc_summ_bert_vectors.pkl', 'rb') as ff: all_vec_dic = pickle.load(ff) pcc_list = [] weights_list =", "for this article article_prefs = {} # still run through all pairs #", "as ff: all_vec_dic = pickle.load(ff) pcc_list = [] weights_list = [] for ii", "with [] causing an exception vec_batch = vec_pairs[pointer * batch_size:(pointer + 1) *", "[seed, learn_rate, model_type, len(train_pairs), len(dev_pairs), len(test_pairs), ii, loss_train, loss_dev, loss_test] print('--> losses (train,dev,test)',", "will use summ2id = {entries_text[article_id][summ_id]: summ_id for summ_id in summ_ids} # put here", "rho = spearmanr(true_scores_all, pred_scores_all)[0] pcc = pearsonr(true_scores_all, pred_scores_all)[0] tau = kendalltau(true_scores_all, pred_scores_all)[0] if", "so this should be set to False def build_pairs_majority_preferences(entries, sorted_scores, target_type='graded', ignore_ties=False, randomize_pref_order=False,", "build_human_pair_scores(pair_list): human_pair_scores = {} for entry in pair_list: article_id = str(entry[0]) sum_id_i =", "pair_list def build_human_pair_scores(pair_list): human_pair_scores = {} for entry in pair_list: article_id = str(entry[0])", "len(summ2id) print(\"topics\", topic_count) print(\"annotations\", anno_count) print(\"summ\", summ_count) print(\"summ pairs\", len(pair_list)) return pair_list def", "ap.add_argument('-lr', '--learn_rate', type=float, help='learning rate', default=3e-4) ap.add_argument('-mt', '--model_type', type=str, help='deep/linear', default='linear') ap.add_argument('-dv', '--device',", "article_prefs.get(unique_summ_id_pair, np.array([0, 0])) + np.array(pref) # transform to target for unique_summ_id_pair, pref in", "torch.nn.ReLU(), torch.nn.Linear(int(vec_length / 2), 1), ) if learn_rate is not None: optimiser =", "+= 1 summ_count = summ_count + len(summ_ids) print(\"topics\", topic_count) print(\"summ\", summ_count) return pair_list", "summ2id[text_j]] # some debug output # noinspection PyUnreachableCode if False: print(\"%s vs. %s", "= random.random() all[article_id] = entry if rand < train_percent: train[article_id] = entry elif", "= 0 else: summ_entry[sum_id_i] = 0 summ_entry[sum_id_j] = 1 human_pair_scores[article_id] = summ_entry return", "true_scores_all = [] pred_scores_all = np.array([]) # print(human_scores) # pred_scores_all = [] for", "pair['summ_id_j'] == int(entry_keys[j][8]): if pair['pref'] == 1: pref = [1, 0] pair_list.append((article_id, summ_ids[i],", "0] # that can be done more efficiently, but who cares... rand =", "1] else: pref = [0.5, 0.5] # if entry[unique_summ_id_pair[0]] > entry[unique_summ_id_pair[1]]: # pref", "but who cares... # rand = random.random() all[article_id] = entry if article_id in", "0 for article_id, scores_list in tqdm(sorted_scores.items()): entry = {} summ_ids = [s['summ_id'] for" ]
[ "interactive shell',action='store_true') args = parser.parse_args() import ipaddress homenetwork = ipaddress.ip_network('192.168.0.0/24') homenetwork_router = ipaddress.ip_address('192.168.0.1')", "to simplify the data for privacy research') parser.add_argument('--nodnsseed', help='do not seed domains from", "data for privacy research') parser.add_argument('--nodnsseed', help='do not seed domains from dnsmasq history',action='store_true') parser.add_argument('--shell',", "not seed domains from dnsmasq history',action='store_true') parser.add_argument('--shell', help='Enable interactive shell',action='store_true') args = parser.parse_args()", "help='do not seed domains from dnsmasq history',action='store_true') parser.add_argument('--shell', help='Enable interactive shell',action='store_true') args =", "parser.add_argument('--shell', help='Enable interactive shell',action='store_true') args = parser.parse_args() import ipaddress homenetwork = ipaddress.ip_network('192.168.0.0/24') homenetwork_router", "parser.parse_args() import ipaddress homenetwork = ipaddress.ip_network('192.168.0.0/24') homenetwork_router = ipaddress.ip_address('192.168.0.1') aggregate_google=True # That is", "seed domains from dnsmasq history',action='store_true') parser.add_argument('--shell', help='Enable interactive shell',action='store_true') args = parser.parse_args() import", "research') parser.add_argument('--nodnsseed', help='do not seed domains from dnsmasq history',action='store_true') parser.add_argument('--shell', help='Enable interactive shell',action='store_true')", "domains from dnsmasq history',action='store_true') parser.add_argument('--shell', help='Enable interactive shell',action='store_true') args = parser.parse_args() import ipaddress", "ipaddress homenetwork = ipaddress.ip_network('192.168.0.0/24') homenetwork_router = ipaddress.ip_address('192.168.0.1') aggregate_google=True # That is a lot", "the data for privacy research') parser.add_argument('--nodnsseed', help='do not seed domains from dnsmasq history',action='store_true')", "ipaddress.ip_network('192.168.0.0/24') homenetwork_router = ipaddress.ip_address('192.168.0.1') aggregate_google=True # That is a lot of domains ignored_domains=[\"osoite.local\"]", "argparse parser = argparse.ArgumentParser(prog=\"connvis\",description='Web-based conntrack that tries to simplify the data for privacy", "args = parser.parse_args() import ipaddress homenetwork = ipaddress.ip_network('192.168.0.0/24') homenetwork_router = ipaddress.ip_address('192.168.0.1') aggregate_google=True #", "homenetwork = ipaddress.ip_network('192.168.0.0/24') homenetwork_router = ipaddress.ip_address('192.168.0.1') aggregate_google=True # That is a lot of", "import argparse parser = argparse.ArgumentParser(prog=\"connvis\",description='Web-based conntrack that tries to simplify the data for", "privacy research') parser.add_argument('--nodnsseed', help='do not seed domains from dnsmasq history',action='store_true') parser.add_argument('--shell', help='Enable interactive", "= argparse.ArgumentParser(prog=\"connvis\",description='Web-based conntrack that tries to simplify the data for privacy research') parser.add_argument('--nodnsseed',", "simplify the data for privacy research') parser.add_argument('--nodnsseed', help='do not seed domains from dnsmasq", "conntrack that tries to simplify the data for privacy research') parser.add_argument('--nodnsseed', help='do not", "from dnsmasq history',action='store_true') parser.add_argument('--shell', help='Enable interactive shell',action='store_true') args = parser.parse_args() import ipaddress homenetwork", "help='Enable interactive shell',action='store_true') args = parser.parse_args() import ipaddress homenetwork = ipaddress.ip_network('192.168.0.0/24') homenetwork_router =", "dnsmasq history',action='store_true') parser.add_argument('--shell', help='Enable interactive shell',action='store_true') args = parser.parse_args() import ipaddress homenetwork =", "tries to simplify the data for privacy research') parser.add_argument('--nodnsseed', help='do not seed domains", "= parser.parse_args() import ipaddress homenetwork = ipaddress.ip_network('192.168.0.0/24') homenetwork_router = ipaddress.ip_address('192.168.0.1') aggregate_google=True # That", "that tries to simplify the data for privacy research') parser.add_argument('--nodnsseed', help='do not seed", "argparse.ArgumentParser(prog=\"connvis\",description='Web-based conntrack that tries to simplify the data for privacy research') parser.add_argument('--nodnsseed', help='do", "parser = argparse.ArgumentParser(prog=\"connvis\",description='Web-based conntrack that tries to simplify the data for privacy research')", "for privacy research') parser.add_argument('--nodnsseed', help='do not seed domains from dnsmasq history',action='store_true') parser.add_argument('--shell', help='Enable", "parser.add_argument('--nodnsseed', help='do not seed domains from dnsmasq history',action='store_true') parser.add_argument('--shell', help='Enable interactive shell',action='store_true') args", "= ipaddress.ip_network('192.168.0.0/24') homenetwork_router = ipaddress.ip_address('192.168.0.1') aggregate_google=True # That is a lot of domains", "history',action='store_true') parser.add_argument('--shell', help='Enable interactive shell',action='store_true') args = parser.parse_args() import ipaddress homenetwork = ipaddress.ip_network('192.168.0.0/24')", "shell',action='store_true') args = parser.parse_args() import ipaddress homenetwork = ipaddress.ip_network('192.168.0.0/24') homenetwork_router = ipaddress.ip_address('192.168.0.1') aggregate_google=True", "import ipaddress homenetwork = ipaddress.ip_network('192.168.0.0/24') homenetwork_router = ipaddress.ip_address('192.168.0.1') aggregate_google=True # That is a" ]
[ "if not infer.code_sequence: continue correct = True for test in example.input_tests + example.tests:", "m.batch_processor(for_eval=True) m.args.max_beam_trees = 64 m.args.max_eval_trials = 64 i = 0 result = []", "test in example.input_tests + example.tests: try: log = the_executor.execute(infer.code_sequence, None, test['input']) if log.result", "continue e = dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0] e.ref_example = dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests,", "m.args.max_eval_trials = 64 i = 0 result = [] while i < len(baseline_report):", "= {'total': len(result), 'fixed': 0} refinement_results = [] for example, infer in result:", "restore_args(args) args.word_vocab = ',,/data/karel/word.vocab' m = karel_model.KarelLGRLRefineModel(args) batch_processor = m.batch_processor(for_eval=True) m.args.max_beam_trees = 64", "for example, infer in result: if not infer.code_sequence: continue correct = True for", "as e: correct = False break refinement_results.append(correct) if correct: stats['fixed'] += 1 print(float(stats['fixed'])", "i) res = m.inference(batch_processor(batch)) for example, infer in zip(batch, res): result.append((example, infer)) #", "',,/data/karel/word.vocab' m = karel_model.KarelLGRLRefineModel(args) batch_processor = m.batch_processor(for_eval=True) m.args.max_beam_trees = 64 m.args.max_eval_trials = 64", "\"\" with open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f: baseline_report = [] print(f.readline()) for line", "= [] print(f.readline()) for line in f: baseline_report.append(json.loads(line)) class Args(object): model_dir = BASE_DIR", "BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step = 250100 args = Args() restore_args(args) args.word_vocab = ',,/data/karel/word.vocab'", "from program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset.karel_runtime import KarelRuntime from program_synthesis.karel.models import karel_model from", "itertools import json import operator import os import re import sys from program_synthesis.karel.dataset", "= karel_model.KarelLGRLRefineModel(args) batch_processor = m.batch_processor(for_eval=True) m.args.max_beam_trees = 64 m.args.max_eval_trials = 64 i =", "f: baseline_report = [] print(f.readline()) for line in f: baseline_report.append(json.loads(line)) class Args(object): model_dir", "> 100: # break print(len(result), len(baseline_report)) the_executor = executor.KarelExecutor() stats = {'total': len(result),", "= BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step = 250100 args = Args() restore_args(args) args.word_vocab =", "correct = False break except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as e: correct = False break", "= \"\" with open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f: baseline_report = [] print(f.readline()) for", "class Args(object): model_dir = BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step = 250100 args = Args()", "if log.result != test['output']: correct = False break except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as e:", "32 and i < len(baseline_report): if baseline_report[i]['code']['info']['trees_checked'] == 1: i += 1 continue", "from program_synthesis.common.tools.saver import restore_args BASE_DIR = \"\" with open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f:", "= executor.KarelExecutor() stats = {'total': len(result), 'fixed': 0} refinement_results = [] for example,", "example.input_tests + example.tests: try: log = the_executor.execute(infer.code_sequence, None, test['input']) if log.result != test['output']:", "!= test['output']: correct = False break except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as e: correct =", "ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0] e.ref_example = dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests) batch.append(e) i +=", "= ',,/data/karel/word.vocab' m = karel_model.KarelLGRLRefineModel(args) batch_processor = m.batch_processor(for_eval=True) m.args.max_beam_trees = 64 m.args.max_eval_trials =", "import re import sys from program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset import executor from", "import os import re import sys from program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset import", "program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset.karel_runtime import KarelRuntime from program_synthesis.karel.models import karel_model from program_synthesis.common.tools.saver", "import karel_model from program_synthesis.common.tools.saver import restore_args BASE_DIR = \"\" with open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\")", "= [] while len(batch) < 32 and i < len(baseline_report): if baseline_report[i]['code']['info']['trees_checked'] ==", "model_dir = BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step = 250100 args = Args() restore_args(args) args.word_vocab", "i > 100: # break print(len(result), len(baseline_report)) the_executor = executor.KarelExecutor() stats = {'total':", "< len(baseline_report): batch = [] while len(batch) < 32 and i < len(baseline_report):", "+= 1 print(\"Starting batch (%d)...\" % i) res = m.inference(batch_processor(batch)) for example, infer", "= 64 i = 0 result = [] while i < len(baseline_report): batch", "import sys from program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset.karel_runtime import", "infer)) # if i > 100: # break print(len(result), len(baseline_report)) the_executor = executor.KarelExecutor()", "karel_model.KarelLGRLRefineModel(args) batch_processor = m.batch_processor(for_eval=True) m.args.max_beam_trees = 64 m.args.max_eval_trials = 64 i = 0", "infer.code_sequence: continue correct = True for test in example.input_tests + example.tests: try: log", "executor from program_synthesis.karel.dataset.karel_runtime import KarelRuntime from program_synthesis.karel.models import karel_model from program_synthesis.common.tools.saver import restore_args", "as f: baseline_report = [] print(f.readline()) for line in f: baseline_report.append(json.loads(line)) class Args(object):", "program_synthesis.karel.dataset.karel_runtime import KarelRuntime from program_synthesis.karel.models import karel_model from program_synthesis.common.tools.saver import restore_args BASE_DIR =", "= dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests) batch.append(e) i += 1 print(\"Starting batch (%d)...\"", "input_tests=e.input_tests, tests=e.tests) batch.append(e) i += 1 print(\"Starting batch (%d)...\" % i) res =", "= [] for example, infer in result: if not infer.code_sequence: continue correct =", "for example, infer in zip(batch, res): result.append((example, infer)) # if i > 100:", "e.ref_example = dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests) batch.append(e) i += 1 print(\"Starting batch", "program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset.karel_runtime import KarelRuntime from program_synthesis.karel.models", "res = m.inference(batch_processor(batch)) for example, infer in zip(batch, res): result.append((example, infer)) # if", "res): result.append((example, infer)) # if i > 100: # break print(len(result), len(baseline_report)) the_executor", "baseline_report = [] print(f.readline()) for line in f: baseline_report.append(json.loads(line)) class Args(object): model_dir =", "m = karel_model.KarelLGRLRefineModel(args) batch_processor = m.batch_processor(for_eval=True) m.args.max_beam_trees = 64 m.args.max_eval_trials = 64 i", "correct = False break refinement_results.append(correct) if correct: stats['fixed'] += 1 print(float(stats['fixed']) / stats['total'],", "= False break refinement_results.append(correct) if correct: stats['fixed'] += 1 print(float(stats['fixed']) / stats['total'], stats['fixed'],", "import operator import os import re import sys from program_synthesis.karel.dataset import dataset from", "= 64 m.args.max_eval_trials = 64 i = 0 result = [] while i", "= m.batch_processor(for_eval=True) m.args.max_beam_trees = 64 m.args.max_eval_trials = 64 i = 0 result =", "len(batch) < 32 and i < len(baseline_report): if baseline_report[i]['code']['info']['trees_checked'] == 1: i +=", "executor.KarelExecutor() stats = {'total': len(result), 'fixed': 0} refinement_results = [] for example, infer", "= m.inference(batch_processor(batch)) for example, infer in zip(batch, res): result.append((example, infer)) # if i", "tests=e.tests) batch.append(e) i += 1 print(\"Starting batch (%d)...\" % i) res = m.inference(batch_processor(batch))", "Args(object): model_dir = BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step = 250100 args = Args() restore_args(args)", "example.tests: try: log = the_executor.execute(infer.code_sequence, None, test['input']) if log.result != test['output']: correct =", "0} refinement_results = [] for example, infer in result: if not infer.code_sequence: continue", "dataset from program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset.karel_runtime import KarelRuntime from program_synthesis.karel.models import karel_model", "line in f: baseline_report.append(json.loads(line)) class Args(object): model_dir = BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step =", "f: baseline_report.append(json.loads(line)) class Args(object): model_dir = BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step = 250100 args", "1: i += 1 continue e = dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0] e.ref_example =", "os import re import sys from program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset import executor", "continue correct = True for test in example.input_tests + example.tests: try: log =", "executor.ExecutorSyntaxException) as e: correct = False break refinement_results.append(correct) if correct: stats['fixed'] += 1", "open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f: baseline_report = [] print(f.readline()) for line in f:", "stats = {'total': len(result), 'fixed': 0} refinement_results = [] for example, infer in", "< 32 and i < len(baseline_report): if baseline_report[i]['code']['info']['trees_checked'] == 1: i += 1", "code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests) batch.append(e) i += 1 print(\"Starting batch (%d)...\" % i) res", "while len(batch) < 32 and i < len(baseline_report): if baseline_report[i]['code']['info']['trees_checked'] == 1: i", "(%d)...\" % i) res = m.inference(batch_processor(batch)) for example, infer in zip(batch, res): result.append((example,", "try: log = the_executor.execute(infer.code_sequence, None, test['input']) if log.result != test['output']: correct = False", "batch = [] while len(batch) < 32 and i < len(baseline_report): if baseline_report[i]['code']['info']['trees_checked']", "sys from program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset.karel_runtime import KarelRuntime", "= 0 result = [] while i < len(baseline_report): batch = [] while", "+= 1 continue e = dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0] e.ref_example = dataset.KarelExample(idx=None, guid=None,", "print(f.readline()) for line in f: baseline_report.append(json.loads(line)) class Args(object): model_dir = BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5'", "e = dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0] e.ref_example = dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests)", "True for test in example.input_tests + example.tests: try: log = the_executor.execute(infer.code_sequence, None, test['input'])", "import itertools import json import operator import os import re import sys from", "refinement_results = [] for example, infer in result: if not infer.code_sequence: continue correct", "restore_args BASE_DIR = \"\" with open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f: baseline_report = []", "zip(batch, res): result.append((example, infer)) # if i > 100: # break print(len(result), len(baseline_report))", "test['output']: correct = False break except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as e: correct = False", "example, infer in zip(batch, res): result.append((example, infer)) # if i > 100: #", "BASE_DIR = \"\" with open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f: baseline_report = [] print(f.readline())", "= dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0] e.ref_example = dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests) batch.append(e)", "the_executor.execute(infer.code_sequence, None, test['input']) if log.result != test['output']: correct = False break except (executor.ExecutorRuntimeException,", "baseline_report[i]['code']['info']['candidates'][0] e.ref_example = dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests) batch.append(e) i += 1 print(\"Starting", "250100 args = Args() restore_args(args) args.word_vocab = ',,/data/karel/word.vocab' m = karel_model.KarelLGRLRefineModel(args) batch_processor =", "collections import cPickle as pickle import glob import itertools import json import operator", "m.args.max_beam_trees = 64 m.args.max_eval_trials = 64 i = 0 result = [] while", "in example.input_tests + example.tests: try: log = the_executor.execute(infer.code_sequence, None, test['input']) if log.result !=", "program_synthesis.common.tools.saver import restore_args BASE_DIR = \"\" with open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f: baseline_report", "in zip(batch, res): result.append((example, infer)) # if i > 100: # break print(len(result),", "Args() restore_args(args) args.word_vocab = ',,/data/karel/word.vocab' m = karel_model.KarelLGRLRefineModel(args) batch_processor = m.batch_processor(for_eval=True) m.args.max_beam_trees =", "import executor from program_synthesis.karel.dataset.karel_runtime import KarelRuntime from program_synthesis.karel.models import karel_model from program_synthesis.common.tools.saver import", "as pickle import glob import itertools import json import operator import os import", "if i > 100: # break print(len(result), len(baseline_report)) the_executor = executor.KarelExecutor() stats =", "# break print(len(result), len(baseline_report)) the_executor = executor.KarelExecutor() stats = {'total': len(result), 'fixed': 0}", "in result: if not infer.code_sequence: continue correct = True for test in example.input_tests", "log = the_executor.execute(infer.code_sequence, None, test['input']) if log.result != test['output']: correct = False break", "64 i = 0 result = [] while i < len(baseline_report): batch =", "break except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as e: correct = False break refinement_results.append(correct) if correct:", "import restore_args BASE_DIR = \"\" with open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f: baseline_report =", "100: # break print(len(result), len(baseline_report)) the_executor = executor.KarelExecutor() stats = {'total': len(result), 'fixed':", "= False break except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as e: correct = False break refinement_results.append(correct)", "dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests) batch.append(e) i += 1 print(\"Starting batch (%d)...\" %", "json import operator import os import re import sys from program_synthesis.karel.dataset import dataset", "import cPickle as pickle import glob import itertools import json import operator import", "False break except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as e: correct = False break refinement_results.append(correct) if", "[] print(f.readline()) for line in f: baseline_report.append(json.loads(line)) class Args(object): model_dir = BASE_DIR +", "None, test['input']) if log.result != test['output']: correct = False break except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException)", "import collections import cPickle as pickle import glob import itertools import json import", "'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step = 250100 args = Args() restore_args(args) args.word_vocab = ',,/data/karel/word.vocab' m =", "= baseline_report[i]['code']['info']['candidates'][0] e.ref_example = dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests) batch.append(e) i += 1", "i = 0 result = [] while i < len(baseline_report): batch = []", "break print(len(result), len(baseline_report)) the_executor = executor.KarelExecutor() stats = {'total': len(result), 'fixed': 0} refinement_results", "the_executor = executor.KarelExecutor() stats = {'total': len(result), 'fixed': 0} refinement_results = [] for", "i < len(baseline_report): if baseline_report[i]['code']['info']['trees_checked'] == 1: i += 1 continue e =", "e: correct = False break refinement_results.append(correct) if correct: stats['fixed'] += 1 print(float(stats['fixed']) /", "= the_executor.execute(infer.code_sequence, None, test['input']) if log.result != test['output']: correct = False break except", "KarelRuntime from program_synthesis.karel.models import karel_model from program_synthesis.common.tools.saver import restore_args BASE_DIR = \"\" with", "pickle import glob import itertools import json import operator import os import re", "with open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f: baseline_report = [] print(f.readline()) for line in", "operator import os import re import sys from program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset", "[] for example, infer in result: if not infer.code_sequence: continue correct = True", "print(len(result), len(baseline_report)) the_executor = executor.KarelExecutor() stats = {'total': len(result), 'fixed': 0} refinement_results =", "step = 250100 args = Args() restore_args(args) args.word_vocab = ',,/data/karel/word.vocab' m = karel_model.KarelLGRLRefineModel(args)", "m.inference(batch_processor(batch)) for example, infer in zip(batch, res): result.append((example, infer)) # if i >", "1 continue e = dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0] e.ref_example = dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence,", "print(\"Starting batch (%d)...\" % i) res = m.inference(batch_processor(batch)) for example, infer in zip(batch,", "re import sys from program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset.karel_runtime", "result.append((example, infer)) # if i > 100: # break print(len(result), len(baseline_report)) the_executor =", "for test in example.input_tests + example.tests: try: log = the_executor.execute(infer.code_sequence, None, test['input']) if", "+ \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f: baseline_report = [] print(f.readline()) for line in f: baseline_report.append(json.loads(line))", "= 250100 args = Args() restore_args(args) args.word_vocab = ',,/data/karel/word.vocab' m = karel_model.KarelLGRLRefineModel(args) batch_processor", "cPickle as pickle import glob import itertools import json import operator import os", "from program_synthesis.karel.dataset.karel_runtime import KarelRuntime from program_synthesis.karel.models import karel_model from program_synthesis.common.tools.saver import restore_args BASE_DIR", "i += 1 print(\"Starting batch (%d)...\" % i) res = m.inference(batch_processor(batch)) for example,", "test['input']) if log.result != test['output']: correct = False break except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as", "not infer.code_sequence: continue correct = True for test in example.input_tests + example.tests: try:", "import json import operator import os import re import sys from program_synthesis.karel.dataset import", "correct = True for test in example.input_tests + example.tests: try: log = the_executor.execute(infer.code_sequence,", "i < len(baseline_report): batch = [] while len(batch) < 32 and i <", "False break refinement_results.append(correct) if correct: stats['fixed'] += 1 print(float(stats['fixed']) / stats['total'], stats['fixed'], stats['total'])", "+ example.tests: try: log = the_executor.execute(infer.code_sequence, None, test['input']) if log.result != test['output']: correct", "result = [] while i < len(baseline_report): batch = [] while len(batch) <", "(executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as e: correct = False break refinement_results.append(correct) if correct: stats['fixed'] +=", "import glob import itertools import json import operator import os import re import", "log.result != test['output']: correct = False break except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as e: correct", "infer in result: if not infer.code_sequence: continue correct = True for test in", "baseline_report.append(json.loads(line)) class Args(object): model_dir = BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step = 250100 args =", "= [] while i < len(baseline_report): batch = [] while len(batch) < 32", "args.word_vocab = ',,/data/karel/word.vocab' m = karel_model.KarelLGRLRefineModel(args) batch_processor = m.batch_processor(for_eval=True) m.args.max_beam_trees = 64 m.args.max_eval_trials", "baseline_report[i]['code']['info']['trees_checked'] == 1: i += 1 continue e = dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0]", "len(result), 'fixed': 0} refinement_results = [] for example, infer in result: if not", "program_synthesis.karel.models import karel_model from program_synthesis.common.tools.saver import restore_args BASE_DIR = \"\" with open(BASE_DIR +", "infer in zip(batch, res): result.append((example, infer)) # if i > 100: # break", "len(baseline_report)) the_executor = executor.KarelExecutor() stats = {'total': len(result), 'fixed': 0} refinement_results = []", "from program_synthesis.karel.models import karel_model from program_synthesis.common.tools.saver import restore_args BASE_DIR = \"\" with open(BASE_DIR", "1 print(\"Starting batch (%d)...\" % i) res = m.inference(batch_processor(batch)) for example, infer in", "batch (%d)...\" % i) res = m.inference(batch_processor(batch)) for example, infer in zip(batch, res):", "# if i > 100: # break print(len(result), len(baseline_report)) the_executor = executor.KarelExecutor() stats", "0 result = [] while i < len(baseline_report): batch = [] while len(batch)", "[] while len(batch) < 32 and i < len(baseline_report): if baseline_report[i]['code']['info']['trees_checked'] == 1:", "except (executor.ExecutorRuntimeException, executor.ExecutorSyntaxException) as e: correct = False break refinement_results.append(correct) if correct: stats['fixed']", "karel_model from program_synthesis.common.tools.saver import restore_args BASE_DIR = \"\" with open(BASE_DIR + \"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as", "and i < len(baseline_report): if baseline_report[i]['code']['info']['trees_checked'] == 1: i += 1 continue e", "+ 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step = 250100 args = Args() restore_args(args) args.word_vocab = ',,/data/karel/word.vocab' m", "while i < len(baseline_report): batch = [] while len(batch) < 32 and i", "len(baseline_report): if baseline_report[i]['code']['info']['trees_checked'] == 1: i += 1 continue e = dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence", "< len(baseline_report): if baseline_report[i]['code']['info']['trees_checked'] == 1: i += 1 continue e = dataset.KarelExample.from_dict(baseline_report[i]['example'])", "'fixed': 0} refinement_results = [] for example, infer in result: if not infer.code_sequence:", "\"text2code-models/karel-sgd-cl1-lr1-lds100k-ldr0.5/report-dev-00100100.jsonl\") as f: baseline_report = [] print(f.readline()) for line in f: baseline_report.append(json.loads(line)) class", "== 1: i += 1 continue e = dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0] e.ref_example", "dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0] e.ref_example = dataset.KarelExample(idx=None, guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests) batch.append(e) i", "in f: baseline_report.append(json.loads(line)) class Args(object): model_dir = BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step = 250100", "batch_processor = m.batch_processor(for_eval=True) m.args.max_beam_trees = 64 m.args.max_eval_trials = 64 i = 0 result", "len(baseline_report): batch = [] while len(batch) < 32 and i < len(baseline_report): if", "guid=None, code_sequence=ref_code_sequence, input_tests=e.input_tests, tests=e.tests) batch.append(e) i += 1 print(\"Starting batch (%d)...\" % i)", "if baseline_report[i]['code']['info']['trees_checked'] == 1: i += 1 continue e = dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence =", "= Args() restore_args(args) args.word_vocab = ',,/data/karel/word.vocab' m = karel_model.KarelLGRLRefineModel(args) batch_processor = m.batch_processor(for_eval=True) m.args.max_beam_trees", "for line in f: baseline_report.append(json.loads(line)) class Args(object): model_dir = BASE_DIR + 'program_synthesis-models/karel-lgrl-ref-m123-sgd-cl1-lr0.1-lds100k-ldr0.5' step", "= True for test in example.input_tests + example.tests: try: log = the_executor.execute(infer.code_sequence, None,", "% i) res = m.inference(batch_processor(batch)) for example, infer in zip(batch, res): result.append((example, infer))", "[] while i < len(baseline_report): batch = [] while len(batch) < 32 and", "import dataset from program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset.karel_runtime import KarelRuntime from program_synthesis.karel.models import", "batch.append(e) i += 1 print(\"Starting batch (%d)...\" % i) res = m.inference(batch_processor(batch)) for", "64 m.args.max_eval_trials = 64 i = 0 result = [] while i <", "glob import itertools import json import operator import os import re import sys", "i += 1 continue e = dataset.KarelExample.from_dict(baseline_report[i]['example']) ref_code_sequence = baseline_report[i]['code']['info']['candidates'][0] e.ref_example = dataset.KarelExample(idx=None,", "result: if not infer.code_sequence: continue correct = True for test in example.input_tests +", "{'total': len(result), 'fixed': 0} refinement_results = [] for example, infer in result: if", "import KarelRuntime from program_synthesis.karel.models import karel_model from program_synthesis.common.tools.saver import restore_args BASE_DIR = \"\"", "args = Args() restore_args(args) args.word_vocab = ',,/data/karel/word.vocab' m = karel_model.KarelLGRLRefineModel(args) batch_processor = m.batch_processor(for_eval=True)", "from program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset.karel_runtime import KarelRuntime from", "example, infer in result: if not infer.code_sequence: continue correct = True for test" ]
[ "lst = AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20]) def template_as_py_list_2(self, map_type): cy_map = MAP[map_type]() cy_map[3] =", "cyt.as_py_list_int32, 'float64' : cyt.as_py_list_int64_float64, 'float32' : cyt.as_py_list_int32_float32, 'object' : cyt.as_py_list_pyobject, } USE_INT =", "= {\"script_args\" : [\"--force\"]}, language_level=3) import unittest import uttemplate import cymapinterfacetester as cyt", "{'int64' : cyt.as_py_list_int64, 'int32' : cyt.as_py_list_int32, 'float64' : cyt.as_py_list_int64_float64, 'float32' : cyt.as_py_list_int32_float32, 'object'", "[5,6,7,8], [2,3]) expected=[6,7] self.assertEqual(received, expected) def template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5] self.assertEqual(received,", "received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5] self.assertEqual(received, expected) def template_as_py_list(self, map_type): cy_map = MAP[map_type]() cy_map[3]", "'float64' : cyt.as_py_list_int64_float64, 'float32' : cyt.as_py_list_int32_float32, 'object' : cyt.as_py_list_pyobject, } USE_INT = {'int64'", "cyt.use_int64_float64, 'float32' : cyt.use_int32_float32, 'object' : cyt.use_pyobject, } USE_FLOAT = {'int64' : cyt.use_float64,", ": cyt.use_float64, 'int32' : cyt.use_float32, 'float64' : cyt.use_float64_float64, 'float32' : cyt.use_float32_float32, 'object' :", "[5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5] self.assertEqual(received, expected) def template_as_py_list(self, map_type): cy_map = MAP[map_type]() cy_map[3] =", "= AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20]) def template_as_py_list_2(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 5", "PyObjectMap AS_LIST = {'int64' : cyt.as_py_list_int64, 'int32' : cyt.as_py_list_int32, 'float64' : cyt.as_py_list_int64_float64, 'float32'", "self.assertEqual(lst, [3,20]) def template_as_py_list_2(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 5 cy_map[4] =", "making sure the interface can be accessed: @uttemplate.from_templates(['int64', 'int32', 'float64', 'float32', ]) class", "'float64' : cyt.use_int64_float64, 'float32' : cyt.use_int32_float32, 'object' : cyt.use_pyobject, } USE_FLOAT = {'int64'", "cyt.as_py_list_int64_float64, 'float32' : cyt.as_py_list_int32_float32, 'object' : cyt.as_py_list_pyobject, } USE_INT = {'int64' : cyt.use_int64,", "import uttemplate import cymapinterfacetester as cyt from cykhash import Int64to64Map, Int32to32Map, Float64to64Map, Float32to32Map,", ": cyt.use_float64_float64, 'float32' : cyt.use_float32_float32, 'object' : cyt.use_pyobject, } MAP = {'int64' :", "Int64to64Map, 'int32' : Int32to32Map, 'float64' : Float64to64Map, 'float32' : Float32to32Map, 'object' : PyObjectMap,", "Float64to64Map, 'float32' : Float32to32Map, 'object' : PyObjectMap, } #just making sure the interface", "cy_map = MAP[map_type]() cy_map[3] = 20 lst = AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20]) def template_as_py_list_2(self,", "'int32' : Int32to32Map, 'float64' : Float64to64Map, 'float32' : Float32to32Map, 'object' : PyObjectMap, }", "import Int64to64Map, Int32to32Map, Float64to64Map, Float32to32Map, PyObjectMap AS_LIST = {'int64' : cyt.as_py_list_int64, 'int32' :", ": cyt.use_pyobject, } USE_FLOAT = {'int64' : cyt.use_float64, 'int32' : cyt.use_float32, 'float64' :", "cyt.as_py_list_int64, 'int32' : cyt.as_py_list_int32, 'float64' : cyt.as_py_list_int64_float64, 'float32' : cyt.as_py_list_int32_float32, 'object' : cyt.as_py_list_pyobject,", ": cyt.as_py_list_pyobject, } USE_INT = {'int64' : cyt.use_int64, 'int32' : cyt.use_int32, 'float64' :", "'object' : cyt.use_pyobject, } USE_FLOAT = {'int64' : cyt.use_float64, 'int32' : cyt.use_float32, 'float64'", "= {'int64' : Int64to64Map, 'int32' : Int32to32Map, 'float64' : Float64to64Map, 'float32' : Float32to32Map,", "the interface can be accessed: @uttemplate.from_templates(['int64', 'int32', 'float64', 'float32', ]) class CyMypInterfaceTester(unittest.TestCase): def", "]) class CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3]) expected=[6,7] self.assertEqual(received, expected) def", "as cyt from cykhash import Int64to64Map, Int32to32Map, Float64to64Map, Float32to32Map, PyObjectMap AS_LIST = {'int64'", ": Float64to64Map, 'float32' : Float32to32Map, 'object' : PyObjectMap, } #just making sure the", "Int64to64Map, Int32to32Map, Float64to64Map, Float32to32Map, PyObjectMap AS_LIST = {'int64' : cyt.as_py_list_int64, 'int32' : cyt.as_py_list_int32,", "map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3]) expected=[6,7] self.assertEqual(received, expected) def template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3])", "[2,3]) expected=[6.5,7.5] self.assertEqual(received, expected) def template_as_py_list(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 20", "def template_as_py_list(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 20 lst = AS_LIST[map_type](cy_map) self.assertEqual(lst,", "class CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3]) expected=[6,7] self.assertEqual(received, expected) def template_cimport_use_float(self,", "} #just making sure the interface can be accessed: @uttemplate.from_templates(['int64', 'int32', 'float64', 'float32',", "'int32' : cyt.as_py_list_int32, 'float64' : cyt.as_py_list_int64_float64, 'float32' : cyt.as_py_list_int32_float32, 'object' : cyt.as_py_list_pyobject, }", "cyt.use_float32, 'float64' : cyt.use_float64_float64, 'float32' : cyt.use_float32_float32, 'object' : cyt.use_pyobject, } MAP =", "cyt.as_py_list_int32_float32, 'object' : cyt.as_py_list_pyobject, } USE_INT = {'int64' : cyt.use_int64, 'int32' : cyt.use_int32,", "sure the interface can be accessed: @uttemplate.from_templates(['int64', 'int32', 'float64', 'float32', ]) class CyMypInterfaceTester(unittest.TestCase):", "'float32' : cyt.as_py_list_int32_float32, 'object' : cyt.as_py_list_pyobject, } USE_INT = {'int64' : cyt.use_int64, 'int32'", "'float64' : cyt.use_float64_float64, 'float32' : cyt.use_float32_float32, 'object' : cyt.use_pyobject, } MAP = {'int64'", "MAP[map_type]() cy_map[3] = 20 lst = AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20]) def template_as_py_list_2(self, map_type): cy_map", "= MAP[map_type]() cy_map[3] = 5 cy_map[4] = 6 lst = AS_LIST[map_type](cy_map) self.assertEqual(set(lst), set([3,4,5,6]))", "@uttemplate.from_templates(['int64', 'int32', 'float64', 'float32', ]) class CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3])", "= MAP[map_type]() cy_map[3] = 20 lst = AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20]) def template_as_py_list_2(self, map_type):", ": cyt.as_py_list_int64_float64, 'float32' : cyt.as_py_list_int32_float32, 'object' : cyt.as_py_list_pyobject, } USE_INT = {'int64' :", "cykhash import Int64to64Map, Int32to32Map, Float64to64Map, Float32to32Map, PyObjectMap AS_LIST = {'int64' : cyt.as_py_list_int64, 'int32'", "from cykhash import Int64to64Map, Int32to32Map, Float64to64Map, Float32to32Map, PyObjectMap AS_LIST = {'int64' : cyt.as_py_list_int64,", "interface can be accessed: @uttemplate.from_templates(['int64', 'int32', 'float64', 'float32', ]) class CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self,", "map_type): cy_map = MAP[map_type]() cy_map[3] = 20 lst = AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20]) def", "} USE_FLOAT = {'int64' : cyt.use_float64, 'int32' : cyt.use_float32, 'float64' : cyt.use_float64_float64, 'float32'", "= {'int64' : cyt.as_py_list_int64, 'int32' : cyt.as_py_list_int32, 'float64' : cyt.as_py_list_int64_float64, 'float32' : cyt.as_py_list_int32_float32,", "[\"--force\"]}, language_level=3) import unittest import uttemplate import cymapinterfacetester as cyt from cykhash import", "Float32to32Map, 'object' : PyObjectMap, } #just making sure the interface can be accessed:", "{'int64' : cyt.use_int64, 'int32' : cyt.use_int32, 'float64' : cyt.use_int64_float64, 'float32' : cyt.use_int32_float32, 'object'", "USE_INT = {'int64' : cyt.use_int64, 'int32' : cyt.use_int32, 'float64' : cyt.use_int64_float64, 'float32' :", "'float32' : cyt.use_float32_float32, 'object' : cyt.use_pyobject, } MAP = {'int64' : Int64to64Map, 'int32'", "{'int64' : Int64to64Map, 'int32' : Int32to32Map, 'float64' : Float64to64Map, 'float32' : Float32to32Map, 'object'", "import pyximport; pyximport.install(setup_args = {\"script_args\" : [\"--force\"]}, language_level=3) import unittest import uttemplate import", "cyt.as_py_list_pyobject, } USE_INT = {'int64' : cyt.use_int64, 'int32' : cyt.use_int32, 'float64' : cyt.use_int64_float64,", ": Int64to64Map, 'int32' : Int32to32Map, 'float64' : Float64to64Map, 'float32' : Float32to32Map, 'object' :", ": Int32to32Map, 'float64' : Float64to64Map, 'float32' : Float32to32Map, 'object' : PyObjectMap, } #just", "accessed: @uttemplate.from_templates(['int64', 'int32', 'float64', 'float32', ]) class CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8],", ": cyt.use_int32_float32, 'object' : cyt.use_pyobject, } USE_FLOAT = {'int64' : cyt.use_float64, 'int32' :", "{\"script_args\" : [\"--force\"]}, language_level=3) import unittest import uttemplate import cymapinterfacetester as cyt from", "be accessed: @uttemplate.from_templates(['int64', 'int32', 'float64', 'float32', ]) class CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4],", "language_level=3) import unittest import uttemplate import cymapinterfacetester as cyt from cykhash import Int64to64Map,", "expected=[6,7] self.assertEqual(received, expected) def template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5] self.assertEqual(received, expected) def", "20 lst = AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20]) def template_as_py_list_2(self, map_type): cy_map = MAP[map_type]() cy_map[3]", "cy_map = MAP[map_type]() cy_map[3] = 5 cy_map[4] = 6 lst = AS_LIST[map_type](cy_map) self.assertEqual(set(lst),", "cyt.use_int64, 'int32' : cyt.use_int32, 'float64' : cyt.use_int64_float64, 'float32' : cyt.use_int32_float32, 'object' : cyt.use_pyobject,", ": cyt.as_py_list_int64, 'int32' : cyt.as_py_list_int32, 'float64' : cyt.as_py_list_int64_float64, 'float32' : cyt.as_py_list_int32_float32, 'object' :", "cyt.use_pyobject, } MAP = {'int64' : Int64to64Map, 'int32' : Int32to32Map, 'float64' : Float64to64Map,", "template_as_py_list(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 20 lst = AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20])", "'object' : cyt.as_py_list_pyobject, } USE_INT = {'int64' : cyt.use_int64, 'int32' : cyt.use_int32, 'float64'", ": cyt.as_py_list_int32, 'float64' : cyt.as_py_list_int64_float64, 'float32' : cyt.as_py_list_int32_float32, 'object' : cyt.as_py_list_pyobject, } USE_INT", "'float64', 'float32', ]) class CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3]) expected=[6,7] self.assertEqual(received,", "cyt.use_float64_float64, 'float32' : cyt.use_float32_float32, 'object' : cyt.use_pyobject, } MAP = {'int64' : Int64to64Map,", "unittest import uttemplate import cymapinterfacetester as cyt from cykhash import Int64to64Map, Int32to32Map, Float64to64Map,", "cyt.use_pyobject, } USE_FLOAT = {'int64' : cyt.use_float64, 'int32' : cyt.use_float32, 'float64' : cyt.use_float64_float64,", ": cyt.use_float32_float32, 'object' : cyt.use_pyobject, } MAP = {'int64' : Int64to64Map, 'int32' :", ": Float32to32Map, 'object' : PyObjectMap, } #just making sure the interface can be", "'float32', ]) class CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3]) expected=[6,7] self.assertEqual(received, expected)", ": [\"--force\"]}, language_level=3) import unittest import uttemplate import cymapinterfacetester as cyt from cykhash", "Float64to64Map, Float32to32Map, PyObjectMap AS_LIST = {'int64' : cyt.as_py_list_int64, 'int32' : cyt.as_py_list_int32, 'float64' :", "uttemplate import cymapinterfacetester as cyt from cykhash import Int64to64Map, Int32to32Map, Float64to64Map, Float32to32Map, PyObjectMap", "[2,3]) expected=[6,7] self.assertEqual(received, expected) def template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5] self.assertEqual(received, expected)", "import unittest import uttemplate import cymapinterfacetester as cyt from cykhash import Int64to64Map, Int32to32Map,", ": cyt.use_float32, 'float64' : cyt.use_float64_float64, 'float32' : cyt.use_float32_float32, 'object' : cyt.use_pyobject, } MAP", ": cyt.use_pyobject, } MAP = {'int64' : Int64to64Map, 'int32' : Int32to32Map, 'float64' :", "AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20]) def template_as_py_list_2(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 5 cy_map[4]", "[3,20]) def template_as_py_list_2(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 5 cy_map[4] = 6", "'object' : PyObjectMap, } #just making sure the interface can be accessed: @uttemplate.from_templates(['int64',", "'float64' : Float64to64Map, 'float32' : Float32to32Map, 'object' : PyObjectMap, } #just making sure", "AS_LIST = {'int64' : cyt.as_py_list_int64, 'int32' : cyt.as_py_list_int32, 'float64' : cyt.as_py_list_int64_float64, 'float32' :", "#just making sure the interface can be accessed: @uttemplate.from_templates(['int64', 'int32', 'float64', 'float32', ])", "received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3]) expected=[6,7] self.assertEqual(received, expected) def template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5]", "'int32' : cyt.use_float32, 'float64' : cyt.use_float64_float64, 'float32' : cyt.use_float32_float32, 'object' : cyt.use_pyobject, }", "import cymapinterfacetester as cyt from cykhash import Int64to64Map, Int32to32Map, Float64to64Map, Float32to32Map, PyObjectMap AS_LIST", "PyObjectMap, } #just making sure the interface can be accessed: @uttemplate.from_templates(['int64', 'int32', 'float64',", "Int32to32Map, 'float64' : Float64to64Map, 'float32' : Float32to32Map, 'object' : PyObjectMap, } #just making", "def template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5] self.assertEqual(received, expected) def template_as_py_list(self, map_type): cy_map", "template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3]) expected=[6,7] self.assertEqual(received, expected) def template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5],", ": cyt.as_py_list_int32_float32, 'object' : cyt.as_py_list_pyobject, } USE_INT = {'int64' : cyt.use_int64, 'int32' :", "template_as_py_list_2(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 5 cy_map[4] = 6 lst =", ": cyt.use_int64, 'int32' : cyt.use_int32, 'float64' : cyt.use_int64_float64, 'float32' : cyt.use_int32_float32, 'object' :", ": PyObjectMap, } #just making sure the interface can be accessed: @uttemplate.from_templates(['int64', 'int32',", "'int32' : cyt.use_int32, 'float64' : cyt.use_int64_float64, 'float32' : cyt.use_int32_float32, 'object' : cyt.use_pyobject, }", "def template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3]) expected=[6,7] self.assertEqual(received, expected) def template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4],", "cyt.use_int32, 'float64' : cyt.use_int64_float64, 'float32' : cyt.use_int32_float32, 'object' : cyt.use_pyobject, } USE_FLOAT =", "cyt.use_int32_float32, 'object' : cyt.use_pyobject, } USE_FLOAT = {'int64' : cyt.use_float64, 'int32' : cyt.use_float32,", "self.assertEqual(received, expected) def template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5] self.assertEqual(received, expected) def template_as_py_list(self,", "map_type): cy_map = MAP[map_type]() cy_map[3] = 5 cy_map[4] = 6 lst = AS_LIST[map_type](cy_map)", "'object' : cyt.use_pyobject, } MAP = {'int64' : Int64to64Map, 'int32' : Int32to32Map, 'float64'", ": cyt.use_int32, 'float64' : cyt.use_int64_float64, 'float32' : cyt.use_int32_float32, 'object' : cyt.use_pyobject, } USE_FLOAT", "cyt from cykhash import Int64to64Map, Int32to32Map, Float64to64Map, Float32to32Map, PyObjectMap AS_LIST = {'int64' :", "cymapinterfacetester as cyt from cykhash import Int64to64Map, Int32to32Map, Float64to64Map, Float32to32Map, PyObjectMap AS_LIST =", "expected=[6.5,7.5] self.assertEqual(received, expected) def template_as_py_list(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 20 lst", "expected) def template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5] self.assertEqual(received, expected) def template_as_py_list(self, map_type):", "cyt.use_float64, 'int32' : cyt.use_float32, 'float64' : cyt.use_float64_float64, 'float32' : cyt.use_float32_float32, 'object' : cyt.use_pyobject,", "template_cimport_use_float(self, map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5] self.assertEqual(received, expected) def template_as_py_list(self, map_type): cy_map =", "{'int64' : cyt.use_float64, 'int32' : cyt.use_float32, 'float64' : cyt.use_float64_float64, 'float32' : cyt.use_float32_float32, 'object'", "MAP = {'int64' : Int64to64Map, 'int32' : Int32to32Map, 'float64' : Float64to64Map, 'float32' :", "can be accessed: @uttemplate.from_templates(['int64', 'int32', 'float64', 'float32', ]) class CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self, map_type):", "def template_as_py_list_2(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 5 cy_map[4] = 6 lst", "'int32', 'float64', 'float32', ]) class CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3]) expected=[6,7]", "cyt.use_float32_float32, 'object' : cyt.use_pyobject, } MAP = {'int64' : Int64to64Map, 'int32' : Int32to32Map,", "} MAP = {'int64' : Int64to64Map, 'int32' : Int32to32Map, 'float64' : Float64to64Map, 'float32'", "expected) def template_as_py_list(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 20 lst = AS_LIST[map_type](cy_map)", "'float32' : cyt.use_int32_float32, 'object' : cyt.use_pyobject, } USE_FLOAT = {'int64' : cyt.use_float64, 'int32'", "USE_FLOAT = {'int64' : cyt.use_float64, 'int32' : cyt.use_float32, 'float64' : cyt.use_float64_float64, 'float32' :", "pyximport; pyximport.install(setup_args = {\"script_args\" : [\"--force\"]}, language_level=3) import unittest import uttemplate import cymapinterfacetester", "self.assertEqual(received, expected) def template_as_py_list(self, map_type): cy_map = MAP[map_type]() cy_map[3] = 20 lst =", "map_type): received=USE_FLOAT[map_type]([1,2,3,4], [5.5,6.5,7.5,8.5], [2,3]) expected=[6.5,7.5] self.assertEqual(received, expected) def template_as_py_list(self, map_type): cy_map = MAP[map_type]()", "CyMypInterfaceTester(unittest.TestCase): def template_cimport_use_int(self, map_type): received=USE_INT[map_type]([1,2,3,4], [5,6,7,8], [2,3]) expected=[6,7] self.assertEqual(received, expected) def template_cimport_use_float(self, map_type):", "= {'int64' : cyt.use_float64, 'int32' : cyt.use_float32, 'float64' : cyt.use_float64_float64, 'float32' : cyt.use_float32_float32,", "Int32to32Map, Float64to64Map, Float32to32Map, PyObjectMap AS_LIST = {'int64' : cyt.as_py_list_int64, 'int32' : cyt.as_py_list_int32, 'float64'", "= 20 lst = AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20]) def template_as_py_list_2(self, map_type): cy_map = MAP[map_type]()", "pyximport.install(setup_args = {\"script_args\" : [\"--force\"]}, language_level=3) import unittest import uttemplate import cymapinterfacetester as", "'float32' : Float32to32Map, 'object' : PyObjectMap, } #just making sure the interface can", ": cyt.use_int64_float64, 'float32' : cyt.use_int32_float32, 'object' : cyt.use_pyobject, } USE_FLOAT = {'int64' :", "} USE_INT = {'int64' : cyt.use_int64, 'int32' : cyt.use_int32, 'float64' : cyt.use_int64_float64, 'float32'", "= {'int64' : cyt.use_int64, 'int32' : cyt.use_int32, 'float64' : cyt.use_int64_float64, 'float32' : cyt.use_int32_float32,", "cy_map[3] = 20 lst = AS_LIST[map_type](cy_map) self.assertEqual(lst, [3,20]) def template_as_py_list_2(self, map_type): cy_map =", "Float32to32Map, PyObjectMap AS_LIST = {'int64' : cyt.as_py_list_int64, 'int32' : cyt.as_py_list_int32, 'float64' : cyt.as_py_list_int64_float64," ]
[ "data_entry_functions.insertSurveyData(file, models, 'survey', 'room_id', 'building', 'event_time', 'occupancy', 'reporter', 'time') models.db.close() print (\"The database", "into database from csv file file = \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models, 'module', 'module_code', 'instructor',", "'email', 'first_name', 'last_name', 'admin', 'password', \"<PASSWORD> <EMAIL>\", 'Don', 'Blaine') # set user password", "'module', 'module_code', 'instructor', 'user', 'username') # setting weight to be linear model coef", "coding: utf-8 -*- \"\"\" Created on Wed Jul 27 17:41:41 2016 @author: <NAME>", "data into room table in db data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 2, 90,", "3, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 4, 220,", "user data_entry_functions.createAdmin(models, 'User', 'username', 'password', 'email', 'first_name', 'last_name', 'admin', 'password', \"<PASSWORD> <EMAIL>\", 'Don',", "insert data into database from csv file file = \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models, 'module',", "of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 3, 90, 'school of computer", "= r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models, 'wifi_log', 'room_id', 'event_time', 'assoc_devices', 'auth_devices', 'time') # insert survey", "models import data_entry_functions import linear_model def main(): # insert tables into database tables", "'time') # insert survey data file = r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models, 'survey', 'room_id', 'building',", "user password data_entry_functions.setPassword(models, 'User', 'username', 'admin', 'password') # insert data into database from", "'User', 'username', 'admin', 'password') # insert data into database from csv file file", "'survey', 'room_id', 'building', 'event_time', 'occupancy', 'reporter', 'time') models.db.close() print (\"The database should now", "import models import data_entry_functions import linear_model def main(): # insert tables into database", "insert survey data file = r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models, 'survey', 'room_id', 'building', 'event_time', 'occupancy',", "insert room data into room table in db data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building',", "['room', 'User', 'module', 'wifi_log', 'timetable', 'survey', 'regressionModel'] data_entry_functions.createTables(models, tables) # insert room data", "coef - create function ? models.regressionModel.create(weight = linear_model.get_linear_coef()) # insert timetable data data_entry_functions.insertTimetableData(file,", "'reg_stu', 'time') # insert wifi log data file = r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models, 'wifi_log',", "'password', 'email', 'first_name', 'last_name', 'admin', 'password', \"<PASSWORD> <EMAIL>\", 'Don', 'Blaine') # set user", "-*- \"\"\" Created on Wed Jul 27 17:41:41 2016 @author: <NAME> \"\"\" import", "# -*- coding: utf-8 -*- \"\"\" Created on Wed Jul 27 17:41:41 2016", "'wifi_log', 'timetable', 'survey', 'regressionModel'] data_entry_functions.createTables(models, tables) # insert room data into room table", "science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 4, 220, 'school of computer science') #", "models, 'timetable', 'room_id', 'building', 'mod_code', 'event_time', 'reg_stu', 'time') # insert wifi log data", "220, 'school of computer science') # create admin user data_entry_functions.createAdmin(models, 'User', 'username', 'password',", "r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models, 'survey', 'room_id', 'building', 'event_time', 'occupancy', 'reporter', 'time') models.db.close() print (\"The", "insert tables into database tables = ['room', 'User', 'module', 'wifi_log', 'timetable', 'survey', 'regressionModel']", "data file = r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models, 'wifi_log', 'room_id', 'event_time', 'assoc_devices', 'auth_devices', 'time') #", "models.regressionModel.create(weight = linear_model.get_linear_coef()) # insert timetable data data_entry_functions.insertTimetableData(file, models, 'timetable', 'room_id', 'building', 'mod_code',", "tables = ['room', 'User', 'module', 'wifi_log', 'timetable', 'survey', 'regressionModel'] data_entry_functions.createTables(models, tables) # insert", "set user password data_entry_functions.setPassword(models, 'User', 'username', 'admin', 'password') # insert data into database", "'room_id', 'event_time', 'assoc_devices', 'auth_devices', 'time') # insert survey data file = r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file,", "db data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 2, 90, 'school of computer science') data_entry_functions.roomCap(models,", "'room', 'room_num', 'room_cap', 'building', 4, 220, 'school of computer science') # create admin", "'password') # insert data into database from csv file file = \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file,", "linear model coef - create function ? models.regressionModel.create(weight = linear_model.get_linear_coef()) # insert timetable", "create function ? models.regressionModel.create(weight = linear_model.get_linear_coef()) # insert timetable data data_entry_functions.insertTimetableData(file, models, 'timetable',", "wifi log data file = r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models, 'wifi_log', 'room_id', 'event_time', 'assoc_devices', 'auth_devices',", "create admin user data_entry_functions.createAdmin(models, 'User', 'username', 'password', 'email', 'first_name', 'last_name', 'admin', 'password', \"<PASSWORD>", "# insert wifi log data file = r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models, 'wifi_log', 'room_id', 'event_time',", "'survey', 'regressionModel'] data_entry_functions.createTables(models, tables) # insert room data into room table in db", "data data_entry_functions.insertTimetableData(file, models, 'timetable', 'room_id', 'building', 'mod_code', 'event_time', 'reg_stu', 'time') # insert wifi", "data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 2, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room',", "'building', 2, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 3,", "'school of computer science') # create admin user data_entry_functions.createAdmin(models, 'User', 'username', 'password', 'email',", "'event_time', 'assoc_devices', 'auth_devices', 'time') # insert survey data file = r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models,", "'Blaine') # set user password data_entry_functions.setPassword(models, 'User', 'username', 'admin', 'password') # insert data", "'building', 4, 220, 'school of computer science') # create admin user data_entry_functions.createAdmin(models, 'User',", "insert timetable data data_entry_functions.insertTimetableData(file, models, 'timetable', 'room_id', 'building', 'mod_code', 'event_time', 'reg_stu', 'time') #", "= linear_model.get_linear_coef()) # insert timetable data data_entry_functions.insertTimetableData(file, models, 'timetable', 'room_id', 'building', 'mod_code', 'event_time',", "17:41:41 2016 @author: <NAME> \"\"\" import models import data_entry_functions import linear_model def main():", "'password', \"<PASSWORD> <EMAIL>\", 'Don', 'Blaine') # set user password data_entry_functions.setPassword(models, 'User', 'username', 'admin',", "4, 220, 'school of computer science') # create admin user data_entry_functions.createAdmin(models, 'User', 'username',", "admin user data_entry_functions.createAdmin(models, 'User', 'username', 'password', 'email', 'first_name', 'last_name', 'admin', 'password', \"<PASSWORD> <EMAIL>\",", "models.db.close() print (\"The database should now be available\") if __name__ == '__main__': main()", "data_entry_functions.setPassword(models, 'User', 'username', 'admin', 'password') # insert data into database from csv file", "setting weight to be linear model coef - create function ? models.regressionModel.create(weight =", "'reporter', 'time') models.db.close() print (\"The database should now be available\") if __name__ ==", "data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 4, 220, 'school of computer science') # create", "'room_id', 'building', 'mod_code', 'event_time', 'reg_stu', 'time') # insert wifi log data file =", "file file = \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models, 'module', 'module_code', 'instructor', 'user', 'username') # setting", "'room_id', 'building', 'event_time', 'occupancy', 'reporter', 'time') models.db.close() print (\"The database should now be", "@author: <NAME> \"\"\" import models import data_entry_functions import linear_model def main(): # insert", "'building', 3, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 4,", "# insert data into database from csv file file = \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models,", "# insert survey data file = r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models, 'survey', 'room_id', 'building', 'event_time',", "survey data file = r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models, 'survey', 'room_id', 'building', 'event_time', 'occupancy', 'reporter',", "'room_cap', 'building', 3, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building',", "utf-8 -*- \"\"\" Created on Wed Jul 27 17:41:41 2016 @author: <NAME> \"\"\"", "file = r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models, 'survey', 'room_id', 'building', 'event_time', 'occupancy', 'reporter', 'time') models.db.close()", "import linear_model def main(): # insert tables into database tables = ['room', 'User',", "'first_name', 'last_name', 'admin', 'password', \"<PASSWORD> <EMAIL>\", 'Don', 'Blaine') # set user password data_entry_functions.setPassword(models,", "# setting weight to be linear model coef - create function ? models.regressionModel.create(weight", "# insert room data into room table in db data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap',", "'auth_devices', 'time') # insert survey data file = r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models, 'survey', 'room_id',", "computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 3, 90, 'school of computer science')", "'Don', 'Blaine') # set user password data_entry_functions.setPassword(models, 'User', 'username', 'admin', 'password') # insert", "room table in db data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 2, 90, 'school of", "computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 4, 220, 'school of computer science')", "science') # create admin user data_entry_functions.createAdmin(models, 'User', 'username', 'password', 'email', 'first_name', 'last_name', 'admin',", "'user', 'username') # setting weight to be linear model coef - create function", "'event_time', 'occupancy', 'reporter', 'time') models.db.close() print (\"The database should now be available\") if", "model coef - create function ? models.regressionModel.create(weight = linear_model.get_linear_coef()) # insert timetable data", "# create admin user data_entry_functions.createAdmin(models, 'User', 'username', 'password', 'email', 'first_name', 'last_name', 'admin', 'password',", "\"<PASSWORD> <EMAIL>\", 'Don', 'Blaine') # set user password data_entry_functions.setPassword(models, 'User', 'username', 'admin', 'password')", "'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 4, 220, 'school of", "data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 3, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room',", "of computer science') # create admin user data_entry_functions.createAdmin(models, 'User', 'username', 'password', 'email', 'first_name',", "password data_entry_functions.setPassword(models, 'User', 'username', 'admin', 'password') # insert data into database from csv", "computer science') # create admin user data_entry_functions.createAdmin(models, 'User', 'username', 'password', 'email', 'first_name', 'last_name',", "r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models, 'wifi_log', 'room_id', 'event_time', 'assoc_devices', 'auth_devices', 'time') # insert survey data", "insert wifi log data file = r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models, 'wifi_log', 'room_id', 'event_time', 'assoc_devices',", "function ? models.regressionModel.create(weight = linear_model.get_linear_coef()) # insert timetable data data_entry_functions.insertTimetableData(file, models, 'timetable', 'room_id',", "table in db data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 2, 90, 'school of computer", "weight to be linear model coef - create function ? models.regressionModel.create(weight = linear_model.get_linear_coef())", "Created on Wed Jul 27 17:41:41 2016 @author: <NAME> \"\"\" import models import", "Jul 27 17:41:41 2016 @author: <NAME> \"\"\" import models import data_entry_functions import linear_model", "import data_entry_functions import linear_model def main(): # insert tables into database tables =", "'occupancy', 'reporter', 'time') models.db.close() print (\"The database should now be available\") if __name__", "into database tables = ['room', 'User', 'module', 'wifi_log', 'timetable', 'survey', 'regressionModel'] data_entry_functions.createTables(models, tables)", "'building', 'mod_code', 'event_time', 'reg_stu', 'time') # insert wifi log data file = r\"cleaned_data/full.csv\"", "'module', 'wifi_log', 'timetable', 'survey', 'regressionModel'] data_entry_functions.createTables(models, tables) # insert room data into room", "'room_cap', 'building', 4, 220, 'school of computer science') # create admin user data_entry_functions.createAdmin(models,", "'room_num', 'room_cap', 'building', 2, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap',", "'event_time', 'reg_stu', 'time') # insert wifi log data file = r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models,", "linear_model.get_linear_coef()) # insert timetable data data_entry_functions.insertTimetableData(file, models, 'timetable', 'room_id', 'building', 'mod_code', 'event_time', 'reg_stu',", "'admin', 'password', \"<PASSWORD> <EMAIL>\", 'Don', 'Blaine') # set user password data_entry_functions.setPassword(models, 'User', 'username',", "csv file file = \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models, 'module', 'module_code', 'instructor', 'user', 'username') #", "\"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models, 'module', 'module_code', 'instructor', 'user', 'username') # setting weight to be", "'time') # insert wifi log data file = r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models, 'wifi_log', 'room_id',", "'room_cap', 'building', 2, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building',", "90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 3, 90, 'school", "in db data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 2, 90, 'school of computer science')", "'room', 'room_num', 'room_cap', 'building', 2, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num',", "of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 4, 220, 'school of computer", "into room table in db data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 2, 90, 'school", "2, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 3, 90,", "90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 4, 220, 'school", "'last_name', 'admin', 'password', \"<PASSWORD> <EMAIL>\", 'Don', 'Blaine') # set user password data_entry_functions.setPassword(models, 'User',", "'room', 'room_num', 'room_cap', 'building', 3, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num',", "data_entry_functions.insertTimetableData(file, models, 'timetable', 'room_id', 'building', 'mod_code', 'event_time', 'reg_stu', 'time') # insert wifi log", "27 17:41:41 2016 @author: <NAME> \"\"\" import models import data_entry_functions import linear_model def", "= ['room', 'User', 'module', 'wifi_log', 'timetable', 'survey', 'regressionModel'] data_entry_functions.createTables(models, tables) # insert room", "data_entry_functions.createTables(models, tables) # insert room data into room table in db data_entry_functions.roomCap(models, 'room',", "= \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models, 'module', 'module_code', 'instructor', 'user', 'username') # setting weight to", "-*- coding: utf-8 -*- \"\"\" Created on Wed Jul 27 17:41:41 2016 @author:", "'room_num', 'room_cap', 'building', 3, 90, 'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap',", "= r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models, 'survey', 'room_id', 'building', 'event_time', 'occupancy', 'reporter', 'time') models.db.close() print", "'User', 'username', 'password', 'email', 'first_name', 'last_name', 'admin', 'password', \"<PASSWORD> <EMAIL>\", 'Don', 'Blaine') #", "models, 'wifi_log', 'room_id', 'event_time', 'assoc_devices', 'auth_devices', 'time') # insert survey data file =", "'instructor', 'user', 'username') # setting weight to be linear model coef - create", "Wed Jul 27 17:41:41 2016 @author: <NAME> \"\"\" import models import data_entry_functions import", "# insert timetable data data_entry_functions.insertTimetableData(file, models, 'timetable', 'room_id', 'building', 'mod_code', 'event_time', 'reg_stu', 'time')", "file = \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models, 'module', 'module_code', 'instructor', 'user', 'username') # setting weight", "'time') models.db.close() print (\"The database should now be available\") if __name__ == '__main__':", "data_entry_functions.insertModCode(file, models, 'module', 'module_code', 'instructor', 'user', 'username') # setting weight to be linear", "data_entry_functions.createAdmin(models, 'User', 'username', 'password', 'email', 'first_name', 'last_name', 'admin', 'password', \"<PASSWORD> <EMAIL>\", 'Don', 'Blaine')", "\"\"\" import models import data_entry_functions import linear_model def main(): # insert tables into", "'school of computer science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 3, 90, 'school of", "<reponame>PaulineLc/OpenDoorData<gh_stars>0 # -*- coding: utf-8 -*- \"\"\" Created on Wed Jul 27 17:41:41", "on Wed Jul 27 17:41:41 2016 @author: <NAME> \"\"\" import models import data_entry_functions", "# insert tables into database tables = ['room', 'User', 'module', 'wifi_log', 'timetable', 'survey',", "'admin', 'password') # insert data into database from csv file file = \"cleaned_data/timetable.csv\"", "to be linear model coef - create function ? models.regressionModel.create(weight = linear_model.get_linear_coef()) #", "'username') # setting weight to be linear model coef - create function ?", "'username', 'password', 'email', 'first_name', 'last_name', 'admin', 'password', \"<PASSWORD> <EMAIL>\", 'Don', 'Blaine') # set", "'regressionModel'] data_entry_functions.createTables(models, tables) # insert room data into room table in db data_entry_functions.roomCap(models,", "'User', 'module', 'wifi_log', 'timetable', 'survey', 'regressionModel'] data_entry_functions.createTables(models, tables) # insert room data into", "2016 @author: <NAME> \"\"\" import models import data_entry_functions import linear_model def main(): #", "- create function ? models.regressionModel.create(weight = linear_model.get_linear_coef()) # insert timetable data data_entry_functions.insertTimetableData(file, models,", "models, 'survey', 'room_id', 'building', 'event_time', 'occupancy', 'reporter', 'time') models.db.close() print (\"The database should", "database from csv file file = \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models, 'module', 'module_code', 'instructor', 'user',", "<NAME> \"\"\" import models import data_entry_functions import linear_model def main(): # insert tables", "from csv file file = \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models, 'module', 'module_code', 'instructor', 'user', 'username')", "tables) # insert room data into room table in db data_entry_functions.roomCap(models, 'room', 'room_num',", "main(): # insert tables into database tables = ['room', 'User', 'module', 'wifi_log', 'timetable',", "tables into database tables = ['room', 'User', 'module', 'wifi_log', 'timetable', 'survey', 'regressionModel'] data_entry_functions.createTables(models,", "data file = r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models, 'survey', 'room_id', 'building', 'event_time', 'occupancy', 'reporter', 'time')", "'building', 'event_time', 'occupancy', 'reporter', 'time') models.db.close() print (\"The database should now be available\")", "science') data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 3, 90, 'school of computer science') data_entry_functions.roomCap(models,", "data into database from csv file file = \"cleaned_data/timetable.csv\" data_entry_functions.insertModCode(file, models, 'module', 'module_code',", "'module_code', 'instructor', 'user', 'username') # setting weight to be linear model coef -", "'mod_code', 'event_time', 'reg_stu', 'time') # insert wifi log data file = r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file,", "data_entry_functions.insertWifiData(file, models, 'wifi_log', 'room_id', 'event_time', 'assoc_devices', 'auth_devices', 'time') # insert survey data file", "room data into room table in db data_entry_functions.roomCap(models, 'room', 'room_num', 'room_cap', 'building', 2,", "'room_num', 'room_cap', 'building', 4, 220, 'school of computer science') # create admin user", "data_entry_functions import linear_model def main(): # insert tables into database tables = ['room',", "'timetable', 'survey', 'regressionModel'] data_entry_functions.createTables(models, tables) # insert room data into room table in", "'wifi_log', 'room_id', 'event_time', 'assoc_devices', 'auth_devices', 'time') # insert survey data file = r\"cleaned_data/survey_data.csv\"", "def main(): # insert tables into database tables = ['room', 'User', 'module', 'wifi_log',", "'assoc_devices', 'auth_devices', 'time') # insert survey data file = r\"cleaned_data/survey_data.csv\" data_entry_functions.insertSurveyData(file, models, 'survey',", "<EMAIL>\", 'Don', 'Blaine') # set user password data_entry_functions.setPassword(models, 'User', 'username', 'admin', 'password') #", "'timetable', 'room_id', 'building', 'mod_code', 'event_time', 'reg_stu', 'time') # insert wifi log data file", "database tables = ['room', 'User', 'module', 'wifi_log', 'timetable', 'survey', 'regressionModel'] data_entry_functions.createTables(models, tables) #", "log data file = r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models, 'wifi_log', 'room_id', 'event_time', 'assoc_devices', 'auth_devices', 'time')", "file = r\"cleaned_data/full.csv\" data_entry_functions.insertWifiData(file, models, 'wifi_log', 'room_id', 'event_time', 'assoc_devices', 'auth_devices', 'time') # insert", "timetable data data_entry_functions.insertTimetableData(file, models, 'timetable', 'room_id', 'building', 'mod_code', 'event_time', 'reg_stu', 'time') # insert", "# set user password data_entry_functions.setPassword(models, 'User', 'username', 'admin', 'password') # insert data into", "\"\"\" Created on Wed Jul 27 17:41:41 2016 @author: <NAME> \"\"\" import models", "be linear model coef - create function ? models.regressionModel.create(weight = linear_model.get_linear_coef()) # insert", "'username', 'admin', 'password') # insert data into database from csv file file =", "? models.regressionModel.create(weight = linear_model.get_linear_coef()) # insert timetable data data_entry_functions.insertTimetableData(file, models, 'timetable', 'room_id', 'building',", "linear_model def main(): # insert tables into database tables = ['room', 'User', 'module',", "models, 'module', 'module_code', 'instructor', 'user', 'username') # setting weight to be linear model" ]
[ "for item in tokenized_idx] src_number_token_values = extract_number_values(orig_tokens, dictionary, tokenizer, send_log_value=False) for sent_i, bon_pos,", "src_number_token_values: if not math.isfinite(value): print(f\"[transformer_numlm] value {value} is not finite!\") tasks = [file_path", "<filename>examples/roberta/test_load_allcorpus.py from fairseq.data.infinibatch.infinibatch_dataset import extract_number_values, word_to_idx from fairseq.data import Dictionary from multiprocessing import", "sent) for sent in tokenized_tokens] orig_tokens = [torch.LongTensor(item) for item in tokenized_idx] src_number_token_values", "dictionary, tokenizer, send_log_value=False) for sent_i, bon_pos, value in src_number_token_values: if not math.isfinite(value): print(f\"[transformer_numlm]", "in src_number_token_values: if not math.isfinite(value): print(f\"[transformer_numlm] value {value} is not finite!\") tasks =", "= open(file_path, 'r', encoding='utf8') try: lines = file.read().strip().split('\\n') except: print(f\"File: {file_path} failed to", "import torch from nltk import word_tokenize import sentencepiece as spm alias = \"\"", "tokenized_tokens = [line.strip().split(' ') for line in lines] tokenized_idx = [word_to_idx(dictionary, sent) for", "print('| Dictionary: {} types'.format(len(dictionary))) tokenizer = spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path): file = open(file_path, 'r',", "extract_number_values, word_to_idx from fairseq.data import Dictionary from multiprocessing import cpu_count, Pool import os", "word_to_idx from fairseq.data import Dictionary from multiprocessing import cpu_count, Pool import os import", "print(f\"File: {file_path} failed to split into lines.\") file.close() tokenized_tokens = [line.strip().split(' ') for", "import os import re import sys import json import glob import math import", "open(file_path, 'r', encoding='utf8') try: lines = file.read().strip().split('\\n') except: print(f\"File: {file_path} failed to split", "from nltk import word_tokenize import sentencepiece as spm alias = \"\" spm_tok_files_path =", "def test_load_file(file_path): file = open(file_path, 'r', encoding='utf8') try: lines = file.read().strip().split('\\n') except: print(f\"File:", "file.read().strip().split('\\n') except: print(f\"File: {file_path} failed to split into lines.\") file.close() tokenized_tokens = [line.strip().split('", "import re import sys import json import glob import math import torch from", "for line in lines] tokenized_idx = [word_to_idx(dictionary, sent) for sent in tokenized_tokens] orig_tokens", "math import torch from nltk import word_tokenize import sentencepiece as spm alias =", "tokenized_idx = [word_to_idx(dictionary, sent) for sent in tokenized_tokens] orig_tokens = [torch.LongTensor(item) for item", "import math import torch from nltk import word_tokenize import sentencepiece as spm alias", "spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path): file = open(file_path, 'r', encoding='utf8') try: lines = file.read().strip().split('\\n') except:", "= [line.strip().split(' ') for line in lines] tokenized_idx = [word_to_idx(dictionary, sent) for sent", "is not finite!\") tasks = [file_path for file_path in glob.glob(spm_tok_files_path+'/*.txt.*')] pool = Pool(cpu_count()", "for sent_i, bon_pos, value in src_number_token_values: if not math.isfinite(value): print(f\"[transformer_numlm] value {value} is", "import sentencepiece as spm alias = \"\" spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\"", "from multiprocessing import cpu_count, Pool import os import re import sys import json", "word_tokenize import sentencepiece as spm alias = \"\" spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path =", "lines.\") file.close() tokenized_tokens = [line.strip().split(' ') for line in lines] tokenized_idx = [word_to_idx(dictionary,", "re import sys import json import glob import math import torch from nltk", "not finite!\") tasks = [file_path for file_path in glob.glob(spm_tok_files_path+'/*.txt.*')] pool = Pool(cpu_count() -", "in tokenized_idx] src_number_token_values = extract_number_values(orig_tokens, dictionary, tokenizer, send_log_value=False) for sent_i, bon_pos, value in", "alias = \"\" spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary", "tokenized_idx] src_number_token_values = extract_number_values(orig_tokens, dictionary, tokenizer, send_log_value=False) for sent_i, bon_pos, value in src_number_token_values:", "math.isfinite(value): print(f\"[transformer_numlm] value {value} is not finite!\") tasks = [file_path for file_path in", "Dictionary.load(dictionary_path) mask_idx = dictionary.add_symbol('<mask>') print('| Dictionary: {} types'.format(len(dictionary))) tokenizer = spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path):", "tokenized_tokens] orig_tokens = [torch.LongTensor(item) for item in tokenized_idx] src_number_token_values = extract_number_values(orig_tokens, dictionary, tokenizer,", "for sent in tokenized_tokens] orig_tokens = [torch.LongTensor(item) for item in tokenized_idx] src_number_token_values =", "tokenizer, send_log_value=False) for sent_i, bon_pos, value in src_number_token_values: if not math.isfinite(value): print(f\"[transformer_numlm] value", "to split into lines.\") file.close() tokenized_tokens = [line.strip().split(' ') for line in lines]", "nltk import word_tokenize import sentencepiece as spm alias = \"\" spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\"", "sentencepiece as spm alias = \"\" spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path", "= file.read().strip().split('\\n') except: print(f\"File: {file_path} failed to split into lines.\") file.close() tokenized_tokens =", "split into lines.\") file.close() tokenized_tokens = [line.strip().split(' ') for line in lines] tokenized_idx", "import glob import math import torch from nltk import word_tokenize import sentencepiece as", "dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary = Dictionary.load(dictionary_path) mask_idx = dictionary.add_symbol('<mask>') print('|", "into lines.\") file.close() tokenized_tokens = [line.strip().split(' ') for line in lines] tokenized_idx =", "[line.strip().split(' ') for line in lines] tokenized_idx = [word_to_idx(dictionary, sent) for sent in", "f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary = Dictionary.load(dictionary_path) mask_idx = dictionary.add_symbol('<mask>') print('| Dictionary: {} types'.format(len(dictionary))) tokenizer =", "bon_pos, value in src_number_token_values: if not math.isfinite(value): print(f\"[transformer_numlm] value {value} is not finite!\")", "import word_tokenize import sentencepiece as spm alias = \"\" spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path", "tokenizer = spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path): file = open(file_path, 'r', encoding='utf8') try: lines =", "item in tokenized_idx] src_number_token_values = extract_number_values(orig_tokens, dictionary, tokenizer, send_log_value=False) for sent_i, bon_pos, value", "dictionary.add_symbol('<mask>') print('| Dictionary: {} types'.format(len(dictionary))) tokenizer = spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path): file = open(file_path,", "glob import math import torch from nltk import word_tokenize import sentencepiece as spm", "'r', encoding='utf8') try: lines = file.read().strip().split('\\n') except: print(f\"File: {file_path} failed to split into", "orig_tokens = [torch.LongTensor(item) for item in tokenized_idx] src_number_token_values = extract_number_values(orig_tokens, dictionary, tokenizer, send_log_value=False)", "= [file_path for file_path in glob.glob(spm_tok_files_path+'/*.txt.*')] pool = Pool(cpu_count() - 1) pool.map(test_load_file, tasks)", "if not math.isfinite(value): print(f\"[transformer_numlm] value {value} is not finite!\") tasks = [file_path for", "{value} is not finite!\") tasks = [file_path for file_path in glob.glob(spm_tok_files_path+'/*.txt.*')] pool =", "types'.format(len(dictionary))) tokenizer = spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path): file = open(file_path, 'r', encoding='utf8') try: lines", "multiprocessing import cpu_count, Pool import os import re import sys import json import", "= \"\" spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary =", "src_number_token_values = extract_number_values(orig_tokens, dictionary, tokenizer, send_log_value=False) for sent_i, bon_pos, value in src_number_token_values: if", "lines = file.read().strip().split('\\n') except: print(f\"File: {file_path} failed to split into lines.\") file.close() tokenized_tokens", "fairseq.data import Dictionary from multiprocessing import cpu_count, Pool import os import re import", "failed to split into lines.\") file.close() tokenized_tokens = [line.strip().split(' ') for line in", "spm alias = \"\" spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\"", "import cpu_count, Pool import os import re import sys import json import glob", "[word_to_idx(dictionary, sent) for sent in tokenized_tokens] orig_tokens = [torch.LongTensor(item) for item in tokenized_idx]", "sys import json import glob import math import torch from nltk import word_tokenize", "finite!\") tasks = [file_path for file_path in glob.glob(spm_tok_files_path+'/*.txt.*')] pool = Pool(cpu_count() - 1)", "line in lines] tokenized_idx = [word_to_idx(dictionary, sent) for sent in tokenized_tokens] orig_tokens =", "= [torch.LongTensor(item) for item in tokenized_idx] src_number_token_values = extract_number_values(orig_tokens, dictionary, tokenizer, send_log_value=False) for", "Dictionary from multiprocessing import cpu_count, Pool import os import re import sys import", "fairseq.data.infinibatch.infinibatch_dataset import extract_number_values, word_to_idx from fairseq.data import Dictionary from multiprocessing import cpu_count, Pool", "as spm alias = \"\" spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path =", "value in src_number_token_values: if not math.isfinite(value): print(f\"[transformer_numlm] value {value} is not finite!\") tasks", "= Dictionary.load(dictionary_path) mask_idx = dictionary.add_symbol('<mask>') print('| Dictionary: {} types'.format(len(dictionary))) tokenizer = spm.SentencePieceProcessor(model_file=spm_path) def", "extract_number_values(orig_tokens, dictionary, tokenizer, send_log_value=False) for sent_i, bon_pos, value in src_number_token_values: if not math.isfinite(value):", "spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary = Dictionary.load(dictionary_path) mask_idx = dictionary.add_symbol('<mask>') print('| Dictionary: {} types'.format(len(dictionary)))", "') for line in lines] tokenized_idx = [word_to_idx(dictionary, sent) for sent in tokenized_tokens]", "json import glob import math import torch from nltk import word_tokenize import sentencepiece", "Dictionary: {} types'.format(len(dictionary))) tokenizer = spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path): file = open(file_path, 'r', encoding='utf8')", "import Dictionary from multiprocessing import cpu_count, Pool import os import re import sys", "file.close() tokenized_tokens = [line.strip().split(' ') for line in lines] tokenized_idx = [word_to_idx(dictionary, sent)", "import json import glob import math import torch from nltk import word_tokenize import", "= dictionary.add_symbol('<mask>') print('| Dictionary: {} types'.format(len(dictionary))) tokenizer = spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path): file =", "print(f\"[transformer_numlm] value {value} is not finite!\") tasks = [file_path for file_path in glob.glob(spm_tok_files_path+'/*.txt.*')]", "from fairseq.data.infinibatch.infinibatch_dataset import extract_number_values, word_to_idx from fairseq.data import Dictionary from multiprocessing import cpu_count,", "= f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary = Dictionary.load(dictionary_path) mask_idx =", "sent_i, bon_pos, value in src_number_token_values: if not math.isfinite(value): print(f\"[transformer_numlm] value {value} is not", "from fairseq.data import Dictionary from multiprocessing import cpu_count, Pool import os import re", "sent in tokenized_tokens] orig_tokens = [torch.LongTensor(item) for item in tokenized_idx] src_number_token_values = extract_number_values(orig_tokens,", "import sys import json import glob import math import torch from nltk import", "import extract_number_values, word_to_idx from fairseq.data import Dictionary from multiprocessing import cpu_count, Pool import", "{file_path} failed to split into lines.\") file.close() tokenized_tokens = [line.strip().split(' ') for line", "in lines] tokenized_idx = [word_to_idx(dictionary, sent) for sent in tokenized_tokens] orig_tokens = [torch.LongTensor(item)", "spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary = Dictionary.load(dictionary_path) mask_idx", "{} types'.format(len(dictionary))) tokenizer = spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path): file = open(file_path, 'r', encoding='utf8') try:", "= spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path): file = open(file_path, 'r', encoding='utf8') try: lines = file.read().strip().split('\\n')", "tasks = [file_path for file_path in glob.glob(spm_tok_files_path+'/*.txt.*')] pool = Pool(cpu_count() - 1) pool.map(test_load_file,", "test_load_file(file_path): file = open(file_path, 'r', encoding='utf8') try: lines = file.read().strip().split('\\n') except: print(f\"File: {file_path}", "os import re import sys import json import glob import math import torch", "value {value} is not finite!\") tasks = [file_path for file_path in glob.glob(spm_tok_files_path+'/*.txt.*')] pool", "torch from nltk import word_tokenize import sentencepiece as spm alias = \"\" spm_tok_files_path", "= f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary = Dictionary.load(dictionary_path) mask_idx = dictionary.add_symbol('<mask>') print('| Dictionary:", "not math.isfinite(value): print(f\"[transformer_numlm] value {value} is not finite!\") tasks = [file_path for file_path", "mask_idx = dictionary.add_symbol('<mask>') print('| Dictionary: {} types'.format(len(dictionary))) tokenizer = spm.SentencePieceProcessor(model_file=spm_path) def test_load_file(file_path): file", "\"\" spm_tok_files_path = f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary = Dictionary.load(dictionary_path)", "file = open(file_path, 'r', encoding='utf8') try: lines = file.read().strip().split('\\n') except: print(f\"File: {file_path} failed", "= [word_to_idx(dictionary, sent) for sent in tokenized_tokens] orig_tokens = [torch.LongTensor(item) for item in", "[torch.LongTensor(item) for item in tokenized_idx] src_number_token_values = extract_number_values(orig_tokens, dictionary, tokenizer, send_log_value=False) for sent_i,", "cpu_count, Pool import os import re import sys import json import glob import", "f\"/home/{alias}/data/linyong/cu/res/allcorpus160g_num-norm_offline\" dictionary_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary = Dictionary.load(dictionary_path) mask_idx = dictionary.add_symbol('<mask>')", "in tokenized_tokens] orig_tokens = [torch.LongTensor(item) for item in tokenized_idx] src_number_token_values = extract_number_values(orig_tokens, dictionary,", "= extract_number_values(orig_tokens, dictionary, tokenizer, send_log_value=False) for sent_i, bon_pos, value in src_number_token_values: if not", "except: print(f\"File: {file_path} failed to split into lines.\") file.close() tokenized_tokens = [line.strip().split(' ')", "try: lines = file.read().strip().split('\\n') except: print(f\"File: {file_path} failed to split into lines.\") file.close()", "send_log_value=False) for sent_i, bon_pos, value in src_number_token_values: if not math.isfinite(value): print(f\"[transformer_numlm] value {value}", "dictionary = Dictionary.load(dictionary_path) mask_idx = dictionary.add_symbol('<mask>') print('| Dictionary: {} types'.format(len(dictionary))) tokenizer = spm.SentencePieceProcessor(model_file=spm_path)", "= f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary = Dictionary.load(dictionary_path) mask_idx = dictionary.add_symbol('<mask>') print('| Dictionary: {} types'.format(len(dictionary))) tokenizer", "encoding='utf8') try: lines = file.read().strip().split('\\n') except: print(f\"File: {file_path} failed to split into lines.\")", "lines] tokenized_idx = [word_to_idx(dictionary, sent) for sent in tokenized_tokens] orig_tokens = [torch.LongTensor(item) for", "f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/dict.txt\" spm_path = f\"/home/{alias}/data/linyong/cu/res/vocab/allcorpus160g_num-norm_64k/sp.num-norm.bpe.model\" dictionary = Dictionary.load(dictionary_path) mask_idx = dictionary.add_symbol('<mask>') print('| Dictionary: {}", "Pool import os import re import sys import json import glob import math" ]
[ "delimiter = '\\t', lineterminator = os.linesep, quotechar = '\\xb6' ) for line in", "\"STRG.(\\d+).\\d+\"', line[8]).group(1) if int(tx_id) % 3 == 0: line[8] = line[8] + '", "#!/usr/bin/env python3 import csv import sys import os import re infile = sys.argv[1]", "fi, open(outfile, 'wt') as fo: tblin = csv.reader(fi, delimiter = '\\t') tblout =", "= sys.argv[2] with open(infile, 'rt') as fi, open(outfile, 'wt') as fo: tblin =", "csv.reader(fi, delimiter = '\\t') tblout = csv.writer(fo, delimiter = '\\t', lineterminator = os.linesep,", "delimiter = '\\t') tblout = csv.writer(fo, delimiter = '\\t', lineterminator = os.linesep, quotechar", "= sys.argv[1] outfile = sys.argv[2] with open(infile, 'rt') as fi, open(outfile, 'wt') as", "for line in tblin: if not line[0].startswith('#'): if 'reference_id' not in line[8]: tx_id", "open(outfile, 'wt') as fo: tblin = csv.reader(fi, delimiter = '\\t') tblout = csv.writer(fo,", "'reference_id' not in line[8]: tx_id = re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1) if int(tx_id) % 3", "line[8]: tx_id = re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1) if int(tx_id) % 3 == 0: line[8]", "outfile = sys.argv[2] with open(infile, 'rt') as fi, open(outfile, 'wt') as fo: tblin", "= csv.reader(fi, delimiter = '\\t') tblout = csv.writer(fo, delimiter = '\\t', lineterminator =", "tblout = csv.writer(fo, delimiter = '\\t', lineterminator = os.linesep, quotechar = '\\xb6' )", "if 'reference_id' not in line[8]: tx_id = re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1) if int(tx_id) %", "sys.argv[2] with open(infile, 'rt') as fi, open(outfile, 'wt') as fo: tblin = csv.reader(fi,", "csv.writer(fo, delimiter = '\\t', lineterminator = os.linesep, quotechar = '\\xb6' ) for line", "int(tx_id) % 3 == 0: line[8] = line[8] + ' novel \"yes\";' tblout.writerow(line)", ") for line in tblin: if not line[0].startswith('#'): if 'reference_id' not in line[8]:", "csv import sys import os import re infile = sys.argv[1] outfile = sys.argv[2]", "if not line[0].startswith('#'): if 'reference_id' not in line[8]: tx_id = re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1)", "import csv import sys import os import re infile = sys.argv[1] outfile =", "fo: tblin = csv.reader(fi, delimiter = '\\t') tblout = csv.writer(fo, delimiter = '\\t',", "'\\t') tblout = csv.writer(fo, delimiter = '\\t', lineterminator = os.linesep, quotechar = '\\xb6'", "sys.argv[1] outfile = sys.argv[2] with open(infile, 'rt') as fi, open(outfile, 'wt') as fo:", "= '\\t', lineterminator = os.linesep, quotechar = '\\xb6' ) for line in tblin:", "os.linesep, quotechar = '\\xb6' ) for line in tblin: if not line[0].startswith('#'): if", "as fi, open(outfile, 'wt') as fo: tblin = csv.reader(fi, delimiter = '\\t') tblout", "= csv.writer(fo, delimiter = '\\t', lineterminator = os.linesep, quotechar = '\\xb6' ) for", "import sys import os import re infile = sys.argv[1] outfile = sys.argv[2] with", "line in tblin: if not line[0].startswith('#'): if 'reference_id' not in line[8]: tx_id =", "not in line[8]: tx_id = re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1) if int(tx_id) % 3 ==", "tblin: if not line[0].startswith('#'): if 'reference_id' not in line[8]: tx_id = re.search('transcript_id \"STRG.(\\d+).\\d+\"',", "lineterminator = os.linesep, quotechar = '\\xb6' ) for line in tblin: if not", "'wt') as fo: tblin = csv.reader(fi, delimiter = '\\t') tblout = csv.writer(fo, delimiter", "= '\\xb6' ) for line in tblin: if not line[0].startswith('#'): if 'reference_id' not", "quotechar = '\\xb6' ) for line in tblin: if not line[0].startswith('#'): if 'reference_id'", "in tblin: if not line[0].startswith('#'): if 'reference_id' not in line[8]: tx_id = re.search('transcript_id", "os import re infile = sys.argv[1] outfile = sys.argv[2] with open(infile, 'rt') as", "open(infile, 'rt') as fi, open(outfile, 'wt') as fo: tblin = csv.reader(fi, delimiter =", "= os.linesep, quotechar = '\\xb6' ) for line in tblin: if not line[0].startswith('#'):", "'\\t', lineterminator = os.linesep, quotechar = '\\xb6' ) for line in tblin: if", "re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1) if int(tx_id) % 3 == 0: line[8] = line[8] +", "if int(tx_id) % 3 == 0: line[8] = line[8] + ' novel \"yes\";'", "= '\\t') tblout = csv.writer(fo, delimiter = '\\t', lineterminator = os.linesep, quotechar =", "as fo: tblin = csv.reader(fi, delimiter = '\\t') tblout = csv.writer(fo, delimiter =", "not line[0].startswith('#'): if 'reference_id' not in line[8]: tx_id = re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1) if", "tx_id = re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1) if int(tx_id) % 3 == 0: line[8] =", "in line[8]: tx_id = re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1) if int(tx_id) % 3 == 0:", "import re infile = sys.argv[1] outfile = sys.argv[2] with open(infile, 'rt') as fi,", "'rt') as fi, open(outfile, 'wt') as fo: tblin = csv.reader(fi, delimiter = '\\t')", "tblin = csv.reader(fi, delimiter = '\\t') tblout = csv.writer(fo, delimiter = '\\t', lineterminator", "line[0].startswith('#'): if 'reference_id' not in line[8]: tx_id = re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1) if int(tx_id)", "= re.search('transcript_id \"STRG.(\\d+).\\d+\"', line[8]).group(1) if int(tx_id) % 3 == 0: line[8] = line[8]", "sys import os import re infile = sys.argv[1] outfile = sys.argv[2] with open(infile,", "import os import re infile = sys.argv[1] outfile = sys.argv[2] with open(infile, 'rt')", "<reponame>agladstein/RNA-Seq-in-the-Cloud #!/usr/bin/env python3 import csv import sys import os import re infile =", "python3 import csv import sys import os import re infile = sys.argv[1] outfile", "line[8]).group(1) if int(tx_id) % 3 == 0: line[8] = line[8] + ' novel", "'\\xb6' ) for line in tblin: if not line[0].startswith('#'): if 'reference_id' not in", "re infile = sys.argv[1] outfile = sys.argv[2] with open(infile, 'rt') as fi, open(outfile,", "with open(infile, 'rt') as fi, open(outfile, 'wt') as fo: tblin = csv.reader(fi, delimiter", "infile = sys.argv[1] outfile = sys.argv[2] with open(infile, 'rt') as fi, open(outfile, 'wt')" ]
[ "import pytest from tests.util import createNode node = createNode() @pytest.mark.query def test_getzmqnotifications(): #", "import createNode node = createNode() @pytest.mark.query def test_getzmqnotifications(): # 01 zmq = node.zmq.getzmqnotifications()", "pytest from tests.util import createNode node = createNode() @pytest.mark.query def test_getzmqnotifications(): # 01", "node = createNode() @pytest.mark.query def test_getzmqnotifications(): # 01 zmq = node.zmq.getzmqnotifications() assert zmq", "from tests.util import createNode node = createNode() @pytest.mark.query def test_getzmqnotifications(): # 01 zmq", "= createNode() @pytest.mark.query def test_getzmqnotifications(): # 01 zmq = node.zmq.getzmqnotifications() assert zmq or", "tests.util import createNode node = createNode() @pytest.mark.query def test_getzmqnotifications(): # 01 zmq =", "def test_getzmqnotifications(): # 01 zmq = node.zmq.getzmqnotifications() assert zmq or zmq == []", "createNode() @pytest.mark.query def test_getzmqnotifications(): # 01 zmq = node.zmq.getzmqnotifications() assert zmq or zmq", "@pytest.mark.query def test_getzmqnotifications(): # 01 zmq = node.zmq.getzmqnotifications() assert zmq or zmq ==", "createNode node = createNode() @pytest.mark.query def test_getzmqnotifications(): # 01 zmq = node.zmq.getzmqnotifications() assert" ]
[ "number \")) l=[] while n>0: a=n%10 l.append(a) n=n//10 l.reverse() for i in l:", "Prints the digits in a given number n=int(input(\"give a number \")) l=[] while", "\")) l=[] while n>0: a=n%10 l.append(a) n=n//10 l.reverse() for i in l: print(i)", "# Prints the digits in a given number n=int(input(\"give a number \")) l=[]", "digits in a given number n=int(input(\"give a number \")) l=[] while n>0: a=n%10", "a number \")) l=[] while n>0: a=n%10 l.append(a) n=n//10 l.reverse() for i in", "in a given number n=int(input(\"give a number \")) l=[] while n>0: a=n%10 l.append(a)", "the digits in a given number n=int(input(\"give a number \")) l=[] while n>0:", "given number n=int(input(\"give a number \")) l=[] while n>0: a=n%10 l.append(a) n=n//10 l.reverse()", "number n=int(input(\"give a number \")) l=[] while n>0: a=n%10 l.append(a) n=n//10 l.reverse() for", "n=int(input(\"give a number \")) l=[] while n>0: a=n%10 l.append(a) n=n//10 l.reverse() for i", "a given number n=int(input(\"give a number \")) l=[] while n>0: a=n%10 l.append(a) n=n//10" ]
[ "# 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id == \"c_1\"')) print(reserve_tb.query('customer_id == \"c_1\"')) if __name__ ==", "# 年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] = reserve_tb['checkin_date'] \\ .apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算 #", "pd.DataFrame({'year_month': [(date(2017, 1, 1) + relativedelta(months=x)).strftime(\"%Y%m\") for x in range(0, 3)]}) # month_mst['year_month']", "from preprocess.load_data.data_loader import load_hotel_reserve import pandas as pd from datetime import date, datetime", "on=['customer_id', 'year_month'], how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id == \"c_1\"')) print(reserve_tb.query('customer_id", "print(reserve_tb) print(customer_tb) # 日付マスタを生成 month_mst = pd.DataFrame({'year_month': [(date(2017, 1, 1) + relativedelta(months=x)).strftime(\"%Y%m\") for", "TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result = pd.merge( customer_mst, reserve_tb[['customer_id', 'year_month', 'total_price']], on=['customer_id', 'year_month'], how='left' ).groupby(['customer_id',", "\"\"\" customer_tb, hotel_tb, reserve_tb = load_hotel_reserve() print(reserve_tb) print(customer_tb) # 日付マスタを生成 month_mst = pd.DataFrame({'year_month':", "= 0 # 顧客テーブルと月テーブルを全結合する customer_mst = pd.merge(customer_tb[['customer_id', 'join_key']], month_mst, on='join_key') customer_mst.info() # 年月の結合キーを予約テーブルで準備", "# 顧客テーブルと月テーブルを全結合する customer_mst = pd.merge(customer_tb[['customer_id', 'join_key']], month_mst, on='join_key') customer_mst.info() # 年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] =", "from pandas._config.config import reset_option from preprocess.load_data.data_loader import load_hotel_reserve import pandas as pd from", "= load_hotel_reserve() print(reserve_tb) print(customer_tb) # 日付マスタを生成 month_mst = pd.DataFrame({'year_month': [(date(2017, 1, 1) +", ".apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算 # TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result = pd.merge( customer_mst,", "x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算 # TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result = pd.merge( customer_mst, reserve_tb[['customer_id',", "年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] = reserve_tb['checkin_date'] \\ .apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算 # TODO:", "'year_month', 'total_price']], on=['customer_id', 'year_month'], how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id ==", "customer_tb['join_key'] = 0 month_mst['join_key'] = 0 # 顧客テーブルと月テーブルを全結合する customer_mst = pd.merge(customer_tb[['customer_id', 'join_key']], month_mst,", "= pd.merge( customer_mst, reserve_tb[['customer_id', 'year_month', 'total_price']], on=['customer_id', 'year_month'], how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換", "date, datetime from dateutil.relativedelta import relativedelta def main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する \"\"\"", "+ relativedelta(months=x)).strftime(\"%Y%m\") for x in range(0, 3)]}) # month_mst['year_month'] = pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備", "month_mst['year_month'] = pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] = 0 month_mst['join_key'] = 0 # 顧客テーブルと月テーブルを全結合する", "reset_option from preprocess.load_data.data_loader import load_hotel_reserve import pandas as pd from datetime import date,", "利用がない日は0とする 日付はチェックイン日付を利用する \"\"\" customer_tb, hotel_tb, reserve_tb = load_hotel_reserve() print(reserve_tb) print(customer_tb) # 日付マスタを生成 month_mst", "customer_tb, hotel_tb, reserve_tb = load_hotel_reserve() print(reserve_tb) print(customer_tb) # 日付マスタを生成 month_mst = pd.DataFrame({'year_month': [(date(2017,", "'total_price']], on=['customer_id', 'year_month'], how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id == \"c_1\"'))", "= 0 month_mst['join_key'] = 0 # 顧客テーブルと月テーブルを全結合する customer_mst = pd.merge(customer_tb[['customer_id', 'join_key']], month_mst, on='join_key')", "予約レコードと結合し、合計予約金額を計算 # TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result = pd.merge( customer_mst, reserve_tb[['customer_id', 'year_month', 'total_price']], on=['customer_id', 'year_month'],", "0 month_mst['join_key'] = 0 # 顧客テーブルと月テーブルを全結合する customer_mst = pd.merge(customer_tb[['customer_id', 'join_key']], month_mst, on='join_key') customer_mst.info()", "pd.merge( customer_mst, reserve_tb[['customer_id', 'year_month', 'total_price']], on=['customer_id', 'year_month'], how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0,", "顧客テーブルと月テーブルを全結合する customer_mst = pd.merge(customer_tb[['customer_id', 'join_key']], month_mst, on='join_key') customer_mst.info() # 年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] = reserve_tb['checkin_date']", "1) + relativedelta(months=x)).strftime(\"%Y%m\") for x in range(0, 3)]}) # month_mst['year_month'] = pd.to_datetime(month_mst['year_month']) #", "how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id == \"c_1\"')) print(reserve_tb.query('customer_id == \"c_1\"'))", "'join_key']], month_mst, on='join_key') customer_mst.info() # 年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] = reserve_tb['checkin_date'] \\ .apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\"))", "pd from datetime import date, datetime from dateutil.relativedelta import relativedelta def main(): \"\"\"全結合処理", "from dateutil.relativedelta import relativedelta def main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する \"\"\" customer_tb, hotel_tb,", "\\ .apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算 # TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result = pd.merge(", "# 予約レコードと結合し、合計予約金額を計算 # TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result = pd.merge( customer_mst, reserve_tb[['customer_id', 'year_month', 'total_price']], on=['customer_id',", "# TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result = pd.merge( customer_mst, reserve_tb[['customer_id', 'year_month', 'total_price']], on=['customer_id', 'year_month'], how='left'", "予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id == \"c_1\"')) print(reserve_tb.query('customer_id == \"c_1\"')) if __name__ == '__main__':", "# month_mst['year_month'] = pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] = 0 month_mst['join_key'] = 0 #", "pandas as pd from datetime import date, datetime from dateutil.relativedelta import relativedelta def", "hotel_tb, reserve_tb = load_hotel_reserve() print(reserve_tb) print(customer_tb) # 日付マスタを生成 month_mst = pd.DataFrame({'year_month': [(date(2017, 1,", "= pd.DataFrame({'year_month': [(date(2017, 1, 1) + relativedelta(months=x)).strftime(\"%Y%m\") for x in range(0, 3)]}) #", "customer_mst, reserve_tb[['customer_id', 'year_month', 'total_price']], on=['customer_id', 'year_month'], how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True)", "reserve_tb['checkin_date'] \\ .apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算 # TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result =", "cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] = 0 month_mst['join_key'] = 0 # 顧客テーブルと月テーブルを全結合する customer_mst = pd.merge(customer_tb[['customer_id', 'join_key']],", "dateutil.relativedelta import relativedelta def main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する \"\"\" customer_tb, hotel_tb, reserve_tb", "= pd.merge(customer_tb[['customer_id', 'join_key']], month_mst, on='join_key') customer_mst.info() # 年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] = reserve_tb['checkin_date'] \\ .apply(lambda", "x in range(0, 3)]}) # month_mst['year_month'] = pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] = 0", "0 # 顧客テーブルと月テーブルを全結合する customer_mst = pd.merge(customer_tb[['customer_id', 'join_key']], month_mst, on='join_key') customer_mst.info() # 年月の結合キーを予約テーブルで準備 reserve_tb['year_month']", "summary_result = pd.merge( customer_mst, reserve_tb[['customer_id', 'year_month', 'total_price']], on=['customer_id', 'year_month'], how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() #", "pandas._config.config import reset_option from preprocess.load_data.data_loader import load_hotel_reserve import pandas as pd from datetime", "for x in range(0, 3)]}) # month_mst['year_month'] = pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] =", "def main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する \"\"\" customer_tb, hotel_tb, reserve_tb = load_hotel_reserve() print(reserve_tb)", "load_hotel_reserve import pandas as pd from datetime import date, datetime from dateutil.relativedelta import", "\"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する \"\"\" customer_tb, hotel_tb, reserve_tb = load_hotel_reserve() print(reserve_tb) print(customer_tb) #", "import date, datetime from dateutil.relativedelta import relativedelta def main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する", "reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算 # TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result = pd.merge( customer_mst, reserve_tb[['customer_id', 'year_month', 'total_price']],", "in range(0, 3)]}) # month_mst['year_month'] = pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] = 0 month_mst['join_key']", ").groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id == \"c_1\"')) print(reserve_tb.query('customer_id == \"c_1\"')) if", "= pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] = 0 month_mst['join_key'] = 0 # 顧客テーブルと月テーブルを全結合する customer_mst", "datetime from dateutil.relativedelta import relativedelta def main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する \"\"\" customer_tb,", "reserve_tb['year_month'] = reserve_tb['checkin_date'] \\ .apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算 # TODO: yearで結合できていない(月単位で結合されてしまっている)", "'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id == \"c_1\"')) print(reserve_tb.query('customer_id == \"c_1\"')) if __name__", "1, 1) + relativedelta(months=x)).strftime(\"%Y%m\") for x in range(0, 3)]}) # month_mst['year_month'] = pd.to_datetime(month_mst['year_month'])", "month_mst['join_key'] = 0 # 顧客テーブルと月テーブルを全結合する customer_mst = pd.merge(customer_tb[['customer_id', 'join_key']], month_mst, on='join_key') customer_mst.info() #", "pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算 # TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result = pd.merge( customer_mst, reserve_tb[['customer_id', 'year_month',", "import relativedelta def main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する \"\"\" customer_tb, hotel_tb, reserve_tb =", "reserve_tb = load_hotel_reserve() print(reserve_tb) print(customer_tb) # 日付マスタを生成 month_mst = pd.DataFrame({'year_month': [(date(2017, 1, 1)", "month_mst = pd.DataFrame({'year_month': [(date(2017, 1, 1) + relativedelta(months=x)).strftime(\"%Y%m\") for x in range(0, 3)]})", "# cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] = 0 month_mst['join_key'] = 0 # 顧客テーブルと月テーブルを全結合する customer_mst = pd.merge(customer_tb[['customer_id',", "main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する \"\"\" customer_tb, hotel_tb, reserve_tb = load_hotel_reserve() print(reserve_tb) print(customer_tb)", "# 日付マスタを生成 month_mst = pd.DataFrame({'year_month': [(date(2017, 1, 1) + relativedelta(months=x)).strftime(\"%Y%m\") for x in", "relativedelta(months=x)).strftime(\"%Y%m\") for x in range(0, 3)]}) # month_mst['year_month'] = pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key']", "range(0, 3)]}) # month_mst['year_month'] = pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] = 0 month_mst['join_key'] =", "customer_mst.info() # 年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] = reserve_tb['checkin_date'] \\ .apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算", "import reset_option from preprocess.load_data.data_loader import load_hotel_reserve import pandas as pd from datetime import", "datetime import date, datetime from dateutil.relativedelta import relativedelta def main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする", "on='join_key') customer_mst.info() # 年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] = reserve_tb['checkin_date'] \\ .apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() #", "yearで結合できていない(月単位で結合されてしまっている) summary_result = pd.merge( customer_mst, reserve_tb[['customer_id', 'year_month', 'total_price']], on=['customer_id', 'year_month'], how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index()", "'year_month'], how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id == \"c_1\"')) print(reserve_tb.query('customer_id ==", "日付マスタを生成 month_mst = pd.DataFrame({'year_month': [(date(2017, 1, 1) + relativedelta(months=x)).strftime(\"%Y%m\") for x in range(0,", "summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id == \"c_1\"')) print(reserve_tb.query('customer_id == \"c_1\"')) if __name__ == '__main__': main()", "preprocess.load_data.data_loader import load_hotel_reserve import pandas as pd from datetime import date, datetime from", "customer_mst = pd.merge(customer_tb[['customer_id', 'join_key']], month_mst, on='join_key') customer_mst.info() # 年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] = reserve_tb['checkin_date'] \\", "[(date(2017, 1, 1) + relativedelta(months=x)).strftime(\"%Y%m\") for x in range(0, 3)]}) # month_mst['year_month'] =", "reserve_tb[['customer_id', 'year_month', 'total_price']], on=['customer_id', 'year_month'], how='left' ).groupby(['customer_id', 'year_month'])['total_price'].sum().reset_index() # 予約レコードがなかった場合の合計金額を値なしから0に変換 summary_result.fillna(0, inplace=True) print(summary_result.query('customer_id", "= reserve_tb['checkin_date'] \\ .apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info() # 予約レコードと結合し、合計予約金額を計算 # TODO: yearで結合できていない(月単位で結合されてしまっている) summary_result", "import pandas as pd from datetime import date, datetime from dateutil.relativedelta import relativedelta", "from datetime import date, datetime from dateutil.relativedelta import relativedelta def main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算", "import load_hotel_reserve import pandas as pd from datetime import date, datetime from dateutil.relativedelta", "日付はチェックイン日付を利用する \"\"\" customer_tb, hotel_tb, reserve_tb = load_hotel_reserve() print(reserve_tb) print(customer_tb) # 日付マスタを生成 month_mst =", "pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] = 0 month_mst['join_key'] = 0 # 顧客テーブルと月テーブルを全結合する customer_mst =", "load_hotel_reserve() print(reserve_tb) print(customer_tb) # 日付マスタを生成 month_mst = pd.DataFrame({'year_month': [(date(2017, 1, 1) + relativedelta(months=x)).strftime(\"%Y%m\")", "relativedelta def main(): \"\"\"全結合処理 顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する \"\"\" customer_tb, hotel_tb, reserve_tb = load_hotel_reserve()", "month_mst, on='join_key') customer_mst.info() # 年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] = reserve_tb['checkin_date'] \\ .apply(lambda x: pd.to_datetime(x).strftime(\"%Y%m\")) reserve_tb.info()", "as pd from datetime import date, datetime from dateutil.relativedelta import relativedelta def main():", "pd.merge(customer_tb[['customer_id', 'join_key']], month_mst, on='join_key') customer_mst.info() # 年月の結合キーを予約テーブルで準備 reserve_tb['year_month'] = reserve_tb['checkin_date'] \\ .apply(lambda x:", "3)]}) # month_mst['year_month'] = pd.to_datetime(month_mst['year_month']) # cross_joinのためにすべて同じ値の結合キーを準備 customer_tb['join_key'] = 0 month_mst['join_key'] = 0", "print(customer_tb) # 日付マスタを生成 month_mst = pd.DataFrame({'year_month': [(date(2017, 1, 1) + relativedelta(months=x)).strftime(\"%Y%m\") for x", "顧客ごとに2017年1月〜2017年3月の月間合計利用金額を計算 利用がない日は0とする 日付はチェックイン日付を利用する \"\"\" customer_tb, hotel_tb, reserve_tb = load_hotel_reserve() print(reserve_tb) print(customer_tb) # 日付マスタを生成" ]
[ "<gh_stars>0 from flask import Blueprint blue_load = Blueprint('load', __name__) from . import view" ]
[ "def snake_case(s): return '_'.join( sub('([A-Z][a-z]+)', r' \\1', sub('([A-Z]+)', r' \\1', s.replace('-', ' '))).split()).lower()", "re import sub def snake_case(s): return '_'.join( sub('([A-Z][a-z]+)', r' \\1', sub('([A-Z]+)', r' \\1',", "sub def snake_case(s): return '_'.join( sub('([A-Z][a-z]+)', r' \\1', sub('([A-Z]+)', r' \\1', s.replace('-', '", "from re import sub def snake_case(s): return '_'.join( sub('([A-Z][a-z]+)', r' \\1', sub('([A-Z]+)', r'", "<reponame>marcelobbfonseca/SFDjango-BPMN<gh_stars>1-10 from re import sub def snake_case(s): return '_'.join( sub('([A-Z][a-z]+)', r' \\1', sub('([A-Z]+)',", "import sub def snake_case(s): return '_'.join( sub('([A-Z][a-z]+)', r' \\1', sub('([A-Z]+)', r' \\1', s.replace('-'," ]
[ "mean_squared_error from sklearn.decomposition import PCA from time import time import numpy as np", "train_Y.values.ravel()) # print(\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_)) model = AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5,", "# print np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\" t = time() # model = GridSearchCV( #", "n_estimators=800, learning_rate=0.1) # 拟合训练数据集 model.fit(train_X, train_Y.values.ravel()) # 预测测试集 test_Y_pred = model.predict(test_X) print \"测试集MSE:\",", "# base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, # min_samples_leaf=3), learning_rate=0.1), # param_grid={\"n_estimators\": range(500, 1501, 100)},", "pca.fit_transform(train_X[sub_idx]) # print np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\" t = time() # model = GridSearchCV(", "import GridSearchCV, train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, mean_squared_error from", "train_Y) # 预测训练集 train_Y_hat = model.predict(train_X[idx]) print \"训练集精确度: \", accuracy_score(train_Y[idx], train_Y_hat) # 预测测试集", "AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, min_samples_leaf=3), n_estimators=1200, learning_rate=0.005) # 拟合训练数据集 model.fit(train_X, train_Y) #", "= PCA(n_components=0.9, whiten=True, random_state=0) # for i in range(int(np.ceil(1.0 * m / num))):", "# num = 30000 # pca = PCA(n_components=0.9, whiten=True, random_state=0) # for i", "= np.shape(train_X) idx = range(m) np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\" t = time() # model", "# pca = PCA(n_components=0.9, whiten=True, random_state=0) # for i in range(int(np.ceil(1.0 * m", "AP:湿度, RH:压强, PE:输出电力 # 样本特征X X = data[['AT', 'V', 'AP', 'RH']] # 数据归一化", "使用PCA降维 # num = 30000 # pca = PCA(n_components=0.9, whiten=True, random_state=0) # for", "model.best_score_)) model = AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5, min_samples_leaf=3), n_estimators=800, learning_rate=0.1) # 拟合训练数据集 model.fit(train_X,", "from sklearn.metrics import accuracy_score, mean_squared_error from sklearn.decomposition import PCA from time import time", "# model = GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth': range(10, 30, 2), 'min_samples_split': range(11, 31, 2),", "= mnist.loadLecunMnistSet() train_X, train_Y, test_X, test_Y = mnistSet[0], mnistSet[1], mnistSet[2], mnistSet[3] m, n", "n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) # 使用PCA降维 # num = 30000", "test_Y, test_Y_hat) # 读取CCPP数据集, 测试AdaBoost的回归模型 data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度, V:压力, AP:湿度, RH:压强,", "min((i + 1) * num, m) # sub_idx = idx[i * num:minEnd] #", "\"测试集精确度: \", accuracy_score(test_Y, test_Y_hat) print \"总耗时:\", time() - t, \"秒\" # 绘制ROC曲线 n_class", "__name__ == \"__main__\": # 读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet = mnist.loadLecunMnistSet() train_X, train_Y, test_X, test_Y", "minEnd = min((i + 1) * num, m) # sub_idx = idx[i *", "* num:minEnd] # train_pca_X = pca.fit_transform(train_X[sub_idx]) # print np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\" t =", "% (model.best_params_, model.best_score_) model = AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, min_samples_leaf=3), n_estimators=1200, learning_rate=0.005)", "from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.preprocessing import", "* num, m) # sub_idx = idx[i * num:minEnd] # train_pca_X = pca.fit_transform(train_X[sub_idx])", "mnistSet[2], mnistSet[3] m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) # 使用PCA降维 #", "# minEnd = min((i + 1) * num, m) # sub_idx = idx[i", "model.fit(train_X, train_Y) # print \"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_) model = AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random',", "StandardScaler().fit_transform(X) # 样本输出Y Y = data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X, train_Y, test_Y =", "1501, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y) # print \"最好的参数是:%s, 此时的得分是:%0.2f\"", "test_Y = mnistSet[0], mnistSet[1], mnistSet[2], mnistSet[3] m, n = np.shape(train_X) idx = range(m)", "train_X, test_X, train_Y, test_Y = train_test_split(X, Y, test_size=0.3, random_state=1) m, n = np.shape(train_X)", "'min_samples_split': range(11, 31, 2), # 'min_samples_leaf': range(2, 8, 1)}, cv=5) # model =", "100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y.values.ravel()) # print(\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_,", "= time() # model = GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth': range(10, 30, 2), 'min_samples_split': range(11,", "# 拟合训练数据集 model.fit(train_X, train_Y) # 预测训练集 train_Y_hat = model.predict(train_X[idx]) print \"训练集精确度: \", accuracy_score(train_Y[idx],", "pandas as pd import mnist import roc if __name__ == \"__main__\": # 读取Mnist数据集,", "# print \"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_) model = AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50,", "cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y) # print \"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_,", "range(100, 1001, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y.values.ravel()) # print(\"最好的参数是:%s, 此时的得分是:%0.2f\"", "model = GridSearchCV( # estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, # min_samples_leaf=3), learning_rate=0.1),", "idx[i * num:minEnd] # train_pca_X = pca.fit_transform(train_X[sub_idx]) # print np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\" t", "AdaBoostRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.preprocessing", "range(m) np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\" t = time() # model = GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth':", "* m / num))): # minEnd = min((i + 1) * num, m)", "test_Y_hat) print \"总耗时:\", time() - t, \"秒\" # 绘制ROC曲线 n_class = len(np.unique(train_Y)) roc.drawROC(n_class,", "30000 # pca = PCA(n_components=0.9, whiten=True, random_state=0) # for i in range(int(np.ceil(1.0 *", "t, \"秒\" # 绘制ROC曲线 n_class = len(np.unique(train_Y)) roc.drawROC(n_class, test_Y, test_Y_hat) # 读取CCPP数据集, 测试AdaBoost的回归模型", "from sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection import", "train_Y_hat = model.predict(train_X[idx]) print \"训练集精确度: \", accuracy_score(train_Y[idx], train_Y_hat) # 预测测试集 test_Y_hat = model.predict(test_X)", "model.fit(train_X, train_Y) # 预测训练集 train_Y_hat = model.predict(train_X[idx]) print \"训练集精确度: \", accuracy_score(train_Y[idx], train_Y_hat) #", "max_depth=28, min_samples_split=11, min_samples_leaf=3), # learning_rate=0.1), param_grid={\"n_estimators\": range(100, 1001, 100)}, cv=3) # # 拟合训练数据集", "31, 2), # 'min_samples_leaf': range(2, 8, 1)}, cv=5) # model = GridSearchCV(AdaBoostRegressor( #", "+ 1) * num, m) # sub_idx = idx[i * num:minEnd] # train_pca_X", "拟合训练数据集 # model.fit(train_X, train_Y.values.ravel()) # print(\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_)) model = AdaBoostRegressor(", "此时的得分是:%0.2f\" % (model.best_params_, model.best_score_)) model = AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5, min_samples_leaf=3), n_estimators=800, learning_rate=0.1)", "sub_idx = idx[i * num:minEnd] # train_pca_X = pca.fit_transform(train_X[sub_idx]) # print np.shape(train_pca_X) print", "此时的得分是:%0.2f\" % (model.best_params_, model.best_score_) model = AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, min_samples_leaf=3), n_estimators=1200,", "# # 拟合训练数据集 # model.fit(train_X, train_Y) # print \"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_)", "预测测试集 test_Y_pred = model.predict(test_X) print \"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred) print \"测试集RMSE:\", np.sqrt(mean_squared_error(test_Y, test_Y_pred)) print", "range(2, 8, 1)}, cv=5) # model = GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11, min_samples_leaf=3),", "model.fit(train_X, train_Y.values.ravel()) # print(\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_)) model = AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20,", "import numpy as np import pandas as pd import mnist import roc if", "mnist.loadLecunMnistSet() train_X, train_Y, test_X, test_Y = mnistSet[0], mnistSet[1], mnistSet[2], mnistSet[3] m, n =", "sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, mean_squared_error from sklearn.decomposition import PCA from", "model = AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5, min_samples_leaf=3), n_estimators=800, learning_rate=0.1) # 拟合训练数据集 model.fit(train_X, train_Y.values.ravel())", "数据归一化 X = StandardScaler().fit_transform(X) # 样本输出Y Y = data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X,", "import AdaBoostClassifier, AdaBoostRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection import GridSearchCV, train_test_split", "# 拟合训练数据集 model.fit(train_X, train_Y.values.ravel()) # 预测测试集 test_Y_pred = model.predict(test_X) print \"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred)", "roc if __name__ == \"__main__\": # 读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet = mnist.loadLecunMnistSet() train_X, train_Y,", "# 拟合训练数据集 # model.fit(train_X, train_Y) # print \"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_) model", "min_samples_split=6, min_samples_leaf=3), n_estimators=1200, learning_rate=0.005) # 拟合训练数据集 model.fit(train_X, train_Y) # 预测训练集 train_Y_hat = model.predict(train_X[idx])", "print \"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred) print \"测试集RMSE:\", np.sqrt(mean_squared_error(test_Y, test_Y_pred)) print \"总耗时:\", time() - t,", "num:minEnd] # train_pca_X = pca.fit_transform(train_X[sub_idx]) # print np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\" t = time()", "train_Y, test_Y = train_test_split(X, Y, test_size=0.3, random_state=1) m, n = np.shape(train_X) idx =", "\"训练集精确度: \", accuracy_score(train_Y[idx], train_Y_hat) # 预测测试集 test_Y_hat = model.predict(test_X) print \"测试集精确度: \", accuracy_score(test_Y,", "(model.best_params_, model.best_score_)) model = AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5, min_samples_leaf=3), n_estimators=800, learning_rate=0.1) # 拟合训练数据集", "# 拟合训练数据集 # model.fit(train_X, train_Y.values.ravel()) # print(\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_)) model =", "from sklearn.decomposition import PCA from time import time import numpy as np import", "2), # 'min_samples_leaf': range(2, 8, 1)}, cv=5) # model = GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random',", "m) # sub_idx = idx[i * num:minEnd] # train_pca_X = pca.fit_transform(train_X[sub_idx]) # print", "pd import mnist import roc if __name__ == \"__main__\": # 读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet", "# train_pca_X = pca.fit_transform(train_X[sub_idx]) # print np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\" t = time() #", "# param_grid={\"n_estimators\": range(500, 1501, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y) #", "= train_test_split(X, Y, test_size=0.3, random_state=1) m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx)", "estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, # min_samples_leaf=3), learning_rate=0.1), # param_grid={\"n_estimators\": range(500, 1501,", "样本特征X X = data[['AT', 'V', 'AP', 'RH']] # 数据归一化 X = StandardScaler().fit_transform(X) #", "# 样本特征X X = data[['AT', 'V', 'AP', 'RH']] # 数据归一化 X = StandardScaler().fit_transform(X)", "'min_samples_leaf': range(2, 8, 1)}, cv=5) # model = GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11,", "time import time import numpy as np import pandas as pd import mnist", "== \"__main__\": # 读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet = mnist.loadLecunMnistSet() train_X, train_Y, test_X, test_Y =", "# min_samples_leaf=3), learning_rate=0.1), # param_grid={\"n_estimators\": range(500, 1501, 100)}, cv=3) # # 拟合训练数据集 #", "\"秒\" # 绘制ROC曲线 n_class = len(np.unique(train_Y)) roc.drawROC(n_class, test_Y, test_Y_hat) # 读取CCPP数据集, 测试AdaBoost的回归模型 data", "print \"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_) model = AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6,", "len(np.unique(train_Y)) roc.drawROC(n_class, test_Y, test_Y_hat) # 读取CCPP数据集, 测试AdaBoost的回归模型 data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度, V:压力,", "in range(int(np.ceil(1.0 * m / num))): # minEnd = min((i + 1) *", "import PCA from time import time import numpy as np import pandas as", "numpy as np import pandas as pd import mnist import roc if __name__", "划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X, train_Y, test_Y = train_test_split(X, Y, test_size=0.3, random_state=1) m, n =", "拟合训练数据集 model.fit(train_X, train_Y) # 预测训练集 train_Y_hat = model.predict(train_X[idx]) print \"训练集精确度: \", accuracy_score(train_Y[idx], train_Y_hat)", "train_Y, test_X, test_Y = mnistSet[0], mnistSet[1], mnistSet[2], mnistSet[3] m, n = np.shape(train_X) idx", "= mnistSet[0], mnistSet[1], mnistSet[2], mnistSet[3] m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx)", "model = GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth': range(10, 30, 2), 'min_samples_split': range(11, 31, 2), #", "# sub_idx = idx[i * num:minEnd] # train_pca_X = pca.fit_transform(train_X[sub_idx]) # print np.shape(train_pca_X)", "time import numpy as np import pandas as pd import mnist import roc", "pca = PCA(n_components=0.9, whiten=True, random_state=0) # for i in range(int(np.ceil(1.0 * m /", "base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11, min_samples_leaf=3), # learning_rate=0.1), param_grid={\"n_estimators\": range(100, 1001, 100)}, cv=3) # #", "# for i in range(int(np.ceil(1.0 * m / num))): # minEnd = min((i", "1)}, cv=5) # model = GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11, min_samples_leaf=3), # learning_rate=0.1),", "model.predict(test_X) print \"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred) print \"测试集RMSE:\", np.sqrt(mean_squared_error(test_Y, test_Y_pred)) print \"总耗时:\", time() -", "V:压力, AP:湿度, RH:压强, PE:输出电力 # 样本特征X X = data[['AT', 'V', 'AP', 'RH']] #", "idx = range(m) np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\" t = time() # model = GridSearchCV(DecisionTreeRegressor(splitter='random'),", "mnistSet[3] m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) # 使用PCA降维 # num", "# 使用PCA降维 # num = 30000 # pca = PCA(n_components=0.9, whiten=True, random_state=0) #", "DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics", "t = time() # model = GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth': range(10, 30, 2), 'min_samples_split':", "max_depth=20, min_samples_split=5, min_samples_leaf=3), n_estimators=800, learning_rate=0.1) # 拟合训练数据集 model.fit(train_X, train_Y.values.ravel()) # 预测测试集 test_Y_pred =", "= range(m) np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\" t = time() # model = GridSearchCV(DecisionTreeRegressor(splitter='random'), #", "# 绘制ROC曲线 n_class = len(np.unique(train_Y)) roc.drawROC(n_class, test_Y, test_Y_hat) # 读取CCPP数据集, 测试AdaBoost的回归模型 data =", "= model.predict(test_X) print \"测试集精确度: \", accuracy_score(test_Y, test_Y_hat) print \"总耗时:\", time() - t, \"秒\"", "读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet = mnist.loadLecunMnistSet() train_X, train_Y, test_X, test_Y = mnistSet[0], mnistSet[1], mnistSet[2],", "GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth': range(10, 30, 2), 'min_samples_split': range(11, 31, 2), # 'min_samples_leaf': range(2,", "import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.preprocessing import StandardScaler from", "= min((i + 1) * num, m) # sub_idx = idx[i * num:minEnd]", "range(int(np.ceil(1.0 * m / num))): # minEnd = min((i + 1) * num,", "= StandardScaler().fit_transform(X) # 样本输出Y Y = data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X, train_Y, test_Y", "import mnist import roc if __name__ == \"__main__\": # 读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet =", "accuracy_score, mean_squared_error from sklearn.decomposition import PCA from time import time import numpy as", "for i in range(int(np.ceil(1.0 * m / num))): # minEnd = min((i +", "learning_rate=0.1), # param_grid={\"n_estimators\": range(500, 1501, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y)", "np.shape(train_X) idx = range(m) np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\" t = time() # model =", "= data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X, train_Y, test_Y = train_test_split(X, Y, test_size=0.3, random_state=1)", "mnistSet[1], mnistSet[2], mnistSet[3] m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) # 使用PCA降维", "train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, mean_squared_error from sklearn.decomposition import", "= GridSearchCV( # estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, # min_samples_leaf=3), learning_rate=0.1), #", "data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X, train_Y, test_Y = train_test_split(X, Y, test_size=0.3, random_state=1) m,", "预测测试集 test_Y_hat = model.predict(test_X) print \"测试集精确度: \", accuracy_score(test_Y, test_Y_hat) print \"总耗时:\", time() -", "range(500, 1501, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y) # print \"最好的参数是:%s,", "import roc if __name__ == \"__main__\": # 读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet = mnist.loadLecunMnistSet() train_X,", "测试AdaBoost的回归模型 data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度, V:压力, AP:湿度, RH:压强, PE:输出电力 # 样本特征X X", "# model.fit(train_X, train_Y) # print \"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_) model = AdaBoostClassifier(", "= GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11, min_samples_leaf=3), # learning_rate=0.1), param_grid={\"n_estimators\": range(100, 1001, 100)},", "'AP', 'RH']] # 数据归一化 X = StandardScaler().fit_transform(X) # 样本输出Y Y = data[['PE']] #", "model = AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, min_samples_leaf=3), n_estimators=1200, learning_rate=0.005) # 拟合训练数据集 model.fit(train_X,", "test_X, test_Y = mnistSet[0], mnistSet[1], mnistSet[2], mnistSet[3] m, n = np.shape(train_X) idx =", "num = 30000 # pca = PCA(n_components=0.9, whiten=True, random_state=0) # for i in", "model.predict(train_X[idx]) print \"训练集精确度: \", accuracy_score(train_Y[idx], train_Y_hat) # 预测测试集 test_Y_hat = model.predict(test_X) print \"测试集精确度:", "train_pca_X = pca.fit_transform(train_X[sub_idx]) # print np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\" t = time() # model", "# AT:温度, V:压力, AP:湿度, RH:压强, PE:输出电力 # 样本特征X X = data[['AT', 'V', 'AP',", "2), 'min_samples_split': range(11, 31, 2), # 'min_samples_leaf': range(2, 8, 1)}, cv=5) # model", "random_state=1) m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\" t =", "learning_rate=0.1) # 拟合训练数据集 model.fit(train_X, train_Y.values.ravel()) # 预测测试集 test_Y_pred = model.predict(test_X) print \"测试集MSE:\", mean_squared_error(test_Y,", "np.shape(train_X) idx = range(m) np.random.shuffle(idx) # 使用PCA降维 # num = 30000 # pca", "# estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, # min_samples_leaf=3), learning_rate=0.1), # param_grid={\"n_estimators\": range(500,", "= pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度, V:压力, AP:湿度, RH:压强, PE:输出电力 # 样本特征X X = data[['AT',", "i in range(int(np.ceil(1.0 * m / num))): # minEnd = min((i + 1)", "max_features=90, max_depth=50, min_samples_split=6, # min_samples_leaf=3), learning_rate=0.1), # param_grid={\"n_estimators\": range(500, 1501, 100)}, cv=3) #", "max_depth=50, min_samples_split=6, # min_samples_leaf=3), learning_rate=0.1), # param_grid={\"n_estimators\": range(500, 1501, 100)}, cv=3) # #", "= range(m) np.random.shuffle(idx) # 使用PCA降维 # num = 30000 # pca = PCA(n_components=0.9,", "# model = GridSearchCV( # estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, # min_samples_leaf=3),", "min_samples_leaf=3), n_estimators=800, learning_rate=0.1) # 拟合训练数据集 model.fit(train_X, train_Y.values.ravel()) # 预测测试集 test_Y_pred = model.predict(test_X) print", "# 'min_samples_leaf': range(2, 8, 1)}, cv=5) # model = GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28,", "= idx[i * num:minEnd] # train_pca_X = pca.fit_transform(train_X[sub_idx]) # print np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\"", "min_samples_leaf=3), # learning_rate=0.1), param_grid={\"n_estimators\": range(100, 1001, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X,", "# 预测测试集 test_Y_pred = model.predict(test_X) print \"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred) print \"测试集RMSE:\", np.sqrt(mean_squared_error(test_Y, test_Y_pred))", "# 读取CCPP数据集, 测试AdaBoost的回归模型 data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度, V:压力, AP:湿度, RH:压强, PE:输出电力 #", "model.best_score_) model = AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, min_samples_leaf=3), n_estimators=1200, learning_rate=0.005) # 拟合训练数据集", "# learning_rate=0.1), param_grid={\"n_estimators\": range(100, 1001, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y.values.ravel())", "= 30000 # pca = PCA(n_components=0.9, whiten=True, random_state=0) # for i in range(int(np.ceil(1.0", "train_Y) # print \"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_) model = AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90,", "accuracy_score(test_Y, test_Y_hat) print \"总耗时:\", time() - t, \"秒\" # 绘制ROC曲线 n_class = len(np.unique(train_Y))", "time() # model = GridSearchCV( # estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, #", "max_features=90, max_depth=50, min_samples_split=6, min_samples_leaf=3), n_estimators=1200, learning_rate=0.005) # 拟合训练数据集 model.fit(train_X, train_Y) # 预测训练集 train_Y_hat", "import time import numpy as np import pandas as pd import mnist import", "Y = data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X, train_Y, test_Y = train_test_split(X, Y, test_size=0.3,", "# 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X, train_Y, test_Y = train_test_split(X, Y, test_size=0.3, random_state=1) m, n", "30, 2), 'min_samples_split': range(11, 31, 2), # 'min_samples_leaf': range(2, 8, 1)}, cv=5) #", "拟合训练数据集 # model.fit(train_X, train_Y) # print \"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_) model =", "pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度, V:压力, AP:湿度, RH:压强, PE:输出电力 # 样本特征X X = data[['AT', 'V',", "% (model.best_params_, model.best_score_)) model = AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5, min_samples_leaf=3), n_estimators=800, learning_rate=0.1) #", "min_samples_split=5, min_samples_leaf=3), n_estimators=800, learning_rate=0.1) # 拟合训练数据集 model.fit(train_X, train_Y.values.ravel()) # 预测测试集 test_Y_pred = model.predict(test_X)", "/ num))): # minEnd = min((i + 1) * num, m) # sub_idx", "m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) # 使用PCA降维 # num =", "DecisionTreeRegressor from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import", "\"\\n**********测试AdaBoostRegressor类**********\" t = time() # model = GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth': range(10, 30, 2),", "accuracy_score(train_Y[idx], train_Y_hat) # 预测测试集 test_Y_hat = model.predict(test_X) print \"测试集精确度: \", accuracy_score(test_Y, test_Y_hat) print", "# 读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet = mnist.loadLecunMnistSet() train_X, train_Y, test_X, test_Y = mnistSet[0], mnistSet[1],", "from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, mean_squared_error from sklearn.decomposition import PCA", "\"总耗时:\", time() - t, \"秒\" # 绘制ROC曲线 n_class = len(np.unique(train_Y)) roc.drawROC(n_class, test_Y, test_Y_hat)", "param_grid={'max_depth': range(10, 30, 2), 'min_samples_split': range(11, 31, 2), # 'min_samples_leaf': range(2, 8, 1)},", "cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y.values.ravel()) # print(\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_))", "np import pandas as pd import mnist import roc if __name__ == \"__main__\":", "train_Y_hat) # 预测测试集 test_Y_hat = model.predict(test_X) print \"测试集精确度: \", accuracy_score(test_Y, test_Y_hat) print \"总耗时:\",", "from time import time import numpy as np import pandas as pd import", "= model.predict(test_X) print \"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred) print \"测试集RMSE:\", np.sqrt(mean_squared_error(test_Y, test_Y_pred)) print \"总耗时:\", time()", "# 预测训练集 train_Y_hat = model.predict(train_X[idx]) print \"训练集精确度: \", accuracy_score(train_Y[idx], train_Y_hat) # 预测测试集 test_Y_hat", "min_samples_leaf=3), learning_rate=0.1), # param_grid={\"n_estimators\": range(500, 1501, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X,", "as pd import mnist import roc if __name__ == \"__main__\": # 读取Mnist数据集, 测试AdaBoost的分类模型", "num))): # minEnd = min((i + 1) * num, m) # sub_idx =", "test_Y = train_test_split(X, Y, test_size=0.3, random_state=1) m, n = np.shape(train_X) idx = range(m)", "= len(np.unique(train_Y)) roc.drawROC(n_class, test_Y, test_Y_hat) # 读取CCPP数据集, 测试AdaBoost的回归模型 data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度,", "param_grid={\"n_estimators\": range(500, 1501, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y) # print", "GridSearchCV, train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, mean_squared_error from sklearn.decomposition", "model = GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11, min_samples_leaf=3), # learning_rate=0.1), param_grid={\"n_estimators\": range(100, 1001,", "m / num))): # minEnd = min((i + 1) * num, m) #", "learning_rate=0.1), param_grid={\"n_estimators\": range(100, 1001, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y.values.ravel()) #", "base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, # min_samples_leaf=3), learning_rate=0.1), # param_grid={\"n_estimators\": range(500, 1501, 100)}, cv=3)", "random_state=0) # for i in range(int(np.ceil(1.0 * m / num))): # minEnd =", "样本输出Y Y = data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X, train_Y, test_Y = train_test_split(X, Y,", "data[['AT', 'V', 'AP', 'RH']] # 数据归一化 X = StandardScaler().fit_transform(X) # 样本输出Y Y =", "print \"\\n**********测试AdaBoostClassifier类**********\" t = time() # model = GridSearchCV( # estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random',", "train_test_split(X, Y, test_size=0.3, random_state=1) m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) print", "import accuracy_score, mean_squared_error from sklearn.decomposition import PCA from time import time import numpy", "print \"训练集精确度: \", accuracy_score(train_Y[idx], train_Y_hat) # 预测测试集 test_Y_hat = model.predict(test_X) print \"测试集精确度: \",", "GridSearchCV( # estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, # min_samples_leaf=3), learning_rate=0.1), # param_grid={\"n_estimators\":", "import StandardScaler from sklearn.metrics import accuracy_score, mean_squared_error from sklearn.decomposition import PCA from time", "sklearn.metrics import accuracy_score, mean_squared_error from sklearn.decomposition import PCA from time import time import", "coding:utf-8 -*- from sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from", "预测训练集 train_Y_hat = model.predict(train_X[idx]) print \"训练集精确度: \", accuracy_score(train_Y[idx], train_Y_hat) # 预测测试集 test_Y_hat =", "- t, \"秒\" # 绘制ROC曲线 n_class = len(np.unique(train_Y)) roc.drawROC(n_class, test_Y, test_Y_hat) # 读取CCPP数据集,", "mnistSet[0], mnistSet[1], mnistSet[2], mnistSet[3] m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) #", "\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_) model = AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, min_samples_leaf=3),", "sklearn.model_selection import GridSearchCV, train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, mean_squared_error", "np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\" t = time() # model = GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth': range(10,", "n_estimators=1200, learning_rate=0.005) # 拟合训练数据集 model.fit(train_X, train_Y) # 预测训练集 train_Y_hat = model.predict(train_X[idx]) print \"训练集精确度:", "n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\" t = time() #", "\"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred) print \"测试集RMSE:\", np.sqrt(mean_squared_error(test_Y, test_Y_pred)) print \"总耗时:\", time() - t, \"秒\"", "AT:温度, V:压力, AP:湿度, RH:压强, PE:输出电力 # 样本特征X X = data[['AT', 'V', 'AP', 'RH']]", "num, m) # sub_idx = idx[i * num:minEnd] # train_pca_X = pca.fit_transform(train_X[sub_idx]) #", "= np.shape(train_X) idx = range(m) np.random.shuffle(idx) # 使用PCA降维 # num = 30000 #", "-*- coding:utf-8 -*- from sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor", "\", accuracy_score(test_Y, test_Y_hat) print \"总耗时:\", time() - t, \"秒\" # 绘制ROC曲线 n_class =", "min_samples_leaf=3), n_estimators=1200, learning_rate=0.005) # 拟合训练数据集 model.fit(train_X, train_Y) # 预测训练集 train_Y_hat = model.predict(train_X[idx]) print", "print \"测试集精确度: \", accuracy_score(test_Y, test_Y_hat) print \"总耗时:\", time() - t, \"秒\" # 绘制ROC曲线", "PCA(n_components=0.9, whiten=True, random_state=0) # for i in range(int(np.ceil(1.0 * m / num))): #", "# model = GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11, min_samples_leaf=3), # learning_rate=0.1), param_grid={\"n_estimators\": range(100,", "= data[['AT', 'V', 'AP', 'RH']] # 数据归一化 X = StandardScaler().fit_transform(X) # 样本输出Y Y", "range(11, 31, 2), # 'min_samples_leaf': range(2, 8, 1)}, cv=5) # model = GridSearchCV(AdaBoostRegressor(", "\"\\n**********测试AdaBoostClassifier类**********\" t = time() # model = GridSearchCV( # estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random', max_features=90,", "100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y) # print \"最好的参数是:%s, 此时的得分是:%0.2f\" %", "train_Y.values.ravel()) # 预测测试集 test_Y_pred = model.predict(test_X) print \"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred) print \"测试集RMSE:\", np.sqrt(mean_squared_error(test_Y,", "读取CCPP数据集, 测试AdaBoost的回归模型 data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度, V:压力, AP:湿度, RH:压强, PE:输出电力 # 样本特征X", "base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, min_samples_leaf=3), n_estimators=1200, learning_rate=0.005) # 拟合训练数据集 model.fit(train_X, train_Y) # 预测训练集", "max_depth=50, min_samples_split=6, min_samples_leaf=3), n_estimators=1200, learning_rate=0.005) # 拟合训练数据集 model.fit(train_X, train_Y) # 预测训练集 train_Y_hat =", "GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11, min_samples_leaf=3), # learning_rate=0.1), param_grid={\"n_estimators\": range(100, 1001, 100)}, cv=3)", "from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score,", "# print(\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_)) model = AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5, min_samples_leaf=3),", "np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\" t = time() # model = GridSearchCV( # estimator=AdaBoostClassifier( #", "print np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\" t = time() # model = GridSearchCV( # estimator=AdaBoostClassifier(", "'V', 'AP', 'RH']] # 数据归一化 X = StandardScaler().fit_transform(X) # 样本输出Y Y = data[['PE']]", "print \"\\n**********测试AdaBoostRegressor类**********\" t = time() # model = GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth': range(10, 30,", "sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.preprocessing import StandardScaler", "# param_grid={'max_depth': range(10, 30, 2), 'min_samples_split': range(11, 31, 2), # 'min_samples_leaf': range(2, 8,", "= model.predict(train_X[idx]) print \"训练集精确度: \", accuracy_score(train_Y[idx], train_Y_hat) # 预测测试集 test_Y_hat = model.predict(test_X) print", "# model.fit(train_X, train_Y.values.ravel()) # print(\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_)) model = AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random',", "print(\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_)) model = AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5, min_samples_leaf=3), n_estimators=800,", "whiten=True, random_state=0) # for i in range(int(np.ceil(1.0 * m / num))): # minEnd", "# base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11, min_samples_leaf=3), # learning_rate=0.1), param_grid={\"n_estimators\": range(100, 1001, 100)}, cv=3) #", "绘制ROC曲线 n_class = len(np.unique(train_Y)) roc.drawROC(n_class, test_Y, test_Y_hat) # 读取CCPP数据集, 测试AdaBoost的回归模型 data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\")", "n_class = len(np.unique(train_Y)) roc.drawROC(n_class, test_Y, test_Y_hat) # 读取CCPP数据集, 测试AdaBoost的回归模型 data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") #", "m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\" t = time()", "range(m) np.random.shuffle(idx) # 使用PCA降维 # num = 30000 # pca = PCA(n_components=0.9, whiten=True,", "\", accuracy_score(train_Y[idx], train_Y_hat) # 预测测试集 test_Y_hat = model.predict(test_X) print \"测试集精确度: \", accuracy_score(test_Y, test_Y_hat)", "测试AdaBoost的分类模型 mnistSet = mnist.loadLecunMnistSet() train_X, train_Y, test_X, test_Y = mnistSet[0], mnistSet[1], mnistSet[2], mnistSet[3]", "<filename>adaboost.py #!/usr/bin/python # -*- coding:utf-8 -*- from sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor from sklearn.tree", "model.predict(test_X) print \"测试集精确度: \", accuracy_score(test_Y, test_Y_hat) print \"总耗时:\", time() - t, \"秒\" #", "idx = range(m) np.random.shuffle(idx) # 使用PCA降维 # num = 30000 # pca =", "as np import pandas as pd import mnist import roc if __name__ ==", "cv=5) # model = GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11, min_samples_leaf=3), # learning_rate=0.1), param_grid={\"n_estimators\":", "X = StandardScaler().fit_transform(X) # 样本输出Y Y = data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X, train_Y,", "拟合训练数据集 model.fit(train_X, train_Y.values.ravel()) # 预测测试集 test_Y_pred = model.predict(test_X) print \"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred) print", "1) * num, m) # sub_idx = idx[i * num:minEnd] # train_pca_X =", "train_X, train_Y, test_X, test_Y = mnistSet[0], mnistSet[1], mnistSet[2], mnistSet[3] m, n = np.shape(train_X)", "# 数据归一化 X = StandardScaler().fit_transform(X) # 样本输出Y Y = data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X,", "X = data[['AT', 'V', 'AP', 'RH']] # 数据归一化 X = StandardScaler().fit_transform(X) # 样本输出Y", "param_grid={\"n_estimators\": range(100, 1001, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y.values.ravel()) # print(\"最好的参数是:%s,", "= AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, min_samples_leaf=3), n_estimators=1200, learning_rate=0.005) # 拟合训练数据集 model.fit(train_X, train_Y)", "test_X, train_Y, test_Y = train_test_split(X, Y, test_size=0.3, random_state=1) m, n = np.shape(train_X) idx", "import pandas as pd import mnist import roc if __name__ == \"__main__\": #", "mnist import roc if __name__ == \"__main__\": # 读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet = mnist.loadLecunMnistSet()", "1001, 100)}, cv=3) # # 拟合训练数据集 # model.fit(train_X, train_Y.values.ravel()) # print(\"最好的参数是:%s, 此时的得分是:%0.2f\" %", "Y, test_size=0.3, random_state=1) m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\"", "StandardScaler from sklearn.metrics import accuracy_score, mean_squared_error from sklearn.decomposition import PCA from time import", "# 预测测试集 test_Y_hat = model.predict(test_X) print \"测试集精确度: \", accuracy_score(test_Y, test_Y_hat) print \"总耗时:\", time()", "mnistSet = mnist.loadLecunMnistSet() train_X, train_Y, test_X, test_Y = mnistSet[0], mnistSet[1], mnistSet[2], mnistSet[3] m,", "= AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5, min_samples_leaf=3), n_estimators=800, learning_rate=0.1) # 拟合训练数据集 model.fit(train_X, train_Y.values.ravel()) #", "#!/usr/bin/python # -*- coding:utf-8 -*- from sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor from sklearn.tree import", "test_Y_pred = model.predict(test_X) print \"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred) print \"测试集RMSE:\", np.sqrt(mean_squared_error(test_Y, test_Y_pred)) print \"总耗时:\",", "time() # model = GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth': range(10, 30, 2), 'min_samples_split': range(11, 31,", "min_samples_split=11, min_samples_leaf=3), # learning_rate=0.1), param_grid={\"n_estimators\": range(100, 1001, 100)}, cv=3) # # 拟合训练数据集 #", "np.random.shuffle(idx) # 使用PCA降维 # num = 30000 # pca = PCA(n_components=0.9, whiten=True, random_state=0)", "model.fit(train_X, train_Y.values.ravel()) # 预测测试集 test_Y_pred = model.predict(test_X) print \"测试集MSE:\", mean_squared_error(test_Y, test_Y_pred) print \"测试集RMSE:\",", "PE:输出电力 # 样本特征X X = data[['AT', 'V', 'AP', 'RH']] # 数据归一化 X =", "# 样本输出Y Y = data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集 train_X, test_X, train_Y, test_Y = train_test_split(X,", "sklearn.decomposition import PCA from time import time import numpy as np import pandas", "= GridSearchCV(DecisionTreeRegressor(splitter='random'), # param_grid={'max_depth': range(10, 30, 2), 'min_samples_split': range(11, 31, 2), # 'min_samples_leaf':", "test_size=0.3, random_state=1) m, n = np.shape(train_X) idx = range(m) np.random.shuffle(idx) print \"\\n**********测试AdaBoostRegressor类**********\" t", "# -*- coding:utf-8 -*- from sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor from sklearn.tree import DecisionTreeClassifier,", "= pca.fit_transform(train_X[sub_idx]) # print np.shape(train_pca_X) print \"\\n**********测试AdaBoostClassifier类**********\" t = time() # model =", "t = time() # model = GridSearchCV( # estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50,", "base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5, min_samples_leaf=3), n_estimators=800, learning_rate=0.1) # 拟合训练数据集 model.fit(train_X, train_Y.values.ravel()) # 预测测试集 test_Y_pred", "(model.best_params_, model.best_score_) model = AdaBoostClassifier( base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6, min_samples_leaf=3), n_estimators=1200, learning_rate=0.005) #", "AdaBoostClassifier, AdaBoostRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection import GridSearchCV, train_test_split from", "-*- from sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection", "test_Y_hat = model.predict(test_X) print \"测试集精确度: \", accuracy_score(test_Y, test_Y_hat) print \"总耗时:\", time() - t,", "print \"总耗时:\", time() - t, \"秒\" # 绘制ROC曲线 n_class = len(np.unique(train_Y)) roc.drawROC(n_class, test_Y,", "PCA from time import time import numpy as np import pandas as pd", "time() - t, \"秒\" # 绘制ROC曲线 n_class = len(np.unique(train_Y)) roc.drawROC(n_class, test_Y, test_Y_hat) #", "# # 拟合训练数据集 # model.fit(train_X, train_Y.values.ravel()) # print(\"最好的参数是:%s, 此时的得分是:%0.2f\" % (model.best_params_, model.best_score_)) model", "test_Y_hat) # 读取CCPP数据集, 测试AdaBoost的回归模型 data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度, V:压力, AP:湿度, RH:压强, PE:输出电力", "8, 1)}, cv=5) # model = GridSearchCV(AdaBoostRegressor( # base_estimator=DecisionTreeRegressor(splitter='random', max_depth=28, min_samples_split=11, min_samples_leaf=3), #", "= time() # model = GridSearchCV( # estimator=AdaBoostClassifier( # base_estimator=DecisionTreeClassifier(splitter='random', max_features=90, max_depth=50, min_samples_split=6,", "AdaBoostRegressor( base_estimator=DecisionTreeRegressor(splitter='random', max_depth=20, min_samples_split=5, min_samples_leaf=3), n_estimators=800, learning_rate=0.1) # 拟合训练数据集 model.fit(train_X, train_Y.values.ravel()) # 预测测试集", "range(10, 30, 2), 'min_samples_split': range(11, 31, 2), # 'min_samples_leaf': range(2, 8, 1)}, cv=5)", "roc.drawROC(n_class, test_Y, test_Y_hat) # 读取CCPP数据集, 测试AdaBoost的回归模型 data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度, V:压力, AP:湿度,", "\"__main__\": # 读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet = mnist.loadLecunMnistSet() train_X, train_Y, test_X, test_Y = mnistSet[0],", "learning_rate=0.005) # 拟合训练数据集 model.fit(train_X, train_Y) # 预测训练集 train_Y_hat = model.predict(train_X[idx]) print \"训练集精确度: \",", "'RH']] # 数据归一化 X = StandardScaler().fit_transform(X) # 样本输出Y Y = data[['PE']] # 划分训练集和测试集,将数据集的70%划入训练集,30%划入测试集", "if __name__ == \"__main__\": # 读取Mnist数据集, 测试AdaBoost的分类模型 mnistSet = mnist.loadLecunMnistSet() train_X, train_Y, test_X,", "data = pd.read_excel(\"data/CCPP/Folds5x2_pp.xlsx\") # AT:温度, V:压力, AP:湿度, RH:压强, PE:输出电力 # 样本特征X X =", "sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection import GridSearchCV,", "RH:压强, PE:输出电力 # 样本特征X X = data[['AT', 'V', 'AP', 'RH']] # 数据归一化 X", "min_samples_split=6, # min_samples_leaf=3), learning_rate=0.1), # param_grid={\"n_estimators\": range(500, 1501, 100)}, cv=3) # # 拟合训练数据集" ]
[ "self defined conf to inputs.conf.spec if endpoint._entities[0] and endpoint._entities[0]._conf_name: lines = [ \"[\"", "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", "+ \".conf.spec\", endpoint.generate_spec(), ) # Add data input of self defined conf to", "op from .rest_conf import RestmapConf, WebConf __all__ = [\"RestBuilderError\", \"RestBuilder\"] class RestBuilderError(Exception): pass", "endpoint._entities[0]._conf_name: lines = [ \"[\" + endpoint._name + \"://<name>]\", \"placeholder = placeholder\", ]", "os.makedirs(path) full_name = op.join(path, file_name) if full_name not in self._content: self._content[full_name] = []", "\"\"\" self._schema = schema self._handler = handler self._output_path = output_path self._args = args", "= product self._root_path = op.abspath(self._path) if not op.isdir(self._root_path): os.makedirs(self._root_path) self._content = {} def", "this file except in compliance with the License. # You may obtain a", "\"[\" + endpoint._name + \"://<name>]\", \"placeholder = placeholder\", ] self.output.put( self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines)", "schema: RestSchema :param handler: :param output_path: :param args: :param kwargs: \"\"\" self._schema =", "+ endpoint._name + \"://<name>]\", \"placeholder = placeholder\", ] self.output.put( self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines) )", "handler, output_path, *args, **kwargs): \"\"\" :param schema: :param schema: RestSchema :param handler: :param", "\"inputs.conf.spec\", \"\\n\".join(lines) ) self.output.put( self.output.bin, endpoint.rh_name + \".py\", endpoint.generate_rh(self._handler), ) self.output.put( self.output.default, \"restmap.conf\",", "self.output.put( self.output.default, endpoint.conf_name + \".conf\", endpoint.generate_default_conf(), ) self.output.put( self.output.readme, endpoint.conf_name + \".conf.spec\", endpoint.generate_spec(),", "self.output.default, endpoint.conf_name + \".conf\", endpoint.generate_default_conf(), ) self.output.put( self.output.readme, endpoint.conf_name + \".conf.spec\", endpoint.generate_spec(), )", "ANY KIND, either express or implied. # See the License for the specific", "= [\"RestBuilderError\", \"RestBuilder\"] class RestBuilderError(Exception): pass class _RestBuilderOutput: readme = \"README\" default =", "def restmap_admin(self): return self._schema.namespace @property def restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints) def build(self): for endpoint", "endpoint._entities[0] and endpoint._entities[0]._conf_name: lines = [ \"[\" + endpoint._name + \"://<name>]\", \"placeholder =", "\"RestBuilder\"] class RestBuilderError(Exception): pass class _RestBuilderOutput: readme = \"README\" default = \"default\" bin", "RestBuilderError(Exception): pass class _RestBuilderOutput: readme = \"README\" default = \"default\" bin = \"bin\"", "if endpoint._name == \"settings\": self.output.put( self.output.default, endpoint.conf_name + \".conf\", endpoint.generate_default_conf(), ) self.output.put( self.output.readme,", "subpath, file_name, content): path = op.join(self._root_path, subpath) if not op.isdir(path): os.makedirs(path) full_name =", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "handler self._output_path = output_path self._args = args self._kwargs = kwargs self.output = _RestBuilderOutput(", "self.output.put( self.output.default, \"restmap.conf\", RestmapConf.build( self._schema.endpoints, self._schema.namespace, self._schema.admin_match, ), ) self.output.put( self.output.default, \"web.conf\", WebConf.build(self._schema.endpoints),", "open(full_name, \"w\") as f: f.writelines(full_content) class RestBuilder: def __init__(self, schema, handler, output_path, *args,", "handler: :param output_path: :param args: :param kwargs: \"\"\" self._schema = schema self._handler =", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "= op.join(path, file_name) if full_name not in self._content: self._content[full_name] = [] self._content[full_name].append(content) def", "= handler self._output_path = output_path self._args = args self._kwargs = kwargs self.output =", "RestmapConf.admin_externals(self._schema.endpoints) def build(self): for endpoint in self._schema.endpoints: # If the endpoint is oauth,", "= args self._kwargs = kwargs self.output = _RestBuilderOutput( self._output_path, self._schema.product, ) @property def", "OF ANY KIND, either express or implied. # See the License for the", "lines = [ \"[\" + endpoint._name + \"://<name>]\", \"placeholder = placeholder\", ] self.output.put(", "{} def put(self, subpath, file_name, content): path = op.join(self._root_path, subpath) if not op.isdir(path):", "should not get created. if endpoint._name != \"oauth\": if endpoint._name == \"settings\": self.output.put(", "= {} def put(self, subpath, file_name, content): path = op.join(self._root_path, subpath) if not", "License. # import os import os.path as op from .rest_conf import RestmapConf, WebConf", "for endpoint in self._schema.endpoints: # If the endpoint is oauth, which is for", "build(self): for endpoint in self._schema.endpoints: # If the endpoint is oauth, which is", "self._kwargs = kwargs self.output = _RestBuilderOutput( self._output_path, self._schema.product, ) @property def restmap_admin(self): return", ":param kwargs: \"\"\" self._schema = schema self._handler = handler self._output_path = output_path self._args", "self.output.put( self.output.bin, endpoint.rh_name + \".py\", endpoint.generate_rh(self._handler), ) self.output.put( self.output.default, \"restmap.conf\", RestmapConf.build( self._schema.endpoints, self._schema.namespace,", "contents in list(self._content.items()): full_content = \"\\n\\n\".join(contents) with open(full_name, \"w\") as f: f.writelines(full_content) class", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "in self._content: self._content[full_name] = [] self._content[full_name].append(content) def save(self): for full_name, contents in list(self._content.items()):", "path = op.join(self._root_path, subpath) if not op.isdir(path): os.makedirs(path) full_name = op.join(path, file_name) if", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "# If the endpoint is oauth, which is for getting accesstoken. Conf file", ":param args: :param kwargs: \"\"\" self._schema = schema self._handler = handler self._output_path =", "entries should not get created. if endpoint._name != \"oauth\": if endpoint._name == \"settings\":", "endpoint.generate_rh(self._handler), ) self.output.put( self.output.default, \"restmap.conf\", RestmapConf.build( self._schema.endpoints, self._schema.namespace, self._schema.admin_match, ), ) self.output.put( self.output.default,", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "= \"\\n\\n\".join(contents) with open(full_name, \"w\") as f: f.writelines(full_content) class RestBuilder: def __init__(self, schema,", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "\"README\" default = \"default\" bin = \"bin\" def __init__(self, path, product): self._path =", "the endpoint is oauth, which is for getting accesstoken. Conf file entries should", "endpoint.conf_name + \".conf.spec\", endpoint.generate_spec(), ) # Add data input of self defined conf", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "return self._schema.namespace @property def restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints) def build(self): for endpoint in self._schema.endpoints:", "f: f.writelines(full_content) class RestBuilder: def __init__(self, schema, handler, output_path, *args, **kwargs): \"\"\" :param", "required by applicable law or agreed to in writing, software # distributed under", "full_content = \"\\n\\n\".join(contents) with open(full_name, \"w\") as f: f.writelines(full_content) class RestBuilder: def __init__(self,", "os.makedirs(self._root_path) self._content = {} def put(self, subpath, file_name, content): path = op.join(self._root_path, subpath)", "# # Copyright 2021 Splunk Inc. # # Licensed under the Apache License,", "applicable law or agreed to in writing, software # distributed under the License", "== \"settings\": self.output.put( self.output.default, endpoint.conf_name + \".conf\", endpoint.generate_default_conf(), ) self.output.put( self.output.readme, endpoint.conf_name +", "or agreed to in writing, software # distributed under the License is distributed", "# Add data input of self defined conf to inputs.conf.spec if endpoint._entities[0] and", "def save(self): for full_name, contents in list(self._content.items()): full_content = \"\\n\\n\".join(contents) with open(full_name, \"w\")", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "[] self._content[full_name].append(content) def save(self): for full_name, contents in list(self._content.items()): full_content = \"\\n\\n\".join(contents) with", "file entries should not get created. if endpoint._name != \"oauth\": if endpoint._name ==", "# Copyright 2021 Splunk Inc. # # Licensed under the Apache License, Version", "schema self._handler = handler self._output_path = output_path self._args = args self._kwargs = kwargs", "endpoint.conf_name + \".conf\", endpoint.generate_default_conf(), ) self.output.put( self.output.readme, endpoint.conf_name + \".conf.spec\", endpoint.generate_spec(), ) #", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "def put(self, subpath, file_name, content): path = op.join(self._root_path, subpath) if not op.isdir(path): os.makedirs(path)", "writing, software # distributed under the License is distributed on an \"AS IS\"", "RestmapConf, WebConf __all__ = [\"RestBuilderError\", \"RestBuilder\"] class RestBuilderError(Exception): pass class _RestBuilderOutput: readme =", "in list(self._content.items()): full_content = \"\\n\\n\".join(contents) with open(full_name, \"w\") as f: f.writelines(full_content) class RestBuilder:", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "!= \"oauth\": if endpoint._name == \"settings\": self.output.put( self.output.default, endpoint.conf_name + \".conf\", endpoint.generate_default_conf(), )", "+ \"://<name>]\", \"placeholder = placeholder\", ] self.output.put( self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines) ) self.output.put( self.output.bin,", "License. # You may obtain a copy of the License at # #", "\"\"\" :param schema: :param schema: RestSchema :param handler: :param output_path: :param args: :param", "op.join(path, file_name) if full_name not in self._content: self._content[full_name] = [] self._content[full_name].append(content) def save(self):", "\"w\") as f: f.writelines(full_content) class RestBuilder: def __init__(self, schema, handler, output_path, *args, **kwargs):", "file_name) if full_name not in self._content: self._content[full_name] = [] self._content[full_name].append(content) def save(self): for", "compliance with the License. # You may obtain a copy of the License", "\"oauth\": if endpoint._name == \"settings\": self.output.put( self.output.default, endpoint.conf_name + \".conf\", endpoint.generate_default_conf(), ) self.output.put(", "content): path = op.join(self._root_path, subpath) if not op.isdir(path): os.makedirs(path) full_name = op.join(path, file_name)", "the License. # import os import os.path as op from .rest_conf import RestmapConf,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "= op.abspath(self._path) if not op.isdir(self._root_path): os.makedirs(self._root_path) self._content = {} def put(self, subpath, file_name,", "specific language governing permissions and # limitations under the License. # import os", "import os.path as op from .rest_conf import RestmapConf, WebConf __all__ = [\"RestBuilderError\", \"RestBuilder\"]", "created. if endpoint._name != \"oauth\": if endpoint._name == \"settings\": self.output.put( self.output.default, endpoint.conf_name +", "with open(full_name, \"w\") as f: f.writelines(full_content) class RestBuilder: def __init__(self, schema, handler, output_path,", "import os import os.path as op from .rest_conf import RestmapConf, WebConf __all__ =", "not use this file except in compliance with the License. # You may", "Add data input of self defined conf to inputs.conf.spec if endpoint._entities[0] and endpoint._entities[0]._conf_name:", "self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines) ) self.output.put( self.output.bin, endpoint.rh_name + \".py\", endpoint.generate_rh(self._handler), ) self.output.put( self.output.default,", "op.abspath(self._path) if not op.isdir(self._root_path): os.makedirs(self._root_path) self._content = {} def put(self, subpath, file_name, content):", "is oauth, which is for getting accesstoken. Conf file entries should not get", "License, Version 2.0 (the \"License\"); # you may not use this file except", "self.output.bin, endpoint.rh_name + \".py\", endpoint.generate_rh(self._handler), ) self.output.put( self.output.default, \"restmap.conf\", RestmapConf.build( self._schema.endpoints, self._schema.namespace, self._schema.admin_match,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "governing permissions and # limitations under the License. # import os import os.path", "self._content = {} def put(self, subpath, file_name, content): path = op.join(self._root_path, subpath) if", "in self._schema.endpoints: # If the endpoint is oauth, which is for getting accesstoken.", "default = \"default\" bin = \"bin\" def __init__(self, path, product): self._path = path", "limitations under the License. # import os import os.path as op from .rest_conf", "# you may not use this file except in compliance with the License.", "inputs.conf.spec if endpoint._entities[0] and endpoint._entities[0]._conf_name: lines = [ \"[\" + endpoint._name + \"://<name>]\",", "op.isdir(path): os.makedirs(path) full_name = op.join(path, file_name) if full_name not in self._content: self._content[full_name] =", "self._output_path, self._schema.product, ) @property def restmap_admin(self): return self._schema.namespace @property def restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints)", "self._schema.endpoints: # If the endpoint is oauth, which is for getting accesstoken. Conf", "agreed to in writing, software # distributed under the License is distributed on", "class _RestBuilderOutput: readme = \"README\" default = \"default\" bin = \"bin\" def __init__(self,", "os.path as op from .rest_conf import RestmapConf, WebConf __all__ = [\"RestBuilderError\", \"RestBuilder\"] class", ".rest_conf import RestmapConf, WebConf __all__ = [\"RestBuilderError\", \"RestBuilder\"] class RestBuilderError(Exception): pass class _RestBuilderOutput:", ":param handler: :param output_path: :param args: :param kwargs: \"\"\" self._schema = schema self._handler", "(the \"License\"); # you may not use this file except in compliance with", "WebConf __all__ = [\"RestBuilderError\", \"RestBuilder\"] class RestBuilderError(Exception): pass class _RestBuilderOutput: readme = \"README\"", "endpoint.generate_default_conf(), ) self.output.put( self.output.readme, endpoint.conf_name + \".conf.spec\", endpoint.generate_spec(), ) # Add data input", "# Unless required by applicable law or agreed to in writing, software #", "by applicable law or agreed to in writing, software # distributed under the", ":param schema: :param schema: RestSchema :param handler: :param output_path: :param args: :param kwargs:", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "= _RestBuilderOutput( self._output_path, self._schema.product, ) @property def restmap_admin(self): return self._schema.namespace @property def restmap_admin_externals(self):", "for full_name, contents in list(self._content.items()): full_content = \"\\n\\n\".join(contents) with open(full_name, \"w\") as f:", "self._schema = schema self._handler = handler self._output_path = output_path self._args = args self._kwargs", "getting accesstoken. Conf file entries should not get created. if endpoint._name != \"oauth\":", "\"://<name>]\", \"placeholder = placeholder\", ] self.output.put( self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines) ) self.output.put( self.output.bin, endpoint.rh_name", ":param output_path: :param args: :param kwargs: \"\"\" self._schema = schema self._handler = handler", "product self._root_path = op.abspath(self._path) if not op.isdir(self._root_path): os.makedirs(self._root_path) self._content = {} def put(self,", "permissions and # limitations under the License. # import os import os.path as", "self._schema.product, ) @property def restmap_admin(self): return self._schema.namespace @property def restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints) def", "file except in compliance with the License. # You may obtain a copy", "_RestBuilderOutput( self._output_path, self._schema.product, ) @property def restmap_admin(self): return self._schema.namespace @property def restmap_admin_externals(self): return", "self._product = product self._root_path = op.abspath(self._path) if not op.isdir(self._root_path): os.makedirs(self._root_path) self._content = {}", "op.join(self._root_path, subpath) if not op.isdir(path): os.makedirs(path) full_name = op.join(path, file_name) if full_name not", "License for the specific language governing permissions and # limitations under the License.", "not op.isdir(path): os.makedirs(path) full_name = op.join(path, file_name) if full_name not in self._content: self._content[full_name]", "if not op.isdir(path): os.makedirs(path) full_name = op.join(path, file_name) if full_name not in self._content:", "to in writing, software # distributed under the License is distributed on an", "= [] self._content[full_name].append(content) def save(self): for full_name, contents in list(self._content.items()): full_content = \"\\n\\n\".join(contents)", "endpoint._name == \"settings\": self.output.put( self.output.default, endpoint.conf_name + \".conf\", endpoint.generate_default_conf(), ) self.output.put( self.output.readme, endpoint.conf_name", "list(self._content.items()): full_content = \"\\n\\n\".join(contents) with open(full_name, \"w\") as f: f.writelines(full_content) class RestBuilder: def", "placeholder\", ] self.output.put( self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines) ) self.output.put( self.output.bin, endpoint.rh_name + \".py\", endpoint.generate_rh(self._handler),", "class RestBuilderError(Exception): pass class _RestBuilderOutput: readme = \"README\" default = \"default\" bin =", "implied. # See the License for the specific language governing permissions and #", "self._content[full_name] = [] self._content[full_name].append(content) def save(self): for full_name, contents in list(self._content.items()): full_content =", "args self._kwargs = kwargs self.output = _RestBuilderOutput( self._output_path, self._schema.product, ) @property def restmap_admin(self):", "args: :param kwargs: \"\"\" self._schema = schema self._handler = handler self._output_path = output_path", "\"License\"); # you may not use this file except in compliance with the", "= [ \"[\" + endpoint._name + \"://<name>]\", \"placeholder = placeholder\", ] self.output.put( self.output.readme,", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "def restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints) def build(self): for endpoint in self._schema.endpoints: # If the", "from .rest_conf import RestmapConf, WebConf __all__ = [\"RestBuilderError\", \"RestBuilder\"] class RestBuilderError(Exception): pass class", "\"\\n\\n\".join(contents) with open(full_name, \"w\") as f: f.writelines(full_content) class RestBuilder: def __init__(self, schema, handler,", "def __init__(self, schema, handler, output_path, *args, **kwargs): \"\"\" :param schema: :param schema: RestSchema", "or implied. # See the License for the specific language governing permissions and", ") self.output.put( self.output.readme, endpoint.conf_name + \".conf.spec\", endpoint.generate_spec(), ) # Add data input of", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "file_name, content): path = op.join(self._root_path, subpath) if not op.isdir(path): os.makedirs(path) full_name = op.join(path,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "which is for getting accesstoken. Conf file entries should not get created. if", "RestBuilder: def __init__(self, schema, handler, output_path, *args, **kwargs): \"\"\" :param schema: :param schema:", "in writing, software # distributed under the License is distributed on an \"AS", "if endpoint._entities[0] and endpoint._entities[0]._conf_name: lines = [ \"[\" + endpoint._name + \"://<name>]\", \"placeholder", "@property def restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints) def build(self): for endpoint in self._schema.endpoints: # If", "import RestmapConf, WebConf __all__ = [\"RestBuilderError\", \"RestBuilder\"] class RestBuilderError(Exception): pass class _RestBuilderOutput: readme", "return RestmapConf.admin_externals(self._schema.endpoints) def build(self): for endpoint in self._schema.endpoints: # If the endpoint is", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "Copyright 2021 Splunk Inc. # # Licensed under the Apache License, Version 2.0", "class RestBuilder: def __init__(self, schema, handler, output_path, *args, **kwargs): \"\"\" :param schema: :param", "output_path: :param args: :param kwargs: \"\"\" self._schema = schema self._handler = handler self._output_path", "if not op.isdir(self._root_path): os.makedirs(self._root_path) self._content = {} def put(self, subpath, file_name, content): path", "= placeholder\", ] self.output.put( self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines) ) self.output.put( self.output.bin, endpoint.rh_name + \".py\",", "self._handler = handler self._output_path = output_path self._args = args self._kwargs = kwargs self.output", "is for getting accesstoken. Conf file entries should not get created. if endpoint._name", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "you may not use this file except in compliance with the License. #", "full_name not in self._content: self._content[full_name] = [] self._content[full_name].append(content) def save(self): for full_name, contents", "output_path self._args = args self._kwargs = kwargs self.output = _RestBuilderOutput( self._output_path, self._schema.product, )", "get created. if endpoint._name != \"oauth\": if endpoint._name == \"settings\": self.output.put( self.output.default, endpoint.conf_name", "use this file except in compliance with the License. # You may obtain", "full_name = op.join(path, file_name) if full_name not in self._content: self._content[full_name] = [] self._content[full_name].append(content)", "def __init__(self, path, product): self._path = path self._product = product self._root_path = op.abspath(self._path)", "= path self._product = product self._root_path = op.abspath(self._path) if not op.isdir(self._root_path): os.makedirs(self._root_path) self._content", "os import os.path as op from .rest_conf import RestmapConf, WebConf __all__ = [\"RestBuilderError\",", "and endpoint._entities[0]._conf_name: lines = [ \"[\" + endpoint._name + \"://<name>]\", \"placeholder = placeholder\",", "\"default\" bin = \"bin\" def __init__(self, path, product): self._path = path self._product =", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", ":param schema: RestSchema :param handler: :param output_path: :param args: :param kwargs: \"\"\" self._schema", "conf to inputs.conf.spec if endpoint._entities[0] and endpoint._entities[0]._conf_name: lines = [ \"[\" + endpoint._name", "language governing permissions and # limitations under the License. # import os import", "\".conf.spec\", endpoint.generate_spec(), ) # Add data input of self defined conf to inputs.conf.spec", "Conf file entries should not get created. if endpoint._name != \"oauth\": if endpoint._name", "**kwargs): \"\"\" :param schema: :param schema: RestSchema :param handler: :param output_path: :param args:", "def build(self): for endpoint in self._schema.endpoints: # If the endpoint is oauth, which", "2.0 (the \"License\"); # you may not use this file except in compliance", "path, product): self._path = path self._product = product self._root_path = op.abspath(self._path) if not", "put(self, subpath, file_name, content): path = op.join(self._root_path, subpath) if not op.isdir(path): os.makedirs(path) full_name", "for the specific language governing permissions and # limitations under the License. #", "[\"RestBuilderError\", \"RestBuilder\"] class RestBuilderError(Exception): pass class _RestBuilderOutput: readme = \"README\" default = \"default\"", "op.isdir(self._root_path): os.makedirs(self._root_path) self._content = {} def put(self, subpath, file_name, content): path = op.join(self._root_path,", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "# import os import os.path as op from .rest_conf import RestmapConf, WebConf __all__", "*args, **kwargs): \"\"\" :param schema: :param schema: RestSchema :param handler: :param output_path: :param", "# # Unless required by applicable law or agreed to in writing, software", "defined conf to inputs.conf.spec if endpoint._entities[0] and endpoint._entities[0]._conf_name: lines = [ \"[\" +", "express or implied. # See the License for the specific language governing permissions", "self._args = args self._kwargs = kwargs self.output = _RestBuilderOutput( self._output_path, self._schema.product, ) @property", "+ \".py\", endpoint.generate_rh(self._handler), ) self.output.put( self.output.default, \"restmap.conf\", RestmapConf.build( self._schema.endpoints, self._schema.namespace, self._schema.admin_match, ), )", "either express or implied. # See the License for the specific language governing", "If the endpoint is oauth, which is for getting accesstoken. Conf file entries", "save(self): for full_name, contents in list(self._content.items()): full_content = \"\\n\\n\".join(contents) with open(full_name, \"w\") as", "\"\\n\".join(lines) ) self.output.put( self.output.bin, endpoint.rh_name + \".py\", endpoint.generate_rh(self._handler), ) self.output.put( self.output.default, \"restmap.conf\", RestmapConf.build(", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "self.output.readme, endpoint.conf_name + \".conf.spec\", endpoint.generate_spec(), ) # Add data input of self defined", "input of self defined conf to inputs.conf.spec if endpoint._entities[0] and endpoint._entities[0]._conf_name: lines =", "endpoint.rh_name + \".py\", endpoint.generate_rh(self._handler), ) self.output.put( self.output.default, \"restmap.conf\", RestmapConf.build( self._schema.endpoints, self._schema.namespace, self._schema.admin_match, ),", "if full_name not in self._content: self._content[full_name] = [] self._content[full_name].append(content) def save(self): for full_name,", "as f: f.writelines(full_content) class RestBuilder: def __init__(self, schema, handler, output_path, *args, **kwargs): \"\"\"", "self.output.put( self.output.readme, endpoint.conf_name + \".conf.spec\", endpoint.generate_spec(), ) # Add data input of self", "self._schema.namespace @property def restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints) def build(self): for endpoint in self._schema.endpoints: #", "the License. # You may obtain a copy of the License at #", "and # limitations under the License. # import os import os.path as op", "endpoint.generate_spec(), ) # Add data input of self defined conf to inputs.conf.spec if", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "self._content[full_name].append(content) def save(self): for full_name, contents in list(self._content.items()): full_content = \"\\n\\n\".join(contents) with open(full_name,", ") # Add data input of self defined conf to inputs.conf.spec if endpoint._entities[0]", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "endpoint._name + \"://<name>]\", \"placeholder = placeholder\", ] self.output.put( self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines) ) self.output.put(", "\"restmap.conf\", RestmapConf.build( self._schema.endpoints, self._schema.namespace, self._schema.admin_match, ), ) self.output.put( self.output.default, \"web.conf\", WebConf.build(self._schema.endpoints), ) self.output.save()", "= output_path self._args = args self._kwargs = kwargs self.output = _RestBuilderOutput( self._output_path, self._schema.product,", "not get created. if endpoint._name != \"oauth\": if endpoint._name == \"settings\": self.output.put( self.output.default,", "subpath) if not op.isdir(path): os.makedirs(path) full_name = op.join(path, file_name) if full_name not in", "with the License. # You may obtain a copy of the License at", "as op from .rest_conf import RestmapConf, WebConf __all__ = [\"RestBuilderError\", \"RestBuilder\"] class RestBuilderError(Exception):", "@property def restmap_admin(self): return self._schema.namespace @property def restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints) def build(self): for", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "= kwargs self.output = _RestBuilderOutput( self._output_path, self._schema.product, ) @property def restmap_admin(self): return self._schema.namespace", "product): self._path = path self._product = product self._root_path = op.abspath(self._path) if not op.isdir(self._root_path):", "schema, handler, output_path, *args, **kwargs): \"\"\" :param schema: :param schema: RestSchema :param handler:", "\".conf\", endpoint.generate_default_conf(), ) self.output.put( self.output.readme, endpoint.conf_name + \".conf.spec\", endpoint.generate_spec(), ) # Add data", "restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints) def build(self): for endpoint in self._schema.endpoints: # If the endpoint", "[ \"[\" + endpoint._name + \"://<name>]\", \"placeholder = placeholder\", ] self.output.put( self.output.readme, \"inputs.conf.spec\",", "self.output = _RestBuilderOutput( self._output_path, self._schema.product, ) @property def restmap_admin(self): return self._schema.namespace @property def", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "data input of self defined conf to inputs.conf.spec if endpoint._entities[0] and endpoint._entities[0]._conf_name: lines", "path self._product = product self._root_path = op.abspath(self._path) if not op.isdir(self._root_path): os.makedirs(self._root_path) self._content =", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "= op.join(self._root_path, subpath) if not op.isdir(path): os.makedirs(path) full_name = op.join(path, file_name) if full_name", "of self defined conf to inputs.conf.spec if endpoint._entities[0] and endpoint._entities[0]._conf_name: lines = [", "to inputs.conf.spec if endpoint._entities[0] and endpoint._entities[0]._conf_name: lines = [ \"[\" + endpoint._name +", "endpoint in self._schema.endpoints: # If the endpoint is oauth, which is for getting", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "oauth, which is for getting accesstoken. Conf file entries should not get created.", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "\"settings\": self.output.put( self.output.default, endpoint.conf_name + \".conf\", endpoint.generate_default_conf(), ) self.output.put( self.output.readme, endpoint.conf_name + \".conf.spec\",", "endpoint is oauth, which is for getting accesstoken. Conf file entries should not", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "__init__(self, path, product): self._path = path self._product = product self._root_path = op.abspath(self._path) if", "= \"bin\" def __init__(self, path, product): self._path = path self._product = product self._root_path", "\"placeholder = placeholder\", ] self.output.put( self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines) ) self.output.put( self.output.bin, endpoint.rh_name +", "self._path = path self._product = product self._root_path = op.abspath(self._path) if not op.isdir(self._root_path): os.makedirs(self._root_path)", "bin = \"bin\" def __init__(self, path, product): self._path = path self._product = product", "See the License for the specific language governing permissions and # limitations under", ") self.output.put( self.output.bin, endpoint.rh_name + \".py\", endpoint.generate_rh(self._handler), ) self.output.put( self.output.default, \"restmap.conf\", RestmapConf.build( self._schema.endpoints,", "kwargs: \"\"\" self._schema = schema self._handler = handler self._output_path = output_path self._args =", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "not in self._content: self._content[full_name] = [] self._content[full_name].append(content) def save(self): for full_name, contents in", "schema: :param schema: RestSchema :param handler: :param output_path: :param args: :param kwargs: \"\"\"", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "under the License. # import os import os.path as op from .rest_conf import", "= schema self._handler = handler self._output_path = output_path self._args = args self._kwargs =", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "\"bin\" def __init__(self, path, product): self._path = path self._product = product self._root_path =", "+ \".conf\", endpoint.generate_default_conf(), ) self.output.put( self.output.readme, endpoint.conf_name + \".conf.spec\", endpoint.generate_spec(), ) # Add", "endpoint._name != \"oauth\": if endpoint._name == \"settings\": self.output.put( self.output.default, endpoint.conf_name + \".conf\", endpoint.generate_default_conf(),", "self._content: self._content[full_name] = [] self._content[full_name].append(content) def save(self): for full_name, contents in list(self._content.items()): full_content", "f.writelines(full_content) class RestBuilder: def __init__(self, schema, handler, output_path, *args, **kwargs): \"\"\" :param schema:", "__all__ = [\"RestBuilderError\", \"RestBuilder\"] class RestBuilderError(Exception): pass class _RestBuilderOutput: readme = \"README\" default", "the specific language governing permissions and # limitations under the License. # import", "= \"default\" bin = \"bin\" def __init__(self, path, product): self._path = path self._product", "not op.isdir(self._root_path): os.makedirs(self._root_path) self._content = {} def put(self, subpath, file_name, content): path =", "Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\");", "restmap_admin(self): return self._schema.namespace @property def restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints) def build(self): for endpoint in", "2021 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the", "Version 2.0 (the \"License\"); # you may not use this file except in", "except in compliance with the License. # You may obtain a copy of", "= \"README\" default = \"default\" bin = \"bin\" def __init__(self, path, product): self._path", "_RestBuilderOutput: readme = \"README\" default = \"default\" bin = \"bin\" def __init__(self, path,", "if endpoint._name != \"oauth\": if endpoint._name == \"settings\": self.output.put( self.output.default, endpoint.conf_name + \".conf\",", "output_path, *args, **kwargs): \"\"\" :param schema: :param schema: RestSchema :param handler: :param output_path:", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", ") self.output.put( self.output.default, \"restmap.conf\", RestmapConf.build( self._schema.endpoints, self._schema.namespace, self._schema.admin_match, ), ) self.output.put( self.output.default, \"web.conf\",", "RestSchema :param handler: :param output_path: :param args: :param kwargs: \"\"\" self._schema = schema", "self._root_path = op.abspath(self._path) if not op.isdir(self._root_path): os.makedirs(self._root_path) self._content = {} def put(self, subpath,", "self.output.default, \"restmap.conf\", RestmapConf.build( self._schema.endpoints, self._schema.namespace, self._schema.admin_match, ), ) self.output.put( self.output.default, \"web.conf\", WebConf.build(self._schema.endpoints), )", "accesstoken. Conf file entries should not get created. if endpoint._name != \"oauth\": if", "\".py\", endpoint.generate_rh(self._handler), ) self.output.put( self.output.default, \"restmap.conf\", RestmapConf.build( self._schema.endpoints, self._schema.namespace, self._schema.admin_match, ), ) self.output.put(", "# limitations under the License. # import os import os.path as op from", "__init__(self, schema, handler, output_path, *args, **kwargs): \"\"\" :param schema: :param schema: RestSchema :param", "self._output_path = output_path self._args = args self._kwargs = kwargs self.output = _RestBuilderOutput( self._output_path,", "for getting accesstoken. Conf file entries should not get created. if endpoint._name !=", ") @property def restmap_admin(self): return self._schema.namespace @property def restmap_admin_externals(self): return RestmapConf.admin_externals(self._schema.endpoints) def build(self):", "full_name, contents in list(self._content.items()): full_content = \"\\n\\n\".join(contents) with open(full_name, \"w\") as f: f.writelines(full_content)", "self.output.put( self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines) ) self.output.put( self.output.bin, endpoint.rh_name + \".py\", endpoint.generate_rh(self._handler), ) self.output.put(", "kwargs self.output = _RestBuilderOutput( self._output_path, self._schema.product, ) @property def restmap_admin(self): return self._schema.namespace @property", "pass class _RestBuilderOutput: readme = \"README\" default = \"default\" bin = \"bin\" def", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "] self.output.put( self.output.readme, \"inputs.conf.spec\", \"\\n\".join(lines) ) self.output.put( self.output.bin, endpoint.rh_name + \".py\", endpoint.generate_rh(self._handler), )", "readme = \"README\" default = \"default\" bin = \"bin\" def __init__(self, path, product):" ]
[]
[ "width needed = area * 1.05 print(\"You need\", needed, \"tiles in metres squared\")", "length = 3.5 width = 2.3 area = length * width needed =", "you will need # when tilling a wall or floor (in m2). length", "wall or floor (in m2). length = 3.5 width = 2.3 area =", "* width needed = area * 1.05 print(\"You need\", needed, \"tiles in metres", "calculates how many tiles you will need # when tilling a wall or", "= length * width needed = area * 1.05 print(\"You need\", needed, \"tiles", "tilling a wall or floor (in m2). length = 3.5 width = 2.3", "floor (in m2). length = 3.5 width = 2.3 area = length *", "will need # when tilling a wall or floor (in m2). length =", "# when tilling a wall or floor (in m2). length = 3.5 width", "<filename>ineedtiles.py # This program calculates how many tiles you will need # when", "or floor (in m2). length = 3.5 width = 2.3 area = length", "# This program calculates how many tiles you will need # when tilling", "a wall or floor (in m2). length = 3.5 width = 2.3 area", "(in m2). length = 3.5 width = 2.3 area = length * width", "many tiles you will need # when tilling a wall or floor (in", "when tilling a wall or floor (in m2). length = 3.5 width =", "tiles you will need # when tilling a wall or floor (in m2).", "= 3.5 width = 2.3 area = length * width needed = area", "how many tiles you will need # when tilling a wall or floor", "2.3 area = length * width needed = area * 1.05 print(\"You need\",", "This program calculates how many tiles you will need # when tilling a", "width = 2.3 area = length * width needed = area * 1.05", "3.5 width = 2.3 area = length * width needed = area *", "program calculates how many tiles you will need # when tilling a wall", "= 2.3 area = length * width needed = area * 1.05 print(\"You", "m2). length = 3.5 width = 2.3 area = length * width needed", "length * width needed = area * 1.05 print(\"You need\", needed, \"tiles in", "area = length * width needed = area * 1.05 print(\"You need\", needed,", "need # when tilling a wall or floor (in m2). length = 3.5" ]
[ "((parsed.hostname is None) or (parsed.hostname[0:3] == \"com\" )): return True #Hostname made no", "entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN) } def host_valid(netloc): parsed=urlparse(f'//{netloc}') try: #If it not", "serial port. if (parsed.port is None) and ((parsed.hostname is None) or (parsed.hostname[0:3] ==", "as vol from .const import DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA = vol.Schema( {", "in configuration.\"\"\" if host in solark_modbus_entries(self.hass): return True return False async def async_step_user(self,", "True return False async def async_step_user(self, user_input=None): \"\"\"Handle the initial step.\"\"\" errors =", "for entry in hass.config_entries.async_entries(DOMAIN) } def host_valid(netloc): parsed=urlparse(f'//{netloc}') try: #If it not a", "import urlparse from homeassistant import config_entries from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL from", "solark_modbus_entries(hass: HomeAssistant): \"\"\"Return the hosts already configured.\"\"\" return { entry.data[CONF_HOST] for entry in", "HomeAssistant): \"\"\"Return the hosts already configured.\"\"\" return { entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN)", "no sense. Error return except: return False return True class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk", "import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant, callback import voluptuous as vol", "False return True class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk Modbus configflow.\"\"\" VERSION = 1 CONNECTION_CLASS", "config_entries from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant, callback import", "import re from urllib.parse import urlparse from homeassistant import config_entries from homeassistant.const import", "return False async def async_step_user(self, user_input=None): \"\"\"Handle the initial step.\"\"\" errors = {}", "CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant, callback import voluptuous as vol from .const", "\"invalid host IP\" else: await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return", "from .const import DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA = vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME):", "<reponame>poldim/HA-solark-PV<filename>custom_components/solark/config_flow.py<gh_stars>10-100 import re from urllib.parse import urlparse from homeassistant import config_entries from homeassistant.const", "await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self.async_show_form( step_id=\"user\", data_schema=DATA_SCHEMA, errors=errors", "None) or (parsed.hostname[0:3] == \"com\" )): return True #Hostname made no sense. Error", "\"\"\"Return True if host exists in configuration.\"\"\" if host in solark_modbus_entries(self.hass): return True", "vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int, } ) @callback def solark_modbus_entries(hass: HomeAssistant): \"\"\"Return the hosts already", "self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self.async_show_form( step_id=\"user\", data_schema=DATA_SCHEMA, errors=errors )", "a serial port. if (parsed.port is None) and ((parsed.hostname is None) or (parsed.hostname[0:3]", "homeassistant.core import HomeAssistant, callback import voluptuous as vol from .const import DEFAULT_NAME, DEFAULT_PORT,", "None: host = user_input[CONF_HOST] if self._host_in_configuration_exists(host): errors[CONF_HOST] = \"already_configured\" elif not host_valid(host): errors[CONF_HOST]", "be a serial port. if (parsed.port is None) and ((parsed.hostname is None) or", "= \"already_configured\" elif not host_valid(host): errors[CONF_HOST] = \"invalid host IP\" else: await self.async_set_unique_id(user_input[CONF_HOST])", "return { entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN) } def host_valid(netloc): parsed=urlparse(f'//{netloc}') try: #If", "and ((parsed.hostname is None) or (parsed.hostname[0:3] == \"com\" )): return True #Hostname made", "homeassistant.const import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant, callback import voluptuous as", "self._host_in_configuration_exists(host): errors[CONF_HOST] = \"already_configured\" elif not host_valid(host): errors[CONF_HOST] = \"invalid host IP\" else:", "urlparse from homeassistant import config_entries from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.core", "#Hostname made no sense. Error return except: return False return True class SolArkModbusConfigFlow(config_entries.ConfigFlow,", "errors[CONF_HOST] = \"invalid host IP\" else: await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_NAME], data=user_input", "host_valid(netloc): parsed=urlparse(f'//{netloc}') try: #If it not a URL it might be a serial", "default=DEFAULT_SCAN_INTERVAL): int, } ) @callback def solark_modbus_entries(hass: HomeAssistant): \"\"\"Return the hosts already configured.\"\"\"", "CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self, host) -> bool: \"\"\"Return True if host exists", "is None) or (parsed.hostname[0:3] == \"com\" )): return True #Hostname made no sense.", "not None: host = user_input[CONF_HOST] if self._host_in_configuration_exists(host): errors[CONF_HOST] = \"already_configured\" elif not host_valid(host):", "in solark_modbus_entries(self.hass): return True return False async def async_step_user(self, user_input=None): \"\"\"Handle the initial", "None) and ((parsed.hostname is None) or (parsed.hostname[0:3] == \"com\" )): return True #Hostname", "= user_input[CONF_HOST] if self._host_in_configuration_exists(host): errors[CONF_HOST] = \"already_configured\" elif not host_valid(host): errors[CONF_HOST] = \"invalid", "URL it might be a serial port. if (parsed.port is None) and ((parsed.hostname", "from homeassistant.core import HomeAssistant, callback import voluptuous as vol from .const import DEFAULT_NAME,", "it not a URL it might be a serial port. if (parsed.port is", "\"already_configured\" elif not host_valid(host): errors[CONF_HOST] = \"invalid host IP\" else: await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured()", "not host_valid(host): errors[CONF_HOST] = \"invalid host IP\" else: await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return self.async_create_entry(", "from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant, callback import voluptuous", "\"\"\"SolArk Modbus configflow.\"\"\" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self, host) ->", "DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA = vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST, default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL,", "vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST, default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int, } ) @callback def", "vol.Required(CONF_HOST, default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int, } ) @callback def solark_modbus_entries(hass: HomeAssistant): \"\"\"Return", "return False return True class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk Modbus configflow.\"\"\" VERSION = 1", "re from urllib.parse import urlparse from homeassistant import config_entries from homeassistant.const import CONF_HOST,", "the hosts already configured.\"\"\" return { entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN) } def", "initial step.\"\"\" errors = {} if user_input is not None: host = user_input[CONF_HOST]", "def host_valid(netloc): parsed=urlparse(f'//{netloc}') try: #If it not a URL it might be a", "already configured.\"\"\" return { entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN) } def host_valid(netloc): parsed=urlparse(f'//{netloc}')", "== \"com\" )): return True #Hostname made no sense. Error return except: return", "return True return False async def async_step_user(self, user_input=None): \"\"\"Handle the initial step.\"\"\" errors", "(parsed.port is None) and ((parsed.hostname is None) or (parsed.hostname[0:3] == \"com\" )): return", "is not None: host = user_input[CONF_HOST] if self._host_in_configuration_exists(host): errors[CONF_HOST] = \"already_configured\" elif not", "class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk Modbus configflow.\"\"\" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def", "= \"invalid host IP\" else: await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_NAME], data=user_input )", "False async def async_step_user(self, user_input=None): \"\"\"Handle the initial step.\"\"\" errors = {} if", "import voluptuous as vol from .const import DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA =", "configured.\"\"\" return { entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN) } def host_valid(netloc): parsed=urlparse(f'//{netloc}') try:", "solark_modbus_entries(self.hass): return True return False async def async_step_user(self, user_input=None): \"\"\"Handle the initial step.\"\"\"", "Modbus configflow.\"\"\" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self, host) -> bool:", "default=DEFAULT_NAME): str, vol.Required(CONF_HOST, default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int, } ) @callback def solark_modbus_entries(hass:", "else: await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self.async_show_form( step_id=\"user\", data_schema=DATA_SCHEMA,", "entry in hass.config_entries.async_entries(DOMAIN) } def host_valid(netloc): parsed=urlparse(f'//{netloc}') try: #If it not a URL", "DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA = vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST, default='localhost'): str,", "async_step_user(self, user_input=None): \"\"\"Handle the initial step.\"\"\" errors = {} if user_input is not", "host) -> bool: \"\"\"Return True if host exists in configuration.\"\"\" if host in", "SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk Modbus configflow.\"\"\" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self,", "is None) and ((parsed.hostname is None) or (parsed.hostname[0:3] == \"com\" )): return True", "True #Hostname made no sense. Error return except: return False return True class", "HomeAssistant, callback import voluptuous as vol from .const import DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN", "from urllib.parse import urlparse from homeassistant import config_entries from homeassistant.const import CONF_HOST, CONF_NAME,", "user_input=None): \"\"\"Handle the initial step.\"\"\" errors = {} if user_input is not None:", "not a URL it might be a serial port. if (parsed.port is None)", "import config_entries from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant, callback", "= vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST, default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int, }", "{ entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN) } def host_valid(netloc): parsed=urlparse(f'//{netloc}') try: #If it", "return except: return False return True class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk Modbus configflow.\"\"\" VERSION", "exists in configuration.\"\"\" if host in solark_modbus_entries(self.hass): return True return False async def", "= config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self, host) -> bool: \"\"\"Return True if host exists in", "host IP\" else: await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self.async_show_form(", "if host exists in configuration.\"\"\" if host in solark_modbus_entries(self.hass): return True return False", "return True #Hostname made no sense. Error return except: return False return True", "try: #If it not a URL it might be a serial port. if", "def async_step_user(self, user_input=None): \"\"\"Handle the initial step.\"\"\" errors = {} if user_input is", "1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self, host) -> bool: \"\"\"Return True if host", "async def async_step_user(self, user_input=None): \"\"\"Handle the initial step.\"\"\" errors = {} if user_input", "configuration.\"\"\" if host in solark_modbus_entries(self.hass): return True return False async def async_step_user(self, user_input=None):", "True if host exists in configuration.\"\"\" if host in solark_modbus_entries(self.hass): return True return", "host exists in configuration.\"\"\" if host in solark_modbus_entries(self.hass): return True return False async", "host in solark_modbus_entries(self.hass): return True return False async def async_step_user(self, user_input=None): \"\"\"Handle the", "import HomeAssistant, callback import voluptuous as vol from .const import DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL,", "Error return except: return False return True class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk Modbus configflow.\"\"\"", "except: return False return True class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk Modbus configflow.\"\"\" VERSION =", "parsed=urlparse(f'//{netloc}') try: #If it not a URL it might be a serial port.", "DOMAIN DATA_SCHEMA = vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST, default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL):", "a URL it might be a serial port. if (parsed.port is None) and", "might be a serial port. if (parsed.port is None) and ((parsed.hostname is None)", "\"\"\"Handle the initial step.\"\"\" errors = {} if user_input is not None: host", "import DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA = vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST,", "domain=DOMAIN): \"\"\"SolArk Modbus configflow.\"\"\" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self, host)", "callback import voluptuous as vol from .const import DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA", "def solark_modbus_entries(hass: HomeAssistant): \"\"\"Return the hosts already configured.\"\"\" return { entry.data[CONF_HOST] for entry", "(parsed.hostname[0:3] == \"com\" )): return True #Hostname made no sense. Error return except:", "} ) @callback def solark_modbus_entries(hass: HomeAssistant): \"\"\"Return the hosts already configured.\"\"\" return {", "int, } ) @callback def solark_modbus_entries(hass: HomeAssistant): \"\"\"Return the hosts already configured.\"\"\" return", "if host in solark_modbus_entries(self.hass): return True return False async def async_step_user(self, user_input=None): \"\"\"Handle", "vol from .const import DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA = vol.Schema( { vol.Required(CONF_NAME,", "sense. Error return except: return False return True class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk Modbus", "VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self, host) -> bool: \"\"\"Return True", "it might be a serial port. if (parsed.port is None) and ((parsed.hostname is", "config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self, host) -> bool: \"\"\"Return True if host exists in configuration.\"\"\"", "} def host_valid(netloc): parsed=urlparse(f'//{netloc}') try: #If it not a URL it might be", "{} if user_input is not None: host = user_input[CONF_HOST] if self._host_in_configuration_exists(host): errors[CONF_HOST] =", ".const import DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA = vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME): str,", "True class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk Modbus configflow.\"\"\" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL", "hass.config_entries.async_entries(DOMAIN) } def host_valid(netloc): parsed=urlparse(f'//{netloc}') try: #If it not a URL it might", "CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant, callback import voluptuous as vol from", "vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST, default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int, } )", "elif not host_valid(host): errors[CONF_HOST] = \"invalid host IP\" else: await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return", "@callback def solark_modbus_entries(hass: HomeAssistant): \"\"\"Return the hosts already configured.\"\"\" return { entry.data[CONF_HOST] for", "step.\"\"\" errors = {} if user_input is not None: host = user_input[CONF_HOST] if", ") @callback def solark_modbus_entries(hass: HomeAssistant): \"\"\"Return the hosts already configured.\"\"\" return { entry.data[CONF_HOST]", "homeassistant import config_entries from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant,", "bool: \"\"\"Return True if host exists in configuration.\"\"\" if host in solark_modbus_entries(self.hass): return", "user_input[CONF_HOST] if self._host_in_configuration_exists(host): errors[CONF_HOST] = \"already_configured\" elif not host_valid(host): errors[CONF_HOST] = \"invalid host", "if self._host_in_configuration_exists(host): errors[CONF_HOST] = \"already_configured\" elif not host_valid(host): errors[CONF_HOST] = \"invalid host IP\"", "in hass.config_entries.async_entries(DOMAIN) } def host_valid(netloc): parsed=urlparse(f'//{netloc}') try: #If it not a URL it", ")): return True #Hostname made no sense. Error return except: return False return", "made no sense. Error return except: return False return True class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):", "from homeassistant import config_entries from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL from homeassistant.core import", "= {} if user_input is not None: host = user_input[CONF_HOST] if self._host_in_configuration_exists(host): errors[CONF_HOST]", "return True class SolArkModbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): \"\"\"SolArk Modbus configflow.\"\"\" VERSION = 1 CONNECTION_CLASS =", "_host_in_configuration_exists(self, host) -> bool: \"\"\"Return True if host exists in configuration.\"\"\" if host", "= 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self, host) -> bool: \"\"\"Return True if", "errors[CONF_HOST] = \"already_configured\" elif not host_valid(host): errors[CONF_HOST] = \"invalid host IP\" else: await", "{ vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST, default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int, } ) @callback", "voluptuous as vol from .const import DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA = vol.Schema(", "errors = {} if user_input is not None: host = user_input[CONF_HOST] if self._host_in_configuration_exists(host):", "str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int, } ) @callback def solark_modbus_entries(hass: HomeAssistant): \"\"\"Return the hosts", "def _host_in_configuration_exists(self, host) -> bool: \"\"\"Return True if host exists in configuration.\"\"\" if", "#If it not a URL it might be a serial port. if (parsed.port", "str, vol.Required(CONF_HOST, default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int, } ) @callback def solark_modbus_entries(hass: HomeAssistant):", "DATA_SCHEMA = vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST, default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int,", "if user_input is not None: host = user_input[CONF_HOST] if self._host_in_configuration_exists(host): errors[CONF_HOST] = \"already_configured\"", "the initial step.\"\"\" errors = {} if user_input is not None: host =", "urllib.parse import urlparse from homeassistant import config_entries from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL", "host = user_input[CONF_HOST] if self._host_in_configuration_exists(host): errors[CONF_HOST] = \"already_configured\" elif not host_valid(host): errors[CONF_HOST] =", "hosts already configured.\"\"\" return { entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN) } def host_valid(netloc):", "configflow.\"\"\" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def _host_in_configuration_exists(self, host) -> bool: \"\"\"Return", "\"com\" )): return True #Hostname made no sense. Error return except: return False", "-> bool: \"\"\"Return True if host exists in configuration.\"\"\" if host in solark_modbus_entries(self.hass):", "\"\"\"Return the hosts already configured.\"\"\" return { entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN) }", "host_valid(host): errors[CONF_HOST] = \"invalid host IP\" else: await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_NAME],", "user_input is not None: host = user_input[CONF_HOST] if self._host_in_configuration_exists(host): errors[CONF_HOST] = \"already_configured\" elif", "or (parsed.hostname[0:3] == \"com\" )): return True #Hostname made no sense. Error return", "IP\" else: await self.async_set_unique_id(user_input[CONF_HOST]) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self.async_show_form( step_id=\"user\",", "CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant, callback import voluptuous as vol from .const import", "default='localhost'): str, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int, } ) @callback def solark_modbus_entries(hass: HomeAssistant): \"\"\"Return the", "port. if (parsed.port is None) and ((parsed.hostname is None) or (parsed.hostname[0:3] == \"com\"", "DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN DATA_SCHEMA = vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST, default='localhost'):", "if (parsed.port is None) and ((parsed.hostname is None) or (parsed.hostname[0:3] == \"com\" )):" ]
[ "e zerada pois não ha mais o que dividir if montante == 0:", "valor a ser sacado (número inteiro) e o progama vai informar quantas cedulas", "a ser sacado?R$')) montante = saque # dinheiro do saque maior_cedula = 50", "= int(input('Qual o valor a ser sacado?R$')) montante = saque # dinheiro do", "da para tirar 50. tire 50 ate onde dé montante = montante -", "= saque # dinheiro do saque maior_cedula = 50 # notas cont_cedulas =", "maior_cedula = 10 elif maior_cedula == 10: maior_cedula = 1 cont_cedulas = 0", "10: maior_cedula = 1 cont_cedulas = 0 # quantidade de celuas e zerada", "status = True while status: if montante >= maior_cedula: # Valor do saque", "quantidade de celuas e zerada pois não ha mais o que dividir if", "celuas e zerada pois não ha mais o que dividir if montante ==", "/ R$1,00 print('{:-^40}'.format('Caixa Eletrônico')) saque = int(input('Qual o valor a ser sacado?R$')) montante", "saque maior_cedula = 50 # notas cont_cedulas = 0 # quantidades de notas", "tirar 50. tire 50 ate onde dé montante = montante - maior_cedula cont_cedulas", "do saque da para tirar 50. tire 50 ate onde dé montante =", "= 1 cont_cedulas = 0 # quantidade de celuas e zerada pois não", "- maior_cedula cont_cedulas = cont_cedulas + 1 else: #cedula de 50 passa 20", "montante - maior_cedula cont_cedulas = cont_cedulas + 1 else: #cedula de 50 passa", "ha mais o que dividir if montante == 0: # Quando o montante", "else: #cedula de 50 passa 20 .se não de mais p tirar 50,", "notas print(f'{cont_cedulas} nota(s) de R${maior_cedula}') if maior_cedula == 50: maior_cedula = 20 elif", "mais o que dividir if montante == 0: # Quando o montante tiver", "usuario # qual será o valor a ser sacado (número inteiro) e o", "qual será o valor a ser sacado (número inteiro) e o progama vai", "cont_cedulas + 1 else: #cedula de 50 passa 20 .se não de mais", "de mais p tirar 50, resto do montante vai tirar 20 ate onde", "ao usuario # qual será o valor a ser sacado (número inteiro) e", "# quantidades de notas usadas status = True while status: if montante >=", "valor # serão entregues. OBS: Considere o caixa possui cedulas de R$50,00 /", "simule o funcionamento de um caixaeletrônico. No inicio, pergunte ao usuario # qual", "#cedula de 50 passa 20 .se não de mais p tirar 50, resto", "inicio, pergunte ao usuario # qual será o valor a ser sacado (número", "valor a ser sacado?R$')) montante = saque # dinheiro do saque maior_cedula =", "de cada valor # serão entregues. OBS: Considere o caixa possui cedulas de", "caixa eletronico # Crie um progama que simule o funcionamento de um caixaeletrônico.", "50: maior_cedula = 20 elif maior_cedula == 20: maior_cedula = 10 elif maior_cedula", "while status: if montante >= maior_cedula: # Valor do saque da para tirar", ">= maior_cedula: # Valor do saque da para tirar 50. tire 50 ate", "de notas usadas status = True while status: if montante >= maior_cedula: #", "ser sacado?R$')) montante = saque # dinheiro do saque maior_cedula = 50 #", "50 passa 20 .se não de mais p tirar 50, resto do montante", "# Valor do saque da para tirar 50. tire 50 ate onde dé", "eletronico # Crie um progama que simule o funcionamento de um caixaeletrônico. No", "sacado?R$')) montante = saque # dinheiro do saque maior_cedula = 50 # notas", "Simulador de caixa eletronico # Crie um progama que simule o funcionamento de", "elif maior_cedula == 10: maior_cedula = 1 cont_cedulas = 0 # quantidade de", "o funcionamento de um caixaeletrônico. No inicio, pergunte ao usuario # qual será", "/ R$10,00 / R$1,00 print('{:-^40}'.format('Caixa Eletrônico')) saque = int(input('Qual o valor a ser", "o valor a ser sacado?R$')) montante = saque # dinheiro do saque maior_cedula", "== 50: maior_cedula = 20 elif maior_cedula == 20: maior_cedula = 10 elif", "R$50,00 / R$20,00 / R$10,00 / R$1,00 print('{:-^40}'.format('Caixa Eletrônico')) saque = int(input('Qual o", "# desconcidera 0 notas print(f'{cont_cedulas} nota(s) de R${maior_cedula}') if maior_cedula == 50: maior_cedula", "serão entregues. OBS: Considere o caixa possui cedulas de R$50,00 / R$20,00 /", "+ 1 else: #cedula de 50 passa 20 .se não de mais p", "saque = int(input('Qual o valor a ser sacado?R$')) montante = saque # dinheiro", "int(input('Qual o valor a ser sacado?R$')) montante = saque # dinheiro do saque", "não de mais p tirar 50, resto do montante vai tirar 20 ate", "o caixa possui cedulas de R$50,00 / R$20,00 / R$10,00 / R$1,00 print('{:-^40}'.format('Caixa", "R$10,00 / R$1,00 print('{:-^40}'.format('Caixa Eletrônico')) saque = int(input('Qual o valor a ser sacado?R$'))", "resto do montante vai tirar 20 ate onde de if cont_cedulas > 0:", "tirar 20 ate onde de if cont_cedulas > 0: # desconcidera 0 notas", "zerada pois não ha mais o que dividir if montante == 0: #", "de celuas e zerada pois não ha mais o que dividir if montante", "notas cont_cedulas = 0 # quantidades de notas usadas status = True while", "saque da para tirar 50. tire 50 ate onde dé montante = montante", "Valor do saque da para tirar 50. tire 50 ate onde dé montante", "elif maior_cedula == 20: maior_cedula = 10 elif maior_cedula == 10: maior_cedula =", "maior_cedula = 20 elif maior_cedula == 20: maior_cedula = 10 elif maior_cedula ==", "pergunte ao usuario # qual será o valor a ser sacado (número inteiro)", "= True while status: if montante >= maior_cedula: # Valor do saque da", "um progama que simule o funcionamento de um caixaeletrônico. No inicio, pergunte ao", "de 50 passa 20 .se não de mais p tirar 50, resto do", "de R${maior_cedula}') if maior_cedula == 50: maior_cedula = 20 elif maior_cedula == 20:", "pois não ha mais o que dividir if montante == 0: # Quando", "No inicio, pergunte ao usuario # qual será o valor a ser sacado", "/ R$20,00 / R$10,00 / R$1,00 print('{:-^40}'.format('Caixa Eletrônico')) saque = int(input('Qual o valor", "não ha mais o que dividir if montante == 0: # Quando o", "= 0 # quantidade de celuas e zerada pois não ha mais o", "cedulas de cada valor # serão entregues. OBS: Considere o caixa possui cedulas", "notas usadas status = True while status: if montante >= maior_cedula: # Valor", "quantas cedulas de cada valor # serão entregues. OBS: Considere o caixa possui", "cada valor # serão entregues. OBS: Considere o caixa possui cedulas de R$50,00", "Eletrônico')) saque = int(input('Qual o valor a ser sacado?R$')) montante = saque #", "quantidades de notas usadas status = True while status: if montante >= maior_cedula:", "if cont_cedulas > 0: # desconcidera 0 notas print(f'{cont_cedulas} nota(s) de R${maior_cedula}') if", "> 0: # desconcidera 0 notas print(f'{cont_cedulas} nota(s) de R${maior_cedula}') if maior_cedula ==", "nota(s) de R${maior_cedula}') if maior_cedula == 50: maior_cedula = 20 elif maior_cedula ==", "# Crie um progama que simule o funcionamento de um caixaeletrônico. No inicio,", "vai informar quantas cedulas de cada valor # serão entregues. OBS: Considere o", "cont_cedulas = cont_cedulas + 1 else: #cedula de 50 passa 20 .se não", "p tirar 50, resto do montante vai tirar 20 ate onde de if", "== 20: maior_cedula = 10 elif maior_cedula == 10: maior_cedula = 1 cont_cedulas", "funcionamento de um caixaeletrônico. No inicio, pergunte ao usuario # qual será o", "inteiro) e o progama vai informar quantas cedulas de cada valor # serão", "possui cedulas de R$50,00 / R$20,00 / R$10,00 / R$1,00 print('{:-^40}'.format('Caixa Eletrônico')) saque", "para tirar 50. tire 50 ate onde dé montante = montante - maior_cedula", "mais p tirar 50, resto do montante vai tirar 20 ate onde de", "que dividir if montante == 0: # Quando o montante tiver zerado. fim", "o progama vai informar quantas cedulas de cada valor # serão entregues. OBS:", "dé montante = montante - maior_cedula cont_cedulas = cont_cedulas + 1 else: #cedula", "50 ate onde dé montante = montante - maior_cedula cont_cedulas = cont_cedulas +", "1 cont_cedulas = 0 # quantidade de celuas e zerada pois não ha", "0 notas print(f'{cont_cedulas} nota(s) de R${maior_cedula}') if maior_cedula == 50: maior_cedula = 20", "ate onde dé montante = montante - maior_cedula cont_cedulas = cont_cedulas + 1", "20: maior_cedula = 10 elif maior_cedula == 10: maior_cedula = 1 cont_cedulas =", "OBS: Considere o caixa possui cedulas de R$50,00 / R$20,00 / R$10,00 /", "Crie um progama que simule o funcionamento de um caixaeletrônico. No inicio, pergunte", "# qual será o valor a ser sacado (número inteiro) e o progama", "= cont_cedulas + 1 else: #cedula de 50 passa 20 .se não de", "# quantidade de celuas e zerada pois não ha mais o que dividir", "entregues. OBS: Considere o caixa possui cedulas de R$50,00 / R$20,00 / R$10,00", "maior_cedula cont_cedulas = cont_cedulas + 1 else: #cedula de 50 passa 20 .se", "status: if montante >= maior_cedula: # Valor do saque da para tirar 50.", "20 .se não de mais p tirar 50, resto do montante vai tirar", "sacado (número inteiro) e o progama vai informar quantas cedulas de cada valor", "do montante vai tirar 20 ate onde de if cont_cedulas > 0: #", "saque # dinheiro do saque maior_cedula = 50 # notas cont_cedulas = 0", "10 elif maior_cedula == 10: maior_cedula = 1 cont_cedulas = 0 # quantidade", "montante >= maior_cedula: # Valor do saque da para tirar 50. tire 50", "= montante - maior_cedula cont_cedulas = cont_cedulas + 1 else: #cedula de 50", "ate onde de if cont_cedulas > 0: # desconcidera 0 notas print(f'{cont_cedulas} nota(s)", "dividir if montante == 0: # Quando o montante tiver zerado. fim status", "20 ate onde de if cont_cedulas > 0: # desconcidera 0 notas print(f'{cont_cedulas}", "progama que simule o funcionamento de um caixaeletrônico. No inicio, pergunte ao usuario", "= 0 # quantidades de notas usadas status = True while status: if", "do saque maior_cedula = 50 # notas cont_cedulas = 0 # quantidades de", "cont_cedulas = 0 # quantidades de notas usadas status = True while status:", "e o progama vai informar quantas cedulas de cada valor # serão entregues.", "caixa possui cedulas de R$50,00 / R$20,00 / R$10,00 / R$1,00 print('{:-^40}'.format('Caixa Eletrônico'))", "= 50 # notas cont_cedulas = 0 # quantidades de notas usadas status", "montante = saque # dinheiro do saque maior_cedula = 50 # notas cont_cedulas", "montante vai tirar 20 ate onde de if cont_cedulas > 0: # desconcidera", "R$1,00 print('{:-^40}'.format('Caixa Eletrônico')) saque = int(input('Qual o valor a ser sacado?R$')) montante =", "cedulas de R$50,00 / R$20,00 / R$10,00 / R$1,00 print('{:-^40}'.format('Caixa Eletrônico')) saque =", "vai tirar 20 ate onde de if cont_cedulas > 0: # desconcidera 0", "Considere o caixa possui cedulas de R$50,00 / R$20,00 / R$10,00 / R$1,00", "será o valor a ser sacado (número inteiro) e o progama vai informar", "de um caixaeletrônico. No inicio, pergunte ao usuario # qual será o valor", "onde dé montante = montante - maior_cedula cont_cedulas = cont_cedulas + 1 else:", "print(f'{cont_cedulas} nota(s) de R${maior_cedula}') if maior_cedula == 50: maior_cedula = 20 elif maior_cedula", "tire 50 ate onde dé montante = montante - maior_cedula cont_cedulas = cont_cedulas", "maior_cedula == 20: maior_cedula = 10 elif maior_cedula == 10: maior_cedula = 1", "cont_cedulas > 0: # desconcidera 0 notas print(f'{cont_cedulas} nota(s) de R${maior_cedula}') if maior_cedula", "if maior_cedula == 50: maior_cedula = 20 elif maior_cedula == 20: maior_cedula =", "# dinheiro do saque maior_cedula = 50 # notas cont_cedulas = 0 #", "maior_cedula: # Valor do saque da para tirar 50. tire 50 ate onde", "maior_cedula == 50: maior_cedula = 20 elif maior_cedula == 20: maior_cedula = 10", "(número inteiro) e o progama vai informar quantas cedulas de cada valor #", "if montante >= maior_cedula: # Valor do saque da para tirar 50. tire", "50 # notas cont_cedulas = 0 # quantidades de notas usadas status =", "# notas cont_cedulas = 0 # quantidades de notas usadas status = True", "montante == 0: # Quando o montante tiver zerado. fim status = False", "0 # quantidade de celuas e zerada pois não ha mais o que", "passa 20 .se não de mais p tirar 50, resto do montante vai", "informar quantas cedulas de cada valor # serão entregues. OBS: Considere o caixa", "50. tire 50 ate onde dé montante = montante - maior_cedula cont_cedulas =", "0 # quantidades de notas usadas status = True while status: if montante", "de if cont_cedulas > 0: # desconcidera 0 notas print(f'{cont_cedulas} nota(s) de R${maior_cedula}')", "que simule o funcionamento de um caixaeletrônico. No inicio, pergunte ao usuario #", "maior_cedula == 10: maior_cedula = 1 cont_cedulas = 0 # quantidade de celuas", "o valor a ser sacado (número inteiro) e o progama vai informar quantas", "progama vai informar quantas cedulas de cada valor # serão entregues. OBS: Considere", "de caixa eletronico # Crie um progama que simule o funcionamento de um", "dinheiro do saque maior_cedula = 50 # notas cont_cedulas = 0 # quantidades", ".se não de mais p tirar 50, resto do montante vai tirar 20", "50, resto do montante vai tirar 20 ate onde de if cont_cedulas >", "20 elif maior_cedula == 20: maior_cedula = 10 elif maior_cedula == 10: maior_cedula", "maior_cedula = 50 # notas cont_cedulas = 0 # quantidades de notas usadas", "R${maior_cedula}') if maior_cedula == 50: maior_cedula = 20 elif maior_cedula == 20: maior_cedula", "um caixaeletrônico. No inicio, pergunte ao usuario # qual será o valor a", "caixaeletrônico. No inicio, pergunte ao usuario # qual será o valor a ser", "0: # desconcidera 0 notas print(f'{cont_cedulas} nota(s) de R${maior_cedula}') if maior_cedula == 50:", "tirar 50, resto do montante vai tirar 20 ate onde de if cont_cedulas", "== 10: maior_cedula = 1 cont_cedulas = 0 # quantidade de celuas e", "usadas status = True while status: if montante >= maior_cedula: # Valor do", "maior_cedula = 1 cont_cedulas = 0 # quantidade de celuas e zerada pois", "= 10 elif maior_cedula == 10: maior_cedula = 1 cont_cedulas = 0 #", "ser sacado (número inteiro) e o progama vai informar quantas cedulas de cada", "# serão entregues. OBS: Considere o caixa possui cedulas de R$50,00 / R$20,00", "= 20 elif maior_cedula == 20: maior_cedula = 10 elif maior_cedula == 10:", "#Desafio Simulador de caixa eletronico # Crie um progama que simule o funcionamento", "print('{:-^40}'.format('Caixa Eletrônico')) saque = int(input('Qual o valor a ser sacado?R$')) montante = saque", "o que dividir if montante == 0: # Quando o montante tiver zerado.", "if montante == 0: # Quando o montante tiver zerado. fim status =", "de R$50,00 / R$20,00 / R$10,00 / R$1,00 print('{:-^40}'.format('Caixa Eletrônico')) saque = int(input('Qual", "True while status: if montante >= maior_cedula: # Valor do saque da para", "desconcidera 0 notas print(f'{cont_cedulas} nota(s) de R${maior_cedula}') if maior_cedula == 50: maior_cedula =", "cont_cedulas = 0 # quantidade de celuas e zerada pois não ha mais", "onde de if cont_cedulas > 0: # desconcidera 0 notas print(f'{cont_cedulas} nota(s) de", "montante = montante - maior_cedula cont_cedulas = cont_cedulas + 1 else: #cedula de", "R$20,00 / R$10,00 / R$1,00 print('{:-^40}'.format('Caixa Eletrônico')) saque = int(input('Qual o valor a", "1 else: #cedula de 50 passa 20 .se não de mais p tirar", "a ser sacado (número inteiro) e o progama vai informar quantas cedulas de" ]
[ "file_okay=True, dir_okay=False)) @click.argument( 'output_path', type=click.Path(exists=False, file_okay=True, dir_okay=False)) def human_performance( split_path: str, output_path: str", "[] with click.open_file(split_path, 'r') as split_file: for ln in split_file: row = json.loads(ln)", "them to OUTPUT_PATH. Human performance is computed by comparing the majority vote label", "resource. Read in the split from SPLIT_PATH, then estimate human performance metrics and", "human performance metrics and write them to OUTPUT_PATH. Human performance is computed by", "computed by comparing the majority vote label of the human performance annotators to", "[] gold_labels = [] with click.open_file(split_path, 'r') as split_file: for ln in split_file:", "for ln in split_file: row = json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with open(output_path, 'w') as", "from ....baselines.metrics import METRICS logger = logging.getLogger(__name__) # main function @click.command() @click.argument( 'split_path',", "split_file: for ln in split_file: row = json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with open(output_path, 'w')", "split_path: str, output_path: str ) -> None: \"\"\"Estimate human performance on the scruples", "'w') as metrics_file: json.dump({ key: metric( y_true=gold_labels, y_pred=human_preds) for key, (_, metric, scorer_kwargs)", "'output_path', type=click.Path(exists=False, file_okay=True, dir_okay=False)) def human_performance( split_path: str, output_path: str ) -> None:", "gold_labels.append(row['gold_label']) with open(output_path, 'w') as metrics_file: json.dump({ key: metric( y_true=gold_labels, y_pred=human_preds) for key,", "majority vote label of the human performance annotators to the majority vote label", "of the gold annotators. \"\"\" logger.info('Computing human performance.') human_preds = [] gold_labels =", "to OUTPUT_PATH. Human performance is computed by comparing the majority vote label of", "the scruples resource.\"\"\" import json import logging import click from ....baselines.metrics import METRICS", "split_file: row = json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with open(output_path, 'w') as metrics_file: json.dump({ key:", "json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with open(output_path, 'w') as metrics_file: json.dump({ key: metric( y_true=gold_labels, y_pred=human_preds)", "label of the gold annotators. \"\"\" logger.info('Computing human performance.') human_preds = [] gold_labels", "@click.argument( 'split_path', type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.argument( 'output_path', type=click.Path(exists=False, file_okay=True, dir_okay=False)) def human_performance( split_path:", "performance on the scruples resource. Read in the split from SPLIT_PATH, then estimate", "click from ....baselines.metrics import METRICS logger = logging.getLogger(__name__) # main function @click.command() @click.argument(", "file_okay=True, dir_okay=False)) def human_performance( split_path: str, output_path: str ) -> None: \"\"\"Estimate human", "human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with open(output_path, 'w') as metrics_file: json.dump({ key: metric( y_true=gold_labels, y_pred=human_preds) for", "= logging.getLogger(__name__) # main function @click.command() @click.argument( 'split_path', type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.argument( 'output_path',", "logging import click from ....baselines.metrics import METRICS logger = logging.getLogger(__name__) # main function", "gold_labels = [] with click.open_file(split_path, 'r') as split_file: for ln in split_file: row", "the human performance annotators to the majority vote label of the gold annotators.", "vote label of the gold annotators. \"\"\" logger.info('Computing human performance.') human_preds = []", "METRICS logger = logging.getLogger(__name__) # main function @click.command() @click.argument( 'split_path', type=click.Path(exists=True, file_okay=True, dir_okay=False))", "performance.') human_preds = [] gold_labels = [] with click.open_file(split_path, 'r') as split_file: for", "type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.argument( 'output_path', type=click.Path(exists=False, file_okay=True, dir_okay=False)) def human_performance( split_path: str, output_path:", "split from SPLIT_PATH, then estimate human performance metrics and write them to OUTPUT_PATH.", "human_preds = [] gold_labels = [] with click.open_file(split_path, 'r') as split_file: for ln", "human performance.') human_preds = [] gold_labels = [] with click.open_file(split_path, 'r') as split_file:", "'split_path', type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.argument( 'output_path', type=click.Path(exists=False, file_okay=True, dir_okay=False)) def human_performance( split_path: str,", "majority vote label of the gold annotators. \"\"\" logger.info('Computing human performance.') human_preds =", "Read in the split from SPLIT_PATH, then estimate human performance metrics and write", "function @click.command() @click.argument( 'split_path', type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.argument( 'output_path', type=click.Path(exists=False, file_okay=True, dir_okay=False)) def", "and write them to OUTPUT_PATH. Human performance is computed by comparing the majority", "the majority vote label of the gold annotators. \"\"\" logger.info('Computing human performance.') human_preds", "the majority vote label of the human performance annotators to the majority vote", "human performance on the scruples resource. Read in the split from SPLIT_PATH, then", "vote label of the human performance annotators to the majority vote label of", "by comparing the majority vote label of the human performance annotators to the", "import METRICS logger = logging.getLogger(__name__) # main function @click.command() @click.argument( 'split_path', type=click.Path(exists=True, file_okay=True,", "def human_performance( split_path: str, output_path: str ) -> None: \"\"\"Estimate human performance on", "@click.command() @click.argument( 'split_path', type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.argument( 'output_path', type=click.Path(exists=False, file_okay=True, dir_okay=False)) def human_performance(", "the split from SPLIT_PATH, then estimate human performance metrics and write them to", "'r') as split_file: for ln in split_file: row = json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with", "estimate human performance metrics and write them to OUTPUT_PATH. Human performance is computed", "json import logging import click from ....baselines.metrics import METRICS logger = logging.getLogger(__name__) #", "-> None: \"\"\"Estimate human performance on the scruples resource. Read in the split", "OUTPUT_PATH. Human performance is computed by comparing the majority vote label of the", ") -> None: \"\"\"Estimate human performance on the scruples resource. Read in the", "str ) -> None: \"\"\"Estimate human performance on the scruples resource. Read in", "SPLIT_PATH, then estimate human performance metrics and write them to OUTPUT_PATH. Human performance", "label of the human performance annotators to the majority vote label of the", "= [] gold_labels = [] with click.open_file(split_path, 'r') as split_file: for ln in", "row = json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with open(output_path, 'w') as metrics_file: json.dump({ key: metric(", "is computed by comparing the majority vote label of the human performance annotators", "human performance annotators to the majority vote label of the gold annotators. \"\"\"", "\"\"\" logger.info('Computing human performance.') human_preds = [] gold_labels = [] with click.open_file(split_path, 'r')", "performance metrics and write them to OUTPUT_PATH. Human performance is computed by comparing", "\"\"\"Estimate human performance for the scruples resource.\"\"\" import json import logging import click", "scruples resource.\"\"\" import json import logging import click from ....baselines.metrics import METRICS logger", "dir_okay=False)) def human_performance( split_path: str, output_path: str ) -> None: \"\"\"Estimate human performance", "resource.\"\"\" import json import logging import click from ....baselines.metrics import METRICS logger =", "from SPLIT_PATH, then estimate human performance metrics and write them to OUTPUT_PATH. Human", "logger = logging.getLogger(__name__) # main function @click.command() @click.argument( 'split_path', type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.argument(", "None: \"\"\"Estimate human performance on the scruples resource. Read in the split from", "# main function @click.command() @click.argument( 'split_path', type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.argument( 'output_path', type=click.Path(exists=False, file_okay=True,", "json.dump({ key: metric( y_true=gold_labels, y_pred=human_preds) for key, (_, metric, scorer_kwargs) in METRICS.items() if", "then estimate human performance metrics and write them to OUTPUT_PATH. Human performance is", "performance for the scruples resource.\"\"\" import json import logging import click from ....baselines.metrics", "str, output_path: str ) -> None: \"\"\"Estimate human performance on the scruples resource.", "metrics and write them to OUTPUT_PATH. Human performance is computed by comparing the", "human_performance( split_path: str, output_path: str ) -> None: \"\"\"Estimate human performance on the", "....baselines.metrics import METRICS logger = logging.getLogger(__name__) # main function @click.command() @click.argument( 'split_path', type=click.Path(exists=True,", "= [] with click.open_file(split_path, 'r') as split_file: for ln in split_file: row =", "annotators. \"\"\" logger.info('Computing human performance.') human_preds = [] gold_labels = [] with click.open_file(split_path,", "y_pred=human_preds) for key, (_, metric, scorer_kwargs) in METRICS.items() if not scorer_kwargs['needs_proba'] }, metrics_file)", "with open(output_path, 'w') as metrics_file: json.dump({ key: metric( y_true=gold_labels, y_pred=human_preds) for key, (_,", "dir_okay=False)) @click.argument( 'output_path', type=click.Path(exists=False, file_okay=True, dir_okay=False)) def human_performance( split_path: str, output_path: str )", "human performance for the scruples resource.\"\"\" import json import logging import click from", "logging.getLogger(__name__) # main function @click.command() @click.argument( 'split_path', type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.argument( 'output_path', type=click.Path(exists=False,", "logger.info('Computing human performance.') human_preds = [] gold_labels = [] with click.open_file(split_path, 'r') as", "to the majority vote label of the gold annotators. \"\"\" logger.info('Computing human performance.')", "import click from ....baselines.metrics import METRICS logger = logging.getLogger(__name__) # main function @click.command()", "gold annotators. \"\"\" logger.info('Computing human performance.') human_preds = [] gold_labels = [] with", "\"\"\"Estimate human performance on the scruples resource. Read in the split from SPLIT_PATH,", "write them to OUTPUT_PATH. Human performance is computed by comparing the majority vote", "import json import logging import click from ....baselines.metrics import METRICS logger = logging.getLogger(__name__)", "= json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with open(output_path, 'w') as metrics_file: json.dump({ key: metric( y_true=gold_labels,", "in the split from SPLIT_PATH, then estimate human performance metrics and write them", "key: metric( y_true=gold_labels, y_pred=human_preds) for key, (_, metric, scorer_kwargs) in METRICS.items() if not", "@click.argument( 'output_path', type=click.Path(exists=False, file_okay=True, dir_okay=False)) def human_performance( split_path: str, output_path: str ) ->", "in split_file: row = json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with open(output_path, 'w') as metrics_file: json.dump({", "y_true=gold_labels, y_pred=human_preds) for key, (_, metric, scorer_kwargs) in METRICS.items() if not scorer_kwargs['needs_proba'] },", "the scruples resource. Read in the split from SPLIT_PATH, then estimate human performance", "type=click.Path(exists=False, file_okay=True, dir_okay=False)) def human_performance( split_path: str, output_path: str ) -> None: \"\"\"Estimate", "open(output_path, 'w') as metrics_file: json.dump({ key: metric( y_true=gold_labels, y_pred=human_preds) for key, (_, metric,", "as metrics_file: json.dump({ key: metric( y_true=gold_labels, y_pred=human_preds) for key, (_, metric, scorer_kwargs) in", "import logging import click from ....baselines.metrics import METRICS logger = logging.getLogger(__name__) # main", "with click.open_file(split_path, 'r') as split_file: for ln in split_file: row = json.loads(ln) human_preds.append(row['human_perf_label'])", "metric( y_true=gold_labels, y_pred=human_preds) for key, (_, metric, scorer_kwargs) in METRICS.items() if not scorer_kwargs['needs_proba']", "performance is computed by comparing the majority vote label of the human performance", "annotators to the majority vote label of the gold annotators. \"\"\" logger.info('Computing human", "Human performance is computed by comparing the majority vote label of the human", "of the human performance annotators to the majority vote label of the gold", "comparing the majority vote label of the human performance annotators to the majority", "performance annotators to the majority vote label of the gold annotators. \"\"\" logger.info('Computing", "on the scruples resource. Read in the split from SPLIT_PATH, then estimate human", "main function @click.command() @click.argument( 'split_path', type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.argument( 'output_path', type=click.Path(exists=False, file_okay=True, dir_okay=False))", "metrics_file: json.dump({ key: metric( y_true=gold_labels, y_pred=human_preds) for key, (_, metric, scorer_kwargs) in METRICS.items()", "for the scruples resource.\"\"\" import json import logging import click from ....baselines.metrics import", "output_path: str ) -> None: \"\"\"Estimate human performance on the scruples resource. Read", "scruples resource. Read in the split from SPLIT_PATH, then estimate human performance metrics", "click.open_file(split_path, 'r') as split_file: for ln in split_file: row = json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label'])", "the gold annotators. \"\"\" logger.info('Computing human performance.') human_preds = [] gold_labels = []", "as split_file: for ln in split_file: row = json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with open(output_path,", "ln in split_file: row = json.loads(ln) human_preds.append(row['human_perf_label']) gold_labels.append(row['gold_label']) with open(output_path, 'w') as metrics_file:" ]
[ "from target_bigquery import stream_utils class TestStreamUtils(unittest.TestCase): \"\"\" Unit Tests \"\"\" def test_add_metadata_values_to_record(self): \"\"\"Test", "metadata when there's no time extracted in the record message \"\"\" record =", "class TestStreamUtils(unittest.TestCase): \"\"\" Unit Tests \"\"\" def test_add_metadata_values_to_record(self): \"\"\"Test adding metadata\"\"\" dt =", "\"2\"} } dt = datetime.now() result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs", "self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs = ['_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs:", "\"type\": \"RECORD\", \"stream\": \"foo\", \"record\": {\"id\": \"2\"} } dt = datetime.now() result =", "'%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs = ['_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr in result) def", "extracted in the record message \"\"\" record = { \"type\": \"RECORD\", \"stream\": \"foo\",", "= datetime.now() result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs = ['_sdc_extracted_at', '_sdc_batched_at',", "self.assertTrue(attr in result) def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding metadata when there's no time extracted", "\"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs = ['_sdc_extracted_at', '_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr", "\"\"\" def test_add_metadata_values_to_record(self): \"\"\"Test adding metadata\"\"\" dt = \"2017-11-20T16:45:33.000Z\" record = { \"type\":", "unittest from datetime import datetime from target_bigquery import stream_utils class TestStreamUtils(unittest.TestCase): \"\"\" Unit", "['_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr in result) def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding", "= \"2017-11-20T16:45:33.000Z\" record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"time_extracted\": dt, \"record\": {\"id\":", "in the record message \"\"\" record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"record\":", "self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs = ['_sdc_extracted_at', '_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr in", "\"\"\"Test adding metadata when there's no time extracted in the record message \"\"\"", "= stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs = ['_sdc_batched_at', '_sdc_deleted_at'] for attr", "result) def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding metadata when there's no time extracted in the", "dt) extra_attrs = ['_sdc_extracted_at', '_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr in result)", "TestStreamUtils(unittest.TestCase): \"\"\" Unit Tests \"\"\" def test_add_metadata_values_to_record(self): \"\"\"Test adding metadata\"\"\" dt = \"2017-11-20T16:45:33.000Z\"", "time extracted in the record message \"\"\" record = { \"type\": \"RECORD\", \"stream\":", "no time extracted in the record message \"\"\" record = { \"type\": \"RECORD\",", "{ \"type\": \"RECORD\", \"stream\": \"foo\", \"time_extracted\": dt, \"record\": {\"id\": \"2\"} } result =", "\"RECORD\", \"stream\": \"foo\", \"time_extracted\": dt, \"record\": {\"id\": \"2\"} } result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"),", "extra_attrs: self.assertTrue(attr in result) def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding metadata when there's no time", "stream_utils class TestStreamUtils(unittest.TestCase): \"\"\" Unit Tests \"\"\" def test_add_metadata_values_to_record(self): \"\"\"Test adding metadata\"\"\" dt", "= ['_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr in result) def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test", "= { \"type\": \"RECORD\", \"stream\": \"foo\", \"record\": {\"id\": \"2\"} } dt = datetime.now()", "\"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs = ['_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr", "record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"record\": {\"id\": \"2\"} } dt =", "record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"time_extracted\": dt, \"record\": {\"id\": \"2\"} }", "\"foo\", \"record\": {\"id\": \"2\"} } dt = datetime.now() result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\")", "\"stream\": \"foo\", \"time_extracted\": dt, \"record\": {\"id\": \"2\"} } result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\")", "} result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs = ['_sdc_batched_at', '_sdc_deleted_at']", "datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs = ['_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr in result)", "there's no time extracted in the record message \"\"\" record = { \"type\":", "in result) def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding metadata when there's no time extracted in", "stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs = ['_sdc_extracted_at', '_sdc_batched_at', '_sdc_deleted_at'] for attr in", "\"RECORD\", \"stream\": \"foo\", \"record\": {\"id\": \"2\"} } dt = datetime.now() result = stream_utils.add_metadata_values_to_record(record)", "\"\"\" Unit Tests \"\"\" def test_add_metadata_values_to_record(self): \"\"\"Test adding metadata\"\"\" dt = \"2017-11-20T16:45:33.000Z\" record", "self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs = ['_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr in", "datetime import datetime from target_bigquery import stream_utils class TestStreamUtils(unittest.TestCase): \"\"\" Unit Tests \"\"\"", "dt = \"2017-11-20T16:45:33.000Z\" record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"time_extracted\": dt, \"record\":", "dt = datetime.now() result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs = ['_sdc_extracted_at',", "\"\"\" record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"record\": {\"id\": \"2\"} } dt", "from datetime import datetime from target_bigquery import stream_utils class TestStreamUtils(unittest.TestCase): \"\"\" Unit Tests", "\"2\"} } result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs = ['_sdc_batched_at',", "\"type\": \"RECORD\", \"stream\": \"foo\", \"time_extracted\": dt, \"record\": {\"id\": \"2\"} } result = stream_utils.add_metadata_values_to_record(record)", "Unit Tests \"\"\" def test_add_metadata_values_to_record(self): \"\"\"Test adding metadata\"\"\" dt = \"2017-11-20T16:45:33.000Z\" record =", "adding metadata\"\"\" dt = \"2017-11-20T16:45:33.000Z\" record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"time_extracted\":", "record message \"\"\" record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"record\": {\"id\": \"2\"}", "the record message \"\"\" record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"record\": {\"id\":", "datetime from target_bigquery import stream_utils class TestStreamUtils(unittest.TestCase): \"\"\" Unit Tests \"\"\" def test_add_metadata_values_to_record(self):", "message \"\"\" record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"record\": {\"id\": \"2\"} }", "def test_add_metadata_values_to_record(self): \"\"\"Test adding metadata\"\"\" dt = \"2017-11-20T16:45:33.000Z\" record = { \"type\": \"RECORD\",", "result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs = ['_sdc_extracted_at', '_sdc_batched_at', '_sdc_deleted_at'] for", "import datetime from target_bigquery import stream_utils class TestStreamUtils(unittest.TestCase): \"\"\" Unit Tests \"\"\" def", "in extra_attrs: self.assertTrue(attr in result) def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding metadata when there's no", "\"stream\": \"foo\", \"record\": {\"id\": \"2\"} } dt = datetime.now() result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"),", "import stream_utils class TestStreamUtils(unittest.TestCase): \"\"\" Unit Tests \"\"\" def test_add_metadata_values_to_record(self): \"\"\"Test adding metadata\"\"\"", "when there's no time extracted in the record message \"\"\" record = {", "\"\"\"Test adding metadata\"\"\" dt = \"2017-11-20T16:45:33.000Z\" record = { \"type\": \"RECORD\", \"stream\": \"foo\",", "Tests \"\"\" def test_add_metadata_values_to_record(self): \"\"\"Test adding metadata\"\"\" dt = \"2017-11-20T16:45:33.000Z\" record = {", "def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding metadata when there's no time extracted in the record", "{ \"type\": \"RECORD\", \"stream\": \"foo\", \"record\": {\"id\": \"2\"} } dt = datetime.now() result", "= stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs = ['_sdc_extracted_at', '_sdc_batched_at', '_sdc_deleted_at'] for attr", "test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding metadata when there's no time extracted in the record message", "extra_attrs = ['_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr in result) def test_add_metadata_values_to_record_when_no_time_extracted(self):", "result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs = ['_sdc_batched_at', '_sdc_deleted_at'] for", "'_sdc_deleted_at'] for attr in extra_attrs: self.assertTrue(attr in result) def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding metadata", "metadata\"\"\" dt = \"2017-11-20T16:45:33.000Z\" record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"time_extracted\": dt,", "{\"id\": \"2\"} } result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs =", "{\"id\": \"2\"} } dt = datetime.now() result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt)", "\"record\": {\"id\": \"2\"} } result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs", "\"record\": {\"id\": \"2\"} } dt = datetime.now() result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"),", "for attr in extra_attrs: self.assertTrue(attr in result) def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding metadata when", "\"time_extracted\": dt, \"record\": {\"id\": \"2\"} } result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt,", "dt, \"record\": {\"id\": \"2\"} } result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ'))", "adding metadata when there's no time extracted in the record message \"\"\" record", "self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs = ['_sdc_extracted_at', '_sdc_batched_at', '_sdc_deleted_at'] for attr in extra_attrs:", "test_add_metadata_values_to_record(self): \"\"\"Test adding metadata\"\"\" dt = \"2017-11-20T16:45:33.000Z\" record = { \"type\": \"RECORD\", \"stream\":", "= { \"type\": \"RECORD\", \"stream\": \"foo\", \"time_extracted\": dt, \"record\": {\"id\": \"2\"} } result", "import unittest from datetime import datetime from target_bigquery import stream_utils class TestStreamUtils(unittest.TestCase): \"\"\"", "\"2017-11-20T16:45:33.000Z\" record = { \"type\": \"RECORD\", \"stream\": \"foo\", \"time_extracted\": dt, \"record\": {\"id\": \"2\"}", "} dt = datetime.now() result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs =", "target_bigquery import stream_utils class TestStreamUtils(unittest.TestCase): \"\"\" Unit Tests \"\"\" def test_add_metadata_values_to_record(self): \"\"\"Test adding", "stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"), datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')) extra_attrs = ['_sdc_batched_at', '_sdc_deleted_at'] for attr in", "datetime.now() result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertGreaterEqual(result.get(\"_sdc_extracted_at\"), dt) extra_attrs = ['_sdc_extracted_at', '_sdc_batched_at', '_sdc_deleted_at']", "\"foo\", \"time_extracted\": dt, \"record\": {\"id\": \"2\"} } result = stream_utils.add_metadata_values_to_record(record) self.assertEqual(result.get(\"id\"), \"2\") self.assertEqual(result.get(\"_sdc_extracted_at\"),", "attr in extra_attrs: self.assertTrue(attr in result) def test_add_metadata_values_to_record_when_no_time_extracted(self): \"\"\"Test adding metadata when there's" ]
[ "### # DRIVER_PATH = \"/usr/local/bin/chromedriver\" ### Only for Mac (End) ### # 請注意!以下皆為機密個資,請小心謹慎,勿上傳至公開平台", "\"https://www.huahuacomputer.com.tw/products/gigabyte-%E6%8A%80%E5%98%89-aorus-15g-yb-%E6%A9%9F%E6%A2%B0%E8%BB%B8%E9%9B%BB%E7%AB%B6%E7%AD%86%E9%9B%BB-1\" DRIVER_PATH = \"chromedriver.exe\" CHROME_PATH = r\"--user-data-dir=C:\\\\Users\\brian\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\Default\" # 可透過網址列輸入 chrome://version/ 找到 ###", "= \"/usr/local/bin/chromedriver\" ### Only for Mac (End) ### # 請注意!以下皆為機密個資,請小心謹慎,勿上傳至公開平台 ACC = \"<EMAIL>\"", "Mac ### # DRIVER_PATH = \"/usr/local/bin/chromedriver\" ### Only for Mac (End) ### #", "### Only for Mac (End) ### # 請注意!以下皆為機密個資,請小心謹慎,勿上傳至公開平台 ACC = \"<EMAIL>\" PWD =", "Only for Mac (End) ### # 請注意!以下皆為機密個資,請小心謹慎,勿上傳至公開平台 ACC = \"<EMAIL>\" PWD = \"<PASSWORD>\"", "DRIVER_PATH = \"/usr/local/bin/chromedriver\" ### Only for Mac (End) ### # 請注意!以下皆為機密個資,請小心謹慎,勿上傳至公開平台 ACC =", "# 可透過網址列輸入 chrome://version/ 找到 ### Only for Mac ### # DRIVER_PATH = \"/usr/local/bin/chromedriver\"", "DRIVER_PATH = \"chromedriver.exe\" CHROME_PATH = r\"--user-data-dir=C:\\\\Users\\brian\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\Default\" # 可透過網址列輸入 chrome://version/ 找到 ### Only", "\"chromedriver.exe\" CHROME_PATH = r\"--user-data-dir=C:\\\\Users\\brian\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\Default\" # 可透過網址列輸入 chrome://version/ 找到 ### Only for Mac", "= \"https://www.huahuacomputer.com.tw/products/gigabyte-%E6%8A%80%E5%98%89-aorus-15g-yb-%E6%A9%9F%E6%A2%B0%E8%BB%B8%E9%9B%BB%E7%AB%B6%E7%AD%86%E9%9B%BB-1\" DRIVER_PATH = \"chromedriver.exe\" CHROME_PATH = r\"--user-data-dir=C:\\\\Users\\brian\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\Default\" # 可透過網址列輸入 chrome://version/ 找到", "<reponame>GlycerinLOL/Hwa_autobuy<filename>settings.py URL = \"https://www.huahuacomputer.com.tw/products/gigabyte-%E6%8A%80%E5%98%89-aorus-15g-yb-%E6%A9%9F%E6%A2%B0%E8%BB%B8%E9%9B%BB%E7%AB%B6%E7%AD%86%E9%9B%BB-1\" DRIVER_PATH = \"chromedriver.exe\" CHROME_PATH = r\"--user-data-dir=C:\\\\Users\\brian\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\Default\" # 可透過網址列輸入", "### Only for Mac ### # DRIVER_PATH = \"/usr/local/bin/chromedriver\" ### Only for Mac", "\"/usr/local/bin/chromedriver\" ### Only for Mac (End) ### # 請注意!以下皆為機密個資,請小心謹慎,勿上傳至公開平台 ACC = \"<EMAIL>\" PWD", "Data\\Default\" # 可透過網址列輸入 chrome://version/ 找到 ### Only for Mac ### # DRIVER_PATH =", "Only for Mac ### # DRIVER_PATH = \"/usr/local/bin/chromedriver\" ### Only for Mac (End)", "= \"chromedriver.exe\" CHROME_PATH = r\"--user-data-dir=C:\\\\Users\\brian\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\Default\" # 可透過網址列輸入 chrome://version/ 找到 ### Only for", "可透過網址列輸入 chrome://version/ 找到 ### Only for Mac ### # DRIVER_PATH = \"/usr/local/bin/chromedriver\" ###", "找到 ### Only for Mac ### # DRIVER_PATH = \"/usr/local/bin/chromedriver\" ### Only for", "= r\"--user-data-dir=C:\\\\Users\\brian\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\Default\" # 可透過網址列輸入 chrome://version/ 找到 ### Only for Mac ### #", "for Mac ### # DRIVER_PATH = \"/usr/local/bin/chromedriver\" ### Only for Mac (End) ###", "URL = \"https://www.huahuacomputer.com.tw/products/gigabyte-%E6%8A%80%E5%98%89-aorus-15g-yb-%E6%A9%9F%E6%A2%B0%E8%BB%B8%E9%9B%BB%E7%AB%B6%E7%AD%86%E9%9B%BB-1\" DRIVER_PATH = \"chromedriver.exe\" CHROME_PATH = r\"--user-data-dir=C:\\\\Users\\brian\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\Default\" # 可透過網址列輸入 chrome://version/", "r\"--user-data-dir=C:\\\\Users\\brian\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\Default\" # 可透過網址列輸入 chrome://version/ 找到 ### Only for Mac ### # DRIVER_PATH", "chrome://version/ 找到 ### Only for Mac ### # DRIVER_PATH = \"/usr/local/bin/chromedriver\" ### Only", "# DRIVER_PATH = \"/usr/local/bin/chromedriver\" ### Only for Mac (End) ### # 請注意!以下皆為機密個資,請小心謹慎,勿上傳至公開平台 ACC", "CHROME_PATH = r\"--user-data-dir=C:\\\\Users\\brian\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\Default\" # 可透過網址列輸入 chrome://version/ 找到 ### Only for Mac ###" ]
[ "*args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__", "for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\" pass @staticmethod def __new__(self,", "__new__(cls: type,structuralType: StructuralType) \"\"\" pass StructuralType = property( lambda self: object(), lambda self,", "ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\" def Dispose(self): \"\"\" Dispose(self: ElementFilter,A_0: bool) \"\"\"", "def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self, *args):", "A filter used to find elements matching a structural type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool)", "\"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) \"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) ->", "def __init__(self, *args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x;", "x.__class__.__doc__ for signature \"\"\" pass @staticmethod def __new__(self, structuralType, inverted=None): \"\"\" __new__(cls: type,structuralType:", "*args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self, *args): \"\"\"", "__exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self, *args):", "IDisposable) -> object \"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back:", "*args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self:", "<reponame>YKato521/ironpython-stubs<filename>release/stubs.min/Autodesk/Revit/DB/__init___parts/ElementStructuralTypeFilter.py class ElementStructuralTypeFilter(ElementQuickFilter, IDisposable): \"\"\" A filter used to find elements matching a", "pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def", "initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes", "bool) ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\" def Dispose(self): \"\"\" Dispose(self: ElementFilter,A_0: bool) \"\"\" pass def", "lambda self: object(), lambda self, v: None, lambda self: None ) \"\"\"The structural", "initializes x; see x.__class__.__doc__ for signature \"\"\" pass @staticmethod def __new__(self, structuralType, inverted=None):", "\"\"\" A filter used to find elements matching a structural type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted:", "__new__(cls: type,structuralType: StructuralType,inverted: bool) __new__(cls: type,structuralType: StructuralType) \"\"\" pass StructuralType = property( lambda", "StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\" def Dispose(self): \"\"\" Dispose(self: ElementFilter,A_0: bool) \"\"\" pass", "signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature", "self, v: None, lambda self: None ) \"\"\"The structural type. Get: StructuralType(self: ElementStructuralTypeFilter)", "lambda self: None ) \"\"\"The structural type. Get: StructuralType(self: ElementStructuralTypeFilter) -> StructuralType \"\"\"", "x; see x.__class__.__doc__ for signature \"\"\" pass @staticmethod def __new__(self, structuralType, inverted=None): \"\"\"", "inverted=None): \"\"\" __new__(cls: type,structuralType: StructuralType,inverted: bool) __new__(cls: type,structuralType: StructuralType) \"\"\" pass StructuralType =", "ElementFilter,disposing: bool) \"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object \"\"\"", "a structural type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\" def Dispose(self): \"\"\" Dispose(self:", "signature \"\"\" pass @staticmethod def __new__(self, structuralType, inverted=None): \"\"\" __new__(cls: type,structuralType: StructuralType,inverted: bool)", "pass StructuralType = property( lambda self: object(), lambda self, v: None, lambda self:", "__init__(self, *args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see", "def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self,", "= property( lambda self: object(), lambda self, v: None, lambda self: None )", "x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\" pass @staticmethod def", "\"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass", "*args): \"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) \"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable)", "pass @staticmethod def __new__(self, structuralType, inverted=None): \"\"\" __new__(cls: type,structuralType: StructuralType,inverted: bool) __new__(cls: type,structuralType:", "pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) \"\"\" pass def __enter__(self, *args):", "StructuralType,inverted: bool) __new__(cls: type,structuralType: StructuralType) \"\"\" pass StructuralType = property( lambda self: object(),", "ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) \"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object", "Dispose(self: ElementFilter,A_0: bool) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) \"\"\"", "object) \"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for", "IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...) initializes x;", "ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) \"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self:", "__enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value:", "StructuralType = property( lambda self: object(), lambda self, v: None, lambda self: None", "object \"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\"", "\"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) \"\"\" pass def __enter__(self,", "class ElementStructuralTypeFilter(ElementQuickFilter, IDisposable): \"\"\" A filter used to find elements matching a structural", "__new__(self, structuralType, inverted=None): \"\"\" __new__(cls: type,structuralType: StructuralType,inverted: bool) __new__(cls: type,structuralType: StructuralType) \"\"\" pass", "\"\"\" __new__(cls: type,structuralType: StructuralType,inverted: bool) __new__(cls: type,structuralType: StructuralType) \"\"\" pass StructuralType = property(", "\"\"\" def Dispose(self): \"\"\" Dispose(self: ElementFilter,A_0: bool) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\"", "structural type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\" def Dispose(self): \"\"\" Dispose(self: ElementFilter,A_0:", "matching a structural type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\" def Dispose(self): \"\"\"", "\"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...)", "for signature \"\"\" pass @staticmethod def __new__(self, structuralType, inverted=None): \"\"\" __new__(cls: type,structuralType: StructuralType,inverted:", "ElementStructuralTypeFilter(ElementQuickFilter, IDisposable): \"\"\" A filter used to find elements matching a structural type.", "object,exc_back: object) \"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__", "Dispose(self): \"\"\" Dispose(self: ElementFilter,A_0: bool) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing:", "self: object(), lambda self, v: None, lambda self: None ) \"\"\"The structural type.", "lambda self, v: None, lambda self: None ) \"\"\"The structural type. Get: StructuralType(self:", "see x.__class__.__doc__ for signature \"\"\" pass @staticmethod def __new__(self, structuralType, inverted=None): \"\"\" __new__(cls:", "signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\" pass @staticmethod def __new__(self, structuralType,", "property( lambda self: object(), lambda self, v: None, lambda self: None ) \"\"\"The", "def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) \"\"\" pass def __enter__(self, *args): \"\"\"", "see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see", "pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self,", "__enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self, *args): \"\"\"", "ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\" def Dispose(self): \"\"\" Dispose(self: ElementFilter,A_0: bool) \"\"\" pass def ReleaseUnmanagedResources(self,", "bool) __new__(cls: type,structuralType: StructuralType) \"\"\" pass StructuralType = property( lambda self: object(), lambda", "\"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for", "v: None, lambda self: None ) \"\"\"The structural type. Get: StructuralType(self: ElementStructuralTypeFilter) ->", "structuralType, inverted=None): \"\"\" __new__(cls: type,structuralType: StructuralType,inverted: bool) __new__(cls: type,structuralType: StructuralType) \"\"\" pass StructuralType", "\"\"\" pass StructuralType = property( lambda self: object(), lambda self, v: None, lambda", "type,structuralType: StructuralType) \"\"\" pass StructuralType = property( lambda self: object(), lambda self, v:", "type,structuralType: StructuralType,inverted: bool) __new__(cls: type,structuralType: StructuralType) \"\"\" pass StructuralType = property( lambda self:", "StructuralType) \"\"\" pass StructuralType = property( lambda self: object(), lambda self, v: None,", "IDisposable): \"\"\" A filter used to find elements matching a structural type. ElementStructuralTypeFilter(structuralType:", "-> object \"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)", "to find elements matching a structural type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\"", "@staticmethod def __new__(self, structuralType, inverted=None): \"\"\" __new__(cls: type,structuralType: StructuralType,inverted: bool) __new__(cls: type,structuralType: StructuralType)", "object(), lambda self, v: None, lambda self: None ) \"\"\"The structural type. Get:", "None, lambda self: None ) \"\"\"The structural type. Get: StructuralType(self: ElementStructuralTypeFilter) -> StructuralType", "def __new__(self, structuralType, inverted=None): \"\"\" __new__(cls: type,structuralType: StructuralType,inverted: bool) __new__(cls: type,structuralType: StructuralType) \"\"\"", "\"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def", "for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for", "bool) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) \"\"\" pass def", "see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\" pass @staticmethod", "x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...)", "x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x;", "x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\" pass", "elements matching a structural type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\" def Dispose(self):", "\"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...)", "\"\"\" Dispose(self: ElementFilter,A_0: bool) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool)", "bool) \"\"\" pass def __enter__(self, *args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass", "used to find elements matching a structural type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType: StructuralType)", "pass def __init__(self, *args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes", "type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\" def Dispose(self): \"\"\" Dispose(self: ElementFilter,A_0: bool)", "def Dispose(self): \"\"\" Dispose(self: ElementFilter,A_0: bool) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self:", "\"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self, *args): \"\"\" __exit__(self: IDisposable,exc_type:", "__exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...) initializes", "x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__", "object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self, *args): \"\"\" x.__init__(...) initializes x; see", "filter used to find elements matching a structural type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType:", "find elements matching a structural type. ElementStructuralTypeFilter(structuralType: StructuralType,inverted: bool) ElementStructuralTypeFilter(structuralType: StructuralType) \"\"\" def", "StructuralType) \"\"\" def Dispose(self): \"\"\" Dispose(self: ElementFilter,A_0: bool) \"\"\" pass def ReleaseUnmanagedResources(self, *args):", "ElementFilter,A_0: bool) \"\"\" pass def ReleaseUnmanagedResources(self, *args): \"\"\" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) \"\"\" pass", "\"\"\" pass @staticmethod def __new__(self, structuralType, inverted=None): \"\"\" __new__(cls: type,structuralType: StructuralType,inverted: bool) __new__(cls:", "initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\"" ]
[ "data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code, 302) def _session_view_test( self, session_id, status_code_expected, result_expected ): response", "= create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() + 1), hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit, ) path = reverse('generate-sessions')", "path = reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': 1, 'track': track.pk, 'capacity_limit':", "SessionAdmin) session_filter.used_parameters['filter'] = None from_this_week_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar)", "= { 'page': 0, 'week_template': week_template.pk, 'track': session.track.pk, 'capacity_limit': session.capacity_limit.pk, } self.assertEquals(Session.objects.count(), 1)", "import BaseTestCase from crossbox.tests.tools import with_login, create_session from crossbox.models.day import Day from crossbox.models.hour", "'ESTIRAMIENTOS'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 1, 'name': 'WOD'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK,", "= Session( date=day, hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), ) session.save() self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk':", "= None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['track'] = 1 kwargs['capacity_limit'] = None with", ") session.save() self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK,", "# TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_days(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self):", "= 1 self.client.post(path=path, data=kwargs) # no raise @with_login() @freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track =", "status_code_expected=HTTPStatus.OK, result_expected={'pk': 3, 'name': 'ESTIRAMIENTOS'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 1, 'name': 'WOD'},", "def test_change_session_type_no_session(self): response = self.client.put( path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01') def test_change_session_type_db_types(self):", "_ = self.client.put(path=path) # session_type ESTIRAMIENTOS response = self.client.put(path=path) self.assertEquals( response.json()['session_type'], {'pk': 4,", "path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'], result_expected) class SessionAdminFilterCase(BaseTestCase): fixtures = ['capacity_limits', 'session_types', 'tracks']", "pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self): pass # TODO @with_login() @freeze_time('2020-01-1') def", "= self.client.put( path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01') def test_change_session_type_db_types(self): \"\"\"Check types are", "with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self): week_template = WeekTemplate.objects.get(pk=1) session = create_session()", "kwargs['track'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['track'] = 1 kwargs['capacity_limit'] = None", "Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self): week_template = WeekTemplate.objects.get(pk=1) session = create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday()", "SessionAdminFilterCase(BaseTestCase): fixtures = ['capacity_limits', 'session_types', 'tracks'] @freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self): hour = Hour(hour=datetime.time(0, 0))", "kwargs = { 'page': None, 'week_template': 1, 'track': 1, 'capacity_limit': 1, } with", "from django.urls import reverse from crossbox.tests.mixins import BaseTestCase from crossbox.tests.tools import with_login, create_session", "@freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self): pass # TODO", "track = Track.objects.get(pk=1) other_track = Track.objects.get(pk=2) session_same_week = Session.objects.create( date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1),", "1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # other week, same track", "capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # same week, other track date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1),", "with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['capacity_limit'] = 1 self.client.post(path=path, data=kwargs) # no raise @with_login()", "SessionAdminFilter class SessionsCase(BaseTestCase): fixtures = [ 'users', 'capacity_limits', 'session_types', 'tracks', 'hours', 'days', 'week_templates',", "= self.client.put(path=path) # session_type ESTIRAMIENTOS response = self.client.put(path=path) self.assertEquals( response.json()['session_type'], {'pk': 4, 'name':", "other track date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, ) self.assertEquals(Session.objects.count(), 3) path", "1, 'capacity_limit': 1, } response = self.client.post(path=path, data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code, 302) def", "@with_login() @freeze_time('2020-01-01') def test_change_session_type_db_types(self): \"\"\"Check types are taken from database\"\"\" SessionType.objects.create(name='new_type') session =", "session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # same week, other track date=datetime.date(2020, 1, 1),", ") self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 1, 'name': 'WOD'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk':", "session_filter.used_parameters['filter'] = 'past' past_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter'] =", "@freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self): response = self.client.get(path=reverse('session-template')) capacity_limits = response.context_data['capacity_limits'] self.assertEqual( {cl.pk for cl", "self.client.post(path=path, data=kwargs) kwargs['page'] = 1 kwargs['week_template'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['week_template']", "self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'], result_expected) class SessionAdminFilterCase(BaseTestCase): fixtures = ['capacity_limits', 'session_types', 'tracks'] @freeze_time('2020-02-1') def", "self.assertEquals(Session.objects.count(), 1) self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 1) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session = Session.objects.all()[0] self.assertEquals(new_session.date,", "day_mar = datetime.date(year=2020, month=3, day=1) Session.objects.bulk_create([ Session(date=day_jan, **kwargs), Session(date=day_feb, **kwargs), Session(date=day_mar, **kwargs), ])", "Session(date=day_jan, **kwargs), Session(date=day_feb, **kwargs), Session(date=day_mar, **kwargs), ]) session_filter = SessionAdminFilter(None, {}, Session, SessionAdmin)", "crossbox.models.session_template import SessionTemplate from crossbox.admin.session import SessionAdmin, SessionAdminFilter class SessionsCase(BaseTestCase): fixtures = [", "response = self.client.put( path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'], result_expected) class SessionAdminFilterCase(BaseTestCase): fixtures =", "4, 'name': 'new_type'} ) @with_login() def test_gen_sessions_invalid_post_params(self): path = reverse('generate-sessions') kwargs = {", "path = reverse('change_session_type', args=[session.pk]) _ = self.client.put(path=path) # session_type OPEN _ = self.client.put(path=path)", "self.client.put(path=path) # session_type OPEN _ = self.client.put(path=path) # session_type ESTIRAMIENTOS response = self.client.put(path=path)", "session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), ) session.save() self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, )", "session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self): pass #", "result_expected={'pk': 1, 'name': 'WOD'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, )", ") path = reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': week_template.pk, 'track': session.track.pk,", "freeze_time from django.urls import reverse from crossbox.tests.mixins import BaseTestCase from crossbox.tests.tools import with_login,", "= None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['week_template'] = 1 kwargs['track'] = None with", "3, 'name': 'ESTIRAMIENTOS'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 1, 'name': 'WOD'}, ) self._session_view_test(", "args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01') def test_change_session_type_db_types(self): \"\"\"Check types are taken from database\"\"\"", "= reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': week_template.pk, 'track': session.track.pk, 'capacity_limit': session.capacity_limit.pk,", "reverse('change_session_type', args=[session.pk]) _ = self.client.put(path=path) # session_type OPEN _ = self.client.put(path=path) # session_type", "# session_type ESTIRAMIENTOS response = self.client.put(path=path) self.assertEquals( response.json()['session_type'], {'pk': 4, 'name': 'new_type'} )", "session.track.pk, 'capacity_limit': session.capacity_limit.pk, } self.assertEquals(Session.objects.count(), 1) self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 1) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk)", "kwargs = { 'hour': hour, 'session_type': SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1), } day_jan", "kwargs['page'] = 1 kwargs['week_template'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['week_template'] = 1", "kwargs['capacity_limit'] = 1 self.client.post(path=path, data=kwargs) # no raise @with_login() @freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track", "session.track) @with_login() def test_gen_sessions_redirect_created_week_page(self): page = 5 path = reverse('generate-sessions') kwargs = {", "response = self.client.get(path=reverse('session-template')) weeks = response.context_data['weeks'] self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], 'Lunes 30/12/2019 - Semana", "= self.client.put( path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'], result_expected) class SessionAdminFilterCase(BaseTestCase): fixtures = ['capacity_limits',", "'page': 0, 'week_template': 1, 'track': track.pk, 'capacity_limit': 1, } self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 2)", "SessionAdminFilter(None, {}, Session, SessionAdmin) session_filter.used_parameters['filter'] = None from_this_week_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date,", "= ['capacity_limits', 'session_types', 'tracks'] @freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() kwargs", "1 kwargs['capacity_limit'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['capacity_limit'] = 1 self.client.post(path=path, data=kwargs)", "{ 'page': 0, 'week_template': 1, 'track': track.pk, 'capacity_limit': 1, } self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(),", "self.client.get(path=reverse('session-template')) weeks = response.context_data['weeks'] self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], 'Lunes 30/12/2019 - Semana 1 (actual)')", "= None from_this_week_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(), 2)", "session = create_session() # session_type WOD path = reverse('change_session_type', args=[session.pk]) _ = self.client.put(path=path)", "SessionsCase(BaseTestCase): fixtures = [ 'users', 'capacity_limits', 'session_types', 'tracks', 'hours', 'days', 'week_templates', ] @with_login()", "week_template = WeekTemplate.objects.get(pk=1) session = create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() + 1), hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit,", "'capacity_limit': 1, } response = self.client.post(path=path, data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code, 302) def _session_view_test(", "response = self.client.get(path=reverse('session-template')) capacity_limits = response.context_data['capacity_limits'] self.assertEqual( {cl.pk for cl in capacity_limits}, {cl.pk", "def test_queryset_depending_on_filter_selected(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() kwargs = { 'hour': hour, 'session_type':", "1, 'name': 'WOD'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) @with_login()", "# TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self):", "self.client.post(path=path, data=kwargs) kwargs['track'] = 1 kwargs['capacity_limit'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['capacity_limit']", "@freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self): pass # TODO", "self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track, session.track) @with_login() def test_gen_sessions_redirect_created_week_page(self): page = 5 path = reverse('generate-sessions')", "= 'past' past_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter'] = 'all_desc'", "session_type ESTIRAMIENTOS response = self.client.put(path=path) self.assertEquals( response.json()['session_type'], {'pk': 4, 'name': 'new_type'} ) @with_login()", "Session(date=day_mar, **kwargs), ]) session_filter = SessionAdminFilter(None, {}, Session, SessionAdmin) session_filter.used_parameters['filter'] = None from_this_week_sessions", "def test_session_template_view_context_data_tracks(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self): pass # TODO @with_login()", "= None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['capacity_limit'] = 1 self.client.post(path=path, data=kwargs) # no", "test_gen_sessions_redirect_created_week_page(self): page = 5 path = reverse('generate-sessions') kwargs = { 'page': page, 'week_template':", "self.assertEquals( response.json()['session_type'], {'pk': 4, 'name': 'new_type'} ) @with_login() def test_gen_sessions_invalid_post_params(self): path = reverse('generate-sessions')", "import Session from crossbox.models.session_type import SessionType from crossbox.models.week_template import WeekTemplate from crossbox.models.capacity_limit import", "52') @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self): pass", "self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01') def test_change_session_type_db_types(self): \"\"\"Check types are taken from database\"\"\" SessionType.objects.create(name='new_type')", "Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter'] = 'all_desc' all_desc_sessions = session_filter.queryset( None, Session.objects.all())", "0, 'week_template': 1, 'track': track.pk, 'capacity_limit': 1, } self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 2) with", "= 1 kwargs['capacity_limit'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['capacity_limit'] = 1 self.client.post(path=path,", "= Hour(hour=datetime.time(0, 0)) hour.save() kwargs = { 'hour': hour, 'session_type': SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1),", "capacity_limit=session.capacity_limit, ) path = reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': week_template.pk, 'track':", "2, 'name': 'OPEN'}, ) @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self): pass # TODO @with_login() @freeze_time('2020-01-1')", "session_filter.used_parameters['filter'] = 'all_desc' all_desc_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date,", "test_queryset_depending_on_filter_selected(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() kwargs = { 'hour': hour, 'session_type': SessionType.objects.get(pk=1),", "pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self): pass # TODO @with_login() @freeze_time('2020-01-1') def", "= WeekTemplate.objects.get(pk=1) session = create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() + 1), hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit, )", "52) self.assertEqual(weeks[0], 'Lunes 30/12/2019 - Semana 1 (actual)') self.assertEqual(weeks[51], 'Lunes 21/12/2020 - Semana", "self.client.put(path=path) self.assertEquals( response.json()['session_type'], {'pk': 4, 'name': 'new_type'} ) @with_login() def test_gen_sessions_invalid_post_params(self): path =", "self.assertEquals(Session.objects.count(), 3) path = reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': 1, 'track':", "self.client.post(path=path, data=kwargs) kwargs['week_template'] = 1 kwargs['track'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['track']", "self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], 'Lunes 30/12/2019 - Semana 1 (actual)') self.assertEqual(weeks[51], 'Lunes 21/12/2020 -", "response.json()['session_type'], {'pk': 4, 'name': 'new_type'} ) @with_login() def test_gen_sessions_invalid_post_params(self): path = reverse('generate-sessions') kwargs", "} day_jan = datetime.date(year=2020, month=1, day=1) day_feb = datetime.date(year=2020, month=2, day=1) day_mar =", "session_filter = SessionAdminFilter(None, {}, Session, SessionAdmin) session_filter.used_parameters['filter'] = None from_this_week_sessions = session_filter.queryset( None,", "session_filter.used_parameters['filter'] = 'all_asc' all_asc_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(all_asc_sessions[0].date, day_jan) self.assertEquals(all_asc_sessions[1].date, day_feb) self.assertEquals(all_asc_sessions[2].date, day_mar)", "fixtures = [ 'users', 'capacity_limits', 'session_types', 'tracks', 'hours', 'days', 'week_templates', ] @with_login() def", "'week_template': week_template.pk, 'track': session.track.pk, 'capacity_limit': session.capacity_limit.pk, } self.assertEquals(Session.objects.count(), 1) self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 1)", "class SessionsCase(BaseTestCase): fixtures = [ 'users', 'capacity_limits', 'session_types', 'tracks', 'hours', 'days', 'week_templates', ]", "import HTTPStatus from freezegun import freeze_time from django.urls import reverse from crossbox.tests.mixins import", "kwargs['week_template'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['week_template'] = 1 kwargs['track'] = None", "self.assertEqual( {cl.pk for cl in capacity_limits}, {cl.pk for cl in CapacityLimit.objects.all()} ) @with_login()", "import SessionType from crossbox.models.week_template import WeekTemplate from crossbox.models.capacity_limit import CapacityLimit from crossbox.models.session_template import", "week_template=week_template, capacity_limit=session.capacity_limit, ) path = reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': week_template.pk,", "'capacity_limit': 1, } with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['page'] = 1 kwargs['week_template'] = None", "'capacity_limit': CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1), } day_jan = datetime.date(year=2020, month=1, day=1) day_feb = datetime.date(year=2020,", "all_desc_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter'] =", "session_type OPEN _ = self.client.put(path=path) # session_type ESTIRAMIENTOS response = self.client.put(path=path) self.assertEquals( response.json()['session_type'],", "@freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track = Track.objects.get(pk=1) other_track = Track.objects.get(pk=2) session_same_week = Session.objects.create( date=datetime.date(2020,", "self.assertEquals(Session.objects.count(), 1) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session = Session.objects.all()[0] self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type,", "= reverse('generate-sessions') kwargs = { 'page': None, 'week_template': 1, 'track': 1, 'capacity_limit': 1,", "1 kwargs['week_template'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['week_template'] = 1 kwargs['track'] =", "@freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self): week_template = WeekTemplate.objects.get(pk=1) session = create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() + 1),", "Session.objects.create( # same week, other track date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track,", "def test_session_template_view_context_data_days(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self): response = self.client.get(path=reverse('session-template')) weeks", "status_code_expected) self.assertEquals(response.json()['session_type'], result_expected) class SessionAdminFilterCase(BaseTestCase): fixtures = ['capacity_limits', 'session_types', 'tracks'] @freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self):", "crossbox.tests.tools import with_login, create_session from crossbox.models.day import Day from crossbox.models.hour import Hour from", "session_filter.queryset( None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter'] = 'all_asc' all_asc_sessions", "from crossbox.models.session_template import SessionTemplate from crossbox.admin.session import SessionAdmin, SessionAdminFilter class SessionsCase(BaseTestCase): fixtures =", "def _session_view_test( self, session_id, status_code_expected, result_expected ): response = self.client.put( path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code,", "session_same_week = Session.objects.create( date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( #", "SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1), } day_jan = datetime.date(year=2020, month=1, day=1) day_feb =", "self, session_id, status_code_expected, result_expected ): response = self.client.put( path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'],", "(actual)') self.assertEqual(weeks[51], 'Lunes 21/12/2020 - Semana 52') @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self): pass #", "'name': 'WOD'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) @with_login() @freeze_time('2020-01-1')", "'capacity_limit': session.capacity_limit.pk, } self.assertEquals(Session.objects.count(), 1) self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 1) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session", "# session_type WOD path = reverse('change_session_type', args=[session.pk]) _ = self.client.put(path=path) # session_type OPEN", "= datetime.date(year=2020, month=1, day=1) day_feb = datetime.date(year=2020, month=2, day=1) day_mar = datetime.date(year=2020, month=3,", "test_session_template_view_context_data_capacity_limits(self): response = self.client.get(path=reverse('session-template')) capacity_limits = response.context_data['capacity_limits'] self.assertEqual( {cl.pk for cl in capacity_limits},", "@with_login() def test_change_session_type(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() day = datetime.date(year=2019, month=1, day=1)", "track date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, ) self.assertEquals(Session.objects.count(), 3) path =", "@freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_days(self): pass # TODO", "day = datetime.date(year=2019, month=1, day=1) session = Session( date=day, hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1),", "response = self.client.put( path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01') def test_change_session_type_db_types(self): \"\"\"Check types", "} self.assertEquals(Session.objects.count(), 1) self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 1) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session = Session.objects.all()[0]", "track=Track.objects.get(pk=1), ) session.save() self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) self._session_view_test( session_id=session.id,", "data=kwargs) kwargs['track'] = 1 kwargs['capacity_limit'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['capacity_limit'] =", "self.client.get(path=reverse('session-template')) capacity_limits = response.context_data['capacity_limits'] self.assertEqual( {cl.pk for cl in capacity_limits}, {cl.pk for cl", "status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 3, 'name': 'ESTIRAMIENTOS'},", "are taken from database\"\"\" SessionType.objects.create(name='new_type') session = create_session() # session_type WOD path =", "session_filter.queryset( None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter'] = 'past' past_sessions", "weeks = response.context_data['weeks'] self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], 'Lunes 30/12/2019 - Semana 1 (actual)') self.assertEqual(weeks[51],", "create_session() # session_type WOD path = reverse('change_session_type', args=[session.pk]) _ = self.client.put(path=path) # session_type", "create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() + 1), hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit, ) path = reverse('generate-sessions') kwargs", "# TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self): response = self.client.get(path=reverse('session-template')) capacity_limits = response.context_data['capacity_limits'] self.assertEqual(", "data=kwargs) kwargs['capacity_limit'] = 1 self.client.post(path=path, data=kwargs) # no raise @with_login() @freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self):", "result_expected={'pk': 3, 'name': 'ESTIRAMIENTOS'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 1, 'name': 'WOD'}, )", "= Session.objects.all()[0] self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track, session.track) @with_login()", "{ 'page': None, 'week_template': 1, 'track': 1, 'capacity_limit': 1, } with self.assertRaises(Exception): self.client.post(path=path,", "1, } with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['page'] = 1 kwargs['week_template'] = None with", "\"\"\"Check types are taken from database\"\"\" SessionType.objects.create(name='new_type') session = create_session() # session_type WOD", "'Lunes 21/12/2020 - Semana 52') @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self): pass # TODO @with_login()", "capacity_limits}, {cl.pk for cl in CapacityLimit.objects.all()} ) @with_login() def test_change_session_type_no_session(self): response = self.client.put(", "day=Day.objects.get(pk=session.date.weekday() + 1), hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit, ) path = reverse('generate-sessions') kwargs = {", "self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter'] = 'past' past_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan)", "None from_this_week_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter']", "month=1, day=1) session = Session( date=day, hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), ) session.save() self._session_view_test(", "datetime.date(year=2020, month=2, day=1) day_mar = datetime.date(year=2020, month=3, day=1) Session.objects.bulk_create([ Session(date=day_jan, **kwargs), Session(date=day_feb, **kwargs),", "= [ 'users', 'capacity_limits', 'session_types', 'tracks', 'hours', 'days', 'week_templates', ] @with_login() def test_change_session_type(self):", "self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter'] = 'all_asc' all_asc_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(all_asc_sessions[0].date, day_jan) self.assertEquals(all_asc_sessions[1].date, day_feb)", "session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter'] = 'all_desc' all_desc_sessions = session_filter.queryset( None,", "'week_templates', ] @with_login() def test_change_session_type(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() day = datetime.date(year=2019,", "0, 'week_template': week_template.pk, 'track': session.track.pk, 'capacity_limit': session.capacity_limit.pk, } self.assertEquals(Session.objects.count(), 1) self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(),", "1 kwargs['track'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['track'] = 1 kwargs['capacity_limit'] =", "@with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self): response =", "data=kwargs) self.assertEquals(Session.objects.count(), 1) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session = Session.objects.all()[0] self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour, session.hour)", "import reverse from crossbox.tests.mixins import BaseTestCase from crossbox.tests.tools import with_login, create_session from crossbox.models.day", "SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() + 1), hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit, ) path = reverse('generate-sessions') kwargs =", "self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter'] = 'past' past_sessions = session_filter.queryset(None, Session.objects.all())", "3) path = reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': 1, 'track': track.pk,", "def test_gen_sessions_invalid_post_params(self): path = reverse('generate-sessions') kwargs = { 'page': None, 'week_template': 1, 'track':", "month=1, day=1) day_feb = datetime.date(year=2020, month=2, day=1) day_mar = datetime.date(year=2020, month=3, day=1) Session.objects.bulk_create([", "'week_template': 1, 'track': track.pk, 'capacity_limit': 1, } self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 2) with self.assertRaises(Session.DoesNotExist):", "new_session = Session.objects.all()[0] self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track, session.track)", "1) session_filter.used_parameters['filter'] = 'all_desc' all_desc_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb)", "from crossbox.admin.session import SessionAdmin, SessionAdminFilter class SessionsCase(BaseTestCase): fixtures = [ 'users', 'capacity_limits', 'session_types',", "'name': 'OPEN'}, ) @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self): pass # TODO @with_login() @freeze_time('2020-01-1') def", "import CapacityLimit from crossbox.models.session_template import SessionTemplate from crossbox.admin.session import SessionAdmin, SessionAdminFilter class SessionsCase(BaseTestCase):", "1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # other week, same track date=datetime.date(2020,", "@with_login() @freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track = Track.objects.get(pk=1) other_track = Track.objects.get(pk=2) session_same_week = Session.objects.create(", "'page': 0, 'week_template': week_template.pk, 'track': session.track.pk, 'capacity_limit': session.capacity_limit.pk, } self.assertEquals(Session.objects.count(), 1) self.client.post(path=path, data=kwargs)", "= self.client.post(path=path, data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code, 302) def _session_view_test( self, session_id, status_code_expected, result_expected", "from crossbox.models.track import Track from crossbox.models.session import Session from crossbox.models.session_type import SessionType from", "types are taken from database\"\"\" SessionType.objects.create(name='new_type') session = create_session() # session_type WOD path", "from database\"\"\" SessionType.objects.create(name='new_type') session = create_session() # session_type WOD path = reverse('change_session_type', args=[session.pk])", "with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session = Session.objects.all()[0] self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit,", "Track.objects.get(pk=2) session_same_week = Session.objects.create( date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create(", "response.context_data['capacity_limits'] self.assertEqual( {cl.pk for cl in capacity_limits}, {cl.pk for cl in CapacityLimit.objects.all()} )", "= datetime.date(year=2020, month=3, day=1) Session.objects.bulk_create([ Session(date=day_jan, **kwargs), Session(date=day_feb, **kwargs), Session(date=day_mar, **kwargs), ]) session_filter", "session.hour) self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track, session.track) @with_login() def test_gen_sessions_redirect_created_week_page(self): page = 5", "test_session_template_view_context_data_hours(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_days(self): pass # TODO @with_login() @freeze_time('2020-01-1')", "self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 1, 'name': 'WOD'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2,", "hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, ) self.assertEquals(Session.objects.count(), 3) path = reverse('generate-sessions') kwargs = {", "@with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_days(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self): response =", "def test_gen_sessions_redirect_created_week_page(self): page = 5 path = reverse('generate-sessions') kwargs = { 'page': page,", "'tracks', 'hours', 'days', 'week_templates', ] @with_login() def test_change_session_type(self): hour = Hour(hour=datetime.time(0, 0)) hour.save()", "= datetime.date(year=2019, month=1, day=1) session = Session( date=day, hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), )", "hour.save() day = datetime.date(year=2019, month=1, day=1) session = Session( date=day, hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1),", "10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # same week, other track date=datetime.date(2020,", "None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['capacity_limit'] = 1 self.client.post(path=path, data=kwargs) # no raise", "import datetime from http import HTTPStatus from freezegun import freeze_time from django.urls import", "pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self): response = self.client.get(path=reverse('session-template')) capacity_limits = response.context_data['capacity_limits']", "month=2, day=1) day_mar = datetime.date(year=2020, month=3, day=1) Session.objects.bulk_create([ Session(date=day_jan, **kwargs), Session(date=day_feb, **kwargs), Session(date=day_mar,", "hour = Hour(hour=datetime.time(0, 0)) hour.save() kwargs = { 'hour': hour, 'session_type': SessionType.objects.get(pk=1), 'capacity_limit':", "] @with_login() def test_change_session_type(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() day = datetime.date(year=2019, month=1,", "month=3, day=1) Session.objects.bulk_create([ Session(date=day_jan, **kwargs), Session(date=day_feb, **kwargs), Session(date=day_mar, **kwargs), ]) session_filter = SessionAdminFilter(None,", "'session_types', 'tracks', 'hours', 'days', 'week_templates', ] @with_login() def test_change_session_type(self): hour = Hour(hour=datetime.time(0, 0))", "]) session_filter = SessionAdminFilter(None, {}, Session, SessionAdmin) session_filter.used_parameters['filter'] = None from_this_week_sessions = session_filter.queryset(", "from freezegun import freeze_time from django.urls import reverse from crossbox.tests.mixins import BaseTestCase from", "from crossbox.models.week_template import WeekTemplate from crossbox.models.capacity_limit import CapacityLimit from crossbox.models.session_template import SessionTemplate from", "= reverse('change_session_type', args=[session.pk]) _ = self.client.put(path=path) # session_type OPEN _ = self.client.put(path=path) #", "args=[session.pk]) _ = self.client.put(path=path) # session_type OPEN _ = self.client.put(path=path) # session_type ESTIRAMIENTOS", "args=[session_id])) self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'], result_expected) class SessionAdminFilterCase(BaseTestCase): fixtures = ['capacity_limits', 'session_types', 'tracks'] @freeze_time('2020-02-1')", "crossbox.models.day import Day from crossbox.models.hour import Hour from crossbox.models.track import Track from crossbox.models.session", "no raise @with_login() @freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track = Track.objects.get(pk=1) other_track = Track.objects.get(pk=2) session_same_week", "session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 3, 'name': 'ESTIRAMIENTOS'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 1, 'name':", "@freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self): pass # TODO", "test_session_template_view_context_data_week_templates(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self): pass # TODO @with_login() @freeze_time('2020-01-1')", "import Track from crossbox.models.session import Session from crossbox.models.session_type import SessionType from crossbox.models.week_template import", "TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self): response", "import Day from crossbox.models.hour import Hour from crossbox.models.track import Track from crossbox.models.session import", ") @with_login() def test_gen_sessions_invalid_post_params(self): path = reverse('generate-sessions') kwargs = { 'page': None, 'week_template':", "session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, ) self.assertEquals(Session.objects.count(), 3) path = reverse('generate-sessions') kwargs = { 'page':", "@with_login() @freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self): week_template = WeekTemplate.objects.get(pk=1) session = create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() +", "self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['track'] = 1 kwargs['capacity_limit'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs)", "'name': 'OPEN'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 3, 'name': 'ESTIRAMIENTOS'}, ) self._session_view_test( session_id=session.id,", "track=track, ) Session.objects.create( # other week, same track date=datetime.date(2020, 1, 10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1),", "track date=datetime.date(2020, 1, 10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # same week,", "kwargs = { 'page': page, 'week_template': 1, 'track': 1, 'capacity_limit': 1, } response", "datetime.date(year=2020, month=3, day=1) Session.objects.bulk_create([ Session(date=day_jan, **kwargs), Session(date=day_feb, **kwargs), Session(date=day_mar, **kwargs), ]) session_filter =", "SessionType from crossbox.models.week_template import WeekTemplate from crossbox.models.capacity_limit import CapacityLimit from crossbox.models.session_template import SessionTemplate", "self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track, session.track) @with_login() def test_gen_sessions_redirect_created_week_page(self): page = 5 path", "status_code_expected, result_expected ): response = self.client.put( path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'], result_expected) class", "'name': 'ESTIRAMIENTOS'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 1, 'name': 'WOD'}, ) self._session_view_test( session_id=session.id,", "kwargs['capacity_limit'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['capacity_limit'] = 1 self.client.post(path=path, data=kwargs) #", "= Track.objects.get(pk=1) other_track = Track.objects.get(pk=2) session_same_week = Session.objects.create( date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1),", "= self.client.put(path=path) # session_type OPEN _ = self.client.put(path=path) # session_type ESTIRAMIENTOS response =", "test_session_template_view_context_data_current_week_template(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self): pass # TODO @with_login() @freeze_time('2020-01-1')", "'hour': hour, 'session_type': SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1), } day_jan = datetime.date(year=2020, month=1,", "self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter'] = 'past' past_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(), 1)", "= Session.objects.create( date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # other", "from crossbox.tests.tools import with_login, create_session from crossbox.models.day import Day from crossbox.models.hour import Hour", "1, 'track': 1, 'capacity_limit': 1, } with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['page'] = 1", "_session_view_test( self, session_id, status_code_expected, result_expected ): response = self.client.put( path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code, status_code_expected)", "from_this_week_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter'] =", "Session.objects.get(pk=session.pk) new_session = Session.objects.all()[0] self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track,", "2, 'name': 'OPEN'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 3, 'name': 'ESTIRAMIENTOS'}, ) self._session_view_test(", "kwargs['week_template'] = 1 kwargs['track'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['track'] = 1", "data=kwargs) kwargs['page'] = 1 kwargs['week_template'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['week_template'] =", "crossbox.models.session import Session from crossbox.models.session_type import SessionType from crossbox.models.week_template import WeekTemplate from crossbox.models.capacity_limit", "cl in capacity_limits}, {cl.pk for cl in CapacityLimit.objects.all()} ) @with_login() def test_change_session_type_no_session(self): response", "session = create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() + 1), hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit, ) path =", "crossbox.models.hour import Hour from crossbox.models.track import Track from crossbox.models.session import Session from crossbox.models.session_type", "WOD path = reverse('change_session_type', args=[session.pk]) _ = self.client.put(path=path) # session_type OPEN _ =", "21/12/2020 - Semana 52') @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self): pass # TODO @with_login() @freeze_time('2020-01-1')", "self.assertEqual(weeks[0], 'Lunes 30/12/2019 - Semana 1 (actual)') self.assertEqual(weeks[51], 'Lunes 21/12/2020 - Semana 52')", "session_filter.used_parameters['filter'] = None from_this_week_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(),", "'session_type': SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1), } day_jan = datetime.date(year=2020, month=1, day=1) day_feb", "@freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self): response = self.client.get(path=reverse('session-template')) weeks = response.context_data['weeks'] self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], 'Lunes", "day_jan = datetime.date(year=2020, month=1, day=1) day_feb = datetime.date(year=2020, month=2, day=1) day_mar = datetime.date(year=2020,", "def test_session_template_view_context_data_hours(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_days(self): pass # TODO @with_login()", "response = self.client.post(path=path, data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code, 302) def _session_view_test( self, session_id, status_code_expected,", "day=1) Session.objects.bulk_create([ Session(date=day_jan, **kwargs), Session(date=day_feb, **kwargs), Session(date=day_mar, **kwargs), ]) session_filter = SessionAdminFilter(None, {},", "hour, 'session_type': SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1), } day_jan = datetime.date(year=2020, month=1, day=1)", "1 (actual)') self.assertEqual(weeks[51], 'Lunes 21/12/2020 - Semana 52') @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self): pass", "'track': session.track.pk, 'capacity_limit': session.capacity_limit.pk, } self.assertEquals(Session.objects.count(), 1) self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 1) with self.assertRaises(Session.DoesNotExist):", "crossbox.tests.mixins import BaseTestCase from crossbox.tests.tools import with_login, create_session from crossbox.models.day import Day from", "self.assertEqual(weeks[51], 'Lunes 21/12/2020 - Semana 52') @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self): pass # TODO", "session.date) self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track, session.track) @with_login() def test_gen_sessions_redirect_created_week_page(self): page", "session_id, status_code_expected, result_expected ): response = self.client.put( path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'], result_expected)", "- Semana 52') @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self): pass # TODO @with_login() @freeze_time('2020-01-1') def", "Session.objects.create( # other week, same track date=datetime.date(2020, 1, 10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track,", "1) self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 1) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session = Session.objects.all()[0] self.assertEquals(new_session.date, session.date)", "result_expected={'pk': 2, 'name': 'OPEN'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 3, 'name': 'ESTIRAMIENTOS'}, )", "status_code_expected=HTTPStatus.OK, result_expected={'pk': 1, 'name': 'WOD'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'},", "response.context_data['weeks'] self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], 'Lunes 30/12/2019 - Semana 1 (actual)') self.assertEqual(weeks[51], 'Lunes 21/12/2020", "crossbox.models.week_template import WeekTemplate from crossbox.models.capacity_limit import CapacityLimit from crossbox.models.session_template import SessionTemplate from crossbox.admin.session", "with_login, create_session from crossbox.models.day import Day from crossbox.models.hour import Hour from crossbox.models.track import", "database\"\"\" SessionType.objects.create(name='new_type') session = create_session() # session_type WOD path = reverse('change_session_type', args=[session.pk]) _", "from crossbox.models.session import Session from crossbox.models.session_type import SessionType from crossbox.models.week_template import WeekTemplate from", "reverse('generate-sessions') kwargs = { 'page': None, 'week_template': 1, 'track': 1, 'capacity_limit': 1, }", "SessionAdmin, SessionAdminFilter class SessionsCase(BaseTestCase): fixtures = [ 'users', 'capacity_limits', 'session_types', 'tracks', 'hours', 'days',", "'capacity_limits', 'session_types', 'tracks', 'hours', 'days', 'week_templates', ] @with_login() def test_change_session_type(self): hour = Hour(hour=datetime.time(0,", "result_expected ): response = self.client.put( path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'], result_expected) class SessionAdminFilterCase(BaseTestCase):", "'name': 'new_type'} ) @with_login() def test_gen_sessions_invalid_post_params(self): path = reverse('generate-sessions') kwargs = { 'page':", "SessionType.objects.create(name='new_type') session = create_session() # session_type WOD path = reverse('change_session_type', args=[session.pk]) _ =", "'OPEN'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 3, 'name': 'ESTIRAMIENTOS'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK,", "reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': week_template.pk, 'track': session.track.pk, 'capacity_limit': session.capacity_limit.pk, }", "1, } response = self.client.post(path=path, data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code, 302) def _session_view_test( self,", "= reverse('generate-sessions') kwargs = { 'page': page, 'week_template': 1, 'track': 1, 'capacity_limit': 1,", "Day from crossbox.models.hour import Hour from crossbox.models.track import Track from crossbox.models.session import Session", "day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter'] = 'all_asc' all_asc_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(all_asc_sessions[0].date,", "same track date=datetime.date(2020, 1, 10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # same", "= Hour(hour=datetime.time(0, 0)) hour.save() day = datetime.date(year=2019, month=1, day=1) session = Session( date=day,", "self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter'] = 'all_desc' all_desc_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date,", "self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 3,", "HTTPStatus from freezegun import freeze_time from django.urls import reverse from crossbox.tests.mixins import BaseTestCase", "def test_session_template_view_context_data_weeks(self): response = self.client.get(path=reverse('session-template')) weeks = response.context_data['weeks'] self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], 'Lunes 30/12/2019", "None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter'] = 'past' past_sessions =", "**kwargs), Session(date=day_mar, **kwargs), ]) session_filter = SessionAdminFilter(None, {}, Session, SessionAdmin) session_filter.used_parameters['filter'] = None", "capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # other week, same track date=datetime.date(2020, 1, 10), hour=Hour.objects.get(pk=1),", "self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track, session.track) @with_login() def test_gen_sessions_redirect_created_week_page(self): page =", "= Track.objects.get(pk=2) session_same_week = Session.objects.create( date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, )", ") Session.objects.create( # other week, same track date=datetime.date(2020, 1, 10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1),", "'track': 1, 'capacity_limit': 1, } response = self.client.post(path=path, data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code, 302)", "@freeze_time('2020-01-01') def test_change_session_type_db_types(self): \"\"\"Check types are taken from database\"\"\" SessionType.objects.create(name='new_type') session = create_session()", "hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit, ) path = reverse('generate-sessions') kwargs = { 'page': 0, 'week_template':", "0)) hour.save() kwargs = { 'hour': hour, 'session_type': SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1),", "def test_session_template_view_context_data_capacity_limits(self): response = self.client.get(path=reverse('session-template')) capacity_limits = response.context_data['capacity_limits'] self.assertEqual( {cl.pk for cl in", "1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, ) self.assertEquals(Session.objects.count(), 3) path = reverse('generate-sessions') kwargs =", "<reponame>acascarla/crossbox import datetime from http import HTTPStatus from freezegun import freeze_time from django.urls", "None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['week_template'] = 1 kwargs['track'] = None with self.assertRaises(Exception):", "1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, ) self.assertEquals(Session.objects.count(), 3) path = reverse('generate-sessions') kwargs", "['capacity_limits', 'session_types', 'tracks'] @freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() kwargs =", "pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self): pass # TODO @with_login() @freeze_time('2020-01-1') def", "test_session_template_view_context_data_current_track(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self): response = self.client.get(path=reverse('session-template')) capacity_limits =", "status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self): pass # TODO", "= self.client.get(path=reverse('session-template')) capacity_limits = response.context_data['capacity_limits'] self.assertEqual( {cl.pk for cl in capacity_limits}, {cl.pk for", "+ 1), hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit, ) path = reverse('generate-sessions') kwargs = { 'page':", "None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter'] = 'all_asc' all_asc_sessions =", "track=other_track, ) self.assertEquals(Session.objects.count(), 3) path = reverse('generate-sessions') kwargs = { 'page': 0, 'week_template':", "self.client.post(path=path, data=kwargs) # no raise @with_login() @freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track = Track.objects.get(pk=1) other_track", "path = reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': week_template.pk, 'track': session.track.pk, 'capacity_limit':", "'track': Track.objects.get(pk=1), } day_jan = datetime.date(year=2020, month=1, day=1) day_feb = datetime.date(year=2020, month=2, day=1)", "self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 1) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session = Session.objects.all()[0] self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour,", "1) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session = Session.objects.all()[0] self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type, session.session_type)", "reverse from crossbox.tests.mixins import BaseTestCase from crossbox.tests.tools import with_login, create_session from crossbox.models.day import", "test_session_template_view_context_data_weeks(self): response = self.client.get(path=reverse('session-template')) weeks = response.context_data['weeks'] self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], 'Lunes 30/12/2019 -", "day=1) session = Session( date=day, hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), ) session.save() self._session_view_test( session_id=session.id,", "self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter'] = 'all_asc' all_asc_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(all_asc_sessions[0].date, day_jan)", "SessionTemplate from crossbox.admin.session import SessionAdmin, SessionAdminFilter class SessionsCase(BaseTestCase): fixtures = [ 'users', 'capacity_limits',", "5 path = reverse('generate-sessions') kwargs = { 'page': page, 'week_template': 1, 'track': 1,", "# no raise @with_login() @freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track = Track.objects.get(pk=1) other_track = Track.objects.get(pk=2)", "def test_session_template_view_context_data_current_track(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self): response = self.client.get(path=reverse('session-template')) capacity_limits", "path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01') def test_change_session_type_db_types(self): \"\"\"Check types are taken from", "datetime.date(year=2020, month=1, day=1) day_feb = datetime.date(year=2020, month=2, day=1) day_mar = datetime.date(year=2020, month=3, day=1)", "@freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self): response = self.client.get(path=reverse('session-template'))", "Session( date=day, hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), ) session.save() self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2,", "kwargs = { 'page': 0, 'week_template': week_template.pk, 'track': session.track.pk, 'capacity_limit': session.capacity_limit.pk, } self.assertEquals(Session.objects.count(),", "None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['track'] = 1 kwargs['capacity_limit'] = None with self.assertRaises(Exception):", "def test_change_session_type(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() day = datetime.date(year=2019, month=1, day=1) session", "crossbox.models.track import Track from crossbox.models.session import Session from crossbox.models.session_type import SessionType from crossbox.models.week_template", "def test_session_template_view_context_data_current_week_template(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self): pass # TODO @with_login()", "response = self.client.put(path=path) self.assertEquals( response.json()['session_type'], {'pk': 4, 'name': 'new_type'} ) @with_login() def test_gen_sessions_invalid_post_params(self):", "CapacityLimit.objects.all()} ) @with_login() def test_change_session_type_no_session(self): response = self.client.put( path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login()", "'page': page, 'week_template': 1, 'track': 1, 'capacity_limit': 1, } response = self.client.post(path=path, data=kwargs)", "week, same track date=datetime.date(2020, 1, 10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( #", "self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code, 302) def _session_view_test( self, session_id, status_code_expected, result_expected ): response =", "= 5 path = reverse('generate-sessions') kwargs = { 'page': page, 'week_template': 1, 'track':", "self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self): week_template = WeekTemplate.objects.get(pk=1) session = create_session() SessionTemplate.objects.create(", "WeekTemplate from crossbox.models.capacity_limit import CapacityLimit from crossbox.models.session_template import SessionTemplate from crossbox.admin.session import SessionAdmin,", "self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self): pass", "Session.objects.create( date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # other week,", "session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track, session.track) @with_login() def test_gen_sessions_redirect_created_week_page(self): page = 5 path =", "= { 'page': page, 'week_template': 1, 'track': 1, 'capacity_limit': 1, } response =", "hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # same week, other track date=datetime.date(2020, 1,", "= { 'hour': hour, 'session_type': SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1), } day_jan =", "= session_filter.queryset( None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter'] = 'past'", "Session.objects.bulk_create([ Session(date=day_jan, **kwargs), Session(date=day_feb, **kwargs), Session(date=day_mar, **kwargs), ]) session_filter = SessionAdminFilter(None, {}, Session,", "'track': 1, 'capacity_limit': 1, } with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['page'] = 1 kwargs['week_template']", "@freeze_time('2020-01-1') def test_session_template_view_context_data_days(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self): response = self.client.get(path=reverse('session-template'))", "**kwargs), ]) session_filter = SessionAdminFilter(None, {}, Session, SessionAdmin) session_filter.used_parameters['filter'] = None from_this_week_sessions =", "result_expected) class SessionAdminFilterCase(BaseTestCase): fixtures = ['capacity_limits', 'session_types', 'tracks'] @freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self): hour =", "@freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() kwargs = { 'hour': hour,", "} with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['page'] = 1 kwargs['week_template'] = None with self.assertRaises(Exception):", ") self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 3, 'name': 'ESTIRAMIENTOS'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk':", "from crossbox.models.hour import Hour from crossbox.models.track import Track from crossbox.models.session import Session from", "'week_template': 1, 'track': 1, 'capacity_limit': 1, } response = self.client.post(path=path, data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}')", "date=day, hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), ) session.save() self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name':", "self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 2) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self): week_template =", "@with_login() def test_gen_sessions_redirect_created_week_page(self): page = 5 path = reverse('generate-sessions') kwargs = { 'page':", "test_gen_sessions_delete_same_track_and_same_week_sessions(self): track = Track.objects.get(pk=1) other_track = Track.objects.get(pk=2) session_same_week = Session.objects.create( date=datetime.date(2020, 1, 1),", "1, 'track': 1, 'capacity_limit': 1, } response = self.client.post(path=path, data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code,", "1 self.client.post(path=path, data=kwargs) # no raise @with_login() @freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track = Track.objects.get(pk=1)", "self.client.put( path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'], result_expected) class SessionAdminFilterCase(BaseTestCase): fixtures = ['capacity_limits', 'session_types',", "self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['page'] = 1 kwargs['week_template'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs)", "self.client.post(path=path, data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code, 302) def _session_view_test( self, session_id, status_code_expected, result_expected ):", "Track.objects.get(pk=1), } day_jan = datetime.date(year=2020, month=1, day=1) day_feb = datetime.date(year=2020, month=2, day=1) day_mar", "'OPEN'}, ) @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_days(self):", "TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self): pass", "day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter'] = 'past' past_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date,", "TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self): response = self.client.get(path=reverse('session-template')) capacity_limits = response.context_data['capacity_limits'] self.assertEqual( {cl.pk", "self.assertEquals(Session.objects.count(), 2) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self): week_template = WeekTemplate.objects.get(pk=1) session", "self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['week_template'] = 1 kwargs['track'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs)", "django.urls import reverse from crossbox.tests.mixins import BaseTestCase from crossbox.tests.tools import with_login, create_session from", "Session(date=day_feb, **kwargs), Session(date=day_mar, **kwargs), ]) session_filter = SessionAdminFilter(None, {}, Session, SessionAdmin) session_filter.used_parameters['filter'] =", "from crossbox.models.day import Day from crossbox.models.hour import Hour from crossbox.models.track import Track from", "from crossbox.models.session_type import SessionType from crossbox.models.week_template import WeekTemplate from crossbox.models.capacity_limit import CapacityLimit from", "self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['capacity_limit'] = 1 self.client.post(path=path, data=kwargs) # no raise @with_login() @freeze_time('2020-01-01')", "= response.context_data['weeks'] self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], 'Lunes 30/12/2019 - Semana 1 (actual)') self.assertEqual(weeks[51], 'Lunes", "= datetime.date(year=2020, month=2, day=1) day_mar = datetime.date(year=2020, month=3, day=1) Session.objects.bulk_create([ Session(date=day_jan, **kwargs), Session(date=day_feb,", "path = reverse('generate-sessions') kwargs = { 'page': None, 'week_template': 1, 'track': 1, 'capacity_limit':", "= { 'page': None, 'week_template': 1, 'track': 1, 'capacity_limit': 1, } with self.assertRaises(Exception):", "self.client.post(path=path, data=kwargs) kwargs['capacity_limit'] = 1 self.client.post(path=path, data=kwargs) # no raise @with_login() @freeze_time('2020-01-01') def", "1, 'capacity_limit': 1, } with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['page'] = 1 kwargs['week_template'] =", "@with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self): pass #", "test_change_session_type_db_types(self): \"\"\"Check types are taken from database\"\"\" SessionType.objects.create(name='new_type') session = create_session() # session_type", "self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session = Session.objects.all()[0] self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit)", "{cl.pk for cl in capacity_limits}, {cl.pk for cl in CapacityLimit.objects.all()} ) @with_login() def", "@with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self): response = self.client.get(path=reverse('session-template')) weeks = response.context_data['weeks'] self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0],", "week_template.pk, 'track': session.track.pk, 'capacity_limit': session.capacity_limit.pk, } self.assertEquals(Session.objects.count(), 1) self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 1) with", "crossbox.models.session_type import SessionType from crossbox.models.week_template import WeekTemplate from crossbox.models.capacity_limit import CapacityLimit from crossbox.models.session_template", "): response = self.client.put( path=reverse('change_session_type', args=[session_id])) self.assertEquals(response.status_code, status_code_expected) self.assertEquals(response.json()['session_type'], result_expected) class SessionAdminFilterCase(BaseTestCase): fixtures", "test_change_session_type(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() day = datetime.date(year=2019, month=1, day=1) session =", "302) def _session_view_test( self, session_id, status_code_expected, result_expected ): response = self.client.put( path=reverse('change_session_type', args=[session_id]))", "1, } self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 2) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self):", "'Lunes 30/12/2019 - Semana 1 (actual)') self.assertEqual(weeks[51], 'Lunes 21/12/2020 - Semana 52') @with_login()", "# other week, same track date=datetime.date(2020, 1, 10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, )", "= SessionAdminFilter(None, {}, Session, SessionAdmin) session_filter.used_parameters['filter'] = None from_this_week_sessions = session_filter.queryset( None, Session.objects.all())", "def test_gen_sessions_new_sessions_for_that_week(self): week_template = WeekTemplate.objects.get(pk=1) session = create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() + 1), hour=session.hour,", "import WeekTemplate from crossbox.models.capacity_limit import CapacityLimit from crossbox.models.session_template import SessionTemplate from crossbox.admin.session import", "data=kwargs) kwargs['week_template'] = 1 kwargs['track'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['track'] =", "Session.objects.all()[0] self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track, session.track) @with_login() def", "[ 'users', 'capacity_limits', 'session_types', 'tracks', 'hours', 'days', 'week_templates', ] @with_login() def test_change_session_type(self): hour", "other_track = Track.objects.get(pk=2) session_same_week = Session.objects.create( date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track,", "self.assertEquals(new_session.track, session.track) @with_login() def test_gen_sessions_redirect_created_week_page(self): page = 5 path = reverse('generate-sessions') kwargs =", "test_change_session_type_no_session(self): response = self.client.put( path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01') def test_change_session_type_db_types(self): \"\"\"Check", "other week, same track date=datetime.date(2020, 1, 10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create(", "test_session_template_view_context_data_days(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self): response = self.client.get(path=reverse('session-template')) weeks =", "ESTIRAMIENTOS response = self.client.put(path=path) self.assertEquals( response.json()['session_type'], {'pk': 4, 'name': 'new_type'} ) @with_login() def", "from crossbox.models.capacity_limit import CapacityLimit from crossbox.models.session_template import SessionTemplate from crossbox.admin.session import SessionAdmin, SessionAdminFilter", "self.assertEquals(response.status_code, 302) def _session_view_test( self, session_id, status_code_expected, result_expected ): response = self.client.put( path=reverse('change_session_type',", "= reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': 1, 'track': track.pk, 'capacity_limit': 1,", "track.pk, 'capacity_limit': 1, } self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 2) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01')", "0)) hour.save() day = datetime.date(year=2019, month=1, day=1) session = Session( date=day, hour=hour, session_type=SessionType.objects.get(pk=1),", "day_jan) self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter'] = 'all_desc' all_desc_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar)", "'new_type'} ) @with_login() def test_gen_sessions_invalid_post_params(self): path = reverse('generate-sessions') kwargs = { 'page': None,", "http import HTTPStatus from freezegun import freeze_time from django.urls import reverse from crossbox.tests.mixins", "self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 3, 'name': 'ESTIRAMIENTOS'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 1,", "day_mar) self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter'] = 'past' past_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(),", "with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['page'] = 1 kwargs['week_template'] = None with self.assertRaises(Exception): self.client.post(path=path,", "Hour from crossbox.models.track import Track from crossbox.models.session import Session from crossbox.models.session_type import SessionType", "Track from crossbox.models.session import Session from crossbox.models.session_type import SessionType from crossbox.models.week_template import WeekTemplate", "taken from database\"\"\" SessionType.objects.create(name='new_type') session = create_session() # session_type WOD path = reverse('change_session_type',", "kwargs['track'] = 1 kwargs['capacity_limit'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['capacity_limit'] = 1", "from crossbox.tests.mixins import BaseTestCase from crossbox.tests.tools import with_login, create_session from crossbox.models.day import Day", "pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self): response = self.client.get(path=reverse('session-template')) weeks = response.context_data['weeks']", "Semana 52') @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self):", "def test_change_session_type_db_types(self): \"\"\"Check types are taken from database\"\"\" SessionType.objects.create(name='new_type') session = create_session() #", "= self.client.get(path=reverse('session-template')) weeks = response.context_data['weeks'] self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], 'Lunes 30/12/2019 - Semana 1", "self.assertEquals(new_session.date, session.date) self.assertEquals(new_session.hour, session.hour) self.assertEquals(new_session.session_type, session.session_type) self.assertEquals(new_session.capacity_limit, session.capacity_limit) self.assertEquals(new_session.track, session.track) @with_login() def test_gen_sessions_redirect_created_week_page(self):", "= session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter'] = 'all_desc' all_desc_sessions = session_filter.queryset(", "'users', 'capacity_limits', 'session_types', 'tracks', 'hours', 'days', 'week_templates', ] @with_login() def test_change_session_type(self): hour =", "} self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 2) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self): week_template", "reverse('generate-sessions') kwargs = { 'page': page, 'week_template': 1, 'track': 1, 'capacity_limit': 1, }", "date=datetime.date(2020, 1, 10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # same week, other", "30/12/2019 - Semana 1 (actual)') self.assertEqual(weeks[51], 'Lunes 21/12/2020 - Semana 52') @with_login() @freeze_time('2020-01-1')", "hour = Hour(hour=datetime.time(0, 0)) hour.save() day = datetime.date(year=2019, month=1, day=1) session = Session(", "= 1 kwargs['track'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['track'] = 1 kwargs['capacity_limit']", "crossbox.admin.session import SessionAdmin, SessionAdminFilter class SessionsCase(BaseTestCase): fixtures = [ 'users', 'capacity_limits', 'session_types', 'tracks',", "= 1 kwargs['week_template'] = None with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['week_template'] = 1 kwargs['track']", "2) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self): week_template = WeekTemplate.objects.get(pk=1) session =", "hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # other week, same track date=datetime.date(2020, 1,", "= self.client.put(path=path) self.assertEquals( response.json()['session_type'], {'pk': 4, 'name': 'new_type'} ) @with_login() def test_gen_sessions_invalid_post_params(self): path", "def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track = Track.objects.get(pk=1) other_track = Track.objects.get(pk=2) session_same_week = Session.objects.create( date=datetime.date(2020, 1,", "_ = self.client.put(path=path) # session_type OPEN _ = self.client.put(path=path) # session_type ESTIRAMIENTOS response", "'WOD'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) @with_login() @freeze_time('2020-01-1') def", "CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1), } day_jan = datetime.date(year=2020, month=1, day=1) day_feb = datetime.date(year=2020, month=2,", "= 'all_desc' all_desc_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan)", "date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, ) self.assertEquals(Session.objects.count(), 3) path = reverse('generate-sessions')", "Session, SessionAdmin) session_filter.used_parameters['filter'] = None from_this_week_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date,", "# same week, other track date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, )", "{'pk': 4, 'name': 'new_type'} ) @with_login() def test_gen_sessions_invalid_post_params(self): path = reverse('generate-sessions') kwargs =", "Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter'] = 'all_asc' all_asc_sessions = session_filter.queryset(None,", "@with_login() def test_gen_sessions_invalid_post_params(self): path = reverse('generate-sessions') kwargs = { 'page': None, 'week_template': 1,", "hour.save() kwargs = { 'hour': hour, 'session_type': SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1), }", "import Hour from crossbox.models.track import Track from crossbox.models.session import Session from crossbox.models.session_type import", "self.client.put(path=path) # session_type ESTIRAMIENTOS response = self.client.put(path=path) self.assertEquals( response.json()['session_type'], {'pk': 4, 'name': 'new_type'}", "# session_type OPEN _ = self.client.put(path=path) # session_type ESTIRAMIENTOS response = self.client.put(path=path) self.assertEquals(", "path = reverse('generate-sessions') kwargs = { 'page': page, 'week_template': 1, 'track': 1, 'capacity_limit':", "'past' past_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter'] = 'all_desc' all_desc_sessions", "None, 'week_template': 1, 'track': 1, 'capacity_limit': 1, } with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['page']", "same week, other track date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, ) self.assertEquals(Session.objects.count(),", "f'/reservation/?page={page}') self.assertEquals(response.status_code, 302) def _session_view_test( self, session_id, status_code_expected, result_expected ): response = self.client.put(", "class SessionAdminFilterCase(BaseTestCase): fixtures = ['capacity_limits', 'session_types', 'tracks'] @freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self): hour = Hour(hour=datetime.time(0,", "import freeze_time from django.urls import reverse from crossbox.tests.mixins import BaseTestCase from crossbox.tests.tools import", "def test_session_template_view_context_data_week_templates(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self): pass # TODO @with_login()", "{ 'page': page, 'week_template': 1, 'track': 1, 'capacity_limit': 1, } response = self.client.post(path=path,", "session.save() self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk':", "= session_filter.queryset( None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter'] = 'all_asc'", "HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01') def test_change_session_type_db_types(self): \"\"\"Check types are taken from database\"\"\" SessionType.objects.create(name='new_type') session", "'days', 'week_templates', ] @with_login() def test_change_session_type(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() day =", "'page': None, 'week_template': 1, 'track': 1, 'capacity_limit': 1, } with self.assertRaises(Exception): self.client.post(path=path, data=kwargs)", "Session from crossbox.models.session_type import SessionType from crossbox.models.week_template import WeekTemplate from crossbox.models.capacity_limit import CapacityLimit", "in capacity_limits}, {cl.pk for cl in CapacityLimit.objects.all()} ) @with_login() def test_change_session_type_no_session(self): response =", "'capacity_limit': 1, } self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 2) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01') def", "page, 'week_template': 1, 'track': 1, 'capacity_limit': 1, } response = self.client.post(path=path, data=kwargs) self.assertEquals(response.url,", "test_session_template_view_context_data_tracks(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self): pass # TODO @with_login() @freeze_time('2020-01-1')", ") @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_days(self): pass", "for cl in CapacityLimit.objects.all()} ) @with_login() def test_change_session_type_no_session(self): response = self.client.put( path=reverse('change_session_type', args=[13371337]))", "page = 5 path = reverse('generate-sessions') kwargs = { 'page': page, 'week_template': 1,", "'session_types', 'tracks'] @freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() kwargs = {", "BaseTestCase from crossbox.tests.tools import with_login, create_session from crossbox.models.day import Day from crossbox.models.hour import", "session_type WOD path = reverse('change_session_type', args=[session.pk]) _ = self.client.put(path=path) # session_type OPEN _", "Hour(hour=datetime.time(0, 0)) hour.save() kwargs = { 'hour': hour, 'session_type': SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1), 'track':", "session = Session( date=day, hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), ) session.save() self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK,", "freezegun import freeze_time from django.urls import reverse from crossbox.tests.mixins import BaseTestCase from crossbox.tests.tools", "raise @with_login() @freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track = Track.objects.get(pk=1) other_track = Track.objects.get(pk=2) session_same_week =", "# TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self): response = self.client.get(path=reverse('session-template')) weeks = response.context_data['weeks'] self.assertEqual(len(weeks),", "@with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self): pass #", ") self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self):", "= { 'page': 0, 'week_template': 1, 'track': track.pk, 'capacity_limit': 1, } self.client.post(path=path, data=kwargs)", "kwargs = { 'page': 0, 'week_template': 1, 'track': track.pk, 'capacity_limit': 1, } self.client.post(path=path,", "reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': 1, 'track': track.pk, 'capacity_limit': 1, }", "= response.context_data['capacity_limits'] self.assertEqual( {cl.pk for cl in capacity_limits}, {cl.pk for cl in CapacityLimit.objects.all()}", "capacity_limits = response.context_data['capacity_limits'] self.assertEqual( {cl.pk for cl in capacity_limits}, {cl.pk for cl in", "@with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_capacity_limits(self): response = self.client.get(path=reverse('session-template')) capacity_limits = response.context_data['capacity_limits'] self.assertEqual( {cl.pk for", "'tracks'] @freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() kwargs = { 'hour':", "# TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self):", "'track': track.pk, 'capacity_limit': 1, } self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 2) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login()", "1, 10), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # same week, other track", "for cl in capacity_limits}, {cl.pk for cl in CapacityLimit.objects.all()} ) @with_login() def test_change_session_type_no_session(self):", "cl in CapacityLimit.objects.all()} ) @with_login() def test_change_session_type_no_session(self): response = self.client.put( path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code,", "result_expected={'pk': 2, 'name': 'OPEN'}, ) @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self): pass # TODO @with_login()", "data=kwargs) self.assertEquals(Session.objects.count(), 2) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk) @with_login() @freeze_time('2020-01-01') def test_gen_sessions_new_sessions_for_that_week(self): week_template = WeekTemplate.objects.get(pk=1)", "WeekTemplate.objects.get(pk=1) session = create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() + 1), hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit, ) path", "Hour(hour=datetime.time(0, 0)) hour.save() day = datetime.date(year=2019, month=1, day=1) session = Session( date=day, hour=hour,", "capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), ) session.save() self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) self._session_view_test(", "in CapacityLimit.objects.all()} ) @with_login() def test_change_session_type_no_session(self): response = self.client.put( path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND)", "track=track, ) Session.objects.create( # same week, other track date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1),", "day_jan) session_filter.used_parameters['filter'] = 'all_asc' all_asc_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(all_asc_sessions[0].date, day_jan) self.assertEquals(all_asc_sessions[1].date, day_feb) self.assertEquals(all_asc_sessions[2].date,", "fixtures = ['capacity_limits', 'session_types', 'tracks'] @freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self): hour = Hour(hour=datetime.time(0, 0)) hour.save()", "'all_desc' all_desc_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter']", "- Semana 1 (actual)') self.assertEqual(weeks[51], 'Lunes 21/12/2020 - Semana 52') @with_login() @freeze_time('2020-01-1') def", "data=kwargs) # no raise @with_login() @freeze_time('2020-01-01') def test_gen_sessions_delete_same_track_and_same_week_sessions(self): track = Track.objects.get(pk=1) other_track =", "capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, ) self.assertEquals(Session.objects.count(), 3) path = reverse('generate-sessions') kwargs = { 'page': 0,", "session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 3, 'name':", "session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 1, 'name': 'WOD'}, ) self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name':", ") self.assertEquals(Session.objects.count(), 3) path = reverse('generate-sessions') kwargs = { 'page': 0, 'week_template': 1,", "Track.objects.get(pk=1) other_track = Track.objects.get(pk=2) session_same_week = Session.objects.create( date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1),", "session.capacity_limit.pk, } self.assertEquals(Session.objects.count(), 1) self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 1) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session.pk) new_session =", "hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), ) session.save() self._session_view_test( session_id=session.id, status_code_expected=HTTPStatus.OK, result_expected={'pk': 2, 'name': 'OPEN'},", "day_feb = datetime.date(year=2020, month=2, day=1) day_mar = datetime.date(year=2020, month=3, day=1) Session.objects.bulk_create([ Session(date=day_jan, **kwargs),", "crossbox.models.capacity_limit import CapacityLimit from crossbox.models.session_template import SessionTemplate from crossbox.admin.session import SessionAdmin, SessionAdminFilter class", "create_session from crossbox.models.day import Day from crossbox.models.hour import Hour from crossbox.models.track import Track", "2) session_filter.used_parameters['filter'] = 'past' past_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter']", "import with_login, create_session from crossbox.models.day import Day from crossbox.models.hour import Hour from crossbox.models.track", "1, 'track': track.pk, 'capacity_limit': 1, } self.client.post(path=path, data=kwargs) self.assertEquals(Session.objects.count(), 2) with self.assertRaises(Session.DoesNotExist): Session.objects.get(pk=session_same_week.pk)", "import SessionTemplate from crossbox.admin.session import SessionAdmin, SessionAdminFilter class SessionsCase(BaseTestCase): fixtures = [ 'users',", "self.client.put( path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01') def test_change_session_type_db_types(self): \"\"\"Check types are taken", "TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self): response = self.client.get(path=reverse('session-template')) weeks = response.context_data['weeks'] self.assertEqual(len(weeks), 52)", "'week_template': 1, 'track': 1, 'capacity_limit': 1, } with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['page'] =", "Semana 1 (actual)') self.assertEqual(weeks[51], 'Lunes 21/12/2020 - Semana 52') @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self):", ") Session.objects.create( # same week, other track date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1),", "@with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_week_templates(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self): pass #", "self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter'] = 'all_desc' all_desc_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date,", "1), hour=session.hour, week_template=week_template, capacity_limit=session.capacity_limit, ) path = reverse('generate-sessions') kwargs = { 'page': 0,", "date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # other week, same", "pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_days(self): pass # TODO @with_login() @freeze_time('2020-01-1') def", "} response = self.client.post(path=path, data=kwargs) self.assertEquals(response.url, f'/reservation/?page={page}') self.assertEquals(response.status_code, 302) def _session_view_test( self, session_id,", "day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter'] = 'all_asc' all_asc_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(all_asc_sessions[0].date, day_jan) self.assertEquals(all_asc_sessions[1].date,", "@with_login() def test_change_session_type_no_session(self): response = self.client.put( path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01') def", "session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=track, ) Session.objects.create( # other week, same track date=datetime.date(2020, 1, 10),", "with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['week_template'] = 1 kwargs['track'] = None with self.assertRaises(Exception): self.client.post(path=path,", "# TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_track(self):", ") @with_login() def test_change_session_type_no_session(self): response = self.client.put( path=reverse('change_session_type', args=[13371337])) self.assertEquals(response.status_code, HTTPStatus.NOT_FOUND) @with_login() @freeze_time('2020-01-01')", "{ 'page': 0, 'week_template': week_template.pk, 'track': session.track.pk, 'capacity_limit': session.capacity_limit.pk, } self.assertEquals(Session.objects.count(), 1) self.client.post(path=path,", "self.assertEquals(response.json()['session_type'], result_expected) class SessionAdminFilterCase(BaseTestCase): fixtures = ['capacity_limits', 'session_types', 'tracks'] @freeze_time('2020-02-1') def test_queryset_depending_on_filter_selected(self): hour", "datetime.date(year=2019, month=1, day=1) session = Session( date=day, hour=hour, session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=Track.objects.get(pk=1), ) session.save()", "with self.assertRaises(Exception): self.client.post(path=path, data=kwargs) kwargs['track'] = 1 kwargs['capacity_limit'] = None with self.assertRaises(Exception): self.client.post(path=path,", "= create_session() # session_type WOD path = reverse('change_session_type', args=[session.pk]) _ = self.client.put(path=path) #", "week, other track date=datetime.date(2020, 1, 1), hour=Hour.objects.get(pk=1), session_type=SessionType.objects.get(pk=1), capacity_limit=CapacityLimit.objects.get(pk=1), track=other_track, ) self.assertEquals(Session.objects.count(), 3)", "self.assertEquals(all_desc_sessions[0].date, day_mar) self.assertEquals(all_desc_sessions[1].date, day_feb) self.assertEquals(all_desc_sessions[2].date, day_jan) session_filter.used_parameters['filter'] = 'all_asc' all_asc_sessions = session_filter.queryset(None, Session.objects.all())", "datetime from http import HTTPStatus from freezegun import freeze_time from django.urls import reverse", "session.capacity_limit) self.assertEquals(new_session.track, session.track) @with_login() def test_gen_sessions_redirect_created_week_page(self): page = 5 path = reverse('generate-sessions') kwargs", "from http import HTTPStatus from freezegun import freeze_time from django.urls import reverse from", "TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_days(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_weeks(self): response", "day=1) day_feb = datetime.date(year=2020, month=2, day=1) day_mar = datetime.date(year=2020, month=3, day=1) Session.objects.bulk_create([ Session(date=day_jan,", "OPEN _ = self.client.put(path=path) # session_type ESTIRAMIENTOS response = self.client.put(path=path) self.assertEquals( response.json()['session_type'], {'pk':", "day=1) day_mar = datetime.date(year=2020, month=3, day=1) Session.objects.bulk_create([ Session(date=day_jan, **kwargs), Session(date=day_feb, **kwargs), Session(date=day_mar, **kwargs),", "test_gen_sessions_new_sessions_for_that_week(self): week_template = WeekTemplate.objects.get(pk=1) session = create_session() SessionTemplate.objects.create( day=Day.objects.get(pk=session.date.weekday() + 1), hour=session.hour, week_template=week_template,", "'hours', 'days', 'week_templates', ] @with_login() def test_change_session_type(self): hour = Hour(hour=datetime.time(0, 0)) hour.save() day", "{}, Session, SessionAdmin) session_filter.used_parameters['filter'] = None from_this_week_sessions = session_filter.queryset( None, Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb)", "import SessionAdmin, SessionAdminFilter class SessionsCase(BaseTestCase): fixtures = [ 'users', 'capacity_limits', 'session_types', 'tracks', 'hours',", "**kwargs), Session(date=day_feb, **kwargs), Session(date=day_mar, **kwargs), ]) session_filter = SessionAdminFilter(None, {}, Session, SessionAdmin) session_filter.used_parameters['filter']", "{ 'hour': hour, 'session_type': SessionType.objects.get(pk=1), 'capacity_limit': CapacityLimit.objects.get(pk=1), 'track': Track.objects.get(pk=1), } day_jan = datetime.date(year=2020,", "past_sessions = session_filter.queryset(None, Session.objects.all()) self.assertEquals(past_sessions[0].date, day_jan) self.assertEquals(past_sessions.count(), 1) session_filter.used_parameters['filter'] = 'all_desc' all_desc_sessions =", "CapacityLimit from crossbox.models.session_template import SessionTemplate from crossbox.admin.session import SessionAdmin, SessionAdminFilter class SessionsCase(BaseTestCase): fixtures", "@with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_hours(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_days(self): pass #", "{cl.pk for cl in CapacityLimit.objects.all()} ) @with_login() def test_change_session_type_no_session(self): response = self.client.put( path=reverse('change_session_type',", "test_gen_sessions_invalid_post_params(self): path = reverse('generate-sessions') kwargs = { 'page': None, 'week_template': 1, 'track': 1,", "Session.objects.all()) self.assertEquals(from_this_week_sessions[0].date, day_feb) self.assertEquals(from_this_week_sessions[1].date, day_mar) self.assertEquals(from_this_week_sessions.count(), 2) session_filter.used_parameters['filter'] = 'past' past_sessions = session_filter.queryset(None,", "TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_current_week_template(self): pass # TODO @with_login() @freeze_time('2020-01-1') def test_session_template_view_context_data_tracks(self): pass" ]
[ ".cpr_head import CPRHead from .p2p_head import P2PHead __all__ = [ 'CPRHead', 'P2PHead', ]", "from .cpr_head import CPRHead from .p2p_head import P2PHead __all__ = [ 'CPRHead', 'P2PHead'," ]
[ "url=scrapedurl)) return itemlist def findvid(item): logger.info(\"[pastebin.py] findvideos\") # Downloads page data = item.url", "fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Seconda Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")]", "__channel__ = \"hokutonoken\" def mainlist(item): logger.info(\"[hokutonoken.py] mainlist\") itemlist = [Item(channel=__channel__, title=\"[COLOR azure]Hokuto no", "in itemlist: videoitem.title = item.title + videoitem.title videoitem.fulltitle = item.fulltitle videoitem.thumbnail = item.thumbnail", "Item(channel=__channel__, action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl)) return itemlist def findvid(item): logger.info(\"[pastebin.py] findvideos\") # Downloads", "logger.info(\"hokutonoken.py episodi\") itemlist = [] # Downloads page data = httptools.downloadpage(item.url).data # Extracts", "entries patron = '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches = re.compile(patron, re.DOTALL).findall(data) for scrapedtitle, scrapedurl", "# Downloads page data = item.url itemlist = servertools.find_video_items(data=data) for videoitem in itemlist:", "no Ken - Prima Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR azure]Hokuto no", "matches = re.compile(patron, re.DOTALL).findall(data) for scrapedtitle, scrapedurl in matches: scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append(", "action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Seconda Serie[/COLOR]\", action=\"episodi\",", "Downloads page data = item.url itemlist = servertools.find_video_items(data=data) for videoitem in itemlist: videoitem.title", "Community Edition - Kodi Addon # ------------------------------------------------------------ # streamondemand.- XBMC Plugin # Canale", "import httptools from platformcode import logger from core import scrapertools from core import", "itemlist def episodi(item): logger.info(\"hokutonoken.py episodi\") itemlist = [] # Downloads page data =", "videoitem in itemlist: videoitem.title = item.title + videoitem.title videoitem.fulltitle = item.fulltitle videoitem.thumbnail =", "[] # Downloads page data = httptools.downloadpage(item.url).data # Extracts the entries patron =", "findvideos\") # Downloads page data = item.url itemlist = servertools.find_video_items(data=data) for videoitem in", "title=\"[COLOR azure]Hokuto no Ken - Seconda Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist", "Ken - Seconda Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist def episodi(item): logger.info(\"hokutonoken.py", "<NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import re from core import httptools from platformcode", "scrapertools from core import servertools from core.item import Item __channel__ = \"hokutonoken\" def", "azure]Hokuto no Ken - Prima Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR azure]Hokuto", "platformcode import logger from core import scrapertools from core import servertools from core.item", "Downloads page data = httptools.downloadpage(item.url).data # Extracts the entries patron = '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot;", "import logger from core import scrapertools from core import servertools from core.item import", "scrapedtitle, scrapedurl in matches: scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__, action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl))", "the entries patron = '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches = re.compile(patron, re.DOTALL).findall(data) for scrapedtitle,", "return itemlist def episodi(item): logger.info(\"hokutonoken.py episodi\") itemlist = [] # Downloads page data", "itemlist: videoitem.title = item.title + videoitem.title videoitem.fulltitle = item.fulltitle videoitem.thumbnail = item.thumbnail videoitem.channel", "re from core import httptools from platformcode import logger from core import scrapertools", "Addon # ------------------------------------------------------------ # streamondemand.- XBMC Plugin # Canale per I <NAME> #", "= [Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Prima Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"),", "Seconda Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist def episodi(item): logger.info(\"hokutonoken.py episodi\") itemlist", "import scrapertools from core import servertools from core.item import Item __channel__ = \"hokutonoken\"", "= scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__, action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl)) return itemlist def findvid(item): logger.info(\"[pastebin.py]", "# streamondemand.- XBMC Plugin # Canale per I <NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------", "return itemlist def findvid(item): logger.info(\"[pastebin.py] findvideos\") # Downloads page data = item.url itemlist", "Plugin # Canale per I <NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import re from", "Prima Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Seconda", "title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl)) return itemlist def findvid(item): logger.info(\"[pastebin.py] findvideos\") # Downloads page data", "patron = '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches = re.compile(patron, re.DOTALL).findall(data) for scrapedtitle, scrapedurl in", "= servertools.find_video_items(data=data) for videoitem in itemlist: videoitem.title = item.title + videoitem.title videoitem.fulltitle =", "- Prima Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken -", "target=&quot;_blank&quot;&gt;' matches = re.compile(patron, re.DOTALL).findall(data) for scrapedtitle, scrapedurl in matches: scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle)", "# ------------------------------------------------------------ import re from core import httptools from platformcode import logger from", "episodi(item): logger.info(\"hokutonoken.py episodi\") itemlist = [] # Downloads page data = httptools.downloadpage(item.url).data #", "+ videoitem.title videoitem.fulltitle = item.fulltitle videoitem.thumbnail = item.thumbnail videoitem.channel = __channel__ return itemlist", "Edition - Kodi Addon # ------------------------------------------------------------ # streamondemand.- XBMC Plugin # Canale per", "thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist def episodi(item): logger.info(\"hokutonoken.py episodi\") itemlist = [] # Downloads", "coding: utf-8 -*- # StreamOnDemand Community Edition - Kodi Addon # ------------------------------------------------------------ #", "logger.info(\"[hokutonoken.py] mainlist\") itemlist = [Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Prima Serie[/COLOR]\", action=\"episodi\",", "videoitem.title = item.title + videoitem.title videoitem.fulltitle = item.fulltitle videoitem.thumbnail = item.thumbnail videoitem.channel =", "in matches: scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__, action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl)) return itemlist", "Kodi Addon # ------------------------------------------------------------ # streamondemand.- XBMC Plugin # Canale per I <NAME>", "# Extracts the entries patron = '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches = re.compile(patron, re.DOTALL).findall(data)", "action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl)) return itemlist def findvid(item): logger.info(\"[pastebin.py] findvideos\") # Downloads page", "# http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import re from core import httptools from platformcode import", "import servertools from core.item import Item __channel__ = \"hokutonoken\" def mainlist(item): logger.info(\"[hokutonoken.py] mainlist\")", "from core import httptools from platformcode import logger from core import scrapertools from", "def mainlist(item): logger.info(\"[hokutonoken.py] mainlist\") itemlist = [Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Prima", "import re from core import httptools from platformcode import logger from core import", "core import servertools from core.item import Item __channel__ = \"hokutonoken\" def mainlist(item): logger.info(\"[hokutonoken.py]", "logger from core import scrapertools from core import servertools from core.item import Item", "episodi\") itemlist = [] # Downloads page data = httptools.downloadpage(item.url).data # Extracts the", "itemlist = [] # Downloads page data = httptools.downloadpage(item.url).data # Extracts the entries", "------------------------------------------------------------ import re from core import httptools from platformcode import logger from core", "no Ken - Seconda Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist def episodi(item):", "import Item __channel__ = \"hokutonoken\" def mainlist(item): logger.info(\"[hokutonoken.py] mainlist\") itemlist = [Item(channel=__channel__, title=\"[COLOR", "XBMC Plugin # Canale per I <NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import re", "-*- # StreamOnDemand Community Edition - Kodi Addon # ------------------------------------------------------------ # streamondemand.- XBMC", "Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist def episodi(item): logger.info(\"hokutonoken.py episodi\") itemlist =", "mainlist(item): logger.info(\"[hokutonoken.py] mainlist\") itemlist = [Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Prima Serie[/COLOR]\",", "mainlist\") itemlist = [Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Prima Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\",", "for scrapedtitle, scrapedurl in matches: scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__, action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail,", "- Seconda Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist def episodi(item): logger.info(\"hokutonoken.py episodi\")", "httptools from platformcode import logger from core import scrapertools from core import servertools", "href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches = re.compile(patron, re.DOTALL).findall(data) for scrapedtitle, scrapedurl in matches: scrapedtitle =", "servertools from core.item import Item __channel__ = \"hokutonoken\" def mainlist(item): logger.info(\"[hokutonoken.py] mainlist\") itemlist", "streamondemand.- XBMC Plugin # Canale per I <NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import", "utf-8 -*- # StreamOnDemand Community Edition - Kodi Addon # ------------------------------------------------------------ # streamondemand.-", "from core import scrapertools from core import servertools from core.item import Item __channel__", "data = item.url itemlist = servertools.find_video_items(data=data) for videoitem in itemlist: videoitem.title = item.title", "scrapedurl in matches: scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__, action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl)) return", "def episodi(item): logger.info(\"hokutonoken.py episodi\") itemlist = [] # Downloads page data = httptools.downloadpage(item.url).data", "- Kodi Addon # ------------------------------------------------------------ # streamondemand.- XBMC Plugin # Canale per I", "itemlist = [Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Prima Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\",", "url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist def episodi(item): logger.info(\"hokutonoken.py episodi\") itemlist = [] #", "core import scrapertools from core import servertools from core.item import Item __channel__ =", "StreamOnDemand Community Edition - Kodi Addon # ------------------------------------------------------------ # streamondemand.- XBMC Plugin #", "-*- coding: utf-8 -*- # StreamOnDemand Community Edition - Kodi Addon # ------------------------------------------------------------", "action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist def episodi(item): logger.info(\"hokutonoken.py episodi\") itemlist = []", "core import httptools from platformcode import logger from core import scrapertools from core", "# Canale per I <NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import re from core", "item.url itemlist = servertools.find_video_items(data=data) for videoitem in itemlist: videoitem.title = item.title + videoitem.title", "thumbnail=item.thumbnail, url=scrapedurl)) return itemlist def findvid(item): logger.info(\"[pastebin.py] findvideos\") # Downloads page data =", "\"hokutonoken\" def mainlist(item): logger.info(\"[hokutonoken.py] mainlist\") itemlist = [Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken -", "page data = httptools.downloadpage(item.url).data # Extracts the entries patron = '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;'", "Ken - Prima Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken", "= [] # Downloads page data = httptools.downloadpage(item.url).data # Extracts the entries patron", "url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Seconda Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\",", "= item.url itemlist = servertools.find_video_items(data=data) for videoitem in itemlist: videoitem.title = item.title +", "Item __channel__ = \"hokutonoken\" def mainlist(item): logger.info(\"[hokutonoken.py] mainlist\") itemlist = [Item(channel=__channel__, title=\"[COLOR azure]Hokuto", "from platformcode import logger from core import scrapertools from core import servertools from", "page data = item.url itemlist = servertools.find_video_items(data=data) for videoitem in itemlist: videoitem.title =", "def findvid(item): logger.info(\"[pastebin.py] findvideos\") # Downloads page data = item.url itemlist = servertools.find_video_items(data=data)", "= re.compile(patron, re.DOTALL).findall(data) for scrapedtitle, scrapedurl in matches: scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__,", "# StreamOnDemand Community Edition - Kodi Addon # ------------------------------------------------------------ # streamondemand.- XBMC Plugin", "itemlist def findvid(item): logger.info(\"[pastebin.py] findvideos\") # Downloads page data = item.url itemlist =", "servertools.find_video_items(data=data) for videoitem in itemlist: videoitem.title = item.title + videoitem.title videoitem.fulltitle = item.fulltitle", "core.item import Item __channel__ = \"hokutonoken\" def mainlist(item): logger.info(\"[hokutonoken.py] mainlist\") itemlist = [Item(channel=__channel__,", "thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Seconda Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\",", "http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import re from core import httptools from platformcode import logger", "I <NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import re from core import httptools from", "scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__, action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl)) return itemlist def findvid(item): logger.info(\"[pastebin.py] findvideos\")", "httptools.downloadpage(item.url).data # Extracts the entries patron = '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches = re.compile(patron,", "azure]Hokuto no Ken - Seconda Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist def", "# ------------------------------------------------------------ # streamondemand.- XBMC Plugin # Canale per I <NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36", "Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Seconda Serie[/COLOR]\",", "= item.title + videoitem.title videoitem.fulltitle = item.fulltitle videoitem.thumbnail = item.thumbnail videoitem.channel = __channel__", "for videoitem in itemlist: videoitem.title = item.title + videoitem.title videoitem.fulltitle = item.fulltitle videoitem.thumbnail", "itemlist.append( Item(channel=__channel__, action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl)) return itemlist def findvid(item): logger.info(\"[pastebin.py] findvideos\") #", "Canale per I <NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import re from core import", "------------------------------------------------------------ # streamondemand.- XBMC Plugin # Canale per I <NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36 #", "re.DOTALL).findall(data) for scrapedtitle, scrapedurl in matches: scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__, action=\"findvid\", title=scrapedtitle,", "findvid(item): logger.info(\"[pastebin.py] findvideos\") # Downloads page data = item.url itemlist = servertools.find_video_items(data=data) for", "from core import servertools from core.item import Item __channel__ = \"hokutonoken\" def mainlist(item):", "itemlist = servertools.find_video_items(data=data) for videoitem in itemlist: videoitem.title = item.title + videoitem.title videoitem.fulltitle", "[Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Prima Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__,", "data = httptools.downloadpage(item.url).data # Extracts the entries patron = '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches", "Extracts the entries patron = '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches = re.compile(patron, re.DOTALL).findall(data) for", "# -*- coding: utf-8 -*- # StreamOnDemand Community Edition - Kodi Addon #", "item.title + videoitem.title videoitem.fulltitle = item.fulltitle videoitem.thumbnail = item.thumbnail videoitem.channel = __channel__ return", "from core.item import Item __channel__ = \"hokutonoken\" def mainlist(item): logger.info(\"[hokutonoken.py] mainlist\") itemlist =", "title=\"[COLOR azure]Hokuto no Ken - Prima Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/BUqD13hb\", thumbnail=\"http://i.imgur.com/MGkqu7c.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\"), Item(channel=__channel__, title=\"[COLOR", "Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken - Seconda Serie[/COLOR]\", action=\"episodi\", url=\"http://pastebin.com/mHXQRBxZ\", thumbnail=\"http://i159.photobucket.com/albums/t123/Janthem/hnk2.jpg\", fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return", "matches: scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__, action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl)) return itemlist def", "scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__, action=\"findvid\", title=scrapedtitle, thumbnail=item.thumbnail, url=scrapedurl)) return itemlist def findvid(item):", "re.compile(patron, re.DOTALL).findall(data) for scrapedtitle, scrapedurl in matches: scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle) itemlist.append( Item(channel=__channel__, action=\"findvid\",", "'>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches = re.compile(patron, re.DOTALL).findall(data) for scrapedtitle, scrapedurl in matches: scrapedtitle", "fanart=\"http://fullhdwp.com/images/wallpapers/Group-fist-of-the-north-star-wallpaper-.jpg\")] return itemlist def episodi(item): logger.info(\"hokutonoken.py episodi\") itemlist = [] # Downloads page", "= \"hokutonoken\" def mainlist(item): logger.info(\"[hokutonoken.py] mainlist\") itemlist = [Item(channel=__channel__, title=\"[COLOR azure]Hokuto no Ken", "# Downloads page data = httptools.downloadpage(item.url).data # Extracts the entries patron = '>&lt;br&gt;(.*?)&lt;a", "= '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches = re.compile(patron, re.DOTALL).findall(data) for scrapedtitle, scrapedurl in matches:", "per I <NAME> # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import re from core import httptools", "logger.info(\"[pastebin.py] findvideos\") # Downloads page data = item.url itemlist = servertools.find_video_items(data=data) for videoitem", "= httptools.downloadpage(item.url).data # Extracts the entries patron = '>&lt;br&gt;(.*?)&lt;a href=&quot;(.*?)&quot; target=&quot;_blank&quot;&gt;' matches =" ]
[ "tg['TargetGroupArn'] in arr_available_target_groups and (tg['Weight'] is 100 or tg['Weight'] is 1) : return", "of lister rules. def get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0 while i < len(http_listener_rules): # Continue", "\") print(event) region = os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups", "= https_listener_rules[i]['Actions'] actions, modify = process_actions(actions, http_target_group_arn, arr_available_target_groups) if modify==1: print(\"Updating SSL listener", "arr_available_target_groups): modify = 0 for ak, action in enumerate(actions): try: if action['Type'] ==", "False def modify_rules(elbv2_client, arn, actions): try: return elbv2_client.modify_rule( RuleArn=arn, Actions=actions ) except Exception", "tg['TargetGroupArn'] except Exception as e: print(e) n +=1 i +=1 return False def", "Event: \") print(event) region = os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS']", "results) return results # Returns the current B/G target group from a list", "CodeDeploy on hook status... def send_codedeploy_validation_status(event, results): region = os.environ['REGION'] codedeploy_client = boto3.client('codedeploy',", "json, boto3 def lambda_handler(event, context): print(\"Trigger Event: \") print(event) region = os.environ['REGION'] elbv2_client", "actions) i +=1 # For ECS After Allow Test Traffic hook print(results) send_codedeploy_validation_status(event,", "group is associated w/out available target and different. # Be wary I found", "e: print(e) n +=1 i +=1 return False def process_actions(actions, http_target_group_arn, arr_available_target_groups): modify", "IF ONE OF THE AVAILABLE TARGETS def check_target_update(old_target_group, arr_available_target_groups): return old_target_group in arr_available_target_groups", "list of lister rules. def get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0 while i < len(http_listener_rules): #", "target arn\") return False print(\"Current HTTP target group: \") print(http_target_group_arn) # Get HTTPS", "the Listener rule is updated at the initial Ready Stage. # DO NOT", "# Get HTTPS listener rules. https_listener_arn = os.environ['SSL_LISTENER_ARN'] https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules =", "send_codedeploy_validation_status(event, results) return results # Returns the current B/G target group from a", "(tg['Weight'] is 100 or tg['Weight'] is 1) : return tg['TargetGroupArn'] except Exception as", "arn\") return False print(\"Current HTTP target group: \") print(http_target_group_arn) # Get HTTPS listener", "the initial Ready Stage. # DO NOT TRY COMPARING OLD AN NEW, SIMPLY", "codedeploy_client = boto3.client('codedeploy', region_name=region) status = ('Failed', 'Succeeded')[len(results) > 0] print(status) try: return", "current B/G target group from a list of lister rules. def get_current_http_target_group(http_listener_rules, arr_available_target_groups):", "TO MATCH HTTP IF ONE OF THE AVAILABLE TARGETS def check_target_update(old_target_group, arr_available_target_groups): return", "+=1 i +=1 return False def process_actions(actions, http_target_group_arn, arr_available_target_groups): modify = 0 for", "Stage. # DO NOT TRY COMPARING OLD AN NEW, SIMPLY ALWAYS UPDATE TO", "\") print(e) return False def modify_rules(elbv2_client, arn, actions): try: return elbv2_client.modify_rule( RuleArn=arn, Actions=actions", "= available_target_groups.split(',') # Get HTTP Target Group. http_listener_arn = os.environ['HTTP_LISTENER_ARN'] http_listener = elbv2_client.describe_rules(", "'Succeeded')[len(results) > 0] print(status) try: return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status ) except Exception", "status=status ) except Exception as e: print(\"Recoverable Exception: \") print(e) return False def", "context): print(\"Trigger Event: \") print(event) region = os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups", "TRY COMPARING OLD AN NEW, SIMPLY ALWAYS UPDATE TO MATCH HTTP IF ONE", "send_codedeploy_validation_status(event, results): region = os.environ['REGION'] codedeploy_client = boto3.client('codedeploy', region_name=region) status = ('Failed', 'Succeeded')[len(results)", "listener rule. if http_listener_rules[i]['IsDefault']==True: i +=1 continue actions = http_listener_rules[i]['Actions'] n=0 while n<len(actions):", "Group. http_listener_arn = os.environ['HTTP_LISTENER_ARN'] http_listener = elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn = get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if", "i < len(https_listener_rules): # Skip default rule if https_listener_rules[i]['IsDefault']==True: i +=1 continue actions", "http_target_group_arn, arr_available_target_groups) if modify==1: print(\"Updating SSL listener rules..\") rule_arn = https_listener_rules[i]['RuleArn'] results[rule_arn] =", "= get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn) results = {} i = 0 while i <", "arr_available_target_groups) if http_target_group_arn==False: print(\"Could not identify the target arn\") return False print(\"Current HTTP", "Continue if default listener rule. if http_listener_rules[i]['IsDefault']==True: i +=1 continue actions = http_listener_rules[i]['Actions']", "OF THE AVAILABLE TARGETS def check_target_update(old_target_group, arr_available_target_groups): return old_target_group in arr_available_target_groups # Sends", "default rule if https_listener_rules[i]['IsDefault']==True: i +=1 continue actions = https_listener_rules[i]['Actions'] actions, modify =", "tg in actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn'] in arr_available_target_groups and (tg['Weight'] is 100 or tg['Weight']", "listener rules..\") rule_arn = https_listener_rules[i]['RuleArn'] results[rule_arn] = modify_rules(elbv2_client, rule_arn, actions) i +=1 #", "get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0 while i < len(http_listener_rules): # Continue if default listener rule.", "print(http_target_group_arn) # Get HTTPS listener rules. https_listener_arn = os.environ['SSL_LISTENER_ARN'] https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules", "= modify_rules(elbv2_client, rule_arn, actions) i +=1 # For ECS After Allow Test Traffic", "ListenerArn=http_listener_arn) http_target_group_arn = get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if http_target_group_arn==False: print(\"Could not identify the target arn\")", "available target and different. # Be wary I found its possible the Listener", "enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except Exception as e: print(e) return (actions),", "continue actions = http_listener_rules[i]['Actions'] n=0 while n<len(actions): try: for tg in actions[n]['ForwardConfig']['TargetGroups']: if", "print(\"Current HTTP target group: \") print(http_target_group_arn) # Get HTTPS listener rules. https_listener_arn =", "results): region = os.environ['REGION'] codedeploy_client = boto3.client('codedeploy', region_name=region) status = ('Failed', 'Succeeded')[len(results) >", "http_target_group_arn, arr_available_target_groups): modify = 0 for ak, action in enumerate(actions): try: if action['Type']", "if action['Type'] == \"forward\" and check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for tgk, target_group in enumerate(action['ForwardConfig']['TargetGroups']):", "its possible the Listener rule is updated at the initial Ready Stage. #", "return old_target_group in arr_available_target_groups # Sends notification to CodeDeploy on hook status... def", "> 0] print(status) try: return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status ) except Exception as", "except Exception as e: print(e) n +=1 i +=1 return False def process_actions(actions,", "results # Returns the current B/G target group from a list of lister", "= os.environ['REGION'] codedeploy_client = boto3.client('codedeploy', region_name=region) status = ('Failed', 'Succeeded')[len(results) > 0] print(status)", "arr_available_target_groups and (tg['Weight'] is 100 or tg['Weight'] is 1) : return tg['TargetGroupArn'] except", "available_target_groups.split(',') # Get HTTP Target Group. http_listener_arn = os.environ['HTTP_LISTENER_ARN'] http_listener = elbv2_client.describe_rules( ListenerArn=http_listener_arn)", "= https_listener['Rules'] print(\"Current HTTPS target group: \") https_target_group_arn = get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn) results", "if http_listener_rules[i]['IsDefault']==True: i +=1 continue actions = http_listener_rules[i]['Actions'] n=0 while n<len(actions): try: for", "modify # Check old target group is associated w/out available target and different.", "http_listener_rules[i]['Actions'] n=0 while n<len(actions): try: for tg in actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn'] in arr_available_target_groups", "\"forward\" and check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for tgk, target_group in enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups):", "rules..\") rule_arn = https_listener_rules[i]['RuleArn'] results[rule_arn] = modify_rules(elbv2_client, rule_arn, actions) i +=1 # For", "HTTP Target Group. http_listener_arn = os.environ['HTTP_LISTENER_ARN'] http_listener = elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn = get_current_http_target_group(http_listener['Rules'],", "http_target_group_arn==False: print(\"Could not identify the target arn\") return False print(\"Current HTTP target group:", "# Continue if default listener rule. if http_listener_rules[i]['IsDefault']==True: i +=1 continue actions =", "target group is associated w/out available target and different. # Be wary I", "SSL listener rules..\") rule_arn = https_listener_rules[i]['RuleArn'] results[rule_arn] = modify_rules(elbv2_client, rule_arn, actions) i +=1", "boto3.client('codedeploy', region_name=region) status = ('Failed', 'Succeeded')[len(results) > 0] print(status) try: return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'],", "= 0 for ak, action in enumerate(actions): try: if action['Type'] == \"forward\" and", "different. # Be wary I found its possible the Listener rule is updated", "# Skip default rule if https_listener_rules[i]['IsDefault']==True: i +=1 continue actions = https_listener_rules[i]['Actions'] actions,", "os import json, boto3 def lambda_handler(event, context): print(\"Trigger Event: \") print(event) region =", "rule if https_listener_rules[i]['IsDefault']==True: i +=1 continue actions = https_listener_rules[i]['Actions'] actions, modify = process_actions(actions,", "enumerate(actions): try: if action['Type'] == \"forward\" and check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for tgk, target_group", "try: if action['Type'] == \"forward\" and check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for tgk, target_group in", "status... def send_codedeploy_validation_status(event, results): region = os.environ['REGION'] codedeploy_client = boto3.client('codedeploy', region_name=region) status =", "default listener rule. if http_listener_rules[i]['IsDefault']==True: i +=1 continue actions = http_listener_rules[i]['Actions'] n=0 while", "def modify_rules(elbv2_client, arn, actions): try: return elbv2_client.modify_rule( RuleArn=arn, Actions=actions ) except Exception as", "Sends notification to CodeDeploy on hook status... def send_codedeploy_validation_status(event, results): region = os.environ['REGION']", "os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_target_groups.split(',') # Get", "Allow Test Traffic hook print(results) send_codedeploy_validation_status(event, results) return results # Returns the current", "DO NOT TRY COMPARING OLD AN NEW, SIMPLY ALWAYS UPDATE TO MATCH HTTP", "results[rule_arn] = modify_rules(elbv2_client, rule_arn, actions) i +=1 # For ECS After Allow Test", "= ('Failed', 'Succeeded')[len(results) > 0] print(status) try: return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status )", "region = os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_target_groups.split(',')", "Check old target group is associated w/out available target and different. # Be", "in arr_available_target_groups # Sends notification to CodeDeploy on hook status... def send_codedeploy_validation_status(event, results):", "boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_target_groups.split(',') # Get HTTP Target Group.", "False print(\"Current HTTP target group: \") print(http_target_group_arn) # Get HTTPS listener rules. https_listener_arn", "\") https_target_group_arn = get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn) results = {} i = 0 while", "the target arn\") return False print(\"Current HTTP target group: \") print(http_target_group_arn) # Get", "arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except Exception as e: print(e) return (actions), modify # Check", "THE AVAILABLE TARGETS def check_target_update(old_target_group, arr_available_target_groups): return old_target_group in arr_available_target_groups # Sends notification", "rule. if http_listener_rules[i]['IsDefault']==True: i +=1 continue actions = http_listener_rules[i]['Actions'] n=0 while n<len(actions): try:", "results = {} i = 0 while i < len(https_listener_rules): # Skip default", "arr_available_target_groups) if modify==1: print(\"Updating SSL listener rules..\") rule_arn = https_listener_rules[i]['RuleArn'] results[rule_arn] = modify_rules(elbv2_client,", "from a list of lister rules. def get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0 while i <", "# Returns the current B/G target group from a list of lister rules.", "in arr_available_target_groups and (tg['Weight'] is 100 or tg['Weight'] is 1) : return tg['TargetGroupArn']", "check_target_update(old_target_group, arr_available_target_groups): return old_target_group in arr_available_target_groups # Sends notification to CodeDeploy on hook", "notification to CodeDeploy on hook status... def send_codedeploy_validation_status(event, results): region = os.environ['REGION'] codedeploy_client", "actions, modify = process_actions(actions, http_target_group_arn, arr_available_target_groups) if modify==1: print(\"Updating SSL listener rules..\") rule_arn", "rules. https_listener_arn = os.environ['SSL_LISTENER_ARN'] https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules = https_listener['Rules'] print(\"Current HTTPS target", "https_listener_arn = os.environ['SSL_LISTENER_ARN'] https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules = https_listener['Rules'] print(\"Current HTTPS target group:", "return tg['TargetGroupArn'] except Exception as e: print(e) n +=1 i +=1 return False", "target_group in enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except Exception as e: print(e)", "if tg['TargetGroupArn'] in arr_available_target_groups and (tg['Weight'] is 100 or tg['Weight'] is 1) :", "return results # Returns the current B/G target group from a list of", "print(\"Current HTTPS target group: \") https_target_group_arn = get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn) results = {}", "deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status ) except Exception as e: print(\"Recoverable Exception: \") print(e) return", "Be wary I found its possible the Listener rule is updated at the", "w/out available target and different. # Be wary I found its possible the", "UPDATE TO MATCH HTTP IF ONE OF THE AVAILABLE TARGETS def check_target_update(old_target_group, arr_available_target_groups):", "tgk, target_group in enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except Exception as e:", "https_listener_rules[i]['IsDefault']==True: i +=1 continue actions = https_listener_rules[i]['Actions'] actions, modify = process_actions(actions, http_target_group_arn, arr_available_target_groups)", "(actions), modify # Check old target group is associated w/out available target and", "os.environ['HTTP_LISTENER_ARN'] http_listener = elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn = get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if http_target_group_arn==False: print(\"Could not", "HTTP target group: \") print(http_target_group_arn) # Get HTTPS listener rules. https_listener_arn = os.environ['SSL_LISTENER_ARN']", "= os.environ['SSL_LISTENER_ARN'] https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules = https_listener['Rules'] print(\"Current HTTPS target group: \")", "print(\"Recoverable Exception: \") print(e) return False def modify_rules(elbv2_client, arn, actions): try: return elbv2_client.modify_rule(", "https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules = https_listener['Rules'] print(\"Current HTTPS target group: \") https_target_group_arn =", "https_listener_rules = https_listener['Rules'] print(\"Current HTTPS target group: \") https_target_group_arn = get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn)", ") except Exception as e: print(\"Recoverable Exception: \") print(e) return False def modify_rules(elbv2_client,", "Get HTTPS listener rules. https_listener_arn = os.environ['SSL_LISTENER_ARN'] https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules = https_listener['Rules']", "MATCH HTTP IF ONE OF THE AVAILABLE TARGETS def check_target_update(old_target_group, arr_available_target_groups): return old_target_group", "at the initial Ready Stage. # DO NOT TRY COMPARING OLD AN NEW,", "0 for ak, action in enumerate(actions): try: if action['Type'] == \"forward\" and check_target_update(action['TargetGroupArn'],", "rule is updated at the initial Ready Stage. # DO NOT TRY COMPARING", "and (tg['Weight'] is 100 or tg['Weight'] is 1) : return tg['TargetGroupArn'] except Exception", "possible the Listener rule is updated at the initial Ready Stage. # DO", "while i < len(http_listener_rules): # Continue if default listener rule. if http_listener_rules[i]['IsDefault']==True: i", "ECS After Allow Test Traffic hook print(results) send_codedeploy_validation_status(event, results) return results # Returns", "http_listener_rules[i]['IsDefault']==True: i +=1 continue actions = http_listener_rules[i]['Actions'] n=0 while n<len(actions): try: for tg", "arn, actions): try: return elbv2_client.modify_rule( RuleArn=arn, Actions=actions ) except Exception as e: print(e)", ": return tg['TargetGroupArn'] except Exception as e: print(e) n +=1 i +=1 return", "0 while i < len(https_listener_rules): # Skip default rule if https_listener_rules[i]['IsDefault']==True: i +=1", "print(\"Could not identify the target arn\") return False print(\"Current HTTP target group: \")", "if modify==1: print(\"Updating SSL listener rules..\") rule_arn = https_listener_rules[i]['RuleArn'] results[rule_arn] = modify_rules(elbv2_client, rule_arn,", "initial Ready Stage. # DO NOT TRY COMPARING OLD AN NEW, SIMPLY ALWAYS", "+=1 return False def process_actions(actions, http_target_group_arn, arr_available_target_groups): modify = 0 for ak, action", "Exception as e: print(\"Recoverable Exception: \") print(e) return False def modify_rules(elbv2_client, arn, actions):", "Listener rule is updated at the initial Ready Stage. # DO NOT TRY", "print(event) region = os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups =", "modify = process_actions(actions, http_target_group_arn, arr_available_target_groups) if modify==1: print(\"Updating SSL listener rules..\") rule_arn =", "os.environ['REGION'] codedeploy_client = boto3.client('codedeploy', region_name=region) status = ('Failed', 'Succeeded')[len(results) > 0] print(status) try:", "check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except Exception as e: print(e) return (actions), modify #", "= http_listener_rules[i]['Actions'] n=0 while n<len(actions): try: for tg in actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn'] in", "found its possible the Listener rule is updated at the initial Ready Stage.", "return False def modify_rules(elbv2_client, arn, actions): try: return elbv2_client.modify_rule( RuleArn=arn, Actions=actions ) except", "Exception as e: print(e) return (actions), modify # Check old target group is", "elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_target_groups.split(',') # Get HTTP", "i +=1 return False def process_actions(actions, http_target_group_arn, arr_available_target_groups): modify = 0 for ak,", "and different. # Be wary I found its possible the Listener rule is", "< len(https_listener_rules): # Skip default rule if https_listener_rules[i]['IsDefault']==True: i +=1 continue actions =", "listener rules. https_listener_arn = os.environ['SSL_LISTENER_ARN'] https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules = https_listener['Rules'] print(\"Current HTTPS", "elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn = get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if http_target_group_arn==False: print(\"Could not identify the target", "rule_arn = https_listener_rules[i]['RuleArn'] results[rule_arn] = modify_rules(elbv2_client, rule_arn, actions) i +=1 # For ECS", "NOT TRY COMPARING OLD AN NEW, SIMPLY ALWAYS UPDATE TO MATCH HTTP IF", "actions = http_listener_rules[i]['Actions'] n=0 while n<len(actions): try: for tg in actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn']", "while i < len(https_listener_rules): # Skip default rule if https_listener_rules[i]['IsDefault']==True: i +=1 continue", "= os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_target_groups.split(',') # Get HTTP Target Group. http_listener_arn = os.environ['HTTP_LISTENER_ARN']", "# For ECS After Allow Test Traffic hook print(results) send_codedeploy_validation_status(event, results) return results", "print(e) return False def modify_rules(elbv2_client, arn, actions): try: return elbv2_client.modify_rule( RuleArn=arn, Actions=actions )", "associated w/out available target and different. # Be wary I found its possible", "not identify the target arn\") return False print(\"Current HTTP target group: \") print(http_target_group_arn)", "return (actions), modify # Check old target group is associated w/out available target", "as e: print(e) return (actions), modify # Check old target group is associated", "target group from a list of lister rules. def get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0 while", "old_target_group in arr_available_target_groups # Sends notification to CodeDeploy on hook status... def send_codedeploy_validation_status(event,", "arr_available_target_groups) print(https_target_group_arn) results = {} i = 0 while i < len(https_listener_rules): #", "codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status ) except Exception as e: print(\"Recoverable Exception: \") print(e)", "100 or tg['Weight'] is 1) : return tg['TargetGroupArn'] except Exception as e: print(e)", "for tg in actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn'] in arr_available_target_groups and (tg['Weight'] is 100 or", "return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status ) except Exception as e: print(\"Recoverable Exception: \")", "actions = https_listener_rules[i]['Actions'] actions, modify = process_actions(actions, http_target_group_arn, arr_available_target_groups) if modify==1: print(\"Updating SSL", "group from a list of lister rules. def get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0 while i", "# Get HTTP Target Group. http_listener_arn = os.environ['HTTP_LISTENER_ARN'] http_listener = elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn", "is associated w/out available target and different. # Be wary I found its", "check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for tgk, target_group in enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1", "= get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if http_target_group_arn==False: print(\"Could not identify the target arn\") return False", "HTTPS target group: \") https_target_group_arn = get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn) results = {} i", "Exception: \") print(e) return False def modify_rules(elbv2_client, arn, actions): try: return elbv2_client.modify_rule( RuleArn=arn,", "in enumerate(actions): try: if action['Type'] == \"forward\" and check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for tgk,", "Traffic hook print(results) send_codedeploy_validation_status(event, results) return results # Returns the current B/G target", "and check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for tgk, target_group in enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn", "AN NEW, SIMPLY ALWAYS UPDATE TO MATCH HTTP IF ONE OF THE AVAILABLE", "ALWAYS UPDATE TO MATCH HTTP IF ONE OF THE AVAILABLE TARGETS def check_target_update(old_target_group,", "= 0 while i < len(https_listener_rules): # Skip default rule if https_listener_rules[i]['IsDefault']==True: i", "a list of lister rules. def get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0 while i < len(http_listener_rules):", "= elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn = get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if http_target_group_arn==False: print(\"Could not identify the", "+=1 # For ECS After Allow Test Traffic hook print(results) send_codedeploy_validation_status(event, results) return", "= os.environ['HTTP_LISTENER_ARN'] http_listener = elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn = get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if http_target_group_arn==False: print(\"Could", "if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except Exception as e: print(e) return (actions), modify", "https_listener_rules[i]['RuleArn'] results[rule_arn] = modify_rules(elbv2_client, rule_arn, actions) i +=1 # For ECS After Allow", "\") print(http_target_group_arn) # Get HTTPS listener rules. https_listener_arn = os.environ['SSL_LISTENER_ARN'] https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn)", "arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for tgk, target_group in enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except", "rule_arn, actions) i +=1 # For ECS After Allow Test Traffic hook print(results)", "to CodeDeploy on hook status... def send_codedeploy_validation_status(event, results): region = os.environ['REGION'] codedeploy_client =", "After Allow Test Traffic hook print(results) send_codedeploy_validation_status(event, results) return results # Returns the", "try: return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status ) except Exception as e: print(\"Recoverable Exception:", "AVAILABLE TARGETS def check_target_update(old_target_group, arr_available_target_groups): return old_target_group in arr_available_target_groups # Sends notification to", "HTTP IF ONE OF THE AVAILABLE TARGETS def check_target_update(old_target_group, arr_available_target_groups): return old_target_group in", "print(https_target_group_arn) results = {} i = 0 while i < len(https_listener_rules): # Skip", "region = os.environ['REGION'] codedeploy_client = boto3.client('codedeploy', region_name=region) status = ('Failed', 'Succeeded')[len(results) > 0]", "rules. def get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0 while i < len(http_listener_rules): # Continue if default", "def check_target_update(old_target_group, arr_available_target_groups): return old_target_group in arr_available_target_groups # Sends notification to CodeDeploy on", "= process_actions(actions, http_target_group_arn, arr_available_target_groups) if modify==1: print(\"Updating SSL listener rules..\") rule_arn = https_listener_rules[i]['RuleArn']", "http_listener_arn = os.environ['HTTP_LISTENER_ARN'] http_listener = elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn = get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if http_target_group_arn==False:", "in actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn'] in arr_available_target_groups and (tg['Weight'] is 100 or tg['Weight'] is", "('Failed', 'Succeeded')[len(results) > 0] print(status) try: return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status ) except", "while n<len(actions): try: for tg in actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn'] in arr_available_target_groups and (tg['Weight']", "len(https_listener_rules): # Skip default rule if https_listener_rules[i]['IsDefault']==True: i +=1 continue actions = https_listener_rules[i]['Actions']", "OLD AN NEW, SIMPLY ALWAYS UPDATE TO MATCH HTTP IF ONE OF THE", "== \"forward\" and check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for tgk, target_group in enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'],", "1) : return tg['TargetGroupArn'] except Exception as e: print(e) n +=1 i +=1", "SIMPLY ALWAYS UPDATE TO MATCH HTTP IF ONE OF THE AVAILABLE TARGETS def", "except Exception as e: print(\"Recoverable Exception: \") print(e) return False def modify_rules(elbv2_client, arn,", "n +=1 i +=1 return False def process_actions(actions, http_target_group_arn, arr_available_target_groups): modify = 0", "B/G target group from a list of lister rules. def get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0", "def send_codedeploy_validation_status(event, results): region = os.environ['REGION'] codedeploy_client = boto3.client('codedeploy', region_name=region) status = ('Failed',", "False def process_actions(actions, http_target_group_arn, arr_available_target_groups): modify = 0 for ak, action in enumerate(actions):", "print(\"Updating SSL listener rules..\") rule_arn = https_listener_rules[i]['RuleArn'] results[rule_arn] = modify_rules(elbv2_client, rule_arn, actions) i", "lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status ) except Exception as e: print(\"Recoverable Exception: \") print(e) return False", "ONE OF THE AVAILABLE TARGETS def check_target_update(old_target_group, arr_available_target_groups): return old_target_group in arr_available_target_groups #", "os.environ['SSL_LISTENER_ARN'] https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules = https_listener['Rules'] print(\"Current HTTPS target group: \") https_target_group_arn", "Test Traffic hook print(results) send_codedeploy_validation_status(event, results) return results # Returns the current B/G", "actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn'] in arr_available_target_groups and (tg['Weight'] is 100 or tg['Weight'] is 1)", "i = 0 while i < len(https_listener_rules): # Skip default rule if https_listener_rules[i]['IsDefault']==True:", "# Be wary I found its possible the Listener rule is updated at", "except Exception as e: print(e) return (actions), modify # Check old target group", "+=1 continue actions = https_listener_rules[i]['Actions'] actions, modify = process_actions(actions, http_target_group_arn, arr_available_target_groups) if modify==1:", "the current B/G target group from a list of lister rules. def get_current_http_target_group(http_listener_rules,", "def lambda_handler(event, context): print(\"Trigger Event: \") print(event) region = os.environ['REGION'] elbv2_client = boto3.client('elbv2',", "group: \") https_target_group_arn = get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn) results = {} i = 0", "https_listener['Rules'] print(\"Current HTTPS target group: \") https_target_group_arn = get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn) results =", "os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_target_groups.split(',') # Get HTTP Target Group. http_listener_arn = os.environ['HTTP_LISTENER_ARN'] http_listener", "or tg['Weight'] is 1) : return tg['TargetGroupArn'] except Exception as e: print(e) n", "group: \") print(http_target_group_arn) # Get HTTPS listener rules. https_listener_arn = os.environ['SSL_LISTENER_ARN'] https_listener =", "https_target_group_arn = get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn) results = {} i = 0 while i", "try: for tg in actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn'] in arr_available_target_groups and (tg['Weight'] is 100", "modify_rules(elbv2_client, rule_arn, actions) i +=1 # For ECS After Allow Test Traffic hook", "Ready Stage. # DO NOT TRY COMPARING OLD AN NEW, SIMPLY ALWAYS UPDATE", "COMPARING OLD AN NEW, SIMPLY ALWAYS UPDATE TO MATCH HTTP IF ONE OF", "HTTPS listener rules. https_listener_arn = os.environ['SSL_LISTENER_ARN'] https_listener = elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules = https_listener['Rules'] print(\"Current", "TARGETS def check_target_update(old_target_group, arr_available_target_groups): return old_target_group in arr_available_target_groups # Sends notification to CodeDeploy", "elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules = https_listener['Rules'] print(\"Current HTTPS target group: \") https_target_group_arn = get_current_http_target_group(https_listener['Rules'], arr_available_target_groups)", "actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except Exception as e: print(e) return (actions), modify # Check old", "len(http_listener_rules): # Continue if default listener rule. if http_listener_rules[i]['IsDefault']==True: i +=1 continue actions", "modify==1: print(\"Updating SSL listener rules..\") rule_arn = https_listener_rules[i]['RuleArn'] results[rule_arn] = modify_rules(elbv2_client, rule_arn, actions)", "Get HTTP Target Group. http_listener_arn = os.environ['HTTP_LISTENER_ARN'] http_listener = elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn =", "http_listener = elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn = get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if http_target_group_arn==False: print(\"Could not identify", "region_name=region) status = ('Failed', 'Succeeded')[len(results) > 0] print(status) try: return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'],", "hook status... def send_codedeploy_validation_status(event, results): region = os.environ['REGION'] codedeploy_client = boto3.client('codedeploy', region_name=region) status", "= {} i = 0 while i < len(https_listener_rules): # Skip default rule", "target group: \") print(http_target_group_arn) # Get HTTPS listener rules. https_listener_arn = os.environ['SSL_LISTENER_ARN'] https_listener", "I found its possible the Listener rule is updated at the initial Ready", "identify the target arn\") return False print(\"Current HTTP target group: \") print(http_target_group_arn) #", "NEW, SIMPLY ALWAYS UPDATE TO MATCH HTTP IF ONE OF THE AVAILABLE TARGETS", "print(results) send_codedeploy_validation_status(event, results) return results # Returns the current B/G target group from", "tg['Weight'] is 1) : return tg['TargetGroupArn'] except Exception as e: print(e) n +=1", "Returns the current B/G target group from a list of lister rules. def", "continue actions = https_listener_rules[i]['Actions'] actions, modify = process_actions(actions, http_target_group_arn, arr_available_target_groups) if modify==1: print(\"Updating", "as e: print(e) n +=1 i +=1 return False def process_actions(actions, http_target_group_arn, arr_available_target_groups):", "https_listener_rules[i]['Actions'] actions, modify = process_actions(actions, http_target_group_arn, arr_available_target_groups) if modify==1: print(\"Updating SSL listener rules..\")", "arr_available_target_groups): i=0 while i < len(http_listener_rules): # Continue if default listener rule. if", "lambda_handler(event, context): print(\"Trigger Event: \") print(event) region = os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region)", "n=0 while n<len(actions): try: for tg in actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn'] in arr_available_target_groups and", "arr_available_target_groups = available_target_groups.split(',') # Get HTTP Target Group. http_listener_arn = os.environ['HTTP_LISTENER_ARN'] http_listener =", "print(\"Trigger Event: \") print(event) region = os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups =", "if https_listener_rules[i]['IsDefault']==True: i +=1 continue actions = https_listener_rules[i]['Actions'] actions, modify = process_actions(actions, http_target_group_arn,", "if default listener rule. if http_listener_rules[i]['IsDefault']==True: i +=1 continue actions = http_listener_rules[i]['Actions'] n=0", "modify=1 except Exception as e: print(e) return (actions), modify # Check old target", "e: print(\"Recoverable Exception: \") print(e) return False def modify_rules(elbv2_client, arn, actions): try: return", "= boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_target_groups.split(',') # Get HTTP Target", "0] print(status) try: return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status ) except Exception as e:", "+=1 continue actions = http_listener_rules[i]['Actions'] n=0 while n<len(actions): try: for tg in actions[n]['ForwardConfig']['TargetGroups']:", "import json, boto3 def lambda_handler(event, context): print(\"Trigger Event: \") print(event) region = os.environ['REGION']", "print(status) try: return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status ) except Exception as e: print(\"Recoverable", "# Check old target group is associated w/out available target and different. #", "wary I found its possible the Listener rule is updated at the initial", "< len(http_listener_rules): # Continue if default listener rule. if http_listener_rules[i]['IsDefault']==True: i +=1 continue", "available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_target_groups.split(',') # Get HTTP Target Group. http_listener_arn =", "Exception as e: print(e) n +=1 i +=1 return False def process_actions(actions, http_target_group_arn,", "Skip default rule if https_listener_rules[i]['IsDefault']==True: i +=1 continue actions = https_listener_rules[i]['Actions'] actions, modify", "actions[ak]['TargetGroupArn']=http_target_group_arn for tgk, target_group in enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except Exception", "modify_rules(elbv2_client, arn, actions): try: return elbv2_client.modify_rule( RuleArn=arn, Actions=actions ) except Exception as e:", "i +=1 continue actions = http_listener_rules[i]['Actions'] n=0 while n<len(actions): try: for tg in", "hook print(results) send_codedeploy_validation_status(event, results) return results # Returns the current B/G target group", "Target Group. http_listener_arn = os.environ['HTTP_LISTENER_ARN'] http_listener = elbv2_client.describe_rules( ListenerArn=http_listener_arn) http_target_group_arn = get_current_http_target_group(http_listener['Rules'], arr_available_target_groups)", "old target group is associated w/out available target and different. # Be wary", "= boto3.client('codedeploy', region_name=region) status = ('Failed', 'Succeeded')[len(results) > 0] print(status) try: return codedeploy_client.put_lifecycle_event_hook_execution_status(", "process_actions(actions, http_target_group_arn, arr_available_target_groups) if modify==1: print(\"Updating SSL listener rules..\") rule_arn = https_listener_rules[i]['RuleArn'] results[rule_arn]", "# Sends notification to CodeDeploy on hook status... def send_codedeploy_validation_status(event, results): region =", "for ak, action in enumerate(actions): try: if action['Type'] == \"forward\" and check_target_update(action['TargetGroupArn'], arr_available_target_groups):", "= elbv2_client.describe_rules(ListenerArn=https_listener_arn) https_listener_rules = https_listener['Rules'] print(\"Current HTTPS target group: \") https_target_group_arn = get_current_http_target_group(https_listener['Rules'],", "def get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0 while i < len(http_listener_rules): # Continue if default listener", "on hook status... def send_codedeploy_validation_status(event, results): region = os.environ['REGION'] codedeploy_client = boto3.client('codedeploy', region_name=region)", "{} i = 0 while i < len(https_listener_rules): # Skip default rule if", "def process_actions(actions, http_target_group_arn, arr_available_target_groups): modify = 0 for ak, action in enumerate(actions): try:", "print(e) n +=1 i +=1 return False def process_actions(actions, http_target_group_arn, arr_available_target_groups): modify =", "action in enumerate(actions): try: if action['Type'] == \"forward\" and check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for", "i=0 while i < len(http_listener_rules): # Continue if default listener rule. if http_listener_rules[i]['IsDefault']==True:", "i +=1 # For ECS After Allow Test Traffic hook print(results) send_codedeploy_validation_status(event, results)", "for tgk, target_group in enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except Exception as", "target and different. # Be wary I found its possible the Listener rule", "= os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_target_groups.split(',') #", "action['Type'] == \"forward\" and check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn for tgk, target_group in enumerate(action['ForwardConfig']['TargetGroups']): if", "arr_available_target_groups # Sends notification to CodeDeploy on hook status... def send_codedeploy_validation_status(event, results): region", "return False def process_actions(actions, http_target_group_arn, arr_available_target_groups): modify = 0 for ak, action in", "print(e) return (actions), modify # Check old target group is associated w/out available", "= https_listener_rules[i]['RuleArn'] results[rule_arn] = modify_rules(elbv2_client, rule_arn, actions) i +=1 # For ECS After", "e: print(e) return (actions), modify # Check old target group is associated w/out", "# DO NOT TRY COMPARING OLD AN NEW, SIMPLY ALWAYS UPDATE TO MATCH", "import os import json, boto3 def lambda_handler(event, context): print(\"Trigger Event: \") print(event) region", "ak, action in enumerate(actions): try: if action['Type'] == \"forward\" and check_target_update(action['TargetGroupArn'], arr_available_target_groups): actions[ak]['TargetGroupArn']=http_target_group_arn", "as e: print(\"Recoverable Exception: \") print(e) return False def modify_rules(elbv2_client, arn, actions): try:", "modify = 0 for ak, action in enumerate(actions): try: if action['Type'] == \"forward\"", "i < len(http_listener_rules): # Continue if default listener rule. if http_listener_rules[i]['IsDefault']==True: i +=1", "n<len(actions): try: for tg in actions[n]['ForwardConfig']['TargetGroups']: if tg['TargetGroupArn'] in arr_available_target_groups and (tg['Weight'] is", "boto3 def lambda_handler(event, context): print(\"Trigger Event: \") print(event) region = os.environ['REGION'] elbv2_client =", "status = ('Failed', 'Succeeded')[len(results) > 0] print(status) try: return codedeploy_client.put_lifecycle_event_hook_execution_status( deploymentId=event['DeploymentId'], lifecycleEventHookExecutionId=event['LifecycleEventHookExecutionId'], status=status", "http_target_group_arn = get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if http_target_group_arn==False: print(\"Could not identify the target arn\") return", "region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_target_groups.split(',') # Get HTTP Target Group. http_listener_arn", "get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn) results = {} i = 0 while i < len(https_listener_rules):", "arr_available_target_groups): return old_target_group in arr_available_target_groups # Sends notification to CodeDeploy on hook status...", "For ECS After Allow Test Traffic hook print(results) send_codedeploy_validation_status(event, results) return results #", "target group: \") https_target_group_arn = get_current_http_target_group(https_listener['Rules'], arr_available_target_groups) print(https_target_group_arn) results = {} i =", "process_actions(actions, http_target_group_arn, arr_available_target_groups): modify = 0 for ak, action in enumerate(actions): try: if", "if http_target_group_arn==False: print(\"Could not identify the target arn\") return False print(\"Current HTTP target", "get_current_http_target_group(http_listener['Rules'], arr_available_target_groups) if http_target_group_arn==False: print(\"Could not identify the target arn\") return False print(\"Current", "is 100 or tg['Weight'] is 1) : return tg['TargetGroupArn'] except Exception as e:", "return False print(\"Current HTTP target group: \") print(http_target_group_arn) # Get HTTPS listener rules.", "updated at the initial Ready Stage. # DO NOT TRY COMPARING OLD AN", "lister rules. def get_current_http_target_group(http_listener_rules, arr_available_target_groups): i=0 while i < len(http_listener_rules): # Continue if", "i +=1 continue actions = https_listener_rules[i]['Actions'] actions, modify = process_actions(actions, http_target_group_arn, arr_available_target_groups) if", "in enumerate(action['ForwardConfig']['TargetGroups']): if check_target_update(target_group['TargetGroupArn'], arr_available_target_groups): actions[ak]['ForwardConfig']['TargetGroups'][tgk]['TargetGroupArn']=http_target_group_arn modify=1 except Exception as e: print(e) return", "is updated at the initial Ready Stage. # DO NOT TRY COMPARING OLD", "is 1) : return tg['TargetGroupArn'] except Exception as e: print(e) n +=1 i" ]
[ "of the models' training sets import numpy as np import sys import scipy", "demos_count[label][d]+=matrix[t,col] for d in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len)) for c in demo_counts.keys():", "filename} + case + control + '.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len print", "analysis, applications, and interpretation of electronic health record-based stroke phenotyping methods\" #This script", "models' training sets import numpy as np import sys import scipy as sp", "case=cases[i] control=controls[i] filename_labels={training_set labels filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics events filenames}", "phenotyping methods\" #This script prints out the demographics of all of the models'", "filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics events filenames} + case + control + '.npy'", "+ control + '.npy' demo_events=np.load(filename_all) filename_mtrain={training_set sparse matrix filename} + case + control", "case + control + '.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len for", "#This script prints out the demographics of all of the models' training sets", "control + '.npy' demo_events=np.load(filename_all) filename_mtrain={training_set sparse matrix filename} + case + control +", "d=='American Indian' or d=='Pacific Islander' or d=='Asian': demos_count[label]['other']+=matrix[t,col] elif d=='U': demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col]", "d in demo_events: col=e2c[d] if d=='American Indian' or d=='Pacific Islander' or d=='Asian': demos_count[label]['other']+=matrix[t,col]", "filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics events filenames} + case + control", "+ '.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len for t in range(0,len(labels)):", "filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics events filenames} + case + control + '.npy' demo_events=np.load(filename_all)", "case + control + '.npy' demo_events=np.load(filename_all) filename_mtrain={training_set sparse matrix filename} + case +", "applications, and interpretation of electronic health record-based stroke phenotyping methods\" #This script prints", "Center #Part of manuscript: \"Comparative analysis, applications, and interpretation of electronic health record-based", "methods\" #This script prints out the demographics of all of the models' training", "demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len)) for c in demo_counts.keys(): for d in demo_counts[c]:", "<NAME> (<EMAIL>), <NAME> Lab at Columbia University Irving Medical Center #Part of manuscript:", "or d=='Pacific Islander' or d=='Asian': demos_count[label]['other']+=matrix[t,col] elif d=='U': demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col] for d", "import csr_matrix from collections import defaultdict demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for", "filename_labels={training_set labels filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics events filenames} + case", "'.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len for t in range(0,len(labels)): label=labels[t]", "for i in range(0,15): case=cases[i] control=controls[i] filename_labels={training_set labels filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i)", "scipy as sp from scipy.sparse import csr_matrix from collections import defaultdict demo_counts=defaultdict(lambda: defaultdict(list))", "e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics events filenames} + case + control + '.npy' demo_events=np.load(filename_all) filename_mtrain={training_set", "demographics of all of the models' training sets import numpy as np import", "from scipy.sparse import csr_matrix from collections import defaultdict demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C']", "manuscript: \"Comparative analysis, applications, and interpretation of electronic health record-based stroke phenotyping methods\"", "control=controls[i] filename_labels={training_set labels filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics events filenames} +", "i in range(0,15): case=cases[i] control=controls[i] filename_labels={training_set labels filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()]", "ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len for t in range(0,len(labels)): label=labels[t] for d in demo_events: col=e2c[d]", "electronic health record-based stroke phenotyping methods\" #This script prints out the demographics of", "as sp from scipy.sparse import csr_matrix from collections import defaultdict demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda:", "+ '.npy' demo_events=np.load(filename_all) filename_mtrain={training_set sparse matrix filename} + case + control + '.npz'", "d=='Asian': demos_count[label]['other']+=matrix[t,col] elif d=='U': demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col] for d in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d])", "+ case + control + '.npy' demo_events=np.load(filename_all) filename_mtrain={training_set sparse matrix filename} + case", "Islander' or d=='Asian': demos_count[label]['other']+=matrix[t,col] elif d=='U': demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col] for d in demos_count[1].keys():", "(<EMAIL>), <NAME> Lab at Columbia University Irving Medical Center #Part of manuscript: \"Comparative", "sys import scipy as sp from scipy.sparse import csr_matrix from collections import defaultdict", "defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len for t in range(0,len(labels)): label=labels[t] for d in", "#Part of manuscript: \"Comparative analysis, applications, and interpretation of electronic health record-based stroke", "health record-based stroke phenotyping methods\" #This script prints out the demographics of all", "collections import defaultdict demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i in range(0,15):", "demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len)) for c in demo_counts.keys(): for d in demo_counts[c]: print c,d,demo_counts[c][d],demo_freqs[c][d]", "cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i in range(0,15): case=cases[i] control=controls[i] filename_labels={training_set labels filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols", "defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i in range(0,15): case=cases[i] control=controls[i] filename_labels={training_set labels filename}+case+control+'.npy' labels=np.load(filename_labels)", "elif d=='U': demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col] for d in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len))", "of manuscript: \"Comparative analysis, applications, and interpretation of electronic health record-based stroke phenotyping", "demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i in range(0,15): case=cases[i] control=controls[i] filename_labels={training_set", "#By <NAME> (<EMAIL>), <NAME> Lab at Columbia University Irving Medical Center #Part of", "e2c=e2c[()] filename_all={demographics events filenames} + case + control + '.npy' demo_events=np.load(filename_all) filename_mtrain={training_set sparse", "print case,control,case_len,ctrl_len for t in range(0,len(labels)): label=labels[t] for d in demo_events: col=e2c[d] if", "prints out the demographics of all of the models' training sets import numpy", "scipy.sparse import csr_matrix from collections import defaultdict demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R']", "+ control + '.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len for t", "Medical Center #Part of manuscript: \"Comparative analysis, applications, and interpretation of electronic health", "<NAME> Lab at Columbia University Irving Medical Center #Part of manuscript: \"Comparative analysis,", "case,control,case_len,ctrl_len for t in range(0,len(labels)): label=labels[t] for d in demo_events: col=e2c[d] if d=='American", "the models' training sets import numpy as np import sys import scipy as", "the demographics of all of the models' training sets import numpy as np", "Indian' or d=='Pacific Islander' or d=='Asian': demos_count[label]['other']+=matrix[t,col] elif d=='U': demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col] for", "Irving Medical Center #Part of manuscript: \"Comparative analysis, applications, and interpretation of electronic", "sp from scipy.sparse import csr_matrix from collections import defaultdict demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list))", "University Irving Medical Center #Part of manuscript: \"Comparative analysis, applications, and interpretation of", "filename_mtrain={training_set sparse matrix filename} + case + control + '.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int))", "interpretation of electronic health record-based stroke phenotyping methods\" #This script prints out the", "+ case + control + '.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len", "sets import numpy as np import sys import scipy as sp from scipy.sparse", "and interpretation of electronic health record-based stroke phenotyping methods\" #This script prints out", "from collections import defaultdict demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i in", "numpy as np import sys import scipy as sp from scipy.sparse import csr_matrix", "filename_all={demographics events filenames} + case + control + '.npy' demo_events=np.load(filename_all) filename_mtrain={training_set sparse matrix", "matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len for t in range(0,len(labels)): label=labels[t] for", "of electronic health record-based stroke phenotyping methods\" #This script prints out the demographics", "demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len for t in range(0,len(labels)): label=labels[t] for d", "import numpy as np import sys import scipy as sp from scipy.sparse import", "col=e2c[d] if d=='American Indian' or d=='Pacific Islander' or d=='Asian': demos_count[label]['other']+=matrix[t,col] elif d=='U': demos_count[label]['Unknown']+=matrix[t,col]", "import defaultdict demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i in range(0,15): case=cases[i]", "sparse matrix filename} + case + control + '.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels)", "defaultdict demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i in range(0,15): case=cases[i] control=controls[i]", "out the demographics of all of the models' training sets import numpy as", "range(0,len(labels)): label=labels[t] for d in demo_events: col=e2c[d] if d=='American Indian' or d=='Pacific Islander'", "labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics events filenames} + case + control +", "demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i in range(0,15): case=cases[i] control=controls[i] filename_labels={training_set labels filename}+case+control+'.npy'", "defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i in range(0,15): case=cases[i] control=controls[i] filename_labels={training_set labels", "labels filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics events filenames} + case +", "\"Comparative analysis, applications, and interpretation of electronic health record-based stroke phenotyping methods\" #This", "in range(0,15): case=cases[i] control=controls[i] filename_labels={training_set labels filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics", "demo_events=np.load(filename_all) filename_mtrain={training_set sparse matrix filename} + case + control + '.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda:", "demos_count[label]['other']+=matrix[t,col] elif d=='U': demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col] for d in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len))", "import scipy as sp from scipy.sparse import csr_matrix from collections import defaultdict demo_counts=defaultdict(lambda:", "case_len=np.sum(labels) ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len for t in range(0,len(labels)): label=labels[t] for d in demo_events:", "'.npy' demo_events=np.load(filename_all) filename_mtrain={training_set sparse matrix filename} + case + control + '.npz' matrix=sp.sparse.load_npz(filename_mtrain)", "d=='U': demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col] for d in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len)) for", "script prints out the demographics of all of the models' training sets import", "Lab at Columbia University Irving Medical Center #Part of manuscript: \"Comparative analysis, applications,", "import sys import scipy as sp from scipy.sparse import csr_matrix from collections import", "all of the models' training sets import numpy as np import sys import", "csr_matrix from collections import defaultdict demo_counts=defaultdict(lambda: defaultdict(list)) demo_freqs=defaultdict(lambda: defaultdict(list)) cases=['G','G','G','G','G','T','T','T','T','T','C','C','C','C','C'] controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i", "or d=='Asian': demos_count[label]['other']+=matrix[t,col] elif d=='U': demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col] for d in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d])", "record-based stroke phenotyping methods\" #This script prints out the demographics of all of", "label=labels[t] for d in demo_events: col=e2c[d] if d=='American Indian' or d=='Pacific Islander' or", "of all of the models' training sets import numpy as np import sys", "in demo_events: col=e2c[d] if d=='American Indian' or d=='Pacific Islander' or d=='Asian': demos_count[label]['other']+=matrix[t,col] elif", "matrix filename} + case + control + '.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len", "else: demos_count[label][d]+=matrix[t,col] for d in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len)) for c in", "d=='Pacific Islander' or d=='Asian': demos_count[label]['other']+=matrix[t,col] elif d=='U': demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col] for d in", "for d in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len)) for c in demo_counts.keys(): for", "at Columbia University Irving Medical Center #Part of manuscript: \"Comparative analysis, applications, and", "if d=='American Indian' or d=='Pacific Islander' or d=='Asian': demos_count[label]['other']+=matrix[t,col] elif d=='U': demos_count[label]['Unknown']+=matrix[t,col] else:", "controls=['N','I','C','CI','R','N','I','C','CI','R','N','I','C','CI','R'] for i in range(0,15): case=cases[i] control=controls[i] filename_labels={training_set labels filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy'", "control + '.npz' matrix=sp.sparse.load_npz(filename_mtrain) demos_count=defaultdict(lambda: defaultdict(int)) case_len=np.sum(labels) ctrl_len=len(labels)-case_len print case,control,case_len,ctrl_len for t in", "as np import sys import scipy as sp from scipy.sparse import csr_matrix from", "np import sys import scipy as sp from scipy.sparse import csr_matrix from collections", "for t in range(0,len(labels)): label=labels[t] for d in demo_events: col=e2c[d] if d=='American Indian'", "in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len)) for c in demo_counts.keys(): for d in", "in range(0,len(labels)): label=labels[t] for d in demo_events: col=e2c[d] if d=='American Indian' or d=='Pacific", "t in range(0,len(labels)): label=labels[t] for d in demo_events: col=e2c[d] if d=='American Indian' or", "filenames} + case + control + '.npy' demo_events=np.load(filename_all) filename_mtrain={training_set sparse matrix filename} +", "demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len)) for c in demo_counts.keys(): for d in demo_counts[c]: print", "for d in demo_events: col=e2c[d] if d=='American Indian' or d=='Pacific Islander' or d=='Asian':", "demo_events: col=e2c[d] if d=='American Indian' or d=='Pacific Islander' or d=='Asian': demos_count[label]['other']+=matrix[t,col] elif d=='U':", "d in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len)) for c in demo_counts.keys(): for d", "training sets import numpy as np import sys import scipy as sp from", "demos_count[label]['Unknown']+=matrix[t,col] else: demos_count[label][d]+=matrix[t,col] for d in demos_count[1].keys(): demo_counts[case+'ca'][d].append(demos_count[1][d]) demo_counts[control+'co'][d].append(demos_count[0][d]) demo_freqs[case+'ca'][d].append(demos_count[1][d]/float(case_len)) demo_freqs[control+'co'][d].append(demos_count[0][d]/float(ctrl_len)) for c", "stroke phenotyping methods\" #This script prints out the demographics of all of the", "range(0,15): case=cases[i] control=controls[i] filename_labels={training_set labels filename}+case+control+'.npy' labels=np.load(filename_labels) filename_e2i={events2cols filename}+case+control+'.npy' e2c=np.load(filename_e2i) e2c=e2c[()] filename_all={demographics events", "Columbia University Irving Medical Center #Part of manuscript: \"Comparative analysis, applications, and interpretation", "events filenames} + case + control + '.npy' demo_events=np.load(filename_all) filename_mtrain={training_set sparse matrix filename}" ]
[ "if resp.status == 200: j = await resp.json() if j['status'] == 'OK': return", "print('WorldTime Location Key Error') raise else: return search async def get_time(self, location: Location)", "def __init__(self, time: datetime, timezone_id: str, timezone_name: str): self.time = time self.timezone_id =", "resp.json() if j['status'] == 'OK': return j elif j['status'] == 'ZERO_RESULTS': return None", "j['status'] == 'OK': return j elif j['status'] == 'ZERO_RESULTS': return None return False", "c not in allowed_chars and not c.isalnum(): text = text.replace(c, '%' + hex(ord(c))[2:])", "async def get_location(self, query: str) -> Location: args = {'address': self.query_encode(query), 'key': self.key}", "time self.timezone_id = timezone_id self.timezone_name = timezone_name class WorldTime: def __init__(self, key: str):", "else: return search @staticmethod async def api_get(url: str) -> dict: with aiohttp.ClientSession() as", "for k, v in options.items(): out += '{}={}&'.format(k, v) out = out[:-1] return", "= long class Time: def __init__(self, time: datetime, timezone_id: str, timezone_name: str): self.time", "key: str): self.key = key async def get_location(self, query: str) -> Location: args", "API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars = [',', '%', '+', '-'] class Location: def __init__(self,", "Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except KeyError: print('WorldTime Time Key Error') raise else: return search", "None return False @staticmethod def query_encode(text: str) -> str: text = ' '.join(text.split())", "query_encode(text: str) -> str: text = ' '.join(text.split()) text = text.replace(' ', '+')", "import datetime API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars = [',', '%', '+',", "= [',', '%', '+', '-'] class Location: def __init__(self, address: str, lat: int", "= search['results'][0] location = Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return location except KeyError: print('WorldTime Location", "for c in text: if c not in allowed_chars and not c.isalnum(): text", "location = Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return location except KeyError: print('WorldTime Location Key Error')", "text = text.replace(c, '%' + hex(ord(c))[2:]) return text @staticmethod def param_encode(options: dict) ->", "address self.latitude = lat self.longitude = long class Time: def __init__(self, time: datetime,", "KeyError: print('WorldTime Location Key Error') raise else: return search async def get_time(self, location:", "print('WorldTime Time Key Error') raise else: return search @staticmethod async def api_get(url: str)", "address: str, lat: int = None, long: int = None): self.address = address", "str, lat: int = None, long: int = None): self.address = address self.latitude", "self.address = address self.latitude = lat self.longitude = long class Time: def __init__(self,", "by CantSayIHave # Created 2018/01/12 # # Fetch time and date from a", "'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars = [',', '%', '+', '-'] class Location: def __init__(self, address: str,", "= None, long: int = None): self.address = address self.latitude = lat self.longitude", "as session: async with session.get(url) as resp: if resp.status == 200: j =", "'+') for c in text: if c not in allowed_chars and not c.isalnum():", "lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return location except KeyError: print('WorldTime Location Key Error') raise else: return", "Fetch time and date from a location # Uses Google Geocoding API and", "= key async def get_location(self, query: str) -> Location: args = {'address': self.query_encode(query),", "text = ' '.join(text.split()) text = text.replace(' ', '+') for c in text:", "query: str) -> Location: args = {'address': self.query_encode(query), 'key': self.key} url = API_GEOCODE", "class WorldTime: def __init__(self, key: str): self.key = key async def get_location(self, query:", "if j['status'] == 'OK': return j elif j['status'] == 'ZERO_RESULTS': return None return", "location_time = unix_now + search['rawOffset'] + search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except KeyError:", "= API_GEOCODE + self.param_encode(args) search = await self.api_get(url) if search: try: result =", "return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except KeyError: print('WorldTime Time Key Error') raise else: return", "dict: with aiohttp.ClientSession() as session: async with session.get(url) as resp: if resp.status ==", "def get_location(self, query: str) -> Location: args = {'address': self.query_encode(query), 'key': self.key} url", "'ZERO_RESULTS': return None return False @staticmethod def query_encode(text: str) -> str: text =", "# # Fetch time and date from a location # Uses Google Geocoding", "'' for k, v in options.items(): out += '{}={}&'.format(k, v) out = out[:-1]", "str, timezone_name: str): self.time = time self.timezone_id = timezone_id self.timezone_name = timezone_name class", "int(time.time()) args = {'location': '{},{}'.format(location.latitude, location.longitude), 'timestamp': unix_now, 'key': self.key} url = API_TIMEZONE", "lat self.longitude = long class Time: def __init__(self, time: datetime, timezone_id: str, timezone_name:", "in text: if c not in allowed_chars and not c.isalnum(): text = text.replace(c,", "from datetime import datetime API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars = [',',", "location: Location) -> Time: unix_now = int(time.time()) args = {'location': '{},{}'.format(location.latitude, location.longitude), 'timestamp':", "= API_TIMEZONE + self.param_encode(args) search = await self.api_get(url) if search: try: location_time =", "resp.status == 200: j = await resp.json() if j['status'] == 'OK': return j", "= unix_now + search['rawOffset'] + search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except KeyError: print('WorldTime", "WorldTime: def __init__(self, key: str): self.key = key async def get_location(self, query: str)", "2018/01/12 # # Fetch time and date from a location # Uses Google", "Error') raise else: return search @staticmethod async def api_get(url: str) -> dict: with", "j = await resp.json() if j['status'] == 'OK': return j elif j['status'] ==", "not in allowed_chars and not c.isalnum(): text = text.replace(c, '%' + hex(ord(c))[2:]) return", "+ hex(ord(c))[2:]) return text @staticmethod def param_encode(options: dict) -> str: out = ''", "raise else: return search async def get_time(self, location: Location) -> Time: unix_now =", "self.api_get(url) if search: try: location_time = unix_now + search['rawOffset'] + search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time),", "aiohttp.ClientSession() as session: async with session.get(url) as resp: if resp.status == 200: j", "False @staticmethod def query_encode(text: str) -> str: text = ' '.join(text.split()) text =", "def __init__(self, key: str): self.key = key async def get_location(self, query: str) ->", "= await self.api_get(url) if search: try: result = search['results'][0] location = Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'],", "search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except KeyError: print('WorldTime Time Key Error') raise else:", "'%' + hex(ord(c))[2:]) return text @staticmethod def param_encode(options: dict) -> str: out =", "if c not in allowed_chars and not c.isalnum(): text = text.replace(c, '%' +", "class Time: def __init__(self, time: datetime, timezone_id: str, timezone_name: str): self.time = time", "long class Time: def __init__(self, time: datetime, timezone_id: str, timezone_name: str): self.time =", "+ search['rawOffset'] + search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except KeyError: print('WorldTime Time Key", "# Created 2018/01/12 # # Fetch time and date from a location #", "', '+') for c in text: if c not in allowed_chars and not", "+ self.param_encode(args) search = await self.api_get(url) if search: try: result = search['results'][0] location", "= 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars = [',', '%', '+', '-'] class Location: def __init__(self, address:", "self.param_encode(args) search = await self.api_get(url) if search: try: result = search['results'][0] location =", "unix_now, 'key': self.key} url = API_TIMEZONE + self.param_encode(args) search = await self.api_get(url) if", "allowed_chars = [',', '%', '+', '-'] class Location: def __init__(self, address: str, lat:", "datetime, timezone_id: str, timezone_name: str): self.time = time self.timezone_id = timezone_id self.timezone_name =", "return location except KeyError: print('WorldTime Location Key Error') raise else: return search async", "timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except KeyError: print('WorldTime Time Key Error') raise else: return search @staticmethod", "= await self.api_get(url) if search: try: location_time = unix_now + search['rawOffset'] + search['dstOffset']", "Geocoding API and Google Time Zone API import aiohttp import time from datetime", "search @staticmethod async def api_get(url: str) -> dict: with aiohttp.ClientSession() as session: async", "def get_time(self, location: Location) -> Time: unix_now = int(time.time()) args = {'location': '{},{}'.format(location.latitude,", "self.timezone_id = timezone_id self.timezone_name = timezone_name class WorldTime: def __init__(self, key: str): self.key", "Zone API import aiohttp import time from datetime import datetime API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?'", "search = await self.api_get(url) if search: try: result = search['results'][0] location = Location(address=result['formatted_address'],", "API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars = [',', '%', '+', '-'] class", "try: result = search['results'][0] location = Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return location except KeyError:", "out = '' for k, v in options.items(): out += '{}={}&'.format(k, v) out", "str) -> dict: with aiohttp.ClientSession() as session: async with session.get(url) as resp: if", "# worldtime module by CantSayIHave # Created 2018/01/12 # # Fetch time and", "get_time(self, location: Location) -> Time: unix_now = int(time.time()) args = {'location': '{},{}'.format(location.latitude, location.longitude),", "API import aiohttp import time from datetime import datetime API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE", "if search: try: result = search['results'][0] location = Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return location", "Uses Google Geocoding API and Google Time Zone API import aiohttp import time", "Location Key Error') raise else: return search async def get_time(self, location: Location) ->", "j elif j['status'] == 'ZERO_RESULTS': return None return False @staticmethod def query_encode(text: str)", "self.key = key async def get_location(self, query: str) -> Location: args = {'address':", "== 200: j = await resp.json() if j['status'] == 'OK': return j elif", "'.join(text.split()) text = text.replace(' ', '+') for c in text: if c not", "str: out = '' for k, v in options.items(): out += '{}={}&'.format(k, v)", "with session.get(url) as resp: if resp.status == 200: j = await resp.json() if", "return search async def get_time(self, location: Location) -> Time: unix_now = int(time.time()) args", "param_encode(options: dict) -> str: out = '' for k, v in options.items(): out", "search: try: result = search['results'][0] location = Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return location except", "import time from datetime import datetime API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars", "async def get_time(self, location: Location) -> Time: unix_now = int(time.time()) args = {'location':", "Time Zone API import aiohttp import time from datetime import datetime API_GEOCODE =", "date from a location # Uses Google Geocoding API and Google Time Zone", "except KeyError: print('WorldTime Location Key Error') raise else: return search async def get_time(self,", "self.query_encode(query), 'key': self.key} url = API_GEOCODE + self.param_encode(args) search = await self.api_get(url) if", "__init__(self, key: str): self.key = key async def get_location(self, query: str) -> Location:", "c in text: if c not in allowed_chars and not c.isalnum(): text =", "api_get(url: str) -> dict: with aiohttp.ClientSession() as session: async with session.get(url) as resp:", "aiohttp import time from datetime import datetime API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?'", "search = await self.api_get(url) if search: try: location_time = unix_now + search['rawOffset'] +", "c.isalnum(): text = text.replace(c, '%' + hex(ord(c))[2:]) return text @staticmethod def param_encode(options: dict)", "-> str: out = '' for k, v in options.items(): out += '{}={}&'.format(k,", "Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return location except KeyError: print('WorldTime Location Key Error') raise else:", "__init__(self, address: str, lat: int = None, long: int = None): self.address =", "Error') raise else: return search async def get_time(self, location: Location) -> Time: unix_now", "= {'location': '{},{}'.format(location.latitude, location.longitude), 'timestamp': unix_now, 'key': self.key} url = API_TIMEZONE + self.param_encode(args)", "# Uses Google Geocoding API and Google Time Zone API import aiohttp import", "session: async with session.get(url) as resp: if resp.status == 200: j = await", "text.replace(' ', '+') for c in text: if c not in allowed_chars and", "from a location # Uses Google Geocoding API and Google Time Zone API", "await self.api_get(url) if search: try: result = search['results'][0] location = Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng'])", "text: if c not in allowed_chars and not c.isalnum(): text = text.replace(c, '%'", "Google Geocoding API and Google Time Zone API import aiohttp import time from", "API and Google Time Zone API import aiohttp import time from datetime import", "'key': self.key} url = API_GEOCODE + self.param_encode(args) search = await self.api_get(url) if search:", "search async def get_time(self, location: Location) -> Time: unix_now = int(time.time()) args =", "session.get(url) as resp: if resp.status == 200: j = await resp.json() if j['status']", "self.time = time self.timezone_id = timezone_id self.timezone_name = timezone_name class WorldTime: def __init__(self,", "j['status'] == 'ZERO_RESULTS': return None return False @staticmethod def query_encode(text: str) -> str:", "and Google Time Zone API import aiohttp import time from datetime import datetime", "Location: args = {'address': self.query_encode(query), 'key': self.key} url = API_GEOCODE + self.param_encode(args) search", "200: j = await resp.json() if j['status'] == 'OK': return j elif j['status']", "= time self.timezone_id = timezone_id self.timezone_name = timezone_name class WorldTime: def __init__(self, key:", "dict) -> str: out = '' for k, v in options.items(): out +=", "self.param_encode(args) search = await self.api_get(url) if search: try: location_time = unix_now + search['rawOffset']", "self.key} url = API_GEOCODE + self.param_encode(args) search = await self.api_get(url) if search: try:", "CantSayIHave # Created 2018/01/12 # # Fetch time and date from a location", "Created 2018/01/12 # # Fetch time and date from a location # Uses", "[',', '%', '+', '-'] class Location: def __init__(self, address: str, lat: int =", "self.timezone_name = timezone_name class WorldTime: def __init__(self, key: str): self.key = key async", "return j elif j['status'] == 'ZERO_RESULTS': return None return False @staticmethod def query_encode(text:", "-> str: text = ' '.join(text.split()) text = text.replace(' ', '+') for c", "int = None): self.address = address self.latitude = lat self.longitude = long class", "= ' '.join(text.split()) text = text.replace(' ', '+') for c in text: if", "args = {'address': self.query_encode(query), 'key': self.key} url = API_GEOCODE + self.param_encode(args) search =", "= text.replace(' ', '+') for c in text: if c not in allowed_chars", "search: try: location_time = unix_now + search['rawOffset'] + search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName'])", "and date from a location # Uses Google Geocoding API and Google Time", "= '' for k, v in options.items(): out += '{}={}&'.format(k, v) out =", "def param_encode(options: dict) -> str: out = '' for k, v in options.items():", "with aiohttp.ClientSession() as session: async with session.get(url) as resp: if resp.status == 200:", "url = API_GEOCODE + self.param_encode(args) search = await self.api_get(url) if search: try: result", "lat: int = None, long: int = None): self.address = address self.latitude =", "class Location: def __init__(self, address: str, lat: int = None, long: int =", "-> dict: with aiohttp.ClientSession() as session: async with session.get(url) as resp: if resp.status", "async def api_get(url: str) -> dict: with aiohttp.ClientSession() as session: async with session.get(url)", "location except KeyError: print('WorldTime Location Key Error') raise else: return search async def", "timezone_name=search['timeZoneName']) except KeyError: print('WorldTime Time Key Error') raise else: return search @staticmethod async", "worldtime module by CantSayIHave # Created 2018/01/12 # # Fetch time and date", "'timestamp': unix_now, 'key': self.key} url = API_TIMEZONE + self.param_encode(args) search = await self.api_get(url)", "str) -> Location: args = {'address': self.query_encode(query), 'key': self.key} url = API_GEOCODE +", "__init__(self, time: datetime, timezone_id: str, timezone_name: str): self.time = time self.timezone_id = timezone_id", "Time: def __init__(self, time: datetime, timezone_id: str, timezone_name: str): self.time = time self.timezone_id", "unix_now = int(time.time()) args = {'location': '{},{}'.format(location.latitude, location.longitude), 'timestamp': unix_now, 'key': self.key} url", "= timezone_name class WorldTime: def __init__(self, key: str): self.key = key async def", "import aiohttp import time from datetime import datetime API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE =", "@staticmethod async def api_get(url: str) -> dict: with aiohttp.ClientSession() as session: async with", "text.replace(c, '%' + hex(ord(c))[2:]) return text @staticmethod def param_encode(options: dict) -> str: out", "return text @staticmethod def param_encode(options: dict) -> str: out = '' for k,", "None): self.address = address self.latitude = lat self.longitude = long class Time: def", "timezone_id: str, timezone_name: str): self.time = time self.timezone_id = timezone_id self.timezone_name = timezone_name", "else: return search async def get_time(self, location: Location) -> Time: unix_now = int(time.time())", "@staticmethod def query_encode(text: str) -> str: text = ' '.join(text.split()) text = text.replace('", "await resp.json() if j['status'] == 'OK': return j elif j['status'] == 'ZERO_RESULTS': return", "text @staticmethod def param_encode(options: dict) -> str: out = '' for k, v", "try: location_time = unix_now + search['rawOffset'] + search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except", "await self.api_get(url) if search: try: location_time = unix_now + search['rawOffset'] + search['dstOffset'] return", "async with session.get(url) as resp: if resp.status == 200: j = await resp.json()", "API_GEOCODE + self.param_encode(args) search = await self.api_get(url) if search: try: result = search['results'][0]", "datetime API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars = [',', '%', '+', '-']", "@staticmethod def param_encode(options: dict) -> str: out = '' for k, v in", "'OK': return j elif j['status'] == 'ZERO_RESULTS': return None return False @staticmethod def", "a location # Uses Google Geocoding API and Google Time Zone API import", "url = API_TIMEZONE + self.param_encode(args) search = await self.api_get(url) if search: try: location_time", "allowed_chars and not c.isalnum(): text = text.replace(c, '%' + hex(ord(c))[2:]) return text @staticmethod", "def __init__(self, address: str, lat: int = None, long: int = None): self.address", "location # Uses Google Geocoding API and Google Time Zone API import aiohttp", "'{},{}'.format(location.latitude, location.longitude), 'timestamp': unix_now, 'key': self.key} url = API_TIMEZONE + self.param_encode(args) search =", "'key': self.key} url = API_TIMEZONE + self.param_encode(args) search = await self.api_get(url) if search:", "not c.isalnum(): text = text.replace(c, '%' + hex(ord(c))[2:]) return text @staticmethod def param_encode(options:", "Time Key Error') raise else: return search @staticmethod async def api_get(url: str) ->", "long=result['geometry']['location']['lng']) return location except KeyError: print('WorldTime Location Key Error') raise else: return search", "def api_get(url: str) -> dict: with aiohttp.ClientSession() as session: async with session.get(url) as", "str): self.key = key async def get_location(self, query: str) -> Location: args =", "elif j['status'] == 'ZERO_RESULTS': return None return False @staticmethod def query_encode(text: str) ->", "'+', '-'] class Location: def __init__(self, address: str, lat: int = None, long:", "as resp: if resp.status == 200: j = await resp.json() if j['status'] ==", "= text.replace(c, '%' + hex(ord(c))[2:]) return text @staticmethod def param_encode(options: dict) -> str:", "== 'OK': return j elif j['status'] == 'ZERO_RESULTS': return None return False @staticmethod", "unix_now + search['rawOffset'] + search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except KeyError: print('WorldTime Time", "timezone_name class WorldTime: def __init__(self, key: str): self.key = key async def get_location(self,", "{'location': '{},{}'.format(location.latitude, location.longitude), 'timestamp': unix_now, 'key': self.key} url = API_TIMEZONE + self.param_encode(args) search", "args = {'location': '{},{}'.format(location.latitude, location.longitude), 'timestamp': unix_now, 'key': self.key} url = API_TIMEZONE +", "get_location(self, query: str) -> Location: args = {'address': self.query_encode(query), 'key': self.key} url =", "self.key} url = API_TIMEZONE + self.param_encode(args) search = await self.api_get(url) if search: try:", "hex(ord(c))[2:]) return text @staticmethod def param_encode(options: dict) -> str: out = '' for", "long: int = None): self.address = address self.latitude = lat self.longitude = long", "' '.join(text.split()) text = text.replace(' ', '+') for c in text: if c", "Key Error') raise else: return search @staticmethod async def api_get(url: str) -> dict:", "= await resp.json() if j['status'] == 'OK': return j elif j['status'] == 'ZERO_RESULTS':", "except KeyError: print('WorldTime Time Key Error') raise else: return search @staticmethod async def", "self.api_get(url) if search: try: result = search['results'][0] location = Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return", "in allowed_chars and not c.isalnum(): text = text.replace(c, '%' + hex(ord(c))[2:]) return text", "module by CantSayIHave # Created 2018/01/12 # # Fetch time and date from", "resp: if resp.status == 200: j = await resp.json() if j['status'] == 'OK':", "return None return False @staticmethod def query_encode(text: str) -> str: text = '", "str: text = ' '.join(text.split()) text = text.replace(' ', '+') for c in", "if search: try: location_time = unix_now + search['rawOffset'] + search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'],", "timezone_name: str): self.time = time self.timezone_id = timezone_id self.timezone_name = timezone_name class WorldTime:", "search['rawOffset'] + search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except KeyError: print('WorldTime Time Key Error')", "self.longitude = long class Time: def __init__(self, time: datetime, timezone_id: str, timezone_name: str):", "Time: unix_now = int(time.time()) args = {'location': '{},{}'.format(location.latitude, location.longitude), 'timestamp': unix_now, 'key': self.key}", "time: datetime, timezone_id: str, timezone_name: str): self.time = time self.timezone_id = timezone_id self.timezone_name", "KeyError: print('WorldTime Time Key Error') raise else: return search @staticmethod async def api_get(url:", "-> Time: unix_now = int(time.time()) args = {'location': '{},{}'.format(location.latitude, location.longitude), 'timestamp': unix_now, 'key':", "datetime import datetime API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars = [',', '%',", "= 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars = [',', '%', '+', '-'] class Location:", "str): self.time = time self.timezone_id = timezone_id self.timezone_name = timezone_name class WorldTime: def", "def query_encode(text: str) -> str: text = ' '.join(text.split()) text = text.replace(' ',", "time and date from a location # Uses Google Geocoding API and Google", "= address self.latitude = lat self.longitude = long class Time: def __init__(self, time:", "Google Time Zone API import aiohttp import time from datetime import datetime API_GEOCODE", "= timezone_id self.timezone_name = timezone_name class WorldTime: def __init__(self, key: str): self.key =", "int = None, long: int = None): self.address = address self.latitude = lat", "'-'] class Location: def __init__(self, address: str, lat: int = None, long: int", "+ self.param_encode(args) search = await self.api_get(url) if search: try: location_time = unix_now +", "k, v in options.items(): out += '{}={}&'.format(k, v) out = out[:-1] return out", "location.longitude), 'timestamp': unix_now, 'key': self.key} url = API_TIMEZONE + self.param_encode(args) search = await", "+ search['dstOffset'] return Time(time=datetime.fromtimestamp(location_time), timezone_id=search['timeZoneId'], timezone_name=search['timeZoneName']) except KeyError: print('WorldTime Time Key Error') raise", "= lat self.longitude = long class Time: def __init__(self, time: datetime, timezone_id: str,", "time from datetime import datetime API_GEOCODE = 'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars =", "key async def get_location(self, query: str) -> Location: args = {'address': self.query_encode(query), 'key':", "None, long: int = None): self.address = address self.latitude = lat self.longitude =", "'https://maps.googleapis.com/maps/api/geocode/json?' API_TIMEZONE = 'https://maps.googleapis.com/maps/api/timezone/json?' allowed_chars = [',', '%', '+', '-'] class Location: def", "self.latitude = lat self.longitude = long class Time: def __init__(self, time: datetime, timezone_id:", "raise else: return search @staticmethod async def api_get(url: str) -> dict: with aiohttp.ClientSession()", "== 'ZERO_RESULTS': return None return False @staticmethod def query_encode(text: str) -> str: text", "str) -> str: text = ' '.join(text.split()) text = text.replace(' ', '+') for", "return False @staticmethod def query_encode(text: str) -> str: text = ' '.join(text.split()) text", "= Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return location except KeyError: print('WorldTime Location Key Error') raise", "return search @staticmethod async def api_get(url: str) -> dict: with aiohttp.ClientSession() as session:", "= None): self.address = address self.latitude = lat self.longitude = long class Time:", "= {'address': self.query_encode(query), 'key': self.key} url = API_GEOCODE + self.param_encode(args) search = await", "Location: def __init__(self, address: str, lat: int = None, long: int = None):", "# Fetch time and date from a location # Uses Google Geocoding API", "Location) -> Time: unix_now = int(time.time()) args = {'location': '{},{}'.format(location.latitude, location.longitude), 'timestamp': unix_now,", "'%', '+', '-'] class Location: def __init__(self, address: str, lat: int = None,", "API_TIMEZONE + self.param_encode(args) search = await self.api_get(url) if search: try: location_time = unix_now", "search['results'][0] location = Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return location except KeyError: print('WorldTime Location Key", "Key Error') raise else: return search async def get_time(self, location: Location) -> Time:", "= int(time.time()) args = {'location': '{},{}'.format(location.latitude, location.longitude), 'timestamp': unix_now, 'key': self.key} url =", "and not c.isalnum(): text = text.replace(c, '%' + hex(ord(c))[2:]) return text @staticmethod def", "text = text.replace(' ', '+') for c in text: if c not in", "{'address': self.query_encode(query), 'key': self.key} url = API_GEOCODE + self.param_encode(args) search = await self.api_get(url)", "timezone_id self.timezone_name = timezone_name class WorldTime: def __init__(self, key: str): self.key = key", "-> Location: args = {'address': self.query_encode(query), 'key': self.key} url = API_GEOCODE + self.param_encode(args)", "result = search['results'][0] location = Location(address=result['formatted_address'], lat=result['geometry']['location']['lat'], long=result['geometry']['location']['lng']) return location except KeyError: print('WorldTime" ]
[ "np from matplotlib import pyplot as plt n = 100 x = range(0,n)", "range(0, n): y[k] = y[k] + 3*np.random.randn() + 100 plt.figure(figsize=(20,10)) plt.scatter(x, y) plt.savefig(\"./images/rawData.png\")", "= range(0,n) for k in range(0, n): y[k] = y[k] + 3*np.random.randn() +", "3*np.random.randn() + 100 plt.figure(figsize=(20,10)) plt.scatter(x, y) plt.savefig(\"./images/rawData.png\") X = np.zeros([n,1]) target = np.zeros([n,1])", "y = range(0,n) for k in range(0, n): y[k] = y[k] + 3*np.random.randn()", "as plt n = 100 x = range(0,n) y = range(0,n) for k", "x = range(0,n) y = range(0,n) for k in range(0, n): y[k] =", "= range(0,n) y = range(0,n) for k in range(0, n): y[k] = y[k]", "range(0,n) for k in range(0, n): y[k] = y[k] + 3*np.random.randn() + 100", "numpy as np from matplotlib import pyplot as plt n = 100 x", "n = 100 x = range(0,n) y = range(0,n) for k in range(0,", "range(0,n) y = range(0,n) for k in range(0, n): y[k] = y[k] +", "+ 3*np.random.randn() + 100 plt.figure(figsize=(20,10)) plt.scatter(x, y) plt.savefig(\"./images/rawData.png\") X = np.zeros([n,1]) target =", "+ 100 plt.figure(figsize=(20,10)) plt.scatter(x, y) plt.savefig(\"./images/rawData.png\") X = np.zeros([n,1]) target = np.zeros([n,1]) X[:,0]", "X[:,0] = x target[:,0] = y np.savetxt(\"X.txt\", X, delimiter=\",\", fmt='%f') np.savetxt(\"y.txt\", target, delimiter=\",\",", "plt.savefig(\"./images/rawData.png\") X = np.zeros([n,1]) target = np.zeros([n,1]) X[:,0] = x target[:,0] = y", "= x target[:,0] = y np.savetxt(\"X.txt\", X, delimiter=\",\", fmt='%f') np.savetxt(\"y.txt\", target, delimiter=\",\", fmt='%f')", "import numpy as np from matplotlib import pyplot as plt n = 100", "plt n = 100 x = range(0,n) y = range(0,n) for k in", "for k in range(0, n): y[k] = y[k] + 3*np.random.randn() + 100 plt.figure(figsize=(20,10))", "from matplotlib import pyplot as plt n = 100 x = range(0,n) y", "import pyplot as plt n = 100 x = range(0,n) y = range(0,n)", "y[k] + 3*np.random.randn() + 100 plt.figure(figsize=(20,10)) plt.scatter(x, y) plt.savefig(\"./images/rawData.png\") X = np.zeros([n,1]) target", "y) plt.savefig(\"./images/rawData.png\") X = np.zeros([n,1]) target = np.zeros([n,1]) X[:,0] = x target[:,0] =", "100 x = range(0,n) y = range(0,n) for k in range(0, n): y[k]", "plt.figure(figsize=(20,10)) plt.scatter(x, y) plt.savefig(\"./images/rawData.png\") X = np.zeros([n,1]) target = np.zeros([n,1]) X[:,0] = x", "100 plt.figure(figsize=(20,10)) plt.scatter(x, y) plt.savefig(\"./images/rawData.png\") X = np.zeros([n,1]) target = np.zeros([n,1]) X[:,0] =", "= 100 x = range(0,n) y = range(0,n) for k in range(0, n):", "y[k] = y[k] + 3*np.random.randn() + 100 plt.figure(figsize=(20,10)) plt.scatter(x, y) plt.savefig(\"./images/rawData.png\") X =", "= np.zeros([n,1]) X[:,0] = x target[:,0] = y np.savetxt(\"X.txt\", X, delimiter=\",\", fmt='%f') np.savetxt(\"y.txt\",", "np.zeros([n,1]) X[:,0] = x target[:,0] = y np.savetxt(\"X.txt\", X, delimiter=\",\", fmt='%f') np.savetxt(\"y.txt\", target,", "= np.zeros([n,1]) target = np.zeros([n,1]) X[:,0] = x target[:,0] = y np.savetxt(\"X.txt\", X,", "matplotlib import pyplot as plt n = 100 x = range(0,n) y =", "as np from matplotlib import pyplot as plt n = 100 x =", "k in range(0, n): y[k] = y[k] + 3*np.random.randn() + 100 plt.figure(figsize=(20,10)) plt.scatter(x,", "= y[k] + 3*np.random.randn() + 100 plt.figure(figsize=(20,10)) plt.scatter(x, y) plt.savefig(\"./images/rawData.png\") X = np.zeros([n,1])", "np.zeros([n,1]) target = np.zeros([n,1]) X[:,0] = x target[:,0] = y np.savetxt(\"X.txt\", X, delimiter=\",\",", "pyplot as plt n = 100 x = range(0,n) y = range(0,n) for", "target = np.zeros([n,1]) X[:,0] = x target[:,0] = y np.savetxt(\"X.txt\", X, delimiter=\",\", fmt='%f')", "n): y[k] = y[k] + 3*np.random.randn() + 100 plt.figure(figsize=(20,10)) plt.scatter(x, y) plt.savefig(\"./images/rawData.png\") X", "X = np.zeros([n,1]) target = np.zeros([n,1]) X[:,0] = x target[:,0] = y np.savetxt(\"X.txt\",", "plt.scatter(x, y) plt.savefig(\"./images/rawData.png\") X = np.zeros([n,1]) target = np.zeros([n,1]) X[:,0] = x target[:,0]", "in range(0, n): y[k] = y[k] + 3*np.random.randn() + 100 plt.figure(figsize=(20,10)) plt.scatter(x, y)" ]
[ "\"\"\" exclude = () if obj: exclude += tuple((get_typograf_field_name(field) for field in obj._meta.typografed_fields))", "exclude def get_form(self, request, obj=None, **kwargs): exclude = self.exclude or () exclude +=", "fields from admin site \"\"\" def _exclude(self, obj=None): \"\"\" Mark typograf fields as", "def _exclude(self, obj=None): \"\"\" Mark typograf fields as exclude \"\"\" exclude = ()", "field in obj._meta.typografed_fields)) exclude += tuple((get_typograf_hash_field_name(field) for field in obj._meta.typografed_fields)) return exclude def", "request, obj=None, **kwargs): exclude = self.exclude or () exclude += self._exclude(obj) kwargs.update(dict(exclude=exclude)) return", "obj._meta.typografed_fields)) return exclude def get_form(self, request, obj=None, **kwargs): exclude = self.exclude or ()", "if obj: exclude += tuple((get_typograf_field_name(field) for field in obj._meta.typografed_fields)) exclude += tuple((get_typograf_hash_field_name(field) for", "in obj._meta.typografed_fields)) exclude += tuple((get_typograf_hash_field_name(field) for field in obj._meta.typografed_fields)) return exclude def get_form(self,", "django.contrib import admin from django_typograf.utils import get_typograf_field_name, get_typograf_hash_field_name class TypografAdmin(admin.ModelAdmin): \"\"\" Admin class", "TypografAdmin(admin.ModelAdmin): \"\"\" Admin class for hide typograf fields from admin site \"\"\" def", "site \"\"\" def _exclude(self, obj=None): \"\"\" Mark typograf fields as exclude \"\"\" exclude", "for field in obj._meta.typografed_fields)) return exclude def get_form(self, request, obj=None, **kwargs): exclude =", "get_typograf_field_name, get_typograf_hash_field_name class TypografAdmin(admin.ModelAdmin): \"\"\" Admin class for hide typograf fields from admin", "from django_typograf.utils import get_typograf_field_name, get_typograf_hash_field_name class TypografAdmin(admin.ModelAdmin): \"\"\" Admin class for hide typograf", "import admin from django_typograf.utils import get_typograf_field_name, get_typograf_hash_field_name class TypografAdmin(admin.ModelAdmin): \"\"\" Admin class for", "exclude += tuple((get_typograf_hash_field_name(field) for field in obj._meta.typografed_fields)) return exclude def get_form(self, request, obj=None,", "tuple((get_typograf_hash_field_name(field) for field in obj._meta.typografed_fields)) return exclude def get_form(self, request, obj=None, **kwargs): exclude", "exclude \"\"\" exclude = () if obj: exclude += tuple((get_typograf_field_name(field) for field in", "obj: exclude += tuple((get_typograf_field_name(field) for field in obj._meta.typografed_fields)) exclude += tuple((get_typograf_hash_field_name(field) for field", "admin site \"\"\" def _exclude(self, obj=None): \"\"\" Mark typograf fields as exclude \"\"\"", "\"\"\" Admin class for hide typograf fields from admin site \"\"\" def _exclude(self,", "obj=None, **kwargs): exclude = self.exclude or () exclude += self._exclude(obj) kwargs.update(dict(exclude=exclude)) return super().get_form(request,", "+= tuple((get_typograf_field_name(field) for field in obj._meta.typografed_fields)) exclude += tuple((get_typograf_hash_field_name(field) for field in obj._meta.typografed_fields))", "get_typograf_hash_field_name class TypografAdmin(admin.ModelAdmin): \"\"\" Admin class for hide typograf fields from admin site", "in obj._meta.typografed_fields)) return exclude def get_form(self, request, obj=None, **kwargs): exclude = self.exclude or", "django_typograf.utils import get_typograf_field_name, get_typograf_hash_field_name class TypografAdmin(admin.ModelAdmin): \"\"\" Admin class for hide typograf fields", "class TypografAdmin(admin.ModelAdmin): \"\"\" Admin class for hide typograf fields from admin site \"\"\"", "as exclude \"\"\" exclude = () if obj: exclude += tuple((get_typograf_field_name(field) for field", "from admin site \"\"\" def _exclude(self, obj=None): \"\"\" Mark typograf fields as exclude", "typograf fields from admin site \"\"\" def _exclude(self, obj=None): \"\"\" Mark typograf fields", "return exclude def get_form(self, request, obj=None, **kwargs): exclude = self.exclude or () exclude", "field in obj._meta.typografed_fields)) return exclude def get_form(self, request, obj=None, **kwargs): exclude = self.exclude", "exclude = self.exclude or () exclude += self._exclude(obj) kwargs.update(dict(exclude=exclude)) return super().get_form(request, obj, **kwargs)", "**kwargs): exclude = self.exclude or () exclude += self._exclude(obj) kwargs.update(dict(exclude=exclude)) return super().get_form(request, obj,", "tuple((get_typograf_field_name(field) for field in obj._meta.typografed_fields)) exclude += tuple((get_typograf_hash_field_name(field) for field in obj._meta.typografed_fields)) return", "for field in obj._meta.typografed_fields)) exclude += tuple((get_typograf_hash_field_name(field) for field in obj._meta.typografed_fields)) return exclude", "fields as exclude \"\"\" exclude = () if obj: exclude += tuple((get_typograf_field_name(field) for", "class for hide typograf fields from admin site \"\"\" def _exclude(self, obj=None): \"\"\"", "Mark typograf fields as exclude \"\"\" exclude = () if obj: exclude +=", "obj=None): \"\"\" Mark typograf fields as exclude \"\"\" exclude = () if obj:", "for hide typograf fields from admin site \"\"\" def _exclude(self, obj=None): \"\"\" Mark", "<reponame>movermeyer/django-typograf from django.contrib import admin from django_typograf.utils import get_typograf_field_name, get_typograf_hash_field_name class TypografAdmin(admin.ModelAdmin): \"\"\"", "\"\"\" def _exclude(self, obj=None): \"\"\" Mark typograf fields as exclude \"\"\" exclude =", "get_form(self, request, obj=None, **kwargs): exclude = self.exclude or () exclude += self._exclude(obj) kwargs.update(dict(exclude=exclude))", "hide typograf fields from admin site \"\"\" def _exclude(self, obj=None): \"\"\" Mark typograf", "Admin class for hide typograf fields from admin site \"\"\" def _exclude(self, obj=None):", "from django.contrib import admin from django_typograf.utils import get_typograf_field_name, get_typograf_hash_field_name class TypografAdmin(admin.ModelAdmin): \"\"\" Admin", "() if obj: exclude += tuple((get_typograf_field_name(field) for field in obj._meta.typografed_fields)) exclude += tuple((get_typograf_hash_field_name(field)", "+= tuple((get_typograf_hash_field_name(field) for field in obj._meta.typografed_fields)) return exclude def get_form(self, request, obj=None, **kwargs):", "def get_form(self, request, obj=None, **kwargs): exclude = self.exclude or () exclude += self._exclude(obj)", "import get_typograf_field_name, get_typograf_hash_field_name class TypografAdmin(admin.ModelAdmin): \"\"\" Admin class for hide typograf fields from", "_exclude(self, obj=None): \"\"\" Mark typograf fields as exclude \"\"\" exclude = () if", "exclude += tuple((get_typograf_field_name(field) for field in obj._meta.typografed_fields)) exclude += tuple((get_typograf_hash_field_name(field) for field in", "obj._meta.typografed_fields)) exclude += tuple((get_typograf_hash_field_name(field) for field in obj._meta.typografed_fields)) return exclude def get_form(self, request,", "admin from django_typograf.utils import get_typograf_field_name, get_typograf_hash_field_name class TypografAdmin(admin.ModelAdmin): \"\"\" Admin class for hide", "exclude = () if obj: exclude += tuple((get_typograf_field_name(field) for field in obj._meta.typografed_fields)) exclude", "typograf fields as exclude \"\"\" exclude = () if obj: exclude += tuple((get_typograf_field_name(field)", "\"\"\" Mark typograf fields as exclude \"\"\" exclude = () if obj: exclude", "= () if obj: exclude += tuple((get_typograf_field_name(field) for field in obj._meta.typografed_fields)) exclude +=" ]
[ "tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural Gas','Coal','Oil','Nuclear','Other'] share=[tot_pv,tot_wind,tot_gas,tot_coal,tot_oil,tot_nuclear,tot_other] fig = go.Figure(data=[go.Pie(labels=labels, values=share)]) fig.show() #print(power_share) #data.update({'share': })", "tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural Gas','Coal','Oil','Nuclear','Other'] share=[tot_pv,tot_wind,tot_gas,tot_coal,tot_oil,tot_nuclear,tot_other] fig = go.Figure(data=[go.Pie(labels=labels, values=share)]) fig.show()", "sum(data['net']) tot_pv = sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural Gas','Coal','Oil','Nuclear','Other']", "tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural Gas','Coal','Oil','Nuclear','Other'] share=[tot_pv,tot_wind,tot_gas,tot_coal,tot_oil,tot_nuclear,tot_other] fig = go.Figure(data=[go.Pie(labels=labels, values=share)]) fig.show() #print(power_share) #data.update({'share':", "sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural Gas','Coal','Oil','Nuclear','Other'] share=[tot_pv,tot_wind,tot_gas,tot_coal,tot_oil,tot_nuclear,tot_other] fig =", "{'pv':[1,4,1,2,4,2], 'wind':[1,2,5,3,2,0], 'net':[10,2,5,0,2,0]} tot_net= sum(data['net']) tot_pv = sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04", "tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural Gas','Coal','Oil','Nuclear','Other'] share=[tot_pv,tot_wind,tot_gas,tot_coal,tot_oil,tot_nuclear,tot_other] fig = go.Figure(data=[go.Pie(labels=labels,", "import plotly.graph_objects as go data = {'pv':[1,4,1,2,4,2], 'wind':[1,2,5,3,2,0], 'net':[10,2,5,0,2,0]} tot_net= sum(data['net']) tot_pv =", "'wind':[1,2,5,3,2,0], 'net':[10,2,5,0,2,0]} tot_net= sum(data['net']) tot_pv = sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03", "= sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural Gas','Coal','Oil','Nuclear','Other'] share=[tot_pv,tot_wind,tot_gas,tot_coal,tot_oil,tot_nuclear,tot_other] fig", "go data = {'pv':[1,4,1,2,4,2], 'wind':[1,2,5,3,2,0], 'net':[10,2,5,0,2,0]} tot_net= sum(data['net']) tot_pv = sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08", "plotly.graph_objects as go data = {'pv':[1,4,1,2,4,2], 'wind':[1,2,5,3,2,0], 'net':[10,2,5,0,2,0]} tot_net= sum(data['net']) tot_pv = sum(data['pv'])+tot_net*0.05", "tot_net= sum(data['net']) tot_pv = sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural", "data = {'pv':[1,4,1,2,4,2], 'wind':[1,2,5,3,2,0], 'net':[10,2,5,0,2,0]} tot_net= sum(data['net']) tot_pv = sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45", "tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural Gas','Coal','Oil','Nuclear','Other'] share=[tot_pv,tot_wind,tot_gas,tot_coal,tot_oil,tot_nuclear,tot_other] fig = go.Figure(data=[go.Pie(labels=labels, values=share)]) fig.show() #print(power_share)", "sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural Gas','Coal','Oil','Nuclear','Other'] share=[tot_pv,tot_wind,tot_gas,tot_coal,tot_oil,tot_nuclear,tot_other] fig = go.Figure(data=[go.Pie(labels=labels, values=share)])", "<gh_stars>0 import plotly.graph_objects as go data = {'pv':[1,4,1,2,4,2], 'wind':[1,2,5,3,2,0], 'net':[10,2,5,0,2,0]} tot_net= sum(data['net']) tot_pv", "as go data = {'pv':[1,4,1,2,4,2], 'wind':[1,2,5,3,2,0], 'net':[10,2,5,0,2,0]} tot_net= sum(data['net']) tot_pv = sum(data['pv'])+tot_net*0.05 tot_wind=", "'net':[10,2,5,0,2,0]} tot_net= sum(data['net']) tot_pv = sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03", "= {'pv':[1,4,1,2,4,2], 'wind':[1,2,5,3,2,0], 'net':[10,2,5,0,2,0]} tot_net= sum(data['net']) tot_pv = sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32", "tot_pv = sum(data['pv'])+tot_net*0.05 tot_wind= sum(data['wind'])*0.08 tot_gas=tot_net*0.45 tot_coal=tot_net*0.32 tot_oil=tot_net*0.04 tot_nuclear=tot_net*0.03 tot_other=tot_net*0.03 labels=['PV','Wind','Natural Gas','Coal','Oil','Nuclear','Other'] share=[tot_pv,tot_wind,tot_gas,tot_coal,tot_oil,tot_nuclear,tot_other]" ]
[ "print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a = datetime.now() b = pd.Timestamp(ts_input=a, tzinfo=a.tzinfo)", "= b.ceil(freq='T') e = d.timestamp() f = int(e) g = datetime.fromtimestamp(f) print(a, c,", "g = datetime.fromtimestamp(f) print(a, c, d, g) delta = datetime.now() - datetime.utcnow() print(delta.seconds", "datetime.fromtimestamp(f) print(a, c, d, g) delta = datetime.now() - datetime.utcnow() print(delta.seconds / 3600)", "f = int(e) g = datetime.fromtimestamp(f) print(a, c, d, g) delta = datetime.now()", "a = datetime.now() b = pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c = b.floor(freq='T') d = b.ceil(freq='T')", "# print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a = datetime.now() b = pd.Timestamp(ts_input=a,", "time import timezone import pandas as pd from datetime import datetime # print(datetime.fromtimestamp(1603209600))", "pandas as pd from datetime import datetime # print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000))", "print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a = datetime.now() b = pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c =", "# print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a = datetime.now() b = pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c", "print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a = datetime.now() b = pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c = b.floor(freq='T')", "d = b.ceil(freq='T') e = d.timestamp() f = int(e) g = datetime.fromtimestamp(f) print(a,", "= d.timestamp() f = int(e) g = datetime.fromtimestamp(f) print(a, c, d, g) delta", "datetime # print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a = datetime.now()", "= b.floor(freq='T') d = b.ceil(freq='T') e = d.timestamp() f = int(e) g =", "from time import timezone import pandas as pd from datetime import datetime #", "= datetime.fromtimestamp(f) print(a, c, d, g) delta = datetime.now() - datetime.utcnow() print(delta.seconds /", "d.timestamp() f = int(e) g = datetime.fromtimestamp(f) print(a, c, d, g) delta =", "pd from datetime import datetime # print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600))", "from datetime import datetime # print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000))", "tzinfo=a.tzinfo) c = b.floor(freq='T') d = b.ceil(freq='T') e = d.timestamp() f = int(e)", "import datetime # print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a =", "b.ceil(freq='T') e = d.timestamp() f = int(e) g = datetime.fromtimestamp(f) print(a, c, d,", "import timezone import pandas as pd from datetime import datetime # print(datetime.fromtimestamp(1603209600)) #", "b.floor(freq='T') d = b.ceil(freq='T') e = d.timestamp() f = int(e) g = datetime.fromtimestamp(f)", "= pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c = b.floor(freq='T') d = b.ceil(freq='T') e = d.timestamp() f", "b = pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c = b.floor(freq='T') d = b.ceil(freq='T') e = d.timestamp()", "int(e) g = datetime.fromtimestamp(f) print(a, c, d, g) delta = datetime.now() - datetime.utcnow()", "print(datetime.fromtimestamp(1640617020000//1000)) a = datetime.now() b = pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c = b.floor(freq='T') d =", "e = d.timestamp() f = int(e) g = datetime.fromtimestamp(f) print(a, c, d, g)", "c = b.floor(freq='T') d = b.ceil(freq='T') e = d.timestamp() f = int(e) g", "pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c = b.floor(freq='T') d = b.ceil(freq='T') e = d.timestamp() f =", "= datetime.now() b = pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c = b.floor(freq='T') d = b.ceil(freq='T') e", "timezone import pandas as pd from datetime import datetime # print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000))", "datetime import datetime # print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a", "import pandas as pd from datetime import datetime # print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000)) #", "print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a = datetime.now() b = pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c = b.floor(freq='T') d", "= int(e) g = datetime.fromtimestamp(f) print(a, c, d, g) delta = datetime.now() -", "# print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a = datetime.now() b", "datetime.now() b = pd.Timestamp(ts_input=a, tzinfo=a.tzinfo) c = b.floor(freq='T') d = b.ceil(freq='T') e =", "print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200)) print(datetime.fromtimestamp(1640649600)) print(datetime.fromtimestamp(1640617020000//1000)) a = datetime.now() b =", "as pd from datetime import datetime # print(datetime.fromtimestamp(1603209600)) # print(datetime.fromtimestamp(1612868324294/1000)) # print(datetime.fromtimestamp(1613283396746//1000)) print(datetime.fromtimestamp(1640851200))" ]
[ "龙头在胸口。 </div> </body> </html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector = lxml.html.fromstring(html3) # content_1 = selector.xpath('//div[@id=\"test3\"]/text()')", "<title></title> </head> <body> <div id=\"test3\"> 我左青龙, <span id=\"tiger\"> 右白虎, <ul>上朱雀, <li>下玄武。</li> </ul> 老牛在当中,", "# for each in content: # print(each) html3 = ''' <!DOCTYPE html> <html>", "for each in content_1: # print(each) # 使用string(.)就可以把数据获取完整 data = selector.xpath('//div[@id=\"test3\"]')[0] info =", "<div id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html1) # content", "<title></title> </head> <body> <div id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html>", "<html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test3\"> 我左青龙, <span id=\"tiger\">", "# print(each) html3 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title>", "id=\"tiger\"> 右白虎, <ul>上朱雀, <li>下玄武。</li> </ul> 老牛在当中, </span> 龙头在胸口。 </div> </body> </html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况", "\"-key\")]/text()') # for each in content: # print(each) html3 = ''' <!DOCTYPE html>", "''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector = lxml.html.fromstring(html3) # content_1 = selector.xpath('//div[@id=\"test3\"]/text()') # for each in", "lxml.html.fromstring(html1) # content = selector.xpath('//div[ends-with(@id, \"-k\")]/text()') # for each in content: # print(each)", "for each in content: # print(each) html3 = ''' <!DOCTYPE html> <html> <head", "lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div> <div", "id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html1) # content =", "content = selector.xpath('//div[contains(@id, \"-key\")]/text()') # for each in content: # print(each) html3 =", "''' # selector = lxml.html.fromstring(html2) # content = selector.xpath('//div[contains(@id, \"-key\")]/text()') # for each", "<!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"abc-key-x\">需要的内容1</div> <div", "selector.xpath('//div[@id=\"test3\"]/text()') # for each in content_1: # print(each) # 使用string(.)就可以把数据获取完整 data = selector.xpath('//div[@id=\"test3\"]')[0]", "html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div>", "<html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div> <div", "content: # print(each) html3 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\">", "<body> <div id=\"test3\"> 我左青龙, <span id=\"tiger\"> 右白虎, <ul>上朱雀, <li>下玄武。</li> </ul> 老牛在当中, </span> 龙头在胸口。", "html3 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body>", "id=\"test3\"> 我左青龙, <span id=\"tiger\"> 右白虎, <ul>上朱雀, <li>下玄武。</li> </ul> 老牛在当中, </span> 龙头在胸口。 </div> </body>", "</body> </html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector = lxml.html.fromstring(html3) # content_1 = selector.xpath('//div[@id=\"test3\"]/text()') # for", "= selector.xpath('//div[contains(@id, \"-key\")]/text()') # for each in content: # print(each) html3 = '''", "# content = selector.xpath('//div[contains(@id, \"-key\")]/text()') # for each in content: # print(each) html3", "in content: # print(each) html3 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta", "id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector =", "<div id=\"test3\"> 我左青龙, <span id=\"tiger\"> 右白虎, <ul>上朱雀, <li>下玄武。</li> </ul> 老牛在当中, </span> 龙头在胸口。 </div>", "</div> </body> </html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector = lxml.html.fromstring(html3) # content_1 = selector.xpath('//div[@id=\"test3\"]/text()') #", "html1 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body>", "in content_1: # print(each) # 使用string(.)就可以把数据获取完整 data = selector.xpath('//div[@id=\"test3\"]')[0] info = data.xpath('string(.)') print(info)", "''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"abc-key-x\">需要的内容1</div>", "each in content: # print(each) html2 = ''' <!DOCTYPE html> <html> <head lang=\"en\">", "html2 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body>", "each in content_1: # print(each) # 使用string(.)就可以把数据获取完整 data = selector.xpath('//div[@id=\"test3\"]')[0] info = data.xpath('string(.)')", "<div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html1) # content = selector.xpath('//div[ends-with(@id,", "selector = lxml.html.fromstring(html2) # content = selector.xpath('//div[contains(@id, \"-key\")]/text()') # for each in content:", "selector = lxml.html.fromstring(html1) # content = selector.xpath('//div[ends-with(@id, \"-k\")]/text()') # for each in content:", "<body> <div id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' #", "<meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test3\"> 我左青龙, <span id=\"tiger\"> 右白虎, <ul>上朱雀, <li>下玄武。</li>", "# content = selector.xpath('//div[ends-with(@id, \"-k\")]/text()') # for each in content: # print(each) html2", "id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html2) # content = selector.xpath('//div[contains(@id, \"-key\")]/text()')", "</ul> 老牛在当中, </span> 龙头在胸口。 </div> </body> </html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector = lxml.html.fromstring(html3) #", "</head> <body> <div id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> '''", "</html> ''' # selector = lxml.html.fromstring(html1) # content = selector.xpath('//div[ends-with(@id, \"-k\")]/text()') # for", "= lxml.html.fromstring(html1) # content = selector.xpath('//div[ends-with(@id, \"-k\")]/text()') # for each in content: #", "charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body>", "<html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div> <div", "<meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div>", "<body> <div id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' #", "print(each) html2 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head>", "<div id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector", "content = selector.xpath('//div[ends-with(@id, \"-k\")]/text()') # for each in content: # print(each) html2 =", "<ul>上朱雀, <li>下玄武。</li> </ul> 老牛在当中, </span> 龙头在胸口。 </div> </body> </html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector =", "<head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div>", "selector.xpath('//div[ends-with(@id, \"-k\")]/text()') # for each in content: # print(each) html2 = ''' <!DOCTYPE", "for each in content: # print(each) html2 = ''' <!DOCTYPE html> <html> <head", "<div id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector", "<li>下玄武。</li> </ul> 老牛在当中, </span> 龙头在胸口。 </div> </body> </html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector = lxml.html.fromstring(html3)", "# content_1 = selector.xpath('//div[@id=\"test3\"]/text()') # for each in content_1: # print(each) # 使用string(.)就可以把数据获取完整", "#如果使用一般的办法,就会出现获取到的数据不完整的情况 selector = lxml.html.fromstring(html3) # content_1 = selector.xpath('//div[@id=\"test3\"]/text()') # for each in content_1:", "lxml.html.fromstring(html2) # content = selector.xpath('//div[contains(@id, \"-key\")]/text()') # for each in content: # print(each)", "<!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test-1-k\">需要的内容1</div> <div", "id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html2) #", "<div id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html2) # content", "</body> </html> ''' # selector = lxml.html.fromstring(html2) # content = selector.xpath('//div[contains(@id, \"-key\")]/text()') #", "<!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test3\"> 我左青龙,", "print(each) html3 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head>", "content_1 = selector.xpath('//div[@id=\"test3\"]/text()') # for each in content_1: # print(each) # 使用string(.)就可以把数据获取完整 data", "id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html2) # content =", "selector = lxml.html.fromstring(html3) # content_1 = selector.xpath('//div[@id=\"test3\"]/text()') # for each in content_1: #", "html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test3\"> 我左青龙, <span", "= lxml.html.fromstring(html2) # content = selector.xpath('//div[contains(@id, \"-key\")]/text()') # for each in content: #", "<div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html2) # content = selector.xpath('//div[contains(@id,", "id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html1) # content = selector.xpath('//div[ends-with(@id, \"-k\")]/text()')", "老牛在当中, </span> 龙头在胸口。 </div> </body> </html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector = lxml.html.fromstring(html3) # content_1", "# selector = lxml.html.fromstring(html1) # content = selector.xpath('//div[ends-with(@id, \"-k\")]/text()') # for each in", "# for each in content: # print(each) html2 = ''' <!DOCTYPE html> <html>", "# print(each) html2 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title>", "id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html1) #", "<meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div>", "content: # print(each) html2 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\">", "</html> ''' # selector = lxml.html.fromstring(html2) # content = selector.xpath('//div[contains(@id, \"-key\")]/text()') # for", "charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test3\"> 我左青龙, <span id=\"tiger\"> 右白虎, <ul>上朱雀, <li>下玄武。</li> </ul>", "charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body>", "我左青龙, <span id=\"tiger\"> 右白虎, <ul>上朱雀, <li>下玄武。</li> </ul> 老牛在当中, </span> 龙头在胸口。 </div> </body> </html>", "''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test-1-k\">需要的内容1</div>", "lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div> <div", "''' # selector = lxml.html.fromstring(html1) # content = selector.xpath('//div[ends-with(@id, \"-k\")]/text()') # for each", "= ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div", "<title></title> </head> <body> <div id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html>", "<head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div>", "each in content: # print(each) html3 = ''' <!DOCTYPE html> <html> <head lang=\"en\">", "# for each in content_1: # print(each) # 使用string(.)就可以把数据获取完整 data = selector.xpath('//div[@id=\"test3\"]')[0] info", "</head> <body> <div id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> '''", "lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test3\"> 我左青龙, <span id=\"tiger\"> 右白虎, <ul>上朱雀,", "lxml.html.fromstring(html3) # content_1 = selector.xpath('//div[@id=\"test3\"]/text()') # for each in content_1: # print(each) #", "''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test3\">", "</head> <body> <div id=\"test3\"> 我左青龙, <span id=\"tiger\"> 右白虎, <ul>上朱雀, <li>下玄武。</li> </ul> 老牛在当中, </span>", "<div id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html1)", "= lxml.html.fromstring(html3) # content_1 = selector.xpath('//div[@id=\"test3\"]/text()') # for each in content_1: # print(each)", "= selector.xpath('//div[ends-with(@id, \"-k\")]/text()') # for each in content: # print(each) html2 = '''", "</span> 龙头在胸口。 </div> </body> </html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector = lxml.html.fromstring(html3) # content_1 =", "<head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"test3\"> 我左青龙, <span id=\"tiger\"> 右白虎,", "</html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector = lxml.html.fromstring(html3) # content_1 = selector.xpath('//div[@id=\"test3\"]/text()') # for each", "html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head> <body> <div id=\"abc-key-x\">需要的内容1</div> <div id=\"123-key-000\">需要的内容2</div>", "<div id=\"123-key-000\">需要的内容2</div> <div id=\"haha-key\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector = lxml.html.fromstring(html2)", "import lxml.html html1 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title>", "<span id=\"tiger\"> 右白虎, <ul>上朱雀, <li>下玄武。</li> </ul> 老牛在当中, </span> 龙头在胸口。 </div> </body> </html> '''", "lxml.html html1 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta charset=\"UTF-8\"> <title></title> </head>", "\"-k\")]/text()') # for each in content: # print(each) html2 = ''' <!DOCTYPE html>", "= selector.xpath('//div[@id=\"test3\"]/text()') # for each in content_1: # print(each) # 使用string(.)就可以把数据获取完整 data =", "# selector = lxml.html.fromstring(html2) # content = selector.xpath('//div[contains(@id, \"-key\")]/text()') # for each in", "selector.xpath('//div[contains(@id, \"-key\")]/text()') # for each in content: # print(each) html3 = ''' <!DOCTYPE", "</body> </html> ''' # selector = lxml.html.fromstring(html1) # content = selector.xpath('//div[ends-with(@id, \"-k\")]/text()') #", "id=\"test-1-k\">需要的内容1</div> <div id=\"test-2-k\">需要的内容2</div> <div id=\"testfault-k\">需要的内容3</div> <div id=\"useless\">这是我不需要的内容</div> </body> </html> ''' # selector =", "in content: # print(each) html2 = ''' <!DOCTYPE html> <html> <head lang=\"en\"> <meta", "右白虎, <ul>上朱雀, <li>下玄武。</li> </ul> 老牛在当中, </span> 龙头在胸口。 </div> </body> </html> ''' #如果使用一般的办法,就会出现获取到的数据不完整的情况 selector" ]
[ "import pytest from now_lms import init_app, lms_app lms_app.app_context().push() @pytest.fixture(scope=\"package\", autouse=True) def setup_database(): init_app()" ]
[]