ngram listlengths 0 67.8k |
|---|
[
"days'.format(years, days)) total_left = total_range_seconds - total_gap years_left = math.floor(total_left / 3600 /",
"> 10) & (df1['Total'] <= 50)].count() i3 = df1[(df1['Total'] > 50) & (df1['Total']",
"365.25) days_left = math.floor((total_left / 3600 / 24 % 365.25)) print('Total left {0}",
"3600 / 24 % 365.25)) print('Total gap {0} years'.format(total_gap / 3600 / 24",
"pd.to_datetime(raw.index) df = raw.resample('1H').mean() total_count = df.count() i0 = df[(df['Value'] == 0)].count() i1",
"300) & (df['Value'] <= 400)].count() i7 = df[(df['Value'] > 400) & (df['Value'] <=",
"if hours > 24: # flow stations total_gap = total_gap + seconds gaps.append(seconds)",
"(df['Value'] <= 100)].count() i6 = df[(df['Value'] > 100)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0:",
"> 50) & (df1['Total'] <= 100)].count() i4 = df1[(df1['Total'] > 100) & (df1['Total']",
"df[(df['Value'] > 10) & (df['Value'] <= 20)].count() i4 = df[(df['Value'] > 20) &",
"in time series\"\"\" df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df = df.set_index(['Date']) df.index = pd.to_datetime(df.index)",
"i0 = df1[(df1['Total'] == 0)].count() i1 = df1[(df1['Total'] > 0) & (df1['Total'] <=",
"/ 3600 / 24 / 365.25)) print('Total gap {0} years {1} days'.format(years, days))",
"= df[(df['Value'] == 0)].count() i1 = df[(df['Value'] > 0) & (df['Value'] <= 10)].count()",
"& (df1['Total'] <= 300)].count() i6 = df1[(df1['Total'] > 300) & (df1['Total'] <= 400)].count()",
"= last_date - first_date total_range_seconds = total_range / np.timedelta64(1, 's') last_read_date = first_date",
"df1[(df1['Total'] > 500) & (df1['Total'] <= 1000)].count() i9 = df1[(df1['Total'] > 1000)].count() print('Total",
"> 1000)].count() print('Total count: {0}'.format(total_count['Total'])) print(' 0: {0}'.format(i0['Total']/total_count['Total'])) print(' 0 - 10: {0}'.format(i1['Total']/total_count['Total']))",
"raw2.resample('1H').mean() raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3 = raw3.set_index(['Date']) raw3.index = pd.to_datetime(raw3.index) df3 =",
"= pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() df1['Total']",
"& (df['Value'] <= 20)].count() i4 = df[(df['Value'] > 20) & (df['Value'] <= 50)].count()",
"resample(station): \"\"\"Resample station data\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index =",
"raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date'])",
"{0}'.format(i6['Total']/total_count['Total'])) print('400 - 500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total']))",
"100: {0}'.format(i3['Total']/total_count['Total'])) print('100 - 200: {0}'.format(i4['Total']/total_count['Total'])) print('200 - 300: {0}'.format(i5['Total']/total_count['Total'])) print('300 - 400:",
"= df1[(df1['Total'] > 10) & (df1['Total'] <= 50)].count() i3 = df1[(df1['Total'] > 50)",
"df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station)) if __name__ == '__main__': station = sys.argv[1] calc_gaps(station) #calc_histogram(station) #calc_histogram2(station)",
"100) & (df['Value'] <= 200)].count() i5 = df[(df['Value'] > 200) & (df['Value'] <=",
"print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw",
"print(' > 100: {0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station): \"\"\"Get median over year sampling rate\"\"\" raw",
"last_date)) total_range = last_date - first_date total_range_seconds = total_range / np.timedelta64(1, 's') last_read_date",
"raw3.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] + df3['Value'] total_count = df1.count() i0 =",
"math.floor(total_gap / 3600 / 24 / 365.25) days = math.floor((total_gap / 3600 /",
"# gap_file = '{0}-gaps.txt'.format(station) # np.savetxt(gap_file, gaps, delimiter=',', fmt=\"%s\") def calc_histogram(station): \"\"\"Get histogram\"\"\"",
"\"\"\" Construct dataset \"\"\" import sys import math import pandas as pd import",
"print('400 - 500: {0}'.format(i7['Value']/total_count['Value'])) print('500 - 1000: {0}'.format(i8['Value']/total_count['Value'])) print(' > 1000: {0}'.format(i9['Value']/total_count['Value'])) def",
"df[(df['Value'] > 400) & (df['Value'] <= 500)].count() i8 = df[(df['Value'] > 500) &",
"= pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() raw3",
"\"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index) df1",
"200: {0}'.format(i4['Total']/total_count['Total'])) print('200 - 300: {0}'.format(i5['Total']/total_count['Total'])) print('300 - 400: {0}'.format(i6['Total']/total_count['Total'])) print('400 - 500:",
"- total_gap years_left = math.floor(total_left / 3600 / 24 / 365.25) days_left =",
"= df.set_index(['Date']) df.index = pd.to_datetime(df.index) dates = df.index.values first_date = dates[0] last_date =",
"= raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() total_count = df.count() i0 =",
"3600 / 24 / 365.25)) print('Total gap {0} years {1} days'.format(years, days)) total_left",
"300)].count() i6 = df1[(df1['Total'] > 300) & (df1['Total'] <= 400)].count() i7 = df1[(df1['Total']",
"200) & (df['Value'] <= 300)].count() i6 = df[(df['Value'] > 300) & (df['Value'] <=",
"pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] total_count = df1.count() i0",
"days_left = math.floor((total_left / 3600 / 24 % 365.25)) print('Total left {0} years'.format(total_left",
"raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() df = df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station)) if __name__",
"i0 = df[(df['Value'] == 0)].count() i1 = df[(df['Value'] > 0) & (df['Value'] <=",
"diff / np.timedelta64(1, 'h') if hours > 72: # met stations # if",
"== '__main__': station = sys.argv[1] calc_gaps(station) #calc_histogram(station) #calc_histogram2(station) #calc_histogram3('D7H014Z', 'D7H015Z', 'D7H016Z') #calc_histogram4('D7H008', 'D7H017PLUS')",
"= df1[(df1['Total'] > 1000)].count() print('Total count: {0}'.format(total_count['Total'])) print(' 0: {0}'.format(i0['Total']/total_count['Total'])) print(' 0 -",
"> 10) & (df['Value'] <= 50)].count() i3 = df[(df['Value'] > 50) & (df['Value']",
"last_read_date seconds = diff / np.timedelta64(1, 's') hours = diff / np.timedelta64(1, 'h')",
"& (df['Value'] <= 100)].count() i6 = df[(df['Value'] > 100)].count() print('Total count: {0}'.format(total_count['Value'])) print('",
"(df['Value'] <= 500)].count() i8 = df[(df['Value'] > 500) & (df['Value'] <= 1000)].count() i9",
"- 10: {0}'.format(i1['Value']/total_count['Value'])) print(' 10 - 50: {0}'.format(i2['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i3['Value']/total_count['Value']))",
"left {0} years'.format(total_left / 3600 / 24 / 365.25)) print('Total left {0} years",
"{0}'.format(i8['Value']/total_count['Value'])) print(' > 1000: {0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1, station2): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1),",
"10: {0}'.format(i1['Total']/total_count['Total'])) print(' 10 - 50: {0}'.format(i2['Total']/total_count['Total'])) print(' 50 - 100: {0}'.format(i3['Total']/total_count['Total'])) print('100",
"1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1, station2, station3): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1",
"1000: {0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1, station2): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 =",
"24 / 365.25) days_left = math.floor((total_left / 3600 / 24 % 365.25)) print('Total",
"/ 3600 / 24 / 365.25) days_left = math.floor((total_left / 3600 / 24",
"{0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 5: {0}'.format(i1['Value']/total_count['Value'])) print(' 5 - 10:",
"rate\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df =",
"/ 24 % 365.25)) print('Total gap {0} years'.format(total_gap / 3600 / 24 /",
"200: {0}'.format(i4['Value']/total_count['Value'])) print('200 - 300: {0}'.format(i5['Value']/total_count['Value'])) print('300 - 400: {0}'.format(i6['Value']/total_count['Value'])) print('400 - 500:",
"/ np.timedelta64(1, 'h') if hours > 72: # met stations # if hours",
"{0}'.format(total_count['Total'])) print(' 0: {0}'.format(i0['Total']/total_count['Total'])) print(' 0 - 10: {0}'.format(i1['Total']/total_count['Total'])) print(' 10 - 50:",
"> 50) & (df['Value'] <= 100)].count() i4 = df[(df['Value'] > 100) & (df['Value']",
"3600 / 24 / 365.25)) print('Total left {0} years {1} days'.format(years_left, days_left)) #",
"raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index) df1 = raw1.resample('1H').mean() raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 =",
"{0} years'.format(total_left / 3600 / 24 / 365.25)) print('Total left {0} years {1}",
"df.count() i0 = df[(df['Value'] == 0)].count() i1 = df[(df['Value'] > 0) & (df['Value']",
"{0}'.format(i5['Total']/total_count['Total'])) print('300 - 400: {0}'.format(i6['Total']/total_count['Total'])) print('400 - 500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total']))",
"delimiter=',', fmt=\"%s\") def calc_histogram(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date'])",
"diff = d - last_read_date seconds = diff / np.timedelta64(1, 's') hours =",
"== 0)].count() i1 = df[(df['Value'] > 0) & (df['Value'] <= 10)].count() i2 =",
"= df1[(df1['Total'] > 50) & (df1['Total'] <= 100)].count() i4 = df1[(df1['Total'] > 100)",
"over year sampling rate\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index =",
"[] total_gap = 0; for d in dates: diff = d - last_read_date",
"df1.count() i0 = df1[(df1['Total'] == 0)].count() i1 = df1[(df1['Total'] > 0) & (df1['Total']",
"{0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1, station2, station3): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 =",
"df1[(df1['Total'] > 400) & (df1['Total'] <= 500)].count() i8 = df1[(df1['Total'] > 500) &",
"(df['Value'] <= 10)].count() i3 = df[(df['Value'] > 10) & (df['Value'] <= 20)].count() i4",
"print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 5: {0}'.format(i1['Value']/total_count['Value'])) print(' 5",
"math.floor((total_gap / 3600 / 24 % 365.25)) print('Total gap {0} years'.format(total_gap / 3600",
"df[(df['Value'] > 100) & (df['Value'] <= 200)].count() i5 = df[(df['Value'] > 200) &",
"first_date total_range_seconds = total_range / np.timedelta64(1, 's') last_read_date = first_date gaps = []",
"= pd.to_datetime(raw3.index) df3 = raw3.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] + df3['Value'] total_count",
"= pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3 = raw3.set_index(['Date']) raw3.index = pd.to_datetime(raw3.index) df3 = raw3.resample('1H').mean() df1['Total']",
"- 20: {0}'.format(i3['Value']/total_count['Value'])) print(' 20 - 50: {0}'.format(i4['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i5['Value']/total_count['Value']))",
"= df[(df['Value'] > 100) & (df['Value'] <= 200)].count() i5 = df[(df['Value'] > 200)",
"> 400) & (df['Value'] <= 500)].count() i8 = df[(df['Value'] > 500) & (df['Value']",
"df[(df['Value'] == 0)].count() i1 = df[(df['Value'] > 0) & (df['Value'] <= 10)].count() i2",
"= pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index) df1 = raw1.resample('1H').mean() raw2",
"> 24: # flow stations total_gap = total_gap + seconds gaps.append(seconds) last_read_date =",
"400: {0}'.format(i6['Value']/total_count['Value'])) print('400 - 500: {0}'.format(i7['Value']/total_count['Value'])) print('500 - 1000: {0}'.format(i8['Value']/total_count['Value'])) print(' > 1000:",
"raw1.resample('1H').mean() raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 =",
"{0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index",
"pd.to_datetime(raw.index) df = raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station): \"\"\"Resample station data\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station),",
"pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index) df1 = raw1.resample('1H').mean() raw2 =",
"50: {0}'.format(i2['Total']/total_count['Total'])) print(' 50 - 100: {0}'.format(i3['Total']/total_count['Total'])) print('100 - 200: {0}'.format(i4['Total']/total_count['Total'])) print('200 -",
"i1 = df[(df['Value'] > 0) & (df['Value'] <= 10)].count() i2 = df[(df['Value'] >",
"def calc_histogram3(station1, station2, station3): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date'])",
"histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index) df1 =",
"24 / 365.25) days = math.floor((total_gap / 3600 / 24 % 365.25)) print('Total",
"& (df1['Total'] <= 10)].count() i2 = df1[(df1['Total'] > 10) & (df1['Total'] <= 50)].count()",
"10 - 50: {0}'.format(i2['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i3['Value']/total_count['Value'])) print('100 - 200: {0}'.format(i4['Value']/total_count['Value']))",
"df[(df['Value'] > 1000)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 10:",
"df2['Value'] total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count() i1 = df1[(df1['Total'] >",
"<= 1000)].count() i9 = df[(df['Value'] > 1000)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value']))",
"first_date gaps = [] total_gap = 0; for d in dates: diff =",
"<= 400)].count() i7 = df[(df['Value'] > 400) & (df['Value'] <= 500)].count() i8 =",
"print(' > 1000: {0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1, station2): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date'])",
"d - last_read_date seconds = diff / np.timedelta64(1, 's') hours = diff /",
"total_gap = total_gap + seconds gaps.append(seconds) last_read_date = d print('Number of gaps {0}'.format(len(gaps)))",
"400)].count() i7 = df1[(df1['Total'] > 400) & (df1['Total'] <= 500)].count() i8 = df1[(df1['Total']",
"stations total_gap = total_gap + seconds gaps.append(seconds) last_read_date = d print('Number of gaps",
"df3 = raw3.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] + df3['Value'] total_count = df1.count()",
"df3['Value'] total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count() i1 = df1[(df1['Total'] >",
"print(' 10 - 20: {0}'.format(i3['Value']/total_count['Value'])) print(' 20 - 50: {0}'.format(i4['Value']/total_count['Value'])) print(' 50 -",
"pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() df =",
"10: {0}'.format(i2['Value']/total_count['Value'])) print(' 10 - 20: {0}'.format(i3['Value']/total_count['Value'])) print(' 20 - 50: {0}'.format(i4['Value']/total_count['Value'])) print('",
"= math.floor(total_left / 3600 / 24 / 365.25) days_left = math.floor((total_left / 3600",
"== 0)].count() i1 = df[(df['Value'] > 0) & (df['Value'] <= 5)].count() i2 =",
"/ 24 % 365.25)) print('Total left {0} years'.format(total_left / 3600 / 24 /",
"print('400 - 500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def",
"24 / 365.25)) print('Total gap {0} years {1} days'.format(years, days)) total_left = total_range_seconds",
"= math.floor((total_left / 3600 / 24 % 365.25)) print('Total left {0} years'.format(total_left /",
"parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station):",
"print(' 50 - 100: {0}'.format(i5['Value']/total_count['Value'])) print(' > 100: {0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station): \"\"\"Get median",
"{0}'.format(i3['Value']/total_count['Value'])) print(' 20 - 50: {0}'.format(i4['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i5['Value']/total_count['Value'])) print(' >",
"pd import numpy as np import csv def calc_gaps(station): \"\"\"Calculate gaps in time",
"50)].count() i3 = df1[(df1['Total'] > 50) & (df1['Total'] <= 100)].count() i4 = df1[(df1['Total']",
"{0}'.format(i2['Value']/total_count['Value'])) print(' 10 - 20: {0}'.format(i3['Value']/total_count['Value'])) print(' 20 - 50: {0}'.format(i4['Value']/total_count['Value'])) print(' 50",
"raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean()",
"<= 1000)].count() i9 = df1[(df1['Total'] > 1000)].count() print('Total count: {0}'.format(total_count['Total'])) print(' 0: {0}'.format(i0['Total']/total_count['Total']))",
"{0}'.format(i3['Total']/total_count['Total'])) print('100 - 200: {0}'.format(i4['Total']/total_count['Total'])) print('200 - 300: {0}'.format(i5['Total']/total_count['Total'])) print('300 - 400: {0}'.format(i6['Total']/total_count['Total']))",
"gaps = [] total_gap = 0; for d in dates: diff = d",
"i5 = df[(df['Value'] > 200) & (df['Value'] <= 300)].count() i6 = df[(df['Value'] >",
"df[(df['Value'] > 0) & (df['Value'] <= 5)].count() i2 = df[(df['Value'] > 5) &",
"raw1 = raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index) df1 = raw1.resample('1H').mean() raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date'])",
"10 - 20: {0}'.format(i3['Value']/total_count['Value'])) print(' 20 - 50: {0}'.format(i4['Value']/total_count['Value'])) print(' 50 - 100:",
"= raw3.set_index(['Date']) raw3.index = pd.to_datetime(raw3.index) df3 = raw3.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value']",
"& (df1['Total'] <= 50)].count() i3 = df1[(df1['Total'] > 50) & (df1['Total'] <= 100)].count()",
"numpy as np import csv def calc_gaps(station): \"\"\"Calculate gaps in time series\"\"\" df",
"500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1, station2,",
"5: {0}'.format(i1['Value']/total_count['Value'])) print(' 5 - 10: {0}'.format(i2['Value']/total_count['Value'])) print(' 10 - 20: {0}'.format(i3['Value']/total_count['Value'])) print('",
"raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('Y').count()",
"= total_gap + seconds gaps.append(seconds) last_read_date = d print('Number of gaps {0}'.format(len(gaps))) years",
"(df['Value'] <= 50)].count() i3 = df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i4",
"{1}'.format(first_date, last_date)) total_range = last_date - first_date total_range_seconds = total_range / np.timedelta64(1, 's')",
"years {1} days'.format(years_left, days_left)) # gap_file = '{0}-gaps.txt'.format(station) # np.savetxt(gap_file, gaps, delimiter=',', fmt=\"%s\")",
"<= 200)].count() i5 = df[(df['Value'] > 200) & (df['Value'] <= 300)].count() i6 =",
"print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 5: {0}'.format(i1['Value']/total_count['Value'])) print(' 5 - 10: {0}'.format(i2['Value']/total_count['Value']))",
"= 0; for d in dates: diff = d - last_read_date seconds =",
"= df1[(df1['Total'] > 500) & (df1['Total'] <= 1000)].count() i9 = df1[(df1['Total'] > 1000)].count()",
"50) & (df['Value'] <= 100)].count() i6 = df[(df['Value'] > 100)].count() print('Total count: {0}'.format(total_count['Value']))",
"print(' 5 - 10: {0}'.format(i2['Value']/total_count['Value'])) print(' 10 - 20: {0}'.format(i3['Value']/total_count['Value'])) print(' 20 -",
"math import pandas as pd import numpy as np import csv def calc_gaps(station):",
"gaps.append(seconds) last_read_date = d print('Number of gaps {0}'.format(len(gaps))) years = math.floor(total_gap / 3600",
"(df1['Total'] <= 200)].count() i5 = df1[(df1['Total'] > 200) & (df1['Total'] <= 300)].count() i6",
"print('Total gap {0} years'.format(total_gap / 3600 / 24 / 365.25)) print('Total gap {0}",
"(df1['Total'] <= 1000)].count() i9 = df1[(df1['Total'] > 1000)].count() print('Total count: {0}'.format(total_count['Total'])) print(' 0:",
"print('Total left {0} years'.format(total_left / 3600 / 24 / 365.25)) print('Total left {0}",
"'h') if hours > 72: # met stations # if hours > 24:",
"/ 365.25)) print('Total left {0} years {1} days'.format(years_left, days_left)) # gap_file = '{0}-gaps.txt'.format(station)",
"np.timedelta64(1, 's') hours = diff / np.timedelta64(1, 'h') if hours > 72: #",
"<= 50)].count() i3 = df1[(df1['Total'] > 50) & (df1['Total'] <= 100)].count() i4 =",
"df = raw.resample('1H').mean() df = df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station)) if __name__ == '__main__': station",
"= df1['Value'] + df2['Value'] total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count() i1",
"print(' 0 - 5: {0}'.format(i1['Value']/total_count['Value'])) print(' 5 - 10: {0}'.format(i2['Value']/total_count['Value'])) print(' 10 -",
"df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i4 = df[(df['Value'] > 100) &",
"= df[(df['Value'] > 10) & (df['Value'] <= 50)].count() i3 = df[(df['Value'] > 50)",
"= raw1.resample('1H').mean() raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2",
"i3 = df[(df['Value'] > 10) & (df['Value'] <= 20)].count() i4 = df[(df['Value'] >",
"in dates: diff = d - last_read_date seconds = diff / np.timedelta64(1, 's')",
"10)].count() i2 = df1[(df1['Total'] > 10) & (df1['Total'] <= 50)].count() i3 = df1[(df1['Total']",
"(df1['Total'] <= 300)].count() i6 = df1[(df1['Total'] > 300) & (df1['Total'] <= 400)].count() i7",
"raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() df = df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station)) if",
"total_gap years_left = math.floor(total_left / 3600 / 24 / 365.25) days_left = math.floor((total_left",
"- 500: {0}'.format(i7['Value']/total_count['Value'])) print('500 - 1000: {0}'.format(i8['Value']/total_count['Value'])) print(' > 1000: {0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1,",
"{0} years'.format(total_gap / 3600 / 24 / 365.25)) print('Total gap {0} years {1}",
"raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() total_count = df.count() i0 = df[(df['Value']",
"= raw3.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] + df3['Value'] total_count = df1.count() i0",
"& (df1['Total'] <= 400)].count() i7 = df1[(df1['Total'] > 400) & (df1['Total'] <= 500)].count()",
"parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() df = df.round({'Value':",
"365.25)) print('Total left {0} years'.format(total_left / 3600 / 24 / 365.25)) print('Total left",
"def calc_histogram2(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index =",
"import numpy as np import csv def calc_gaps(station): \"\"\"Calculate gaps in time series\"\"\"",
"df = raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station): \"\"\"Resample station data\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date'])",
"50) & (df1['Total'] <= 100)].count() i4 = df1[(df1['Total'] > 100) & (df1['Total'] <=",
"50) & (df['Value'] <= 100)].count() i4 = df[(df['Value'] > 100) & (df['Value'] <=",
"= diff / np.timedelta64(1, 's') hours = diff / np.timedelta64(1, 'h') if hours",
"i4 = df[(df['Value'] > 20) & (df['Value'] <= 50)].count() i5 = df[(df['Value'] >",
"raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean()",
"total_range / np.timedelta64(1, 's') last_read_date = first_date gaps = [] total_gap = 0;",
"raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() df1['Total'] = df1['Value'] +",
"print('200 - 300: {0}'.format(i5['Total']/total_count['Total'])) print('300 - 400: {0}'.format(i6['Total']/total_count['Total'])) print('400 - 500: {0}'.format(i7['Total']/total_count['Total'])) print('500",
"> 100: {0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station): \"\"\"Get median over year sampling rate\"\"\" raw =",
"if __name__ == '__main__': station = sys.argv[1] calc_gaps(station) #calc_histogram(station) #calc_histogram2(station) #calc_histogram3('D7H014Z', 'D7H015Z', 'D7H016Z')",
"= raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index) df1 = raw1.resample('1H').mean() raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2",
"500: {0}'.format(i7['Value']/total_count['Value'])) print('500 - 1000: {0}'.format(i8['Value']/total_count['Value'])) print(' > 1000: {0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1, station2):",
"raw1.index = pd.to_datetime(raw1.index) df1 = raw1.resample('1H').mean() raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date'])",
"- 300: {0}'.format(i5['Value']/total_count['Value'])) print('300 - 400: {0}'.format(i6['Value']/total_count['Value'])) print('400 - 500: {0}'.format(i7['Value']/total_count['Value'])) print('500 -",
"of gaps {0}'.format(len(gaps))) years = math.floor(total_gap / 3600 / 24 / 365.25) days",
"np.timedelta64(1, 'h') if hours > 72: # met stations # if hours >",
"& (df1['Total'] <= 200)].count() i5 = df1[(df1['Total'] > 200) & (df1['Total'] <= 300)].count()",
"{0}'.format(i6['Value']/total_count['Value'])) print('400 - 500: {0}'.format(i7['Value']/total_count['Value'])) print('500 - 1000: {0}'.format(i8['Value']/total_count['Value'])) print(' > 1000: {0}'.format(i9['Value']/total_count['Value']))",
"'s') hours = diff / np.timedelta64(1, 'h') if hours > 72: # met",
"raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() total_count = df.count() i0",
"df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df = df.set_index(['Date']) df.index = pd.to_datetime(df.index) dates = df.index.values",
"i3 = df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i4 = df[(df['Value'] >",
"= [] total_gap = 0; for d in dates: diff = d -",
"met stations # if hours > 24: # flow stations total_gap = total_gap",
"300: {0}'.format(i5['Value']/total_count['Value'])) print('300 - 400: {0}'.format(i6['Value']/total_count['Value'])) print('400 - 500: {0}'.format(i7['Value']/total_count['Value'])) print('500 - 1000:",
"- 400: {0}'.format(i6['Total']/total_count['Total'])) print('400 - 500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' >",
"50: {0}'.format(i2['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i3['Value']/total_count['Value'])) print('100 - 200: {0}'.format(i4['Value']/total_count['Value'])) print('200 -",
"> 100) & (df1['Total'] <= 200)].count() i5 = df1[(df1['Total'] > 200) & (df1['Total']",
"300)].count() i6 = df[(df['Value'] > 300) & (df['Value'] <= 400)].count() i7 = df[(df['Value']",
"<= 400)].count() i7 = df1[(df1['Total'] > 400) & (df1['Total'] <= 500)].count() i8 =",
"365.25)) print('Total left {0} years {1} days'.format(years_left, days_left)) # gap_file = '{0}-gaps.txt'.format(station) #",
"print('Total left {0} years {1} days'.format(years_left, days_left)) # gap_file = '{0}-gaps.txt'.format(station) # np.savetxt(gap_file,",
"- 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station): \"\"\"Get histogram\"\"\" raw =",
"{0}'.format(i5['Value']/total_count['Value'])) print(' > 100: {0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station): \"\"\"Get median over year sampling rate\"\"\"",
"station2, station3): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index =",
"> 20) & (df['Value'] <= 50)].count() i5 = df[(df['Value'] > 50) & (df['Value']",
"- first_date total_range_seconds = total_range / np.timedelta64(1, 's') last_read_date = first_date gaps =",
"> 1000: {0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1, station2): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1",
"> 500) & (df1['Total'] <= 1000)].count() i9 = df1[(df1['Total'] > 1000)].count() print('Total count:",
"pd.to_datetime(raw.index) df = raw.resample('1H').mean() df = df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station)) if __name__ == '__main__':",
"# met stations # if hours > 24: # flow stations total_gap =",
"/ np.timedelta64(1, 's') last_read_date = first_date gaps = [] total_gap = 0; for",
"= raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3",
"pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3 = raw3.set_index(['Date']) raw3.index = pd.to_datetime(raw3.index) df3 = raw3.resample('1H').mean() df1['Total'] =",
"series\"\"\" df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df = df.set_index(['Date']) df.index = pd.to_datetime(df.index) dates =",
"(df1['Total'] <= 500)].count() i8 = df1[(df1['Total'] > 500) & (df1['Total'] <= 1000)].count() i9",
"10)].count() i3 = df[(df['Value'] > 10) & (df['Value'] <= 20)].count() i4 = df[(df['Value']",
"total_gap + seconds gaps.append(seconds) last_read_date = d print('Number of gaps {0}'.format(len(gaps))) years =",
"(df['Value'] <= 10)].count() i2 = df[(df['Value'] > 10) & (df['Value'] <= 50)].count() i3",
"df1['Value'] + df2['Value'] total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count() i1 =",
"d print('Number of gaps {0}'.format(len(gaps))) years = math.floor(total_gap / 3600 / 24 /",
"10) & (df['Value'] <= 20)].count() i4 = df[(df['Value'] > 20) & (df['Value'] <=",
"i3 = df1[(df1['Total'] > 50) & (df1['Total'] <= 100)].count() i4 = df1[(df1['Total'] >",
"= df1[(df1['Total'] == 0)].count() i1 = df1[(df1['Total'] > 0) & (df1['Total'] <= 10)].count()",
"0: {0}'.format(i0['Total']/total_count['Total'])) print(' 0 - 10: {0}'.format(i1['Total']/total_count['Total'])) print(' 10 - 50: {0}'.format(i2['Total']/total_count['Total'])) print('",
"0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 5: {0}'.format(i1['Value']/total_count['Value'])) print(' 5 - 10: {0}'.format(i2['Value']/total_count['Value'])) print('",
"= df[(df['Value'] > 5) & (df['Value'] <= 10)].count() i3 = df[(df['Value'] > 10)",
"to {1}'.format(first_date, last_date)) total_range = last_date - first_date total_range_seconds = total_range / np.timedelta64(1,",
"# if hours > 24: # flow stations total_gap = total_gap + seconds",
"- 10: {0}'.format(i1['Total']/total_count['Total'])) print(' 10 - 50: {0}'.format(i2['Total']/total_count['Total'])) print(' 50 - 100: {0}'.format(i3['Total']/total_count['Total']))",
"years'.format(total_left / 3600 / 24 / 365.25)) print('Total left {0} years {1} days'.format(years_left,",
"i2 = df[(df['Value'] > 10) & (df['Value'] <= 50)].count() i3 = df[(df['Value'] >",
"left {0} years {1} days'.format(years_left, days_left)) # gap_file = '{0}-gaps.txt'.format(station) # np.savetxt(gap_file, gaps,",
"from {0} to {1}'.format(first_date, last_date)) total_range = last_date - first_date total_range_seconds = total_range",
"raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() total_count = df.count() i0 = df[(df['Value'] ==",
"df[(df['Value'] > 500) & (df['Value'] <= 1000)].count() i9 = df[(df['Value'] > 1000)].count() print('Total",
"> 0) & (df1['Total'] <= 10)].count() i2 = df1[(df1['Total'] > 10) & (df1['Total']",
"= pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() df",
"= raw2.resample('1H').mean() raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3 = raw3.set_index(['Date']) raw3.index = pd.to_datetime(raw3.index) df3",
"(df['Value'] <= 400)].count() i7 = df[(df['Value'] > 400) & (df['Value'] <= 500)].count() i8",
"{1} days'.format(years, days)) total_left = total_range_seconds - total_gap years_left = math.floor(total_left / 3600",
"print(' 0 - 10: {0}'.format(i1['Total']/total_count['Total'])) print(' 10 - 50: {0}'.format(i2['Total']/total_count['Total'])) print(' 50 -",
"raw3 = raw3.set_index(['Date']) raw3.index = pd.to_datetime(raw3.index) df3 = raw3.resample('1H').mean() df1['Total'] = df1['Value'] +",
"stations # if hours > 24: # flow stations total_gap = total_gap +",
"{0}'.format(i3['Value']/total_count['Value'])) print('100 - 200: {0}'.format(i4['Value']/total_count['Value'])) print('200 - 300: {0}'.format(i5['Value']/total_count['Value'])) print('300 - 400: {0}'.format(i6['Value']/total_count['Value']))",
"{0}'.format(i4['Total']/total_count['Total'])) print('200 - 300: {0}'.format(i5['Total']/total_count['Total'])) print('300 - 400: {0}'.format(i6['Total']/total_count['Total'])) print('400 - 500: {0}'.format(i7['Total']/total_count['Total']))",
"> 0) & (df['Value'] <= 5)].count() i2 = df[(df['Value'] > 5) & (df['Value']",
"50)].count() i5 = df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i6 = df[(df['Value']",
"<= 100)].count() i4 = df[(df['Value'] > 100) & (df['Value'] <= 200)].count() i5 =",
"100: {0}'.format(i5['Value']/total_count['Value'])) print(' > 100: {0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station): \"\"\"Get median over year sampling",
"> 50) & (df['Value'] <= 100)].count() i6 = df[(df['Value'] > 100)].count() print('Total count:",
"total_range_seconds - total_gap years_left = math.floor(total_left / 3600 / 24 / 365.25) days_left",
"{0}'.format(i2['Total']/total_count['Total'])) print(' 50 - 100: {0}'.format(i3['Total']/total_count['Total'])) print('100 - 200: {0}'.format(i4['Total']/total_count['Total'])) print('200 - 300:",
"= df1['Value'] + df2['Value'] + df3['Value'] total_count = df1.count() i0 = df1[(df1['Total'] ==",
"= diff / np.timedelta64(1, 'h') if hours > 72: # met stations #",
"station2): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index)",
"dates[0] last_date = dates[-1] print('Data from {0} to {1}'.format(first_date, last_date)) total_range = last_date",
"days_left)) # gap_file = '{0}-gaps.txt'.format(station) # np.savetxt(gap_file, gaps, delimiter=',', fmt=\"%s\") def calc_histogram(station): \"\"\"Get",
"- 1000: {0}'.format(i8['Value']/total_count['Value'])) print(' > 1000: {0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1, station2): \"\"\"Get histogram\"\"\" raw1",
"200)].count() i5 = df1[(df1['Total'] > 200) & (df1['Total'] <= 300)].count() i6 = df1[(df1['Total']",
"500) & (df['Value'] <= 1000)].count() i9 = df[(df['Value'] > 1000)].count() print('Total count: {0}'.format(total_count['Value']))",
"dates[-1] print('Data from {0} to {1}'.format(first_date, last_date)) total_range = last_date - first_date total_range_seconds",
"for d in dates: diff = d - last_read_date seconds = diff /",
"= df1[(df1['Total'] > 0) & (df1['Total'] <= 10)].count() i2 = df1[(df1['Total'] > 10)",
"= raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() df = df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station))",
"gaps {0}'.format(len(gaps))) years = math.floor(total_gap / 3600 / 24 / 365.25) days =",
"400) & (df['Value'] <= 500)].count() i8 = df[(df['Value'] > 500) & (df['Value'] <=",
"df.index.values first_date = dates[0] last_date = dates[-1] print('Data from {0} to {1}'.format(first_date, last_date))",
"<= 500)].count() i8 = df1[(df1['Total'] > 500) & (df1['Total'] <= 1000)].count() i9 =",
"total_range = last_date - first_date total_range_seconds = total_range / np.timedelta64(1, 's') last_read_date =",
"gap_file = '{0}-gaps.txt'.format(station) # np.savetxt(gap_file, gaps, delimiter=',', fmt=\"%s\") def calc_histogram(station): \"\"\"Get histogram\"\"\" raw",
"pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() total_count =",
"= raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station): \"\"\"Resample station",
"calc_gaps(station): \"\"\"Calculate gaps in time series\"\"\" df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df = df.set_index(['Date'])",
"days = math.floor((total_gap / 3600 / 24 % 365.25)) print('Total gap {0} years'.format(total_gap",
"/ 24 / 365.25)) print('Total left {0} years {1} days'.format(years_left, days_left)) # gap_file",
"> 0) & (df['Value'] <= 10)].count() i2 = df[(df['Value'] > 10) & (df['Value']",
"pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df = df.set_index(['Date']) df.index = pd.to_datetime(df.index) dates = df.index.values first_date =",
"1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1, station2, station3): \"\"\"Get histogram\"\"\" raw1",
"= first_date gaps = [] total_gap = 0; for d in dates: diff",
"i1 = df[(df['Value'] > 0) & (df['Value'] <= 5)].count() i2 = df[(df['Value'] >",
"parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() total_count = df.count()",
"= raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station): \"\"\"Resample station data\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw",
"seconds gaps.append(seconds) last_read_date = d print('Number of gaps {0}'.format(len(gaps))) years = math.floor(total_gap /",
"{0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station): \"\"\"Get median over year sampling rate\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date'])",
"= total_range / np.timedelta64(1, 's') last_read_date = first_date gaps = [] total_gap =",
"raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station): \"\"\"Resample station data\"\"\"",
"count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 10: {0}'.format(i1['Value']/total_count['Value'])) print(' 10 -",
"flow stations total_gap = total_gap + seconds gaps.append(seconds) last_read_date = d print('Number of",
"- 100: {0}'.format(i3['Value']/total_count['Value'])) print('100 - 200: {0}'.format(i4['Value']/total_count['Value'])) print('200 - 300: {0}'.format(i5['Value']/total_count['Value'])) print('300 -",
"days)) total_left = total_range_seconds - total_gap years_left = math.floor(total_left / 3600 / 24",
"print(' 10 - 50: {0}'.format(i2['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i3['Value']/total_count['Value'])) print('100 - 200:",
"(df['Value'] <= 5)].count() i2 = df[(df['Value'] > 5) & (df['Value'] <= 10)].count() i3",
"hours > 24: # flow stations total_gap = total_gap + seconds gaps.append(seconds) last_read_date",
"i9 = df1[(df1['Total'] > 1000)].count() print('Total count: {0}'.format(total_count['Total'])) print(' 0: {0}'.format(i0['Total']/total_count['Total'])) print(' 0",
"500)].count() i8 = df1[(df1['Total'] > 500) & (df1['Total'] <= 1000)].count() i9 = df1[(df1['Total']",
"i6 = df[(df['Value'] > 300) & (df['Value'] <= 400)].count() i7 = df[(df['Value'] >",
"raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3 = raw3.set_index(['Date'])",
"pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def",
"i5 = df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i6 = df[(df['Value'] >",
"import csv def calc_gaps(station): \"\"\"Calculate gaps in time series\"\"\" df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date'])",
"+ df2['Value'] + df3['Value'] total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count() i1",
"& (df['Value'] <= 10)].count() i2 = df[(df['Value'] > 10) & (df['Value'] <= 50)].count()",
"- 400: {0}'.format(i6['Value']/total_count['Value'])) print('400 - 500: {0}'.format(i7['Value']/total_count['Value'])) print('500 - 1000: {0}'.format(i8['Value']/total_count['Value'])) print(' >",
"5 - 10: {0}'.format(i2['Value']/total_count['Value'])) print(' 10 - 20: {0}'.format(i3['Value']/total_count['Value'])) print(' 20 - 50:",
"gap {0} years'.format(total_gap / 3600 / 24 / 365.25)) print('Total gap {0} years",
"24: # flow stations total_gap = total_gap + seconds gaps.append(seconds) last_read_date = d",
"print(' 50 - 100: {0}'.format(i3['Value']/total_count['Value'])) print('100 - 200: {0}'.format(i4['Value']/total_count['Value'])) print('200 - 300: {0}'.format(i5['Value']/total_count['Value']))",
"/ 24 / 365.25) days_left = math.floor((total_left / 3600 / 24 % 365.25))",
"df.to_csv('{0}_resampled.csv'.format(station)) if __name__ == '__main__': station = sys.argv[1] calc_gaps(station) #calc_histogram(station) #calc_histogram2(station) #calc_histogram3('D7H014Z', 'D7H015Z',",
"print('100 - 200: {0}'.format(i4['Total']/total_count['Total'])) print('200 - 300: {0}'.format(i5['Total']/total_count['Total'])) print('300 - 400: {0}'.format(i6['Total']/total_count['Total'])) print('400",
"np import csv def calc_gaps(station): \"\"\"Calculate gaps in time series\"\"\" df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station),",
"<= 10)].count() i2 = df1[(df1['Total'] > 10) & (df1['Total'] <= 50)].count() i3 =",
"<= 100)].count() i4 = df1[(df1['Total'] > 100) & (df1['Total'] <= 200)].count() i5 =",
"/ 24 / 365.25) days = math.floor((total_gap / 3600 / 24 % 365.25))",
"i9 = df[(df['Value'] > 1000)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0",
"df[(df['Value'] > 300) & (df['Value'] <= 400)].count() i7 = df[(df['Value'] > 400) &",
"parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() df1['Total'] = df1['Value']",
"print('300 - 400: {0}'.format(i6['Total']/total_count['Total'])) print('400 - 500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print('",
"- 100: {0}'.format(i3['Total']/total_count['Total'])) print('100 - 200: {0}'.format(i4['Total']/total_count['Total'])) print('200 - 300: {0}'.format(i5['Total']/total_count['Total'])) print('300 -",
"{0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1, station2): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date'])",
"100: {0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station): \"\"\"Get median over year sampling rate\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station),",
"\"\"\"Get median over year sampling rate\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date'])",
"parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index) df1 = raw1.resample('1H').mean() raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2),",
"= df[(df['Value'] > 500) & (df['Value'] <= 1000)].count() i9 = df[(df['Value'] > 1000)].count()",
"count: {0}'.format(total_count['Total'])) print(' 0: {0}'.format(i0['Total']/total_count['Total'])) print(' 0 - 10: {0}'.format(i1['Total']/total_count['Total'])) print(' 10 -",
"df1['Total'] = df1['Value'] + df2['Value'] + df3['Value'] total_count = df1.count() i0 = df1[(df1['Total']",
"pd.to_datetime(df.index) dates = df.index.values first_date = dates[0] last_date = dates[-1] print('Data from {0}",
"hours = diff / np.timedelta64(1, 'h') if hours > 72: # met stations",
"i7 = df[(df['Value'] > 400) & (df['Value'] <= 500)].count() i8 = df[(df['Value'] >",
"df.index = pd.to_datetime(df.index) dates = df.index.values first_date = dates[0] last_date = dates[-1] print('Data",
"station = sys.argv[1] calc_gaps(station) #calc_histogram(station) #calc_histogram2(station) #calc_histogram3('D7H014Z', 'D7H015Z', 'D7H016Z') #calc_histogram4('D7H008', 'D7H017PLUS') #median_sampling_rate(station) #resample(station)",
"24 % 365.25)) print('Total left {0} years'.format(total_left / 3600 / 24 / 365.25))",
"& (df['Value'] <= 300)].count() i6 = df[(df['Value'] > 300) & (df['Value'] <= 400)].count()",
"0) & (df['Value'] <= 10)].count() i2 = df[(df['Value'] > 10) & (df['Value'] <=",
"i8 = df[(df['Value'] > 500) & (df['Value'] <= 1000)].count() i9 = df[(df['Value'] >",
"- 50: {0}'.format(i4['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i5['Value']/total_count['Value'])) print(' > 100: {0}'.format(i6['Value']/total_count['Value'])) def",
"i5 = df1[(df1['Total'] > 200) & (df1['Total'] <= 300)].count() i6 = df1[(df1['Total'] >",
"print('200 - 300: {0}'.format(i5['Value']/total_count['Value'])) print('300 - 400: {0}'.format(i6['Value']/total_count['Value'])) print('400 - 500: {0}'.format(i7['Value']/total_count['Value'])) print('500",
"median_sampling_rate(station): \"\"\"Get median over year sampling rate\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw =",
"> 72: # met stations # if hours > 24: # flow stations",
"/ 3600 / 24 / 365.25) days = math.floor((total_gap / 3600 / 24",
"pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() df1['Total'] =",
"= df1[(df1['Total'] > 100) & (df1['Total'] <= 200)].count() i5 = df1[(df1['Total'] > 200)",
"<= 20)].count() i4 = df[(df['Value'] > 20) & (df['Value'] <= 50)].count() i5 =",
"0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 10: {0}'.format(i1['Value']/total_count['Value'])) print(' 10 - 50: {0}'.format(i2['Value']/total_count['Value'])) print('",
"print('Total gap {0} years {1} days'.format(years, days)) total_left = total_range_seconds - total_gap years_left",
"calc_histogram3(station1, station2, station3): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index",
"& (df['Value'] <= 500)].count() i8 = df[(df['Value'] > 500) & (df['Value'] <= 1000)].count()",
"def calc_gaps(station): \"\"\"Calculate gaps in time series\"\"\" df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df =",
"time series\"\"\" df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df = df.set_index(['Date']) df.index = pd.to_datetime(df.index) dates",
"import sys import math import pandas as pd import numpy as np import",
"& (df['Value'] <= 100)].count() i4 = df[(df['Value'] > 100) & (df['Value'] <= 200)].count()",
"<= 300)].count() i6 = df[(df['Value'] > 300) & (df['Value'] <= 400)].count() i7 =",
"400)].count() i7 = df[(df['Value'] > 400) & (df['Value'] <= 500)].count() i8 = df[(df['Value']",
"0)].count() i1 = df[(df['Value'] > 0) & (df['Value'] <= 5)].count() i2 = df[(df['Value']",
"(df1['Total'] <= 400)].count() i7 = df1[(df1['Total'] > 400) & (df1['Total'] <= 500)].count() i8",
"/ 365.25) days_left = math.floor((total_left / 3600 / 24 % 365.25)) print('Total left",
"== 0)].count() i1 = df1[(df1['Total'] > 0) & (df1['Total'] <= 10)].count() i2 =",
"= df1.count() i0 = df1[(df1['Total'] == 0)].count() i1 = df1[(df1['Total'] > 0) &",
"{0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 10: {0}'.format(i1['Value']/total_count['Value'])) print(' 10 - 50:",
"df2['Value'] + df3['Value'] total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count() i1 =",
"\"\"\"Calculate gaps in time series\"\"\" df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df = df.set_index(['Date']) df.index",
"/ 3600 / 24 / 365.25)) print('Total left {0} years {1} days'.format(years_left, days_left))",
"{0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1, station2, station3): \"\"\"Get histogram\"\"\" raw1 =",
"\"\"\" import sys import math import pandas as pd import numpy as np",
"= total_range_seconds - total_gap years_left = math.floor(total_left / 3600 / 24 / 365.25)",
"- last_read_date seconds = diff / np.timedelta64(1, 's') hours = diff / np.timedelta64(1,",
"= df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i6 = df[(df['Value'] > 100)].count()",
"raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index) df1 = raw1.resample('1H').mean()",
"= pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3 = raw3.set_index(['Date']) raw3.index",
"= df.index.values first_date = dates[0] last_date = dates[-1] print('Data from {0} to {1}'.format(first_date,",
"{0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 10: {0}'.format(i1['Value']/total_count['Value'])) print(' 10 - 50: {0}'.format(i2['Value']/total_count['Value'])) print(' 50",
"= pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station))",
"calc_histogram(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index)",
"/ 365.25)) print('Total gap {0} years {1} days'.format(years, days)) total_left = total_range_seconds -",
"0) & (df1['Total'] <= 10)].count() i2 = df1[(df1['Total'] > 10) & (df1['Total'] <=",
"+ df3['Value'] total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count() i1 = df1[(df1['Total']",
"raw2.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] total_count = df1.count() i0 = df1[(df1['Total'] ==",
"csv def calc_gaps(station): \"\"\"Calculate gaps in time series\"\"\" df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df",
"df[(df['Value'] > 5) & (df['Value'] <= 10)].count() i3 = df[(df['Value'] > 10) &",
"\"\"\"Resample station data\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index)",
"10 - 50: {0}'.format(i2['Total']/total_count['Total'])) print(' 50 - 100: {0}'.format(i3['Total']/total_count['Total'])) print('100 - 200: {0}'.format(i4['Total']/total_count['Total']))",
"= df1[(df1['Total'] > 300) & (df1['Total'] <= 400)].count() i7 = df1[(df1['Total'] > 400)",
"& (df1['Total'] <= 1000)].count() i9 = df1[(df1['Total'] > 1000)].count() print('Total count: {0}'.format(total_count['Total'])) print('",
"50: {0}'.format(i4['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i5['Value']/total_count['Value'])) print(' > 100: {0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station):",
"print('300 - 400: {0}'.format(i6['Value']/total_count['Value'])) print('400 - 500: {0}'.format(i7['Value']/total_count['Value'])) print('500 - 1000: {0}'.format(i8['Value']/total_count['Value'])) print('",
"{0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date'])",
"pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3 = raw3.set_index(['Date']) raw3.index =",
"= df.count() i0 = df[(df['Value'] == 0)].count() i1 = df[(df['Value'] > 0) &",
"df2 = raw2.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] total_count = df1.count() i0 =",
"50)].count() i3 = df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i4 = df[(df['Value']",
"= pd.to_datetime(raw.index) df = raw.resample('1H').mean() df = df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station)) if __name__ ==",
"df1['Total'] = df1['Value'] + df2['Value'] total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count()",
"> 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw =",
"print('100 - 200: {0}'.format(i4['Value']/total_count['Value'])) print('200 - 300: {0}'.format(i5['Value']/total_count['Value'])) print('300 - 400: {0}'.format(i6['Value']/total_count['Value'])) print('400",
"3600 / 24 / 365.25) days = math.floor((total_gap / 3600 / 24 %",
"# np.savetxt(gap_file, gaps, delimiter=',', fmt=\"%s\") def calc_histogram(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date'])",
"= df[(df['Value'] > 100)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 -",
"def calc_histogram(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index =",
"sampling rate\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df",
"raw.resample('1H').mean() df = df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station)) if __name__ == '__main__': station = sys.argv[1]",
"= '{0}-gaps.txt'.format(station) # np.savetxt(gap_file, gaps, delimiter=',', fmt=\"%s\") def calc_histogram(station): \"\"\"Get histogram\"\"\" raw =",
"np.timedelta64(1, 's') last_read_date = first_date gaps = [] total_gap = 0; for d",
"df = raw.resample('1H').mean() total_count = df.count() i0 = df[(df['Value'] == 0)].count() i1 =",
"data\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df =",
"= df[(df['Value'] > 1000)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 -",
"math.floor(total_left / 3600 / 24 / 365.25) days_left = math.floor((total_left / 3600 /",
"{0}'.format(i4['Value']/total_count['Value'])) print('200 - 300: {0}'.format(i5['Value']/total_count['Value'])) print('300 - 400: {0}'.format(i6['Value']/total_count['Value'])) print('400 - 500: {0}'.format(i7['Value']/total_count['Value']))",
"= pd.to_datetime(raw1.index) df1 = raw1.resample('1H').mean() raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index",
"= df[(df['Value'] == 0)].count() i1 = df[(df['Value'] > 0) & (df['Value'] <= 5)].count()",
"(df['Value'] <= 300)].count() i6 = df[(df['Value'] > 300) & (df['Value'] <= 400)].count() i7",
"df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i6 = df[(df['Value'] > 100)].count() print('Total",
"= raw2.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] total_count = df1.count() i0 = df1[(df1['Total']",
"- 5: {0}'.format(i1['Value']/total_count['Value'])) print(' 5 - 10: {0}'.format(i2['Value']/total_count['Value'])) print(' 10 - 20: {0}'.format(i3['Value']/total_count['Value']))",
"raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station): \"\"\"Resample station data\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw =",
"gaps, delimiter=',', fmt=\"%s\") def calc_histogram(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw =",
"{0}'.format(i1['Total']/total_count['Total'])) print(' 10 - 50: {0}'.format(i2['Total']/total_count['Total'])) print(' 50 - 100: {0}'.format(i3['Total']/total_count['Total'])) print('100 -",
"& (df1['Total'] <= 100)].count() i4 = df1[(df1['Total'] > 100) & (df1['Total'] <= 200)].count()",
"<= 300)].count() i6 = df1[(df1['Total'] > 300) & (df1['Total'] <= 400)].count() i7 =",
"0)].count() i1 = df[(df['Value'] > 0) & (df['Value'] <= 10)].count() i2 = df[(df['Value']",
"<= 5)].count() i2 = df[(df['Value'] > 5) & (df['Value'] <= 10)].count() i3 =",
"0)].count() i1 = df1[(df1['Total'] > 0) & (df1['Total'] <= 10)].count() i2 = df1[(df1['Total']",
"count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 5: {0}'.format(i1['Value']/total_count['Value'])) print(' 5 -",
"fmt=\"%s\") def calc_histogram(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index",
"calc_histogram2(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index)",
"(df['Value'] <= 50)].count() i5 = df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i6",
"df1[(df1['Total'] > 50) & (df1['Total'] <= 100)].count() i4 = df1[(df1['Total'] > 100) &",
"0 - 10: {0}'.format(i1['Total']/total_count['Total'])) print(' 10 - 50: {0}'.format(i2['Total']/total_count['Total'])) print(' 50 - 100:",
"= pd.to_datetime(df.index) dates = df.index.values first_date = dates[0] last_date = dates[-1] print('Data from",
"> 1000)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 10: {0}'.format(i1['Value']/total_count['Value']))",
"parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3),",
"pd.to_datetime(raw1.index) df1 = raw1.resample('1H').mean() raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index =",
"/ 3600 / 24 % 365.25)) print('Total gap {0} years'.format(total_gap / 3600 /",
"300: {0}'.format(i5['Total']/total_count['Total'])) print('300 - 400: {0}'.format(i6['Total']/total_count['Total'])) print('400 - 500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000:",
"0; for d in dates: diff = d - last_read_date seconds = diff",
"math.floor((total_left / 3600 / 24 % 365.25)) print('Total left {0} years'.format(total_left / 3600",
"i2 = df[(df['Value'] > 5) & (df['Value'] <= 10)].count() i3 = df[(df['Value'] >",
"= pd.to_datetime(raw.index) df = raw.resample('1H').mean() total_count = df.count() i0 = df[(df['Value'] == 0)].count()",
"365.25)) print('Total gap {0} years'.format(total_gap / 3600 / 24 / 365.25)) print('Total gap",
"400) & (df1['Total'] <= 500)].count() i8 = df1[(df1['Total'] > 500) & (df1['Total'] <=",
"100)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 5: {0}'.format(i1['Value']/total_count['Value'])) print('",
"- 500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1,",
"<= 100)].count() i6 = df[(df['Value'] > 100)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value']))",
"total_gap = 0; for d in dates: diff = d - last_read_date seconds",
"& (df['Value'] <= 10)].count() i3 = df[(df['Value'] > 10) & (df['Value'] <= 20)].count()",
"def median_sampling_rate(station): \"\"\"Get median over year sampling rate\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw",
"raw3.set_index(['Date']) raw3.index = pd.to_datetime(raw3.index) df3 = raw3.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] +",
"<= 50)].count() i5 = df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i6 =",
"\"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df",
"0 - 5: {0}'.format(i1['Value']/total_count['Value'])) print(' 5 - 10: {0}'.format(i2['Value']/total_count['Value'])) print(' 10 - 20:",
"raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] total_count",
"{1} days'.format(years_left, days_left)) # gap_file = '{0}-gaps.txt'.format(station) # np.savetxt(gap_file, gaps, delimiter=',', fmt=\"%s\") def",
"{0}'.format(i1['Value']/total_count['Value'])) print(' 5 - 10: {0}'.format(i2['Value']/total_count['Value'])) print(' 10 - 20: {0}'.format(i3['Value']/total_count['Value'])) print(' 20",
"df[(df['Value'] == 0)].count() i1 = df[(df['Value'] > 0) & (df['Value'] <= 5)].count() i2",
"def calc_histogram4(station1, station2): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index",
"- 50: {0}'.format(i2['Total']/total_count['Total'])) print(' 50 - 100: {0}'.format(i3['Total']/total_count['Total'])) print('100 - 200: {0}'.format(i4['Total']/total_count['Total'])) print('200",
"= pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df = df.set_index(['Date']) df.index = pd.to_datetime(df.index) dates = df.index.values first_date",
"% 365.25)) print('Total left {0} years'.format(total_left / 3600 / 24 / 365.25)) print('Total",
"median over year sampling rate\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index",
"= df[(df['Value'] > 10) & (df['Value'] <= 20)].count() i4 = df[(df['Value'] > 20)",
"years_left = math.floor(total_left / 3600 / 24 / 365.25) days_left = math.floor((total_left /",
"df1['Value'] + df2['Value'] + df3['Value'] total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count()",
"(df['Value'] <= 1000)].count() i9 = df[(df['Value'] > 1000)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0:",
"10) & (df1['Total'] <= 50)].count() i3 = df1[(df1['Total'] > 50) & (df1['Total'] <=",
"500) & (df1['Total'] <= 1000)].count() i9 = df1[(df1['Total'] > 1000)].count() print('Total count: {0}'.format(total_count['Total']))",
"10) & (df['Value'] <= 50)].count() i3 = df[(df['Value'] > 50) & (df['Value'] <=",
"print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 10: {0}'.format(i1['Value']/total_count['Value'])) print(' 10 - 50: {0}'.format(i2['Value']/total_count['Value']))",
"df[(df['Value'] > 10) & (df['Value'] <= 50)].count() i3 = df[(df['Value'] > 50) &",
"df1[(df1['Total'] > 0) & (df1['Total'] <= 10)].count() i2 = df1[(df1['Total'] > 10) &",
"raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3 = raw3.set_index(['Date']) raw3.index = pd.to_datetime(raw3.index) df3 = raw3.resample('1H').mean()",
"print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 10: {0}'.format(i1['Value']/total_count['Value'])) print(' 10",
"= df[(df['Value'] > 20) & (df['Value'] <= 50)].count() i5 = df[(df['Value'] > 50)",
"= math.floor(total_gap / 3600 / 24 / 365.25) days = math.floor((total_gap / 3600",
"total_count = df.count() i0 = df[(df['Value'] == 0)].count() i1 = df[(df['Value'] > 0)",
"/ 365.25) days = math.floor((total_gap / 3600 / 24 % 365.25)) print('Total gap",
"station3): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index = pd.to_datetime(raw1.index)",
"365.25)) print('Total gap {0} years {1} days'.format(years, days)) total_left = total_range_seconds - total_gap",
"& (df['Value'] <= 400)].count() i7 = df[(df['Value'] > 400) & (df['Value'] <= 500)].count()",
"__name__ == '__main__': station = sys.argv[1] calc_gaps(station) #calc_histogram(station) #calc_histogram2(station) #calc_histogram3('D7H014Z', 'D7H015Z', 'D7H016Z') #calc_histogram4('D7H008',",
"100: {0}'.format(i3['Value']/total_count['Value'])) print('100 - 200: {0}'.format(i4['Value']/total_count['Value'])) print('200 - 300: {0}'.format(i5['Value']/total_count['Value'])) print('300 - 400:",
"> 5) & (df['Value'] <= 10)].count() i3 = df[(df['Value'] > 10) & (df['Value']",
"{0}'.format(i4['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i5['Value']/total_count['Value'])) print(' > 100: {0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station): \"\"\"Get",
"= raw.resample('1H').mean() total_count = df.count() i0 = df[(df['Value'] == 0)].count() i1 = df[(df['Value']",
"print(' 50 - 100: {0}'.format(i3['Total']/total_count['Total'])) print('100 - 200: {0}'.format(i4['Total']/total_count['Total'])) print('200 - 300: {0}'.format(i5['Total']/total_count['Total']))",
"'{0}-gaps.txt'.format(station) # np.savetxt(gap_file, gaps, delimiter=',', fmt=\"%s\") def calc_histogram(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station),",
"parse_dates=['Date']) df = df.set_index(['Date']) df.index = pd.to_datetime(df.index) dates = df.index.values first_date = dates[0]",
"+ seconds gaps.append(seconds) last_read_date = d print('Number of gaps {0}'.format(len(gaps))) years = math.floor(total_gap",
"10: {0}'.format(i1['Value']/total_count['Value'])) print(' 10 - 50: {0}'.format(i2['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i3['Value']/total_count['Value'])) print('100",
"20) & (df['Value'] <= 50)].count() i5 = df[(df['Value'] > 50) & (df['Value'] <=",
"& (df1['Total'] <= 500)].count() i8 = df1[(df1['Total'] > 500) & (df1['Total'] <= 1000)].count()",
"0 - 10: {0}'.format(i1['Value']/total_count['Value'])) print(' 10 - 50: {0}'.format(i2['Value']/total_count['Value'])) print(' 50 - 100:",
"raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] total_count =",
"/ 3600 / 24 % 365.25)) print('Total left {0} years'.format(total_left / 3600 /",
"raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3 =",
"365.25) days = math.floor((total_gap / 3600 / 24 % 365.25)) print('Total gap {0}",
"& (df['Value'] <= 50)].count() i3 = df[(df['Value'] > 50) & (df['Value'] <= 100)].count()",
"total_range_seconds = total_range / np.timedelta64(1, 's') last_read_date = first_date gaps = [] total_gap",
"raw3.index = pd.to_datetime(raw3.index) df3 = raw3.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] + df3['Value']",
"raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() df = df.round({'Value': 0})",
"1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date'])",
"50 - 100: {0}'.format(i3['Total']/total_count['Total'])) print('100 - 200: {0}'.format(i4['Total']/total_count['Total'])) print('200 - 300: {0}'.format(i5['Total']/total_count['Total'])) print('300",
"0}) df.to_csv('{0}_resampled.csv'.format(station)) if __name__ == '__main__': station = sys.argv[1] calc_gaps(station) #calc_histogram(station) #calc_histogram2(station) #calc_histogram3('D7H014Z',",
"years = math.floor(total_gap / 3600 / 24 / 365.25) days = math.floor((total_gap /",
"1000: {0}'.format(i8['Value']/total_count['Value'])) print(' > 1000: {0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1, station2): \"\"\"Get histogram\"\"\" raw1 =",
"200)].count() i5 = df[(df['Value'] > 200) & (df['Value'] <= 300)].count() i6 = df[(df['Value']",
"> 400) & (df1['Total'] <= 500)].count() i8 = df1[(df1['Total'] > 500) & (df1['Total']",
"20 - 50: {0}'.format(i4['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i5['Value']/total_count['Value'])) print(' > 100: {0}'.format(i6['Value']/total_count['Value']))",
"print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station): \"\"\"Get histogram\"\"\" raw",
"last_read_date = first_date gaps = [] total_gap = 0; for d in dates:",
"sys import math import pandas as pd import numpy as np import csv",
"i6 = df[(df['Value'] > 100)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0",
"100)].count() i6 = df[(df['Value'] > 100)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print('",
"& (df['Value'] <= 1000)].count() i9 = df[(df['Value'] > 1000)].count() print('Total count: {0}'.format(total_count['Value'])) print('",
"500)].count() i8 = df[(df['Value'] > 500) & (df['Value'] <= 1000)].count() i9 = df[(df['Value']",
"0) & (df['Value'] <= 5)].count() i2 = df[(df['Value'] > 5) & (df['Value'] <=",
"- 10: {0}'.format(i2['Value']/total_count['Value'])) print(' 10 - 20: {0}'.format(i3['Value']/total_count['Value'])) print(' 20 - 50: {0}'.format(i4['Value']/total_count['Value']))",
"{0}'.format(len(gaps))) years = math.floor(total_gap / 3600 / 24 / 365.25) days = math.floor((total_gap",
"import math import pandas as pd import numpy as np import csv def",
"years {1} days'.format(years, days)) total_left = total_range_seconds - total_gap years_left = math.floor(total_left /",
"500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station): \"\"\"Get",
"i2 = df1[(df1['Total'] > 10) & (df1['Total'] <= 50)].count() i3 = df1[(df1['Total'] >",
"last_read_date = d print('Number of gaps {0}'.format(len(gaps))) years = math.floor(total_gap / 3600 /",
"i4 = df[(df['Value'] > 100) & (df['Value'] <= 200)].count() i5 = df[(df['Value'] >",
"calc_histogram4(station1, station2): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date']) raw1 = raw1.set_index(['Date']) raw1.index =",
"raw.resample('1H').mean() total_count = df.count() i0 = df[(df['Value'] == 0)].count() i1 = df[(df['Value'] >",
"{0} to {1}'.format(first_date, last_date)) total_range = last_date - first_date total_range_seconds = total_range /",
"print(' 0 - 10: {0}'.format(i1['Value']/total_count['Value'])) print(' 10 - 50: {0}'.format(i2['Value']/total_count['Value'])) print(' 50 -",
"& (df['Value'] <= 5)].count() i2 = df[(df['Value'] > 5) & (df['Value'] <= 10)].count()",
"200) & (df1['Total'] <= 300)].count() i6 = df1[(df1['Total'] > 300) & (df1['Total'] <=",
"df2 = raw2.resample('1H').mean() raw3 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station3), parse_dates=['Date']) raw3 = raw3.set_index(['Date']) raw3.index = pd.to_datetime(raw3.index)",
"= d - last_read_date seconds = diff / np.timedelta64(1, 's') hours = diff",
"= df[(df['Value'] > 300) & (df['Value'] <= 400)].count() i7 = df[(df['Value'] > 400)",
"(df1['Total'] <= 100)].count() i4 = df1[(df1['Total'] > 100) & (df1['Total'] <= 200)].count() i5",
"{0}'.format(i7['Value']/total_count['Value'])) print('500 - 1000: {0}'.format(i8['Value']/total_count['Value'])) print(' > 1000: {0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1, station2): \"\"\"Get",
"hours > 72: # met stations # if hours > 24: # flow",
"df[(df['Value'] > 0) & (df['Value'] <= 10)].count() i2 = df[(df['Value'] > 10) &",
"df[(df['Value'] > 20) & (df['Value'] <= 50)].count() i5 = df[(df['Value'] > 50) &",
"station data\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df",
"df1 = raw1.resample('1H').mean() raw2 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index)",
"{0}'.format(i0['Total']/total_count['Total'])) print(' 0 - 10: {0}'.format(i1['Total']/total_count['Total'])) print(' 10 - 50: {0}'.format(i2['Total']/total_count['Total'])) print(' 50",
"dataset \"\"\" import sys import math import pandas as pd import numpy as",
"> 300) & (df1['Total'] <= 400)].count() i7 = df1[(df1['Total'] > 400) & (df1['Total']",
"5) & (df['Value'] <= 10)].count() i3 = df[(df['Value'] > 10) & (df['Value'] <=",
"<= 50)].count() i3 = df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i4 =",
"df1[(df1['Total'] > 300) & (df1['Total'] <= 400)].count() i7 = df1[(df1['Total'] > 400) &",
"(df['Value'] <= 200)].count() i5 = df[(df['Value'] > 200) & (df['Value'] <= 300)].count() i6",
"= dates[0] last_date = dates[-1] print('Data from {0} to {1}'.format(first_date, last_date)) total_range =",
"df1[(df1['Total'] > 1000)].count() print('Total count: {0}'.format(total_count['Total'])) print(' 0: {0}'.format(i0['Total']/total_count['Total'])) print(' 0 - 10:",
"{0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1, station2, station3):",
"- 300: {0}'.format(i5['Total']/total_count['Total'])) print('300 - 400: {0}'.format(i6['Total']/total_count['Total'])) print('400 - 500: {0}'.format(i7['Total']/total_count['Total'])) print('500 -",
"gap {0} years {1} days'.format(years, days)) total_left = total_range_seconds - total_gap years_left =",
"df1[(df1['Total'] == 0)].count() i1 = df1[(df1['Total'] > 0) & (df1['Total'] <= 10)].count() i2",
"{0} years {1} days'.format(years_left, days_left)) # gap_file = '{0}-gaps.txt'.format(station) # np.savetxt(gap_file, gaps, delimiter=',',",
"(df1['Total'] <= 10)].count() i2 = df1[(df1['Total'] > 10) & (df1['Total'] <= 50)].count() i3",
"seconds = diff / np.timedelta64(1, 's') hours = diff / np.timedelta64(1, 'h') if",
"(df1['Total'] <= 50)].count() i3 = df1[(df1['Total'] > 50) & (df1['Total'] <= 100)].count() i4",
"= pd.to_datetime(raw.index) df = raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station): \"\"\"Resample station data\"\"\" raw =",
"> 500) & (df['Value'] <= 1000)].count() i9 = df[(df['Value'] > 1000)].count() print('Total count:",
"years'.format(total_gap / 3600 / 24 / 365.25)) print('Total gap {0} years {1} days'.format(years,",
"df = df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station)) if __name__ == '__main__': station = sys.argv[1] calc_gaps(station)",
"= raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value']",
"400: {0}'.format(i6['Total']/total_count['Total'])) print('400 - 500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000:",
"= pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('1H').mean() total_count",
"i1 = df1[(df1['Total'] > 0) & (df1['Total'] <= 10)].count() i2 = df1[(df1['Total'] >",
"total_left = total_range_seconds - total_gap years_left = math.floor(total_left / 3600 / 24 /",
"- 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1, station2, station3): \"\"\"Get histogram\"\"\"",
"def resample(station): \"\"\"Resample station data\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index",
"<= 10)].count() i2 = df[(df['Value'] > 10) & (df['Value'] <= 50)].count() i3 =",
"& (df['Value'] <= 50)].count() i5 = df[(df['Value'] > 50) & (df['Value'] <= 100)].count()",
"(df['Value'] <= 100)].count() i4 = df[(df['Value'] > 100) & (df['Value'] <= 200)].count() i5",
"df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station): \"\"\"Resample station data\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date'])",
"i4 = df1[(df1['Total'] > 100) & (df1['Total'] <= 200)].count() i5 = df1[(df1['Total'] >",
"df = df.set_index(['Date']) df.index = pd.to_datetime(df.index) dates = df.index.values first_date = dates[0] last_date",
"{0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 5: {0}'.format(i1['Value']/total_count['Value'])) print(' 5 - 10: {0}'.format(i2['Value']/total_count['Value'])) print(' 10",
"pandas as pd import numpy as np import csv def calc_gaps(station): \"\"\"Calculate gaps",
"print('Number of gaps {0}'.format(len(gaps))) years = math.floor(total_gap / 3600 / 24 / 365.25)",
"/ 24 / 365.25)) print('Total gap {0} years {1} days'.format(years, days)) total_left =",
"> 300) & (df['Value'] <= 400)].count() i7 = df[(df['Value'] > 400) & (df['Value']",
"df1[(df1['Total'] > 200) & (df1['Total'] <= 300)].count() i6 = df1[(df1['Total'] > 300) &",
"{0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station): \"\"\"Get histogram\"\"\"",
"if hours > 72: # met stations # if hours > 24: #",
"= df[(df['Value'] > 400) & (df['Value'] <= 500)].count() i8 = df[(df['Value'] > 500)",
"300) & (df1['Total'] <= 400)].count() i7 = df1[(df1['Total'] > 400) & (df1['Total'] <=",
"= d print('Number of gaps {0}'.format(len(gaps))) years = math.floor(total_gap / 3600 / 24",
"1000)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 10: {0}'.format(i1['Value']/total_count['Value'])) print('",
"Construct dataset \"\"\" import sys import math import pandas as pd import numpy",
"= df[(df['Value'] > 0) & (df['Value'] <= 10)].count() i2 = df[(df['Value'] > 10)",
"= raw.resample('1H').mean() df = df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station)) if __name__ == '__main__': station =",
"histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df =",
"print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1, station2, station3): \"\"\"Get",
"> 200) & (df['Value'] <= 300)].count() i6 = df[(df['Value'] > 300) & (df['Value']",
"print('500 - 1000: {0}'.format(i8['Value']/total_count['Value'])) print(' > 1000: {0}'.format(i9['Value']/total_count['Value'])) def calc_histogram4(station1, station2): \"\"\"Get histogram\"\"\"",
"% 365.25)) print('Total gap {0} years'.format(total_gap / 3600 / 24 / 365.25)) print('Total",
"df[(df['Value'] > 100)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 5:",
"1000)].count() i9 = df1[(df1['Total'] > 1000)].count() print('Total count: {0}'.format(total_count['Total'])) print(' 0: {0}'.format(i0['Total']/total_count['Total'])) print('",
"'__main__': station = sys.argv[1] calc_gaps(station) #calc_histogram(station) #calc_histogram2(station) #calc_histogram3('D7H014Z', 'D7H015Z', 'D7H016Z') #calc_histogram4('D7H008', 'D7H017PLUS') #median_sampling_rate(station)",
"print(' 20 - 50: {0}'.format(i4['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i5['Value']/total_count['Value'])) print(' > 100:",
"i8 = df1[(df1['Total'] > 500) & (df1['Total'] <= 1000)].count() i9 = df1[(df1['Total'] >",
"= dates[-1] print('Data from {0} to {1}'.format(first_date, last_date)) total_range = last_date - first_date",
"= df.round({'Value': 0}) df.to_csv('{0}_resampled.csv'.format(station)) if __name__ == '__main__': station = sys.argv[1] calc_gaps(station) #calc_histogram(station)",
"last_date = dates[-1] print('Data from {0} to {1}'.format(first_date, last_date)) total_range = last_date -",
"<= 500)].count() i8 = df[(df['Value'] > 500) & (df['Value'] <= 1000)].count() i9 =",
"<= 10)].count() i3 = df[(df['Value'] > 10) & (df['Value'] <= 20)].count() i4 =",
"= df[(df['Value'] > 50) & (df['Value'] <= 100)].count() i4 = df[(df['Value'] > 100)",
"= df[(df['Value'] > 200) & (df['Value'] <= 300)].count() i6 = df[(df['Value'] > 300)",
"# flow stations total_gap = total_gap + seconds gaps.append(seconds) last_read_date = d print('Number",
"& (df['Value'] <= 200)].count() i5 = df[(df['Value'] > 200) & (df['Value'] <= 300)].count()",
"first_date = dates[0] last_date = dates[-1] print('Data from {0} to {1}'.format(first_date, last_date)) total_range",
"24 % 365.25)) print('Total gap {0} years'.format(total_gap / 3600 / 24 / 365.25))",
"last_date - first_date total_range_seconds = total_range / np.timedelta64(1, 's') last_read_date = first_date gaps",
"1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station),",
"gaps in time series\"\"\" df = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) df = df.set_index(['Date']) df.index =",
"> 10) & (df['Value'] <= 20)].count() i4 = df[(df['Value'] > 20) & (df['Value']",
"3600 / 24 / 365.25) days_left = math.floor((total_left / 3600 / 24 %",
"> 100) & (df['Value'] <= 200)].count() i5 = df[(df['Value'] > 200) & (df['Value']",
"dates: diff = d - last_read_date seconds = diff / np.timedelta64(1, 's') hours",
"- 200: {0}'.format(i4['Value']/total_count['Value'])) print('200 - 300: {0}'.format(i5['Value']/total_count['Value'])) print('300 - 400: {0}'.format(i6['Value']/total_count['Value'])) print('400 -",
"= pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] total_count = df1.count()",
"diff / np.timedelta64(1, 's') hours = diff / np.timedelta64(1, 'h') if hours >",
"df1[(df1['Total'] > 10) & (df1['Total'] <= 50)].count() i3 = df1[(df1['Total'] > 50) &",
"+ df2['Value'] total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count() i1 = df1[(df1['Total']",
"days'.format(years_left, days_left)) # gap_file = '{0}-gaps.txt'.format(station) # np.savetxt(gap_file, gaps, delimiter=',', fmt=\"%s\") def calc_histogram(station):",
"{0} years {1} days'.format(years, days)) total_left = total_range_seconds - total_gap years_left = math.floor(total_left",
"= df1[(df1['Total'] > 400) & (df1['Total'] <= 500)].count() i8 = df1[(df1['Total'] > 500)",
"pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station2), parse_dates=['Date']) raw2 = raw2.set_index(['Date']) raw2.index = pd.to_datetime(raw2.index) df2 = raw2.resample('1H').mean() raw3 =",
"50 - 100: {0}'.format(i5['Value']/total_count['Value'])) print(' > 100: {0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station): \"\"\"Get median over",
"<= 200)].count() i5 = df1[(df1['Total'] > 200) & (df1['Total'] <= 300)].count() i6 =",
"- 100: {0}'.format(i5['Value']/total_count['Value'])) print(' > 100: {0}'.format(i6['Value']/total_count['Value'])) def median_sampling_rate(station): \"\"\"Get median over year",
"10)].count() i2 = df[(df['Value'] > 10) & (df['Value'] <= 50)].count() i3 = df[(df['Value']",
"1000)].count() i9 = df[(df['Value'] > 1000)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print('",
"d in dates: diff = d - last_read_date seconds = diff / np.timedelta64(1,",
"df[(df['Value'] > 200) & (df['Value'] <= 300)].count() i6 = df[(df['Value'] > 300) &",
"100) & (df1['Total'] <= 200)].count() i5 = df1[(df1['Total'] > 200) & (df1['Total'] <=",
"pd.to_datetime(raw3.index) df3 = raw3.resample('1H').mean() df1['Total'] = df1['Value'] + df2['Value'] + df3['Value'] total_count =",
"= math.floor((total_gap / 3600 / 24 % 365.25)) print('Total gap {0} years'.format(total_gap /",
"as np import csv def calc_gaps(station): \"\"\"Calculate gaps in time series\"\"\" df =",
"> 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1, station2, station3): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1), parse_dates=['Date'])",
"year sampling rate\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index)",
"> 200) & (df1['Total'] <= 300)].count() i6 = df1[(df1['Total'] > 300) & (df1['Total']",
"20)].count() i4 = df[(df['Value'] > 20) & (df['Value'] <= 50)].count() i5 = df[(df['Value']",
"100)].count() i4 = df[(df['Value'] > 100) & (df['Value'] <= 200)].count() i5 = df[(df['Value']",
"24 / 365.25)) print('Total left {0} years {1} days'.format(years_left, days_left)) # gap_file =",
"np.savetxt(gap_file, gaps, delimiter=',', fmt=\"%s\") def calc_histogram(station): \"\"\"Get histogram\"\"\" raw = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station), parse_dates=['Date']) raw",
"- 500: {0}'.format(i7['Total']/total_count['Total'])) print('500 - 1000: {0}'.format(i8['Total']/total_count['Total'])) print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram2(station):",
"total_count = df1.count() i0 = df1[(df1['Total'] == 0)].count() i1 = df1[(df1['Total'] > 0)",
"20: {0}'.format(i3['Value']/total_count['Value'])) print(' 20 - 50: {0}'.format(i4['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i5['Value']/total_count['Value'])) print('",
"print(' > 1000: {0}'.format(i9['Total']/total_count['Total'])) def calc_histogram3(station1, station2, station3): \"\"\"Get histogram\"\"\" raw1 = pd.read_csv('../data/all_clean/{0}-clean.txt'.format(station1),",
"as pd import numpy as np import csv def calc_gaps(station): \"\"\"Calculate gaps in",
"'s') last_read_date = first_date gaps = [] total_gap = 0; for d in",
"72: # met stations # if hours > 24: # flow stations total_gap",
"dates = df.index.values first_date = dates[0] last_date = dates[-1] print('Data from {0} to",
"{0}'.format(i1['Value']/total_count['Value'])) print(' 10 - 50: {0}'.format(i2['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i3['Value']/total_count['Value'])) print('100 -",
"= df1[(df1['Total'] > 200) & (df1['Total'] <= 300)].count() i6 = df1[(df1['Total'] > 300)",
"raw = raw.set_index(['Date']) raw.index = pd.to_datetime(raw.index) df = raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station): \"\"\"Resample",
"- 200: {0}'.format(i4['Total']/total_count['Total'])) print('200 - 300: {0}'.format(i5['Total']/total_count['Total'])) print('300 - 400: {0}'.format(i6['Total']/total_count['Total'])) print('400 -",
"= df[(df['Value'] > 0) & (df['Value'] <= 5)].count() i2 = df[(df['Value'] > 5)",
"raw.index = pd.to_datetime(raw.index) df = raw.resample('Y').count() df.to_csv('{0}_sample_count.csv'.format(station)) def resample(station): \"\"\"Resample station data\"\"\" raw",
"print(' 0: {0}'.format(i0['Total']/total_count['Total'])) print(' 0 - 10: {0}'.format(i1['Total']/total_count['Total'])) print(' 10 - 50: {0}'.format(i2['Total']/total_count['Total']))",
"parse_dates=['Date']) raw3 = raw3.set_index(['Date']) raw3.index = pd.to_datetime(raw3.index) df3 = raw3.resample('1H').mean() df1['Total'] = df1['Value']",
"i7 = df1[(df1['Total'] > 400) & (df1['Total'] <= 500)].count() i8 = df1[(df1['Total'] >",
"5)].count() i2 = df[(df['Value'] > 5) & (df['Value'] <= 10)].count() i3 = df[(df['Value']",
"50 - 100: {0}'.format(i3['Value']/total_count['Value'])) print('100 - 200: {0}'.format(i4['Value']/total_count['Value'])) print('200 - 300: {0}'.format(i5['Value']/total_count['Value'])) print('300",
"/ np.timedelta64(1, 's') hours = diff / np.timedelta64(1, 'h') if hours > 72:",
"print('Data from {0} to {1}'.format(first_date, last_date)) total_range = last_date - first_date total_range_seconds =",
"3600 / 24 % 365.25)) print('Total left {0} years'.format(total_left / 3600 / 24",
"(df['Value'] <= 20)].count() i4 = df[(df['Value'] > 20) & (df['Value'] <= 50)].count() i5",
"df1[(df1['Total'] > 100) & (df1['Total'] <= 200)].count() i5 = df1[(df1['Total'] > 200) &",
"df.set_index(['Date']) df.index = pd.to_datetime(df.index) dates = df.index.values first_date = dates[0] last_date = dates[-1]",
"print('Total count: {0}'.format(total_count['Total'])) print(' 0: {0}'.format(i0['Total']/total_count['Total'])) print(' 0 - 10: {0}'.format(i1['Total']/total_count['Total'])) print(' 10",
"> 100)].count() print('Total count: {0}'.format(total_count['Value'])) print(' 0: {0}'.format(i0['Value']/total_count['Value'])) print(' 0 - 5: {0}'.format(i1['Value']/total_count['Value']))",
"{0}'.format(i2['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i3['Value']/total_count['Value'])) print('100 - 200: {0}'.format(i4['Value']/total_count['Value'])) print('200 - 300:",
"print(' 10 - 50: {0}'.format(i2['Total']/total_count['Total'])) print(' 50 - 100: {0}'.format(i3['Total']/total_count['Total'])) print('100 - 200:",
"100)].count() i4 = df1[(df1['Total'] > 100) & (df1['Total'] <= 200)].count() i5 = df1[(df1['Total']",
"import pandas as pd import numpy as np import csv def calc_gaps(station): \"\"\"Calculate",
"- 50: {0}'.format(i2['Value']/total_count['Value'])) print(' 50 - 100: {0}'.format(i3['Value']/total_count['Value'])) print('100 - 200: {0}'.format(i4['Value']/total_count['Value'])) print('200",
"1000)].count() print('Total count: {0}'.format(total_count['Total'])) print(' 0: {0}'.format(i0['Total']/total_count['Total'])) print(' 0 - 10: {0}'.format(i1['Total']/total_count['Total'])) print('",
"{0}'.format(i5['Value']/total_count['Value'])) print('300 - 400: {0}'.format(i6['Value']/total_count['Value'])) print('400 - 500: {0}'.format(i7['Value']/total_count['Value'])) print('500 - 1000: {0}'.format(i8['Value']/total_count['Value']))",
"i6 = df1[(df1['Total'] > 300) & (df1['Total'] <= 400)].count() i7 = df1[(df1['Total'] >"
] |
[
"app, socketio if __name__ == '__main__': app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True socketio.run(app)",
"from app import app, socketio if __name__ == '__main__': app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD']",
"app import app, socketio if __name__ == '__main__': app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] =",
"import app, socketio if __name__ == '__main__': app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True"
] |
[
"to input window offset = 1 class Model(ModelBase): def __init__(self, input_shape: tuple =",
"x, *args, **kwargs): return self.model.predict(x, *args, **kwargs) def train(self, x, y, *args, **kwargs):",
"expand=True), axis=0) y_pred = tsutils.free_run_batch(model.predict, ctx, predict_points, ts, batch_size=1) y_true = ts.get_test_data() y_pred_flat",
"y_train, epochs=200) #x_test, y_test, t_test = ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx = np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0)",
"t_test = ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx = np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0) y_pred = tsutils.free_run_batch(model.predict, ctx,",
"padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs))",
"y_all, t_all = ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred = model.predict(x_all) t_all_flat = ts.inverse_y(np.squeeze(t_all)) y_all_flat =",
"'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data = np.genfromtxt(path) print('Data len: {0}'.format(len(data))) predict_points = 8 model = Model()",
"def __init__(self, input_shape: tuple = (5, 1), outputs: int = 1): self.input_window =",
"model.compile(optimizer='adam', loss='mse', metrics=['mae']) self.model = model def predict(self, x, *args, **kwargs): return self.model.predict(x,",
"print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape', 'mae', 'umbrae'))) ''' x_all, y_all, t_all = ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred",
"= 1): self.input_window = input_shape[0] self.output_window = outputs self.offset = outputs model =",
"= 1 class Model(ModelBase): def __init__(self, input_shape: tuple = (5, 1), outputs: int",
"= ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat) plt.show() ''' #y_free_run_flat = np.squeeze(predictions) #plt.plot(np.reshape(y_all, (-1,",
"given context output_window = None # How output is shifted w.r.t. to input",
"= (5, 1), outputs: int = 1): self.input_window = input_shape[0] self.output_window = outputs",
"How many point the model can predict for a single given context output_window",
"metrics class ModelBase(object): # Required 'context' information for a model input_window = None",
"*args, **kwargs): return self.model.predict(x, *args, **kwargs) def train(self, x, y, *args, **kwargs): self.model.fit(x,",
"window offset = 1 class Model(ModelBase): def __init__(self, input_shape: tuple = (5, 1),",
"*args, **kwargs): self.model.fit(x, y, *args, **kwargs) def main(): path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data =",
"expand=True) model.train(x_train, y_train, epochs=200) #x_test, y_test, t_test = ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx = np.expand_dims(ts.get_test_context(model.input_window,",
"padding='same', kernel_size=3, activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse', metrics=['mae']) self.model =",
"t_train = ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True) model.train(x_train, y_train, epochs=200) #x_test, y_test, t_test = ts.train_data(input_window=model.input_window,",
"= np.genfromtxt(path) print('Data len: {0}'.format(len(data))) predict_points = 8 model = Model() ts =",
"input_shape[0] self.output_window = outputs self.offset = outputs model = keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same',",
"axis=0) y_pred = tsutils.free_run_batch(model.predict, ctx, predict_points, ts, batch_size=1) y_true = ts.get_test_data() y_pred_flat =",
"How output is shifted w.r.t. to input window offset = 1 class Model(ModelBase):",
"= None # How many point the model can predict for a single",
"self.model = model def predict(self, x, *args, **kwargs): return self.model.predict(x, *args, **kwargs) def",
"model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs))",
"context output_window = None # How output is shifted w.r.t. to input window",
"for a single given context output_window = None # How output is shifted",
"model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse', metrics=['mae']) self.model",
"(5, 1), outputs: int = 1): self.input_window = input_shape[0] self.output_window = outputs self.offset",
"**kwargs): self.model.fit(x, y, *args, **kwargs) def main(): path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data = np.genfromtxt(path)",
"= ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape', 'mae', 'umbrae'))) ''' x_all, y_all, t_all = ts.train_data(input_window=model.input_window,",
"= Model() ts = tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler()) x_train, y_train, t_train = ts.train_data(input_window=model.input_window, output_window=model.output_window,",
"for a model input_window = None # How many point the model can",
"plt.show() ''' #y_free_run_flat = np.squeeze(predictions) #plt.plot(np.reshape(y_all, (-1, ))) #plt.plot(np.concatenate((y_pred_flat, y_free_run_flat))) #plt.show() if __name__",
"input_shape: tuple = (5, 1), outputs: int = 1): self.input_window = input_shape[0] self.output_window",
"activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape))",
"Required 'context' information for a model input_window = None # How many point",
"ctx = np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0) y_pred = tsutils.free_run_batch(model.predict, ctx, predict_points, ts, batch_size=1) y_true",
"# Required 'context' information for a model input_window = None # How many",
"input_shape=input_shape, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Flatten())",
"tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler()) x_train, y_train, t_train = ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True) model.train(x_train, y_train, epochs=200)",
"a single given context output_window = None # How output is shifted w.r.t.",
"outputs: int = 1): self.input_window = input_shape[0] self.output_window = outputs self.offset = outputs",
"= ts.inverse_y(np.squeeze(t_all)) y_all_flat = ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat) plt.show()",
"import keras.layers as klayers import time_series as tsutils import processing import metrics class",
"= model.predict(x_all) t_all_flat = ts.inverse_y(np.squeeze(t_all)) y_all_flat = ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat)",
"ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True) model.train(x_train, y_train, epochs=200) #x_test, y_test, t_test = ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx",
"self.model.fit(x, y, *args, **kwargs) def main(): path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data = np.genfromtxt(path) print('Data",
"ts = tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler()) x_train, y_train, t_train = ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True) model.train(x_train,",
"y_test, t_test = ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx = np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0) y_pred = tsutils.free_run_batch(model.predict,",
"can predict for a single given context output_window = None # How output",
"input window offset = 1 class Model(ModelBase): def __init__(self, input_shape: tuple = (5,",
"= ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred = model.predict(x_all) t_all_flat = ts.inverse_y(np.squeeze(t_all)) y_all_flat = ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat",
"= 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data = np.genfromtxt(path) print('Data len: {0}'.format(len(data))) predict_points = 8 model =",
"model def predict(self, x, *args, **kwargs): return self.model.predict(x, *args, **kwargs) def train(self, x,",
"ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx = np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0) y_pred = tsutils.free_run_batch(model.predict, ctx, predict_points, ts,",
"as np import matplotlib.pyplot as plt import keras import keras.layers as klayers import",
"y, *args, **kwargs): self.model.fit(x, y, *args, **kwargs) def main(): path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data",
"None # How output is shifted w.r.t. to input window offset = 1",
"x, y, *args, **kwargs): self.model.fit(x, y, *args, **kwargs) def main(): path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv'",
"**kwargs): return self.model.predict(x, *args, **kwargs) def train(self, x, y, *args, **kwargs): self.model.fit(x, y,",
"outputs model = keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu'))",
"= input_shape[0] self.output_window = outputs self.offset = outputs model = keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape,",
"predict for a single given context output_window = None # How output is",
"y, *args, **kwargs) def main(): path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data = np.genfromtxt(path) print('Data len:",
"time_series as tsutils import processing import metrics class ModelBase(object): # Required 'context' information",
"1 class Model(ModelBase): def __init__(self, input_shape: tuple = (5, 1), outputs: int =",
"epochs=200) #x_test, y_test, t_test = ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx = np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0) y_pred",
"x_all, y_all, t_all = ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred = model.predict(x_all) t_all_flat = ts.inverse_y(np.squeeze(t_all)) y_all_flat",
"main(): path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data = np.genfromtxt(path) print('Data len: {0}'.format(len(data))) predict_points = 8",
"1), outputs: int = 1): self.input_window = input_shape[0] self.output_window = outputs self.offset =",
"'mae', 'umbrae'))) ''' x_all, y_all, t_all = ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred = model.predict(x_all) t_all_flat",
"'umbrae'))) ''' x_all, y_all, t_all = ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred = model.predict(x_all) t_all_flat =",
"self.offset = outputs model = keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same',",
"= ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat) plt.show() ''' #y_free_run_flat =",
"class Model(ModelBase): def __init__(self, input_shape: tuple = (5, 1), outputs: int = 1):",
"model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse', metrics=['mae']) self.model = model def predict(self, x,",
"len: {0}'.format(len(data))) predict_points = 8 model = Model() ts = tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler())",
"ctx, predict_points, ts, batch_size=1) y_true = ts.get_test_data() y_pred_flat = ts.inverse_y(np.squeeze(y_pred)) y_true_flat = ts.inverse_y(np.squeeze(y_true))",
"y_true = ts.get_test_data() y_pred_flat = ts.inverse_y(np.squeeze(y_pred)) y_true_flat = ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape', 'mae',",
"single given context output_window = None # How output is shifted w.r.t. to",
"keras import keras.layers as klayers import time_series as tsutils import processing import metrics",
"Model(ModelBase): def __init__(self, input_shape: tuple = (5, 1), outputs: int = 1): self.input_window",
"input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse', metrics=['mae']) self.model = model def predict(self, x, *args, **kwargs):",
"y_all_flat = ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat) plt.show() ''' #y_free_run_flat",
"model input_window = None # How many point the model can predict for",
"activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse', metrics=['mae']) self.model = model def",
"''' x_all, y_all, t_all = ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred = model.predict(x_all) t_all_flat = ts.inverse_y(np.squeeze(t_all))",
"the model can predict for a single given context output_window = None #",
"input_window = None # How many point the model can predict for a",
"import numpy as np import matplotlib.pyplot as plt import keras import keras.layers as",
"t_all = ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred = model.predict(x_all) t_all_flat = ts.inverse_y(np.squeeze(t_all)) y_all_flat = ts.inverse_y(np.squeeze(y_all))",
"#y_free_run_flat = np.squeeze(predictions) #plt.plot(np.reshape(y_all, (-1, ))) #plt.plot(np.concatenate((y_pred_flat, y_free_run_flat))) #plt.show() if __name__ == '__main__':",
"y_true_flat = ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape', 'mae', 'umbrae'))) ''' x_all, y_all, t_all =",
"= outputs self.offset = outputs model = keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same', kernel_size=3, activation='relu'))",
"model.predict(x_all) t_all_flat = ts.inverse_y(np.squeeze(t_all)) y_all_flat = ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat,",
"y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat) plt.show() ''' #y_free_run_flat = np.squeeze(predictions) #plt.plot(np.reshape(y_all,",
"processing import metrics class ModelBase(object): # Required 'context' information for a model input_window",
"predict_points = 8 model = Model() ts = tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler()) x_train, y_train,",
"= outputs model = keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3,",
"= ts.inverse_y(np.squeeze(y_pred)) y_true_flat = ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape', 'mae', 'umbrae'))) ''' x_all, y_all,",
"y_pred = tsutils.free_run_batch(model.predict, ctx, predict_points, ts, batch_size=1) y_true = ts.get_test_data() y_pred_flat = ts.inverse_y(np.squeeze(y_pred))",
"metrics=('smape', 'mae', 'umbrae'))) ''' x_all, y_all, t_all = ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred = model.predict(x_all)",
"int = 1): self.input_window = input_shape[0] self.output_window = outputs self.offset = outputs model",
"import time_series as tsutils import processing import metrics class ModelBase(object): # Required 'context'",
"shifted w.r.t. to input window offset = 1 class Model(ModelBase): def __init__(self, input_shape:",
"1): self.input_window = input_shape[0] self.output_window = outputs self.offset = outputs model = keras.Sequential()",
"model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse', metrics=['mae']) self.model = model def predict(self,",
"data = np.genfromtxt(path) print('Data len: {0}'.format(len(data))) predict_points = 8 model = Model() ts",
"batch_size=1) y_true = ts.get_test_data() y_pred_flat = ts.inverse_y(np.squeeze(y_pred)) y_true_flat = ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape',",
"ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred = model.predict(x_all) t_all_flat = ts.inverse_y(np.squeeze(t_all)) y_all_flat = ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat =",
"t_all_flat = ts.inverse_y(np.squeeze(t_all)) y_all_flat = ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat)",
"def train(self, x, y, *args, **kwargs): self.model.fit(x, y, *args, **kwargs) def main(): path",
"as klayers import time_series as tsutils import processing import metrics class ModelBase(object): #",
"**kwargs) def main(): path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data = np.genfromtxt(path) print('Data len: {0}'.format(len(data))) predict_points",
"a model input_window = None # How many point the model can predict",
"keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3,",
"#model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse', metrics=['mae']) self.model = model def predict(self, x, *args,",
"tuple = (5, 1), outputs: int = 1): self.input_window = input_shape[0] self.output_window =",
"np import matplotlib.pyplot as plt import keras import keras.layers as klayers import time_series",
"*args, **kwargs) def main(): path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data = np.genfromtxt(path) print('Data len: {0}'.format(len(data)))",
"8 model = Model() ts = tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler()) x_train, y_train, t_train =",
"plt import keras import keras.layers as klayers import time_series as tsutils import processing",
"print('Data len: {0}'.format(len(data))) predict_points = 8 model = Model() ts = tsutils.TimeSeries(data, test_size=predict_points,",
"predict(self, x, *args, **kwargs): return self.model.predict(x, *args, **kwargs) def train(self, x, y, *args,",
"#x_test, y_test, t_test = ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx = np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0) y_pred =",
"y_pred_flat = ts.inverse_y(np.squeeze(y_pred)) y_true_flat = ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape', 'mae', 'umbrae'))) ''' x_all,",
"= np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0) y_pred = tsutils.free_run_batch(model.predict, ctx, predict_points, ts, batch_size=1) y_true =",
"ts.inverse_y(np.squeeze(y_pred)) y_true_flat = ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape', 'mae', 'umbrae'))) ''' x_all, y_all, t_all",
"y_all_pred = model.predict(x_all) t_all_flat = ts.inverse_y(np.squeeze(t_all)) y_all_flat = ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat,",
"y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat) plt.show() ''' #y_free_run_flat = np.squeeze(predictions) #plt.plot(np.reshape(y_all, (-1, ))) #plt.plot(np.concatenate((y_pred_flat, y_free_run_flat)))",
"Model() ts = tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler()) x_train, y_train, t_train = ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True)",
"import matplotlib.pyplot as plt import keras import keras.layers as klayers import time_series as",
"self.input_window = input_shape[0] self.output_window = outputs self.offset = outputs model = keras.Sequential() model.add(klayers.Conv1D(10,",
"predict_points, ts, batch_size=1) y_true = ts.get_test_data() y_pred_flat = ts.inverse_y(np.squeeze(y_pred)) y_true_flat = ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat,",
"y_train, t_train = ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True) model.train(x_train, y_train, epochs=200) #x_test, y_test, t_test =",
"= 8 model = Model() ts = tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler()) x_train, y_train, t_train",
"keras.layers as klayers import time_series as tsutils import processing import metrics class ModelBase(object):",
"is shifted w.r.t. to input window offset = 1 class Model(ModelBase): def __init__(self,",
"point the model can predict for a single given context output_window = None",
"ts.inverse_y(np.squeeze(t_all)) y_all_flat = ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat) plt.show() '''",
"class ModelBase(object): # Required 'context' information for a model input_window = None #",
"padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam',",
"= keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same',",
"def predict(self, x, *args, **kwargs): return self.model.predict(x, *args, **kwargs) def train(self, x, y,",
"return self.model.predict(x, *args, **kwargs) def train(self, x, y, *args, **kwargs): self.model.fit(x, y, *args,",
"def main(): path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data = np.genfromtxt(path) print('Data len: {0}'.format(len(data))) predict_points =",
"matplotlib.pyplot as plt import keras import keras.layers as klayers import time_series as tsutils",
"outputs self.offset = outputs model = keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10,",
"kernel_size=3, activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse', metrics=['mae']) self.model = model",
"{0}'.format(len(data))) predict_points = 8 model = Model() ts = tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler()) x_train,",
"= model def predict(self, x, *args, **kwargs): return self.model.predict(x, *args, **kwargs) def train(self,",
"None # How many point the model can predict for a single given",
"path = 'D:\\\\data\\\\M3\\\\M3Other\\\\N2836.csv' data = np.genfromtxt(path) print('Data len: {0}'.format(len(data))) predict_points = 8 model",
"kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse',",
"model = keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10,",
"x_train, y_train, t_train = ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True) model.train(x_train, y_train, epochs=200) #x_test, y_test, t_test",
"model can predict for a single given context output_window = None # How",
"output_window = None # How output is shifted w.r.t. to input window offset",
"kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10,",
"ModelBase(object): # Required 'context' information for a model input_window = None # How",
"*args, **kwargs) def train(self, x, y, *args, **kwargs): self.model.fit(x, y, *args, **kwargs) def",
"**kwargs) def train(self, x, y, *args, **kwargs): self.model.fit(x, y, *args, **kwargs) def main():",
"as tsutils import processing import metrics class ModelBase(object): # Required 'context' information for",
"= None # How output is shifted w.r.t. to input window offset =",
"activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Flatten()) model.add(klayers.Dense(outputs)) #model.add(klayers.Dense(10, input_shape=input_shape)) #model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse', metrics=['mae'])",
"output_window=model.output_window) ctx = np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0) y_pred = tsutils.free_run_batch(model.predict, ctx, predict_points, ts, batch_size=1)",
"#model.add(klayers.Dense(outputs)) model.compile(optimizer='adam', loss='mse', metrics=['mae']) self.model = model def predict(self, x, *args, **kwargs): return",
"train(self, x, y, *args, **kwargs): self.model.fit(x, y, *args, **kwargs) def main(): path =",
"ts, batch_size=1) y_true = ts.get_test_data() y_pred_flat = ts.inverse_y(np.squeeze(y_pred)) y_true_flat = ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat,",
"ts.get_test_data() y_pred_flat = ts.inverse_y(np.squeeze(y_pred)) y_true_flat = ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape', 'mae', 'umbrae'))) '''",
"import processing import metrics class ModelBase(object): # Required 'context' information for a model",
"output_window=model.output_window) y_all_pred = model.predict(x_all) t_all_flat = ts.inverse_y(np.squeeze(t_all)) y_all_flat = ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred))",
"offset = 1 class Model(ModelBase): def __init__(self, input_shape: tuple = (5, 1), outputs:",
"output_window=model.output_window, expand=True) model.train(x_train, y_train, epochs=200) #x_test, y_test, t_test = ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx =",
"tsutils import processing import metrics class ModelBase(object): # Required 'context' information for a",
"plt.plot(t_all_flat, y_pred_pred_flat) plt.show() ''' #y_free_run_flat = np.squeeze(predictions) #plt.plot(np.reshape(y_all, (-1, ))) #plt.plot(np.concatenate((y_pred_flat, y_free_run_flat))) #plt.show()",
"''' #y_free_run_flat = np.squeeze(predictions) #plt.plot(np.reshape(y_all, (-1, ))) #plt.plot(np.concatenate((y_pred_flat, y_free_run_flat))) #plt.show() if __name__ ==",
"= tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler()) x_train, y_train, t_train = ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True) model.train(x_train, y_train,",
"klayers import time_series as tsutils import processing import metrics class ModelBase(object): # Required",
"ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape', 'mae', 'umbrae'))) ''' x_all, y_all, t_all = ts.train_data(input_window=model.input_window, output_window=model.output_window)",
"scaler=processing.StandardScaler()) x_train, y_train, t_train = ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True) model.train(x_train, y_train, epochs=200) #x_test, y_test,",
"test_size=predict_points, scaler=processing.StandardScaler()) x_train, y_train, t_train = ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True) model.train(x_train, y_train, epochs=200) #x_test,",
"ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat) plt.show() ''' #y_free_run_flat = np.squeeze(predictions) #plt.plot(np.reshape(y_all, (-1, )))",
"numpy as np import matplotlib.pyplot as plt import keras import keras.layers as klayers",
"model = Model() ts = tsutils.TimeSeries(data, test_size=predict_points, scaler=processing.StandardScaler()) x_train, y_train, t_train = ts.train_data(input_window=model.input_window,",
"self.model.predict(x, *args, **kwargs) def train(self, x, y, *args, **kwargs): self.model.fit(x, y, *args, **kwargs)",
"np.genfromtxt(path) print('Data len: {0}'.format(len(data))) predict_points = 8 model = Model() ts = tsutils.TimeSeries(data,",
"information for a model input_window = None # How many point the model",
"'context' information for a model input_window = None # How many point the",
"loss='mse', metrics=['mae']) self.model = model def predict(self, x, *args, **kwargs): return self.model.predict(x, *args,",
"np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0) y_pred = tsutils.free_run_batch(model.predict, ctx, predict_points, ts, batch_size=1) y_true = ts.get_test_data()",
"w.r.t. to input window offset = 1 class Model(ModelBase): def __init__(self, input_shape: tuple",
"= tsutils.free_run_batch(model.predict, ctx, predict_points, ts, batch_size=1) y_true = ts.get_test_data() y_pred_flat = ts.inverse_y(np.squeeze(y_pred)) y_true_flat",
"# How output is shifted w.r.t. to input window offset = 1 class",
"tsutils.free_run_batch(model.predict, ctx, predict_points, ts, batch_size=1) y_true = ts.get_test_data() y_pred_flat = ts.inverse_y(np.squeeze(y_pred)) y_true_flat =",
"= ts.get_test_data() y_pred_flat = ts.inverse_y(np.squeeze(y_pred)) y_true_flat = ts.inverse_y(np.squeeze(y_true)) print(metrics.evaluate(y_true_flat, y_pred_flat, metrics=('smape', 'mae', 'umbrae')))",
"ts.inverse_y(np.squeeze(y_all)) y_pred_pred_flat = ts.inverse_y(np.squeeze(y_all_pred)) plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat) plt.show() ''' #y_free_run_flat = np.squeeze(predictions)",
"= ts.train_data(input_window=model.input_window, output_window=model.output_window, expand=True) model.train(x_train, y_train, epochs=200) #x_test, y_test, t_test = ts.train_data(input_window=model.input_window, output_window=model.output_window)",
"output is shifted w.r.t. to input window offset = 1 class Model(ModelBase): def",
"many point the model can predict for a single given context output_window =",
"model.train(x_train, y_train, epochs=200) #x_test, y_test, t_test = ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx = np.expand_dims(ts.get_test_context(model.input_window, expand=True),",
"as plt import keras import keras.layers as klayers import time_series as tsutils import",
"y_pred_flat, metrics=('smape', 'mae', 'umbrae'))) ''' x_all, y_all, t_all = ts.train_data(input_window=model.input_window, output_window=model.output_window) y_all_pred =",
"import keras import keras.layers as klayers import time_series as tsutils import processing import",
"metrics=['mae']) self.model = model def predict(self, x, *args, **kwargs): return self.model.predict(x, *args, **kwargs)",
"import metrics class ModelBase(object): # Required 'context' information for a model input_window =",
"plt.plot(t_all_flat, y_all_flat) plt.plot(t_all_flat, y_pred_pred_flat) plt.show() ''' #y_free_run_flat = np.squeeze(predictions) #plt.plot(np.reshape(y_all, (-1, ))) #plt.plot(np.concatenate((y_pred_flat,",
"= ts.train_data(input_window=model.input_window, output_window=model.output_window) ctx = np.expand_dims(ts.get_test_context(model.input_window, expand=True), axis=0) y_pred = tsutils.free_run_batch(model.predict, ctx, predict_points,",
"self.output_window = outputs self.offset = outputs model = keras.Sequential() model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same', kernel_size=3,",
"= np.squeeze(predictions) #plt.plot(np.reshape(y_all, (-1, ))) #plt.plot(np.concatenate((y_pred_flat, y_free_run_flat))) #plt.show() if __name__ == '__main__': main()",
"# How many point the model can predict for a single given context",
"model.add(klayers.Conv1D(10, input_shape=input_shape, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu')) model.add(klayers.Conv1D(10, padding='same', kernel_size=3, activation='relu'))",
"y_pred_pred_flat) plt.show() ''' #y_free_run_flat = np.squeeze(predictions) #plt.plot(np.reshape(y_all, (-1, ))) #plt.plot(np.concatenate((y_pred_flat, y_free_run_flat))) #plt.show() if",
"__init__(self, input_shape: tuple = (5, 1), outputs: int = 1): self.input_window = input_shape[0]"
] |
[
"str) -> str: counts = Counter(s) chars = defaultdict(list) for char in counts:",
"Solution: def frequencySort(self, s: str) -> str: counts = Counter(s) chars = defaultdict(list)",
"for char in counts: chars[counts[char]].append(char) ans = '' for count in sorted(chars.keys(),reverse=True): for",
"chars[counts[char]].append(char) ans = '' for count in sorted(chars.keys(),reverse=True): for char in chars[count]: ans",
"Counter(s) chars = defaultdict(list) for char in counts: chars[counts[char]].append(char) ans = '' for",
"= '' for count in sorted(chars.keys(),reverse=True): for char in chars[count]: ans += char*count",
"= Counter(s) chars = defaultdict(list) for char in counts: chars[counts[char]].append(char) ans = ''",
"s: str) -> str: counts = Counter(s) chars = defaultdict(list) for char in",
"char in counts: chars[counts[char]].append(char) ans = '' for count in sorted(chars.keys(),reverse=True): for char",
"for count in sorted(chars.keys(),reverse=True): for char in chars[count]: ans += char*count return ans",
"in counts: chars[counts[char]].append(char) ans = '' for count in sorted(chars.keys(),reverse=True): for char in",
"counts = Counter(s) chars = defaultdict(list) for char in counts: chars[counts[char]].append(char) ans =",
"'' for count in sorted(chars.keys(),reverse=True): for char in chars[count]: ans += char*count return",
"chars = defaultdict(list) for char in counts: chars[counts[char]].append(char) ans = '' for count",
"str: counts = Counter(s) chars = defaultdict(list) for char in counts: chars[counts[char]].append(char) ans",
"counts: chars[counts[char]].append(char) ans = '' for count in sorted(chars.keys(),reverse=True): for char in chars[count]:",
"frequencySort(self, s: str) -> str: counts = Counter(s) chars = defaultdict(list) for char",
"defaultdict(list) for char in counts: chars[counts[char]].append(char) ans = '' for count in sorted(chars.keys(),reverse=True):",
"= defaultdict(list) for char in counts: chars[counts[char]].append(char) ans = '' for count in",
"ans = '' for count in sorted(chars.keys(),reverse=True): for char in chars[count]: ans +=",
"def frequencySort(self, s: str) -> str: counts = Counter(s) chars = defaultdict(list) for",
"-> str: counts = Counter(s) chars = defaultdict(list) for char in counts: chars[counts[char]].append(char)",
"class Solution: def frequencySort(self, s: str) -> str: counts = Counter(s) chars ="
] |
[
"Union | {'login', 'user', 'employee', 'users', 'employees'} # Intersection & {'users', 'employees'} #",
"for k, v in result.items(): print(f'{k}: {v}') # # login: (0, 0, 1000)",
"for key in relevant} return result result = identify(n1, n2, n3) for k,",
"| set(n2) | set(n3)) - (set(n1) & set(n2) & set(n3)) print(set_differ) # Union",
"0), node3.get(i, 0)) for i in node} my_nodes = nodes(n1, n2, n3) print('my_nodes",
"dict_differ = dict_union - dict_intersection print('Union |', dict_union) print('Intersection &', dict_intersection) print('Difference -',",
"| set(node2) | set(node3)) - (set(node1) & set(node2) & set(node3)) node = get_node()",
"{v}') # # login: (0, 0, 1000) # user: (100, 230, 0) #",
"set_differ = (set(n1) | set(n2) | set(n3)) - (set(n1) & set(n2) & set(n3))",
"n1.keys() | n2.keys() | n3.keys() dict_intersection = n1.keys() & n2.keys() & n3.keys() dict_differ",
"0), n2.get(i, 0), n3.get(i, 0)) def identify(node1, node2, node3): union = node1.keys() |",
"print('Intersection &', dict_intersection) print('Difference -', dict_differ) set_differ = (set(n1) | set(n2) | set(n3))",
"| node3.keys() intersection = node1.keys() & node2.keys() & node3.keys() relevant = union -",
"node3.get(key, 0)) for key in relevant} return result result = identify(n1, n2, n3)",
"= {'employees': 250, 'users': 23, 'user': 230} n3 = {'employees': 150, 'users': 4,",
"& set(n3)) print(set_differ) # Union | {'login', 'user', 'employee', 'users', 'employees'} # Intersection",
"node2.get(i, 0), node3.get(i, 0)) for i in node} my_nodes = nodes(n1, n2, n3)",
"n2.get(i, 0), n3.get(i, 0)) def identify(node1, node2, node3): union = node1.keys() | node2.keys()",
"0), node3.get(key, 0)) for key in relevant} return result result = identify(n1, n2,",
"{'login', 'employee', 'user'} def nodes(node1, node2, node3): node_order = (node1, node2, node3) def",
"Difference - {'login', 'employee', 'user'} def nodes(node1, node2, node3): node_order = (node1, node2,",
"'login': 1000} dict_union = n1.keys() | n2.keys() | n3.keys() dict_intersection = n1.keys() &",
"| n3.keys() dict_intersection = n1.keys() & n2.keys() & n3.keys() dict_differ = dict_union -",
"# zip(n1.get(i, 0), n2.get(i, 0), n3.get(i, 0)) def identify(node1, node2, node3): union =",
"0)) for key in relevant} return result result = identify(n1, n2, n3) for",
"result.items(): print(f'{k}: {v}') # # login: (0, 0, 1000) # user: (100, 230,",
"i in node} my_nodes = nodes(n1, n2, n3) print('my_nodes -->', my_nodes) # {'login',",
"key in relevant} return result result = identify(n1, n2, n3) for k, v",
"nodes(node1, node2, node3): node_order = (node1, node2, node3) def get_node(): return (set(node1) |",
"-->', my_nodes) # {'login', 'employee', 'user'} # zip(n1.get(i, 0), n2.get(i, 0), n3.get(i, 0))",
"0), node2.get(key, 0), node3.get(key, 0)) for key in relevant} return result result =",
"23, 'user': 230} n3 = {'employees': 150, 'users': 4, 'login': 1000} dict_union =",
"relevant = union - intersection result = {key: (node1.get(key, 0), node2.get(key, 0), node3.get(key,",
"return (set(node1) | set(node2) | set(node3)) - (set(node1) & set(node2) & set(node3)) node",
"10, 'user': 100} n2 = {'employees': 250, 'users': 23, 'user': 230} n3 =",
"0, 1000) # user: (100, 230, 0) # employee: (5000, 0, 0) #",
"dict_intersection print('Union |', dict_union) print('Intersection &', dict_intersection) print('Difference -', dict_differ) set_differ = (set(n1)",
"k, v in result.items(): print(f'{k}: {v}') # # login: (0, 0, 1000) #",
"'employees'} # Difference - {'login', 'employee', 'user'} def nodes(node1, node2, node3): node_order =",
"(node1.get(i, 0), node2.get(i, 0), node3.get(i, 0)) for i in node} my_nodes = nodes(n1,",
"230} n3 = {'employees': 150, 'users': 4, 'login': 1000} dict_union = n1.keys() |",
"| n2.keys() | n3.keys() dict_intersection = n1.keys() & n2.keys() & n3.keys() dict_differ =",
"&', dict_intersection) print('Difference -', dict_differ) set_differ = (set(n1) | set(n2) | set(n3)) -",
"relevant} return result result = identify(n1, n2, n3) for k, v in result.items():",
"# Difference - {'login', 'employee', 'user'} def nodes(node1, node2, node3): node_order = (node1,",
"n3 = {'employees': 150, 'users': 4, 'login': 1000} dict_union = n1.keys() | n2.keys()",
"node_order = (node1, node2, node3) def get_node(): return (set(node1) | set(node2) | set(node3))",
"= (set(n1) | set(n2) | set(n3)) - (set(n1) & set(n2) & set(n3)) print(set_differ)",
"dict_union - dict_intersection print('Union |', dict_union) print('Intersection &', dict_intersection) print('Difference -', dict_differ) set_differ",
"5000, 'users': 10, 'user': 100} n2 = {'employees': 250, 'users': 23, 'user': 230}",
"'user': 230} n3 = {'employees': 150, 'users': 4, 'login': 1000} dict_union = n1.keys()",
"result result = identify(n1, n2, n3) for k, v in result.items(): print(f'{k}: {v}')",
"n2.keys() | n3.keys() dict_intersection = n1.keys() & n2.keys() & n3.keys() dict_differ = dict_union",
"'employee', 'users', 'employees'} # Intersection & {'users', 'employees'} # Difference - {'login', 'employee',",
"node2, node3): node_order = (node1, node2, node3) def get_node(): return (set(node1) | set(node2)",
"set(n2) & set(n3)) print(set_differ) # Union | {'login', 'user', 'employee', 'users', 'employees'} #",
"n3) for k, v in result.items(): print(f'{k}: {v}') # # login: (0, 0,",
"| set(node3)) - (set(node1) & set(node2) & set(node3)) node = get_node() return {i:",
"'users', 'employees'} # Intersection & {'users', 'employees'} # Difference - {'login', 'employee', 'user'}",
"node = get_node() return {i: (node1.get(i, 0), node2.get(i, 0), node3.get(i, 0)) for i",
"'employee': 5000, 'users': 10, 'user': 100} n2 = {'employees': 250, 'users': 23, 'user':",
"'user'} # zip(n1.get(i, 0), n2.get(i, 0), n3.get(i, 0)) def identify(node1, node2, node3): union",
"n2 = {'employees': 250, 'users': 23, 'user': 230} n3 = {'employees': 150, 'users':",
"# # login: (0, 0, 1000) # user: (100, 230, 0) # employee:",
"= {key: (node1.get(key, 0), node2.get(key, 0), node3.get(key, 0)) for key in relevant} return",
"{key: (node1.get(key, 0), node2.get(key, 0), node3.get(key, 0)) for key in relevant} return result",
"| {'login', 'user', 'employee', 'users', 'employees'} # Intersection & {'users', 'employees'} # Difference",
"= get_node() return {i: (node1.get(i, 0), node2.get(i, 0), node3.get(i, 0)) for i in",
"zip(n1.get(i, 0), n2.get(i, 0), n3.get(i, 0)) def identify(node1, node2, node3): union = node1.keys()",
"= union - intersection result = {key: (node1.get(key, 0), node2.get(key, 0), node3.get(key, 0))",
"get_node() return {i: (node1.get(i, 0), node2.get(i, 0), node3.get(i, 0)) for i in node}",
"print('my_nodes -->', my_nodes) # {'login', 'employee', 'user'} # zip(n1.get(i, 0), n2.get(i, 0), n3.get(i,",
"# login: (0, 0, 1000) # user: (100, 230, 0) # employee: (5000,",
"'users': 23, 'user': 230} n3 = {'employees': 150, 'users': 4, 'login': 1000} dict_union",
"print('Difference -', dict_differ) set_differ = (set(n1) | set(n2) | set(n3)) - (set(n1) &",
"150, 'users': 4, 'login': 1000} dict_union = n1.keys() | n2.keys() | n3.keys() dict_intersection",
"in relevant} return result result = identify(n1, n2, n3) for k, v in",
"{'employees': 150, 'users': 4, 'login': 1000} dict_union = n1.keys() | n2.keys() | n3.keys()",
"n1.keys() & n2.keys() & n3.keys() dict_differ = dict_union - dict_intersection print('Union |', dict_union)",
"my_nodes = nodes(n1, n2, n3) print('my_nodes -->', my_nodes) # {'login', 'employee', 'user'} #",
"set(node3)) node = get_node() return {i: (node1.get(i, 0), node2.get(i, 0), node3.get(i, 0)) for",
"{'login', 'user', 'employee', 'users', 'employees'} # Intersection & {'users', 'employees'} # Difference -",
"'employee', 'user'} # zip(n1.get(i, 0), n2.get(i, 0), n3.get(i, 0)) def identify(node1, node2, node3):",
"dict_union) print('Intersection &', dict_intersection) print('Difference -', dict_differ) set_differ = (set(n1) | set(n2) |",
"& {'users', 'employees'} # Difference - {'login', 'employee', 'user'} def nodes(node1, node2, node3):",
"intersection result = {key: (node1.get(key, 0), node2.get(key, 0), node3.get(key, 0)) for key in",
"print(set_differ) # Union | {'login', 'user', 'employee', 'users', 'employees'} # Intersection & {'users',",
"= dict_union - dict_intersection print('Union |', dict_union) print('Intersection &', dict_intersection) print('Difference -', dict_differ)",
"n1 = {'employees': 100, 'employee': 5000, 'users': 10, 'user': 100} n2 = {'employees':",
"node3): union = node1.keys() | node2.keys() | node3.keys() intersection = node1.keys() & node2.keys()",
"n2.keys() & n3.keys() dict_differ = dict_union - dict_intersection print('Union |', dict_union) print('Intersection &',",
"# Intersection & {'users', 'employees'} # Difference - {'login', 'employee', 'user'} def nodes(node1,",
"(set(node1) & set(node2) & set(node3)) node = get_node() return {i: (node1.get(i, 0), node2.get(i,",
"& set(node2) & set(node3)) node = get_node() return {i: (node1.get(i, 0), node2.get(i, 0),",
"0)) for i in node} my_nodes = nodes(n1, n2, n3) print('my_nodes -->', my_nodes)",
"0)) def identify(node1, node2, node3): union = node1.keys() | node2.keys() | node3.keys() intersection",
"node2.keys() & node3.keys() relevant = union - intersection result = {key: (node1.get(key, 0),",
"{'employees': 100, 'employee': 5000, 'users': 10, 'user': 100} n2 = {'employees': 250, 'users':",
"set(node2) | set(node3)) - (set(node1) & set(node2) & set(node3)) node = get_node() return",
"node2, node3) def get_node(): return (set(node1) | set(node2) | set(node3)) - (set(node1) &",
"nodes(n1, n2, n3) print('my_nodes -->', my_nodes) # {'login', 'employee', 'user'} # zip(n1.get(i, 0),",
"set(n2) | set(n3)) - (set(n1) & set(n2) & set(n3)) print(set_differ) # Union |",
"def identify(node1, node2, node3): union = node1.keys() | node2.keys() | node3.keys() intersection =",
"identify(n1, n2, n3) for k, v in result.items(): print(f'{k}: {v}') # # login:",
"= node1.keys() & node2.keys() & node3.keys() relevant = union - intersection result =",
"(node1, node2, node3) def get_node(): return (set(node1) | set(node2) | set(node3)) - (set(node1)",
"set(node2) & set(node3)) node = get_node() return {i: (node1.get(i, 0), node2.get(i, 0), node3.get(i,",
"= identify(n1, n2, n3) for k, v in result.items(): print(f'{k}: {v}') # #",
"result = {key: (node1.get(key, 0), node2.get(key, 0), node3.get(key, 0)) for key in relevant}",
"# {'login', 'employee', 'user'} # zip(n1.get(i, 0), n2.get(i, 0), n3.get(i, 0)) def identify(node1,",
"1000} dict_union = n1.keys() | n2.keys() | n3.keys() dict_intersection = n1.keys() & n2.keys()",
"= {'employees': 100, 'employee': 5000, 'users': 10, 'user': 100} n2 = {'employees': 250,",
"node} my_nodes = nodes(n1, n2, n3) print('my_nodes -->', my_nodes) # {'login', 'employee', 'user'}",
"- dict_intersection print('Union |', dict_union) print('Intersection &', dict_intersection) print('Difference -', dict_differ) set_differ =",
"return result result = identify(n1, n2, n3) for k, v in result.items(): print(f'{k}:",
"n3.keys() dict_differ = dict_union - dict_intersection print('Union |', dict_union) print('Intersection &', dict_intersection) print('Difference",
"def get_node(): return (set(node1) | set(node2) | set(node3)) - (set(node1) & set(node2) &",
"{i: (node1.get(i, 0), node2.get(i, 0), node3.get(i, 0)) for i in node} my_nodes =",
"'users': 10, 'user': 100} n2 = {'employees': 250, 'users': 23, 'user': 230} n3",
"| node2.keys() | node3.keys() intersection = node1.keys() & node2.keys() & node3.keys() relevant =",
"v in result.items(): print(f'{k}: {v}') # # login: (0, 0, 1000) # user:",
"<reponame>ASHISHKUMAR2411/Programming-CookBook n1 = {'employees': 100, 'employee': 5000, 'users': 10, 'user': 100} n2 =",
"Intersection & {'users', 'employees'} # Difference - {'login', 'employee', 'user'} def nodes(node1, node2,",
"print(f'{k}: {v}') # # login: (0, 0, 1000) # user: (100, 230, 0)",
"n2, n3) print('my_nodes -->', my_nodes) # {'login', 'employee', 'user'} # zip(n1.get(i, 0), n2.get(i,",
"{'login', 'employee', 'user'} # zip(n1.get(i, 0), n2.get(i, 0), n3.get(i, 0)) def identify(node1, node2,",
"'user', 'employee', 'users', 'employees'} # Intersection & {'users', 'employees'} # Difference - {'login',",
"& set(node3)) node = get_node() return {i: (node1.get(i, 0), node2.get(i, 0), node3.get(i, 0))",
"intersection = node1.keys() & node2.keys() & node3.keys() relevant = union - intersection result",
"0), node2.get(i, 0), node3.get(i, 0)) for i in node} my_nodes = nodes(n1, n2,",
"login: (0, 0, 1000) # user: (100, 230, 0) # employee: (5000, 0,",
"def nodes(node1, node2, node3): node_order = (node1, node2, node3) def get_node(): return (set(node1)",
"dict_intersection) print('Difference -', dict_differ) set_differ = (set(n1) | set(n2) | set(n3)) - (set(n1)",
"'employees'} # Intersection & {'users', 'employees'} # Difference - {'login', 'employee', 'user'} def",
"= n1.keys() | n2.keys() | n3.keys() dict_intersection = n1.keys() & n2.keys() & n3.keys()",
"my_nodes) # {'login', 'employee', 'user'} # zip(n1.get(i, 0), n2.get(i, 0), n3.get(i, 0)) def",
"node3): node_order = (node1, node2, node3) def get_node(): return (set(node1) | set(node2) |",
"= (node1, node2, node3) def get_node(): return (set(node1) | set(node2) | set(node3)) -",
"result = identify(n1, n2, n3) for k, v in result.items(): print(f'{k}: {v}') #",
"set(node3)) - (set(node1) & set(node2) & set(node3)) node = get_node() return {i: (node1.get(i,",
"dict_union = n1.keys() | n2.keys() | n3.keys() dict_intersection = n1.keys() & n2.keys() &",
"& node2.keys() & node3.keys() relevant = union - intersection result = {key: (node1.get(key,",
"(set(n1) | set(n2) | set(n3)) - (set(n1) & set(n2) & set(n3)) print(set_differ) #",
"100} n2 = {'employees': 250, 'users': 23, 'user': 230} n3 = {'employees': 150,",
"'user': 100} n2 = {'employees': 250, 'users': 23, 'user': 230} n3 = {'employees':",
"= n1.keys() & n2.keys() & n3.keys() dict_differ = dict_union - dict_intersection print('Union |',",
"& set(n2) & set(n3)) print(set_differ) # Union | {'login', 'user', 'employee', 'users', 'employees'}",
"(0, 0, 1000) # user: (100, 230, 0) # employee: (5000, 0, 0)",
"n3.keys() dict_intersection = n1.keys() & n2.keys() & n3.keys() dict_differ = dict_union - dict_intersection",
"{'users', 'employees'} # Difference - {'login', 'employee', 'user'} def nodes(node1, node2, node3): node_order",
"n3) print('my_nodes -->', my_nodes) # {'login', 'employee', 'user'} # zip(n1.get(i, 0), n2.get(i, 0),",
"node3.keys() relevant = union - intersection result = {key: (node1.get(key, 0), node2.get(key, 0),",
"& n3.keys() dict_differ = dict_union - dict_intersection print('Union |', dict_union) print('Intersection &', dict_intersection)",
"(set(node1) | set(node2) | set(node3)) - (set(node1) & set(node2) & set(node3)) node =",
"node1.keys() & node2.keys() & node3.keys() relevant = union - intersection result = {key:",
"n2, n3) for k, v in result.items(): print(f'{k}: {v}') # # login: (0,",
"node3.keys() intersection = node1.keys() & node2.keys() & node3.keys() relevant = union - intersection",
"set(n3)) - (set(n1) & set(n2) & set(n3)) print(set_differ) # Union | {'login', 'user',",
"get_node(): return (set(node1) | set(node2) | set(node3)) - (set(node1) & set(node2) & set(node3))",
"union - intersection result = {key: (node1.get(key, 0), node2.get(key, 0), node3.get(key, 0)) for",
"'employee', 'user'} def nodes(node1, node2, node3): node_order = (node1, node2, node3) def get_node():",
"& node3.keys() relevant = union - intersection result = {key: (node1.get(key, 0), node2.get(key,",
"in result.items(): print(f'{k}: {v}') # # login: (0, 0, 1000) # user: (100,",
"print('Union |', dict_union) print('Intersection &', dict_intersection) print('Difference -', dict_differ) set_differ = (set(n1) |",
"node3.get(i, 0)) for i in node} my_nodes = nodes(n1, n2, n3) print('my_nodes -->',",
"identify(node1, node2, node3): union = node1.keys() | node2.keys() | node3.keys() intersection = node1.keys()",
"node2.get(key, 0), node3.get(key, 0)) for key in relevant} return result result = identify(n1,",
"node3) def get_node(): return (set(node1) | set(node2) | set(node3)) - (set(node1) & set(node2)",
"= node1.keys() | node2.keys() | node3.keys() intersection = node1.keys() & node2.keys() & node3.keys()",
"'user'} def nodes(node1, node2, node3): node_order = (node1, node2, node3) def get_node(): return",
"set(n3)) print(set_differ) # Union | {'login', 'user', 'employee', 'users', 'employees'} # Intersection &",
"node1.keys() | node2.keys() | node3.keys() intersection = node1.keys() & node2.keys() & node3.keys() relevant",
"dict_differ) set_differ = (set(n1) | set(n2) | set(n3)) - (set(n1) & set(n2) &",
"(node1.get(key, 0), node2.get(key, 0), node3.get(key, 0)) for key in relevant} return result result",
"& n2.keys() & n3.keys() dict_differ = dict_union - dict_intersection print('Union |', dict_union) print('Intersection",
"'users': 4, 'login': 1000} dict_union = n1.keys() | n2.keys() | n3.keys() dict_intersection =",
"- (set(n1) & set(n2) & set(n3)) print(set_differ) # Union | {'login', 'user', 'employee',",
"in node} my_nodes = nodes(n1, n2, n3) print('my_nodes -->', my_nodes) # {'login', 'employee',",
"- {'login', 'employee', 'user'} def nodes(node1, node2, node3): node_order = (node1, node2, node3)",
"- intersection result = {key: (node1.get(key, 0), node2.get(key, 0), node3.get(key, 0)) for key",
"union = node1.keys() | node2.keys() | node3.keys() intersection = node1.keys() & node2.keys() &",
"# Union | {'login', 'user', 'employee', 'users', 'employees'} # Intersection & {'users', 'employees'}",
"node2, node3): union = node1.keys() | node2.keys() | node3.keys() intersection = node1.keys() &",
"0), n3.get(i, 0)) def identify(node1, node2, node3): union = node1.keys() | node2.keys() |",
"return {i: (node1.get(i, 0), node2.get(i, 0), node3.get(i, 0)) for i in node} my_nodes",
"| set(n3)) - (set(n1) & set(n2) & set(n3)) print(set_differ) # Union | {'login',",
"{'employees': 250, 'users': 23, 'user': 230} n3 = {'employees': 150, 'users': 4, 'login':",
"(set(n1) & set(n2) & set(n3)) print(set_differ) # Union | {'login', 'user', 'employee', 'users',",
"100, 'employee': 5000, 'users': 10, 'user': 100} n2 = {'employees': 250, 'users': 23,",
"= nodes(n1, n2, n3) print('my_nodes -->', my_nodes) # {'login', 'employee', 'user'} # zip(n1.get(i,",
"= {'employees': 150, 'users': 4, 'login': 1000} dict_union = n1.keys() | n2.keys() |",
"-', dict_differ) set_differ = (set(n1) | set(n2) | set(n3)) - (set(n1) & set(n2)",
"n3.get(i, 0)) def identify(node1, node2, node3): union = node1.keys() | node2.keys() | node3.keys()",
"4, 'login': 1000} dict_union = n1.keys() | n2.keys() | n3.keys() dict_intersection = n1.keys()",
"node2.keys() | node3.keys() intersection = node1.keys() & node2.keys() & node3.keys() relevant = union",
"|', dict_union) print('Intersection &', dict_intersection) print('Difference -', dict_differ) set_differ = (set(n1) | set(n2)",
"- (set(node1) & set(node2) & set(node3)) node = get_node() return {i: (node1.get(i, 0),",
"dict_intersection = n1.keys() & n2.keys() & n3.keys() dict_differ = dict_union - dict_intersection print('Union",
"for i in node} my_nodes = nodes(n1, n2, n3) print('my_nodes -->', my_nodes) #",
"250, 'users': 23, 'user': 230} n3 = {'employees': 150, 'users': 4, 'login': 1000}"
] |
[
".models import * class AddForm(forms.ModelForm): class Meta: model = Post fields = ('title','desc')",
"models from django.db.models import fields from .models import * class AddForm(forms.ModelForm): class Meta:",
"import models from django.db.models import fields from .models import * class AddForm(forms.ModelForm): class",
"import forms from django.db import models from django.db.models import fields from .models import",
"django import forms from django.db import models from django.db.models import fields from .models",
"from django import forms from django.db import models from django.db.models import fields from",
"from django.db.models import fields from .models import * class AddForm(forms.ModelForm): class Meta: model",
"fields from .models import * class AddForm(forms.ModelForm): class Meta: model = Post fields",
"from .models import * class AddForm(forms.ModelForm): class Meta: model = Post fields =",
"django.db import models from django.db.models import fields from .models import * class AddForm(forms.ModelForm):",
"django.db.models import fields from .models import * class AddForm(forms.ModelForm): class Meta: model =",
"from django.db import models from django.db.models import fields from .models import * class",
"forms from django.db import models from django.db.models import fields from .models import *",
"import fields from .models import * class AddForm(forms.ModelForm): class Meta: model = Post",
"<gh_stars>0 from django import forms from django.db import models from django.db.models import fields"
] |
[
"\"\"\" global _global_style try: _global_style = Style(style, **overrides) if overrides else style yield",
"When a style is requested from a ``Style`` and cannot be found in",
"\"\"\" Called by ``StyleableMixin`` objects to receive updates on whenever this style changes.",
"not None} def get_style(self, key): \"\"\" Return the style corresponding to the given",
"all the named fonts. This must be called prior to attempting to use",
"tk.Entry = Entry tk.Frame = Frame tk.Label = Label tk.LabelFrame = LabelFrame tk.Listbox",
"be used instead. (Although configuring \"functional\" styles through ``widget.configure`` is perfect fine.) There",
"tkinter widgets with their styleable equivalents.\"\"\" tk.Button = Button tk.Canvas = Canvas tk.Checkbutton",
"\"#335555\" MUTE_PURPLE = \"#553377\" MUTE_PINK = \"#663366\" MUTE_ORANGE = \"#774433\" RED_TEAM = \"#992222\"",
"dictionary of the styles specific to this ``Style``.\"\"\" self._styled = [] \"\"\" A",
"in cooperation with the ``Style`` class. Styleable widgets should never use their ``widget.configure``",
"else: self._overrides = styled if style: if self._style: self._style.unregister_styleable(self) self._style = style style.register_styleable(self)",
"their styleable equivalents.\"\"\" try: patch_tk_widgets() yield finally: unpatch_tk_widgets() @contextmanager def stylize(style, **overrides): \"\"\"",
"fonts. \"\"\" import tkinter as tk import tkinter.font as tkfont from contextlib import",
"constructor. :param style: An initial style to employ. :type style: Style :param overrides:",
"size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL = tkfont.Font(root,",
"employ a parent-child system in which a ``Style`` can have one or more",
"version of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\",",
"style to employ, or None to clear the current style (if ``keep_style`` is",
"functional options from the styled ones. functional, styled = {}, {} for k,",
"of default (platform-specific) styles to revert to if an initially explicitly given style",
":type style: Style :param overrides: Style overrides to use. \"\"\" super().__init__(master, cnf, *args)",
"looked for in its ancestors, prioritizing the first ones specified in the constructor.",
"\"relief\", \"overrelief\", \"justify\"] class Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable version of ``tkinter.Canvas``.\"\"\" STYLED_OPTS = [\"bg\",",
"\"\"\" Configure this ``Style``'s styles. :param kwargs: The styles to add/edit. \"\"\" self._dict.update(kwargs)",
"hierarchical styling system for the non-ttk widgets; - a collection of colour constants;",
"``Style`` in ``Style._signal_style_changed``. \"\"\" for parent in parents: parent._register_child(self) def register_styleable(self, styleable): \"\"\"",
"of ``tkinter.Text``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"insertbackground\", \"insertborderwidth\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"for tkinter widgets. Some features include: - a hierarchical styling system for the",
"named fonts. This must be called prior to attempting to use any of",
"of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\",",
"``init_fonts`` must be called to initialize this font. \"\"\" # Backup copies of",
"changes. :param style: The child ``Style``. :type style: Style \"\"\" self._children.append(style) # Keep",
"``StyleableMixin``s register themselves to ``Style``s so that whenever a ``Style`` is updated, any",
"used instead. (Although configuring \"functional\" styles through ``widget.configure`` is perfect fine.) There are",
"= \"#222222\" GRAY_SCALE_3 = \"#333333\" GRAY_SCALE_4 = \"#444444\" GRAY_SCALE_5 = \"#555555\" GRAY_SCALE_6 =",
"method to update all the ``StyleableMixin`` widgets registered to this ``Style`` and its",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable version of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS =",
"dictionary of default styles. \"\"\" cls._assure_default_dicts_exist() if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults",
"with the class-specific user-provided defaults. (Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style: # Update the",
"the global style, which may be set by the stylize context # manger.",
"import tkinter as tk import tkinter.font as tkfont from contextlib import contextmanager #",
"``init_fonts`` must be called to initialize this font. \"\"\" FONT_SERIF_NORMAL = None \"\"\"",
"self.cget(k)) for k in styles_dict if k not in tk_defaults) self.configure(styles_dict) @classmethod def",
"tkinter. def configure(self, **kwargs): \"\"\" Configure this ``Style``'s styles. :param kwargs: The styles",
"_tkScale tk.Scrollbar = _tkScrollbar tk.Spinbox = _tkSpinbox tk.Text = _tkText tk.Toplevel = _tkToplevel",
"= tk.Frame _tkLabel = tk.Label _tkLabelFrame = tk.LabelFrame _tkListbox = tk.Listbox _tkMenu =",
"tk.Toplevel): \"\"\"Styleable version of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"]",
"**overrides): \"\"\" Context manager to temporarily apply a global-level style and some overrides.",
"= _tkCheckbutton tk.Entry = _tkEntry tk.Frame = _tkFrame tk.Label = _tkLabel tk.LabelFrame =",
"self._overrides = None \"\"\"A dictionary of the widget's currently-overridden styles.\"\"\" self._assure_default_dicts_exist() # Initialize",
"priority (1). We # will update the dict with increasing style priority so",
"configure the widget, save any of the styles set to this widget by",
"the default styles for this class. :param keep_existing: Whether to keep the already",
"self._parents: ret = p._get_style(key) if ret is not None: break return ret @classmethod",
"update the global default styles (``Style.DEFAULTS``). :param keep_existing: Whether to keep the already",
"not in this ``Style``. :param styles: Style names to remove. \"\"\" for style",
"One may also set this at runtime through ``StyleableMixin.set_defaults``, but any changes made",
"- size: 10 - family: \"Courier\" - weight: BOLD ``init_fonts`` must be called",
"style: Style \"\"\" self._children.append(style) # Keep the same naming scheme as tkinter. def",
"use. \"\"\" global _global_style try: _global_style = Style(style, **overrides) if overrides else style",
"Scrollbar tk.Spinbox = Spinbox tk.Text = Text tk.Toplevel = Toplevel def unpatch_tk_widgets(): \"\"\"Revert",
"- family: \"Courier\" ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SERIF_TITLE",
"in self._parents: ret = p._get_style(key) if ret is not None: break return ret",
"the given style name or None if it could not be found. \"\"\"",
"in styles: del self._dict[style] self._signal_style_changed() def _signal_style_changed(self): \"\"\" Internal method to update all",
"tk.Spinbox _tkText = tk.Text _tkToplevel = tk.Toplevel _global_style = None \"\"\"A global ``Style``",
"given style or the global style, which may be set by the stylize",
"= {} \"\"\"Global default styles for all ``Style`` objects. This should be set",
"``StyleableMixin``s are automatically updated to reflect the changes. ``Style``s employ a parent-child system",
"built for each unique styled class (i.e. a style is added to this",
"init_fonts(root): \"\"\" Initialize all the named fonts. This must be called prior to",
"updates on whenever this style changes. :param style: The child ``Style``. :type style:",
"GRAY_SCALE_6 = \"#666666\" GRAY_SCALE_7 = \"#777777\" GRAY_SCALE_8 = \"#888888\" GRAY_SCALE_9 = \"#999999\" GRAY_SCALE_A",
"defaults: A dictionary of default styles. \"\"\" cls._assure_default_dicts_exist() if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS",
"registered child ``Style``s. These are signaled of any changes to this ``Style`` in",
"use their ``widget.configure`` method to set styles in their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should be",
"be called prior to attempting to use any of the named fonts. :param",
"current ``Style``.\"\"\" self._overrides = None \"\"\"A dictionary of the widget's currently-overridden styles.\"\"\" self._assure_default_dicts_exist()",
"registered ``StyleableMixin``s are automatically updated to reflect the changes. ``Style``s employ a parent-child",
"only be used by ``StyleableMixin``s if they're not explicitly given a ``Style`` object",
"_tkToplevel = tk.Toplevel _global_style = None \"\"\"A global ``Style`` object used by the",
"whenever this style changes. :param style: The child ``Style``. :type style: Style \"\"\"",
"is given. :type keep_style: bool :param keep_overrides: Whether to append the given ``overrides``",
"Update the dict with the styles from the Style object. (Priority 3) styles_dict.update(self._style.get_relevant_styles(self))",
"_tkEntry = tk.Entry _tkFrame = tk.Frame _tkLabel = tk.Label _tkLabelFrame = tk.LabelFrame _tkListbox",
"styles. :param kwargs: The styles to add/edit. \"\"\" self._dict.update(kwargs) self._signal_style_changed() config = configure",
"``StyleableMixin`` widgets registered to this ``Style`` and its children. \"\"\" for s in",
"to this widget by default so we may return # to them if",
"= None \"\"\" Tkinter named font with these properties: - size: 10 -",
"styles for this class. :param keep_existing: Whether to keep the already existing default",
"from a ``Style`` and cannot be found in said ``Style``'s own styles, the",
"styleable widget to unregister. :type styleable: StyleableMixin \"\"\" # This will raise an",
"any of the styles set to this widget by default so we may",
"\"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Scale(StyleableMixin,",
"which may be set by the stylize context # manger. self.apply_style(style or _global_style,",
"Tk (root)? class Button(StyleableMixin, tk.Button): \"\"\"Styleable version of ``tkinter.Button``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"# Update the dict with the class-specific user-provided defaults. (Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES) if",
"(if ``keep_style`` is False). :type style: Style :param keep_style: If ``style`` is None,",
"are signaled of any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" for parent",
"tk.PanedWindow _tkRadiobutton = tk.Radiobutton _tkScale = tk.Scale _tkScrollbar = tk.Scrollbar _tkSpinbox = tk.Spinbox",
"[\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\",",
"requested from a ``Style`` and cannot be found in said ``Style``'s own styles,",
"\"#992222\" BLUE_TEAM = \"#222299\" UNKNOWN_TEAM = GRAY_SCALE_B BOOL_TRUE = MUTE_GREEN BOOL_FALSE = MUTE_RED",
"be called to initialize this font. \"\"\" FONT_SANS_SERIF_TITLE = None \"\"\" Tkinter named",
"are considered \"functional\" and hence won't be regulated in any way by this",
"bool :param overrides: Style overrides to use. \"\"\" # Sort out the functional",
"this ``Style``. This will raise a ``KeyError`` if any of the given style",
"= PanedWindow tk.Radiobutton = Radiobutton tk.Scale = Scale tk.Scrollbar = Scrollbar tk.Spinbox =",
"\"Courier\" ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SERIF_TITLE = None",
"list of registered ``StyleableMixin``s. These are signaled of any changes to this ``Style``",
"tkinter widget. \"\"\" return {k: v for k, v in map(lambda k: (k,",
"of the given style names are not in this ``Style``. :param styles: Style",
"\"\"\"Styleable version of ``tkinter.Menu``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\",",
":param overrides: Style overrides to use. \"\"\" global _global_style try: _global_style = Style(style,",
"to clear the current style (if ``keep_style`` is False). :type style: Style :param",
"MUTE_ORANGE = \"#774433\" RED_TEAM = \"#992222\" BLUE_TEAM = \"#222299\" UNKNOWN_TEAM = GRAY_SCALE_B BOOL_TRUE",
"of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"relief\", \"sashrelief\", \"showhandle\"] class Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable",
"\"\"\" import tkinter as tk import tkinter.font as tkfont from contextlib import contextmanager",
"= self._dict.get(key) if ret is None: for p in self._parents: ret = p._get_style(key)",
"into effect on instances of that class until ``StyleableMixin.update_style`` is called. \"\"\" def",
"objects. This should be set through ``Style.set_defaults``.\"\"\" def __init__(self, *parents, **styles): \"\"\" :param",
"this ``Style``.\"\"\" self._styled = [] \"\"\" A list of registered ``StyleableMixin``s. These are",
"The style corresponding to the given style name or None if it could",
"2. ``StyleableMixin.DEFAULT_STYLES`` 3. A given ``Style`` instance 4. A given dictionary of overrides",
"font. \"\"\" FONT_SANS_SERIF_TITLE = None \"\"\" Tkinter named font with these properties: -",
"user code. :param styleable: The styleable widget to unregister. :type styleable: StyleableMixin \"\"\"",
"of these; if they were initialized to an empty dict in ``StyleableMixin`` then",
"\"bd\", \"relief\", \"sashrelief\", \"showhandle\"] class Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable version of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS =",
"_tkPanedWindow = tk.PanedWindow _tkRadiobutton = tk.Radiobutton _tkScale = tk.Scale _tkScrollbar = tk.Scrollbar _tkSpinbox",
"= \"#111111\" GRAY_SCALE_2 = \"#222222\" GRAY_SCALE_3 = \"#333333\" GRAY_SCALE_4 = \"#444444\" GRAY_SCALE_5 =",
"``Style``'s ``Style._dict``. If that fails, recursively search this widget's parents. :param key: The",
"\"\"\" return {k: v for k, v in map(lambda k: (k, self.get_style(k)), widget.keys())",
"\"\"\" Determine and return all the styles in this ``Style`` recognized by the",
"tk.Checkbutton = _tkCheckbutton tk.Entry = _tkEntry tk.Frame = _tkFrame tk.Label = _tkLabel tk.LabelFrame",
"Colour constants: GRAY_SCALE_0 = \"#000000\" GRAY_SCALE_1 = \"#111111\" GRAY_SCALE_2 = \"#222222\" GRAY_SCALE_3 =",
"the given style names are not in this ``Style``. :param styles: Style names",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"labelanchor\"] class Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable version of ``tkinter.Listbox``.\"\"\" STYLED_OPTS",
"naming scheme as tkinter. def configure(self, **kwargs): \"\"\" Configure this ``Style``'s styles. :param",
"by user code. :param styleable: The styleable widget to unregister. :type styleable: StyleableMixin",
"= \"#DDDDDD\" GRAY_SCALE_E = \"#EEEEEE\" GRAY_SCALE_F = \"#FFFFFF\" MUTE_BLUE = \"#333355\" MUTE_GREEN =",
"class used to make a widget \"styleable\". This class works in cooperation with",
"[\"font\", \"bg\", \"activebackground\", \"fg\", \"bd\", \"showvalue\", \"sliderrelief\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class",
"to receive updates on whenever this style changes. :param style: The child ``Style``.",
"configuring \"functional\" styles through ``widget.configure`` is perfect fine.) There are four sources of",
"\"functional\" styles through ``widget.configure`` is perfect fine.) There are four sources of style",
"child._signal_style_changed() def get_relevant_styles(self, widget): \"\"\" Determine and return all the styles in this",
"widget's parents. :param key: The style name. :type key: str :return: The style",
"\"activebackground\", \"fg\", \"bd\", \"showvalue\", \"sliderrelief\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Scrollbar(StyleableMixin, tk.Scrollbar):",
"style names are not in this ``Style``. :param styles: Style names to remove.",
"= \"#AAAAAA\" GRAY_SCALE_B = \"#BBBBBB\" GRAY_SCALE_C = \"#CCCCCC\" GRAY_SCALE_D = \"#DDDDDD\" GRAY_SCALE_E =",
"specified in the constructor. When a ``Style`` is updated, all child ``Style``s of",
"- a hierarchical styling system for the non-ttk widgets; - a collection of",
"or None to clear the current style (if ``keep_style`` is False). :type style:",
"is perfect fine.) There are four sources of style options and they work",
"style: The style to employ, or None to clear the current style (if",
"self._style.unregister_styleable(self) self._style = None self.update_style() def update_style(self): \"\"\"Update this widget's styles.\"\"\" # Alias",
"def unpatch_tk_widgets(): \"\"\"Revert the tkinter widgets back to their defaults after monkey patching",
"tk_defaults.update((k, self.cget(k)) for k in styles_dict if k not in tk_defaults) self.configure(styles_dict) @classmethod",
"class until ``StyleableMixin.update_style`` is called. \"\"\" def __init__(self, master=None, cnf={}, *args, style=None, **overrides):",
"its ancestors, prioritizing the first ones specified in the constructor. When a ``Style``",
"bool :param defaults: A dictionary of styles. \"\"\" if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS",
"p in self._parents: ret = p._get_style(key) if ret is not None: break return",
"is requested from a ``Style`` and cannot be found in said ``Style``'s own",
"Start off the styles_dict with a copy of the tk_defaults, since those styles",
"\"relief\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Menu(StyleableMixin, tk.Menu): \"\"\"Styleable version of",
"\"bd\", \"insertbackground\", \"insertborderwidth\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Toplevel(StyleableMixin, tk.Toplevel):",
"= [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Style: \"\"\" A dictionary proxy",
"defaults def patch_tk_widgets(): \"\"\"Monkey patch the tkinter widgets with their styleable equivalents.\"\"\" tk.Button",
"styles specific to this ``Style``.\"\"\" self._styled = [] \"\"\" A list of registered",
"overrides. This global-level style will only be used by ``StyleableMixin``s if they're not",
"of ``tkinter.Label``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\",",
"``Style`` class. Styleable widgets should never use their ``widget.configure`` method to set styles",
"for this class. :param keep_existing: Whether to keep the already existing default styles,",
"else: cls.DEFAULTS = defaults # TODO: Styleable Tk (root)? class Button(StyleableMixin, tk.Button): \"\"\"Styleable",
"global default styles (``Style.DEFAULTS``). :param key: The style name. :type key: str :return:",
"and hence won't be regulated in any way by this class. Subclasses should",
"= Button tk.Canvas = Canvas tk.Checkbutton = Checkbutton tk.Entry = Entry tk.Frame =",
"\"relief\"] class Style: \"\"\" A dictionary proxy for tkinter widget styles. ``StyleableMixin``s register",
"collection of colour constants; - and reasonable cross-platform named fonts. \"\"\" import tkinter",
"\"\"\" A list of registered ``StyleableMixin``s. These are signaled of any changes to",
"_global_style try: _global_style = Style(style, **overrides) if overrides else style yield finally: _global_style",
"to the given style name, first checking this ``Style`` and its parents, then",
"if overrides else style yield finally: _global_style = None def init_fonts(root): \"\"\" Initialize",
"\"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\"] class LabelFrame(StyleableMixin,",
"the ``stylize`` context manager.\"\"\" class StyleableMixin: \"\"\" Mixin class used to make a",
"styles (``Style.DEFAULTS``). :param keep_existing: Whether to keep the already existing default styles, or",
"font with these properties: - size: 8 - family: \"Helvetica\" ``init_fonts`` must be",
"so we may return # to them if an explicit style option on",
"\"#222222\" GRAY_SCALE_3 = \"#333333\" GRAY_SCALE_4 = \"#444444\" GRAY_SCALE_5 = \"#555555\" GRAY_SCALE_6 = \"#666666\"",
"of lowest priority (1). We # will update the dict with increasing style",
"``tkinter.Text``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"insertbackground\", \"insertborderwidth\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\",",
"could not be found. \"\"\" ret = self._dict.get(key) if ret is None: for",
"to their defaults after monkey patching them with ``patch_tk_widgets``.\"\"\" tk.Button = _tkButton tk.Canvas",
"self._dict[style] self._signal_style_changed() def _signal_style_changed(self): \"\"\" Internal method to update all the ``StyleableMixin`` widgets",
"to initialize this font. \"\"\" FONT_SANS_SERIF_NORMAL = None \"\"\" Tkinter named font with",
"font. \"\"\" FONT_SERIF_NORMAL = None \"\"\" Tkinter named font with these properties: -",
"already. :param style: The style to apply. :type style: Style :param overrides: Style",
"\"\"\" # This will raise an error if the styleable is not already",
"Context manager to temporarily apply a global-level style and some overrides. This global-level",
"\"indicatoron\", \"offrelief\", \"selectcolor\"] class Entry(StyleableMixin, tk.Entry): \"\"\"Styleable version of ``tkinter.Entry``.\"\"\" STYLED_OPTS = [\"font\",",
"Scale tk.Scrollbar = Scrollbar tk.Spinbox = Spinbox tk.Text = Text tk.Toplevel = Toplevel",
"style name or None if it could not be found. \"\"\" return self._get_style(key)",
"unpatch_tk_widgets(): \"\"\"Revert the tkinter widgets back to their defaults after monkey patching them",
"\"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"] class Text(StyleableMixin, tk.Text): \"\"\"Styleable",
"\"#DDDDDD\" GRAY_SCALE_E = \"#EEEEEE\" GRAY_SCALE_F = \"#FFFFFF\" MUTE_BLUE = \"#333355\" MUTE_GREEN = \"#335533\"",
"of any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" self._parents = parents \"\"\"A",
"Style overrides to use. \"\"\" # Sort out the functional options from the",
"= [\"font\", \"bg\", \"activebackground\", \"fg\", \"bd\", \"showvalue\", \"sliderrelief\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"]",
"already registered. self._styled.remove(styleable) def _register_child(self, style): \"\"\" Called by child ``Style``s to receive",
"\"\"\" DEFAULT_STYLES = None \"\"\" A dictionary of default user-defined styles for a",
"@classmethod def _assure_default_dicts_exist(cls): \"\"\" Make sure that this class's ``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES`` are",
"Tkinter named font with these properties: - size: 10 - family: \"Courier\" -",
"if style: if self._style: self._style.unregister_styleable(self) self._style = style style.register_styleable(self) elif self._style and not",
"cls.TK_DEFAULT_STYLES is None: cls.TK_DEFAULT_STYLES = {} if cls.DEFAULT_STYLES is None: cls.DEFAULT_STYLES = {}",
"_tkText tk.Toplevel = _tkToplevel @contextmanager def patch(): \"\"\"Context manager to temporarily monkey patch",
"This must be called prior to attempting to use any of the named",
"``Style``'s own styles, the style is looked for in its ancestors, prioritizing the",
"in overrides.items(): if k in self.STYLED_OPTS: styled[k] = v else: functional[k] = v",
"A dictionary of configuration options. This is here to mimic the tkinter widget",
"tk.Entry _tkFrame = tk.Frame _tkLabel = tk.Label _tkLabelFrame = tk.LabelFrame _tkListbox = tk.Listbox",
"style option is revoked. This dictionary is lazily built for each unique styled",
"\"sliderrelief\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable version of ``tkinter.Scrollbar``.\"\"\"",
"for styling; any other options encountered are considered \"functional\" and hence won't be",
"configure(self, **kwargs): \"\"\" Configure this ``Style``'s styles. :param kwargs: The styles to add/edit.",
"widget. :type root: tkinter.Tk \"\"\" global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE",
"overrides to use. \"\"\" global _global_style try: _global_style = Style(style, **overrides) if overrides",
"a global-level style and some overrides. This global-level style will only be used",
"dictionary is lazily built for each unique styled class (i.e. a style is",
":param defaults: A dictionary of default styles. \"\"\" cls._assure_default_dicts_exist() if keep_existing: cls.DEFAULTS.update(defaults) else:",
"= [\"bg\", \"bd\", \"relief\", \"sashrelief\", \"showhandle\"] class Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable version of ``tkinter.Radiobutton``.\"\"\"",
"list of strings specifying all the widget options (i.e. the ones that would",
"tk.LabelFrame): \"\"\"Styleable version of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"highlightcolor\", \"highlightbackground\",",
"tk.Menu = Menu tk.PanedWindow = PanedWindow tk.Radiobutton = Radiobutton tk.Scale = Scale tk.Scrollbar",
"overridden. styles_dict = tk_defaults.copy() # Update the dict with the class-specific user-provided defaults.",
"\"#555555\" GRAY_SCALE_6 = \"#666666\" GRAY_SCALE_7 = \"#777777\" GRAY_SCALE_8 = \"#888888\" GRAY_SCALE_9 = \"#999999\"",
"registered ``StyleableMixin``s. These are signaled of any changes to this ``Style`` in ``Style._signal_style_changed``.",
"tk.Listbox = Listbox tk.Menu = Menu tk.PanedWindow = PanedWindow tk.Radiobutton = Radiobutton tk.Scale",
"tkinter.Tk \"\"\" global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE = tkfont.Font(root, size=10,",
":type style: Style :param keep_style: If ``style`` is None, setting this will keep",
"class Scale(StyleableMixin, tk.Scale): \"\"\"Styleable version of ``tkinter.Scale``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\",",
"Style(style, **overrides) if overrides else style yield finally: _global_style = None def init_fonts(root):",
"recursively informed of the change. \"\"\" DEFAULTS = {} \"\"\"Global default styles for",
"_tkCanvas tk.Checkbutton = _tkCheckbutton tk.Entry = _tkEntry tk.Frame = _tkFrame tk.Label = _tkLabel",
"global-level style will only be used by ``StyleableMixin``s if they're not explicitly given",
"``tkinter.Canvas``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class",
"\"\"\" cls._assure_default_dicts_exist() if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults # TODO: Styleable Tk",
"\"\"\" Contains styling utilities for tkinter widgets. Some features include: - a hierarchical",
"in map(lambda k: (k, self.get_style(k)), widget.keys()) if v is not None} def get_style(self,",
"must be called to initialize this font. \"\"\" FONT_SANS_SERIF_NORMAL = None \"\"\" Tkinter",
"\"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Frame(StyleableMixin, tk.Frame): \"\"\"Styleable version of ``tkinter.Frame``.\"\"\" STYLED_OPTS = [\"bg\",",
"\"highlightthickness\", \"relief\", \"labelanchor\"] class Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable version of ``tkinter.Listbox``.\"\"\" STYLED_OPTS = [\"font\",",
"\"\"\" Initialize all the named fonts. This must be called prior to attempting",
"keep_overrides: Whether to append the given ``overrides`` to the already existing overridden styles,",
"StyleableMixin \"\"\" # This will raise an error if the styleable is not",
"this class's ``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES`` are defined (every class needs its own version",
"``StyleableMixin.apply_style`` should be used instead. (Although configuring \"functional\" styles through ``widget.configure`` is perfect",
"[\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\",",
"their defaults after monkey patching them with ``patch_tk_widgets``.\"\"\" tk.Button = _tkButton tk.Canvas =",
"to initialize this font. \"\"\" FONT_SERIF_TITLE = None \"\"\" Tkinter named font with",
"must be called to initialize this font. \"\"\" FONT_MONOSPACE_NORMAL = None \"\"\" Tkinter",
"FONT_MONOSPACE_NORMAL = None \"\"\" Tkinter named font with these properties: - size: 8",
"\"#888833\" MUTE_TURQUOISE = \"#335555\" MUTE_PURPLE = \"#553377\" MUTE_PINK = \"#663366\" MUTE_ORANGE = \"#774433\"",
":param style: The style to apply. :type style: Style :param overrides: Style overrides",
"not be called by user code. :param styleable: The styleable widget to register.",
"this ``Style`` and its children. \"\"\" for s in self._styled: s.update_style() for child",
"with these properties: - size: 8 - family: \"Helvetica\" ``init_fonts`` must be called",
"There are four sources of style options and they work on a priority",
"should be set through ``Style.set_defaults``.\"\"\" def __init__(self, *parents, **styles): \"\"\" :param parents: ``Style``s",
"means higher priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES`` 3. A given ``Style`` instance 4.",
"default styles. \"\"\" cls._assure_default_dicts_exist() if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults # TODO:",
"named font with these properties: - size: 10 - family: \"Times\" - weight:",
"GRAY_SCALE_8 = \"#888888\" GRAY_SCALE_9 = \"#999999\" GRAY_SCALE_A = \"#AAAAAA\" GRAY_SCALE_B = \"#BBBBBB\" GRAY_SCALE_C",
"first time it changes from its default). \"\"\" DEFAULT_STYLES = None \"\"\" A",
"2) styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style: # Update the dict with the styles from the",
"font with these properties: - size: 8 - family: \"Times\" ``init_fonts`` must be",
":param styles: Styles to use. \"\"\" self._dict = styles \"\"\"A dictionary of the",
"replace them. :type keep_existing: bool :param defaults: A dictionary of default styles. \"\"\"",
"weight: BOLD ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SANS_SERIF_NORMAL =",
"of \"normal\" tkinter widgets: _tkButton = tk.Button _tkCanvas = tk.Canvas _tkCheckbutton = tk.Checkbutton",
"tk.Scale = _tkScale tk.Scrollbar = _tkScrollbar tk.Spinbox = _tkSpinbox tk.Text = _tkText tk.Toplevel",
"def get_relevant_styles(self, widget): \"\"\" Determine and return all the styles in this ``Style``",
"config = configure \"\"\"Alias for ``Style.configure``.\"\"\" def remove_styles(self, *styles): \"\"\" Remove the given",
"for k, v in map(lambda k: (k, self.get_style(k)), widget.keys()) if v is not",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"]",
"user-defined styles for a given class. Subclasses may define this. One may also",
"styleable: StyleableMixin \"\"\" # This will raise an error if the styleable is",
"class Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable version of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\",",
"\"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Frame(StyleableMixin, tk.Frame): \"\"\"Styleable version of ``tkinter.Frame``.\"\"\" STYLED_OPTS =",
"size: 8 - family: \"Courier\" ``init_fonts`` must be called to initialize this font.",
"instances of that class until ``StyleableMixin.update_style`` is called. \"\"\" def __init__(self, master=None, cnf={},",
"informed of the change. \"\"\" DEFAULTS = {} \"\"\"Global default styles for all",
"the class-specific user-provided defaults. (Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style: # Update the dict",
"Sort out the functional options from the styled ones. functional, styled = {},",
"tk.Label = _tkLabel tk.LabelFrame = _tkLabelFrame tk.Listbox = _tkListbox tk.Menu = _tkMenu tk.PanedWindow",
"# Backup copies of \"normal\" tkinter widgets: _tkButton = tk.Button _tkCanvas = tk.Canvas",
"changes. This should not be called by user code. :param styleable: The styleable",
"= \"#553377\" MUTE_PINK = \"#663366\" MUTE_ORANGE = \"#774433\" RED_TEAM = \"#992222\" BLUE_TEAM =",
"styles for. :return: All the styles recognized by the given tkinter widget. \"\"\"",
"def _get_style(self, key): \"\"\" Attempt to retrieve the given style from this ``Style``'s",
"the named fonts. This must be called prior to attempting to use any",
"initialize this font. \"\"\" FONT_SANS_SERIF_NORMAL = None \"\"\" Tkinter named font with these",
"to update the default styles for this class. :param keep_existing: Whether to keep",
"\"\"\"Styleable version of ``tkinter.Frame``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class",
"list of registered child ``Style``s. These are signaled of any changes to this",
"\"highlightthickness\", \"relief\"] class Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable version of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS = [\"bg\", \"activebackground\",",
"\"\"\"Styleable version of ``tkinter.Text``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"insertbackground\", \"insertborderwidth\", \"highlightcolor\",",
"ancestors, prioritizing the first ones specified in the constructor. When a ``Style`` is",
"version of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS = [\"bg\", \"activebackground\", \"activerelief\", \"bd\", \"elementborderwidth\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\",",
"the functional options self.configure(functional) if keep_overrides: self._overrides.update(styled) else: self._overrides = styled if style:",
"class's ``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES`` are defined (every class needs its own version of",
"# Named fonts: FONT_MONOSPACE_TITLE = None \"\"\" Tkinter named font with these properties:",
"{}, {} for k, v in overrides.items(): if k in self.STYLED_OPTS: styled[k] =",
"self._styled.append(styleable) def unregister_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to stop receiving updates",
"MUTE_YELLOW = \"#888833\" MUTE_TURQUOISE = \"#335555\" MUTE_PURPLE = \"#553377\" MUTE_PINK = \"#663366\" MUTE_ORANGE",
"work on a priority system (higher number means higher priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2.",
"if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults # TODO: Styleable Tk (root)? class",
"Entry(StyleableMixin, tk.Entry): \"\"\"Styleable version of ``tkinter.Entry``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\",",
"\"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"] class",
"Before we actually configure the widget, save any of the styles set to",
"specific to this ``Style``.\"\"\" self._styled = [] \"\"\" A list of registered ``StyleableMixin``s.",
"``Style``'s parent ``Style``s.\"\"\" self._children = [] \"\"\" A list of registered child ``Style``s.",
"be found. \"\"\" return self._get_style(key) or self.__class__.DEFAULTS.get(key) def _get_style(self, key): \"\"\" Attempt to",
"family: \"Helvetica\" ``init_fonts`` must be called to initialize this font. \"\"\" # Backup",
"None: for p in self._parents: ret = p._get_style(key) if ret is not None:",
"called to initialize this font. \"\"\" FONT_SERIF_NORMAL = None \"\"\" Tkinter named font",
"to be considered for styling; any other options encountered are considered \"functional\" and",
"\"selectcolor\"] class Entry(StyleableMixin, tk.Entry): \"\"\"Styleable version of ``tkinter.Entry``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\",",
"global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE = tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\",",
"= \"#BBBBBB\" GRAY_SCALE_C = \"#CCCCCC\" GRAY_SCALE_D = \"#DDDDDD\" GRAY_SCALE_E = \"#EEEEEE\" GRAY_SCALE_F =",
"**overrides): \"\"\" Apply the given style with the given overrides. :param style: The",
"\"\"\" Apply the given style with the given overrides. :param style: The style",
"of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\",",
"the styleable is not already registered. self._styled.remove(styleable) def _register_child(self, style): \"\"\" Called by",
"this ``Style``'s styles. :param kwargs: The styles to add/edit. \"\"\" self._dict.update(kwargs) self._signal_style_changed() config",
"_tkLabelFrame = tk.LabelFrame _tkListbox = tk.Listbox _tkMenu = tk.Menu _tkPanedWindow = tk.PanedWindow _tkRadiobutton",
"tk.Menu _tkPanedWindow = tk.PanedWindow _tkRadiobutton = tk.Radiobutton _tkScale = tk.Scale _tkScrollbar = tk.Scrollbar",
"the styled ones. functional, styled = {}, {} for k, v in overrides.items():",
"features include: - a hierarchical styling system for the non-ttk widgets; - a",
"the tkinter widget constructors. :type cnf: dict :param args: Additional args for the",
"\"activebackground\", \"activerelief\", \"bd\", \"elementborderwidth\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable",
"by the given tkinter widget. \"\"\" return {k: v for k, v in",
"= [\"bg\", \"activebackground\", \"activerelief\", \"bd\", \"elementborderwidth\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Spinbox(StyleableMixin,",
"cooperation with the ``Style`` class. Styleable widgets should never use their ``widget.configure`` method",
"tk.Scale _tkScrollbar = tk.Scrollbar _tkSpinbox = tk.Spinbox _tkText = tk.Text _tkToplevel = tk.Toplevel",
"the previous style. Does nothing if ``style`` is given. :type keep_style: bool :param",
"objects to stop receiving updates on whenever this style changes. This should not",
":param styleable: The styleable widget to unregister. :type styleable: StyleableMixin \"\"\" # This",
"runtime through ``StyleableMixin.set_defaults``, but any changes made won't be taken into effect on",
"\"\"\" DEFAULTS = {} \"\"\"Global default styles for all ``Style`` objects. This should",
"widget to find styles for. :return: All the styles recognized by the given",
"cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults def patch_tk_widgets(): \"\"\"Monkey patch the tkinter widgets with",
"is revoked. This dictionary is lazily built for each unique styled class (i.e.",
"class Text(StyleableMixin, tk.Text): \"\"\"Styleable version of ``tkinter.Text``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\",",
"style name, first checking this ``Style`` and its parents, then resorting to the",
"BOLD ``init_fonts`` must be called to initialize this font. \"\"\" FONT_MONOSPACE_NORMAL = None",
"# Alias TK_DEFAULT_STYLES for conciseness. tk_defaults = self.__class__.TK_DEFAULT_STYLES # Start off the styles_dict",
"a ``KeyError`` if any of the given style names are not in this",
"be found in said ``Style``'s own styles, the style is looked for in",
"- size: 8 - family: \"Courier\" ``init_fonts`` must be called to initialize this",
"\"highlightthickness\", \"relief\"] class Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable version of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"is None, setting this will keep the previous style. Does nothing if ``style``",
"should define this. \"\"\" TK_DEFAULT_STYLES = None \"\"\" A dictionary of default (platform-specific)",
"STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"insertbackground\", \"insertborderwidth\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"selectbackground\",",
"in which a ``Style`` can have one or more parents to inherit styles",
"keep_existing: bool :param defaults: A dictionary of styles. \"\"\" if keep_existing: cls.DEFAULTS.update(defaults) else:",
"# will update the dict with increasing style priority so that lower priority",
"10 - family: \"Helvetica\" - weight: BOLD ``init_fonts`` must be called to initialize",
"= tk.Scrollbar _tkSpinbox = tk.Spinbox _tkText = tk.Text _tkToplevel = tk.Toplevel _global_style =",
"through ``Style.set_defaults``.\"\"\" def __init__(self, *parents, **styles): \"\"\" :param parents: ``Style``s to inherit styles",
"\"\"\" Called by child ``Style``s to receive updates on whenever this style changes.",
"in styles_dict if k not in tk_defaults) self.configure(styles_dict) @classmethod def _assure_default_dicts_exist(cls): \"\"\" Make",
"in tk_defaults) self.configure(styles_dict) @classmethod def _assure_default_dicts_exist(cls): \"\"\" Make sure that this class's ``StyleableMixin.TK_DEFAULT_STYLES``",
"specifying all the widget options (i.e. the ones that would normally be passed",
"remove_styles(self, *styles): \"\"\" Remove the given styles from this ``Style``. This will raise",
"10 - family: \"Times\" - weight: BOLD ``init_fonts`` must be called to initialize",
"a ``Style`` object already. :param style: The style to apply. :type style: Style",
"whenever a ``Style`` is updated, any registered ``StyleableMixin``s are automatically updated to reflect",
"\"#BBBBBB\" GRAY_SCALE_C = \"#CCCCCC\" GRAY_SCALE_D = \"#DDDDDD\" GRAY_SCALE_E = \"#EEEEEE\" GRAY_SCALE_F = \"#FFFFFF\"",
"style=None, *, keep_style=False, keep_overrides=False, **overrides): \"\"\" Apply the given style with the given",
"configure \"\"\"Alias for ``Style.configure``.\"\"\" def remove_styles(self, *styles): \"\"\" Remove the given styles from",
"_tkCanvas = tk.Canvas _tkCheckbutton = tk.Checkbutton _tkEntry = tk.Entry _tkFrame = tk.Frame _tkLabel",
"if they were initialized to an empty dict in ``StyleableMixin`` then all classes",
"= _tkLabelFrame tk.Listbox = _tkListbox tk.Menu = _tkMenu tk.PanedWindow = _tkPanedWindow tk.Radiobutton =",
"updated, all child ``Style``s of the changed ``Style`` are recursively informed of the",
"named font with these properties: - size: 10 - family: \"Courier\" - weight:",
"class (i.e. a style is added to this dictionary the first time it",
"use. \"\"\" super().__init__(master, cnf, *args) self._style = None \"\"\"The widget's current ``Style``.\"\"\" self._overrides",
"``Style`` and cannot be found in said ``Style``'s own styles, the style is",
"perfect fine.) There are four sources of style options and they work on",
"class Menu(StyleableMixin, tk.Menu): \"\"\"Styleable version of ``tkinter.Menu``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\",",
"cls._assure_default_dicts_exist() if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults # TODO: Styleable Tk (root)?",
"\"highlightthickness\", \"relief\", \"justify\"] class LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable version of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS = [\"font\",",
"**defaults): \"\"\" Convenience method to update the default styles for this class. :param",
"will raise a ``KeyError`` if any of the given style names are not",
"to the global default styles (``Style.DEFAULTS``). :param key: The style name. :type key:",
"object already. :param style: The style to apply. :type style: Style :param overrides:",
"overrides.items(): if k in self.STYLED_OPTS: styled[k] = v else: functional[k] = v #",
"= \"#333355\" MUTE_GREEN = \"#335533\" MUTE_RED = \"#663333\" MUTE_YELLOW = \"#888833\" MUTE_TURQUOISE =",
"``tkinter.Listbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activestyle\", \"fg\", \"disabledforeground\", \"bd\", \"relief\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"to stop receiving updates on whenever this style changes. This should not be",
"(root)? class Button(StyleableMixin, tk.Button): \"\"\"Styleable version of ``tkinter.Button``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\",",
"style: Style :param overrides: Style overrides to use. \"\"\" super().__init__(master, cnf, *args) self._style",
"1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES`` 3. A given ``Style`` instance 4. A given dictionary",
"priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES`` 3. A given ``Style`` instance 4. A given",
"change. \"\"\" DEFAULTS = {} \"\"\"Global default styles for all ``Style`` objects. This",
"options self.configure(functional) if keep_overrides: self._overrides.update(styled) else: self._overrides = styled if style: if self._style:",
"\"relief\"] class Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable version of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS = [\"bg\", \"activebackground\", \"activerelief\",",
"- family: \"Helvetica\" - weight: BOLD ``init_fonts`` must be called to initialize this",
"version of ``tkinter.Menu``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"selectcolor\",",
"Called by child ``Style``s to receive updates on whenever this style changes. :param",
"\"\"\"Styleable version of ``tkinter.Entry``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\",",
"class Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable version of ``tkinter.Listbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activestyle\", \"fg\",",
"\"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Entry(StyleableMixin, tk.Entry): \"\"\"Styleable version of ``tkinter.Entry``.\"\"\" STYLED_OPTS =",
"The style to employ, or None to clear the current style (if ``keep_style``",
"the given tkinter widget. :param widget: The tkinter widget to find styles for.",
"``Style``.\"\"\" self._overrides = None \"\"\"A dictionary of the widget's currently-overridden styles.\"\"\" self._assure_default_dicts_exist() #",
"\"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Frame(StyleableMixin, tk.Frame): \"\"\"Styleable version of ``tkinter.Frame``.\"\"\" STYLED_OPTS",
"\"\"\"Styleable version of ``tkinter.Scale``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"bd\", \"showvalue\", \"sliderrelief\",",
"StyleableMixin: \"\"\" Mixin class used to make a widget \"styleable\". This class works",
"{} \"\"\"Global default styles for all ``Style`` objects. This should be set through",
"DEFAULT_STYLES = None \"\"\" A dictionary of default user-defined styles for a given",
"at runtime through ``StyleableMixin.set_defaults``, but any changes made won't be taken into effect",
"defaults # TODO: Styleable Tk (root)? class Button(StyleableMixin, tk.Button): \"\"\"Styleable version of ``tkinter.Button``.\"\"\"",
"GRAY_SCALE_D = \"#DDDDDD\" GRAY_SCALE_E = \"#EEEEEE\" GRAY_SCALE_F = \"#FFFFFF\" MUTE_BLUE = \"#333355\" MUTE_GREEN",
"with these properties: - size: 10 - family: \"Helvetica\" - weight: BOLD ``init_fonts``",
"**overrides) def apply_style(self, style=None, *, keep_style=False, keep_overrides=False, **overrides): \"\"\" Apply the given style",
"tk.Scale): \"\"\"Styleable version of ``tkinter.Scale``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"bd\", \"showvalue\",",
"\"\"\" A dictionary of default (platform-specific) styles to revert to if an initially",
"to revert to if an initially explicitly given style option is revoked. This",
"are signaled of any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" self._parents =",
"patch(): \"\"\"Context manager to temporarily monkey patch the tkinter widgets with their styleable",
"_tkScrollbar tk.Spinbox = _tkSpinbox tk.Text = _tkText tk.Toplevel = _tkToplevel @contextmanager def patch():",
"@contextmanager def stylize(style, **overrides): \"\"\" Context manager to temporarily apply a global-level style",
"v # Directly apply the functional options self.configure(functional) if keep_overrides: self._overrides.update(styled) else: self._overrides",
"after monkey patching them with ``patch_tk_widgets``.\"\"\" tk.Button = _tkButton tk.Canvas = _tkCanvas tk.Checkbutton",
"by ``StyleableMixin``s if they're not explicitly given a ``Style`` object already. :param style:",
"must be called prior to attempting to use any of the named fonts.",
"\"\"\" Convenience method to update the default styles for this class. :param keep_existing:",
"corresponding to the given style name, first checking this ``Style`` and its parents,",
"widgets with their styleable equivalents.\"\"\" try: patch_tk_widgets() yield finally: unpatch_tk_widgets() @contextmanager def stylize(style,",
"[\"bg\", \"bd\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable",
"Tkinter named font with these properties: - size: 8 - family: \"Courier\" ``init_fonts``",
"Menu(StyleableMixin, tk.Menu): \"\"\"Styleable version of ``tkinter.Menu``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\",",
"that whenever a ``Style`` is updated, any registered ``StyleableMixin``s are automatically updated to",
"tk.Button = _tkButton tk.Canvas = _tkCanvas tk.Checkbutton = _tkCheckbutton tk.Entry = _tkEntry tk.Frame",
"reasonable cross-platform named fonts. \"\"\" import tkinter as tk import tkinter.font as tkfont",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable version of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS =",
"properties: - size: 8 - family: \"Times\" ``init_fonts`` must be called to initialize",
"functional[k] = v # Directly apply the functional options self.configure(functional) if keep_overrides: self._overrides.update(styled)",
"be set through ``Style.set_defaults``.\"\"\" def __init__(self, *parents, **styles): \"\"\" :param parents: ``Style``s to",
"``StyleableMixin.update_style`` is called. \"\"\" def __init__(self, master=None, cnf={}, *args, style=None, **overrides): \"\"\" :param",
"\"\"\" super().__init__(master, cnf, *args) self._style = None \"\"\"The widget's current ``Style``.\"\"\" self._overrides =",
"set styles in their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should be used instead. (Although configuring \"functional\"",
"actually configure the widget, save any of the styles set to this widget",
"= Radiobutton tk.Scale = Scale tk.Scrollbar = Scrollbar tk.Spinbox = Spinbox tk.Text =",
"patch_tk_widgets(): \"\"\"Monkey patch the tkinter widgets with their styleable equivalents.\"\"\" tk.Button = Button",
"the styles_dict with a copy of the tk_defaults, since those styles are of",
"ones specified in the constructor. When a ``Style`` is updated, all child ``Style``s",
"added to this dictionary the first time it changes from its default). \"\"\"",
"Radiobutton tk.Scale = Scale tk.Scrollbar = Scrollbar tk.Spinbox = Spinbox tk.Text = Text",
"We # will update the dict with increasing style priority so that lower",
"changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" self._parents = parents \"\"\"A list of",
"UNKNOWN_TEAM = GRAY_SCALE_B BOOL_TRUE = MUTE_GREEN BOOL_FALSE = MUTE_RED # Named fonts: FONT_MONOSPACE_TITLE",
"def __init__(self, master=None, cnf={}, *args, style=None, **overrides): \"\"\" :param master: The master tkinter",
"the ``StyleableMixin`` widgets registered to this ``Style`` and its children. \"\"\" for s",
"tk.PanedWindow = _tkPanedWindow tk.Radiobutton = _tkRadiobutton tk.Scale = _tkScale tk.Scrollbar = _tkScrollbar tk.Spinbox",
"named font with these properties: - size: 8 - family: \"Courier\" ``init_fonts`` must",
"tkinter widget. :param widget: The tkinter widget to find styles for. :return: All",
"the tkinter widgets back to their defaults after monkey patching them with ``patch_tk_widgets``.\"\"\"",
"system (higher number means higher priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES`` 3. A given",
"objects to receive updates on whenever this style changes. This should not be",
"default styles for all ``Style`` objects. This should be set through ``Style.set_defaults``.\"\"\" def",
"_global_style = None def init_fonts(root): \"\"\" Initialize all the named fonts. This must",
"``Style`` recognized by the given tkinter widget. :param widget: The tkinter widget to",
"of ``tkinter.Frame``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Label(StyleableMixin, tk.Label):",
"its own version of these; if they were initialized to an empty dict",
"size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL = tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE = tkfont.Font(root,",
"in ``StyleableMixin`` then all classes would share the same dictionaries). \"\"\" if cls.TK_DEFAULT_STYLES",
"**defaults): \"\"\" Convenience method to update the global default styles (``Style.DEFAULTS``). :param keep_existing:",
"global _global_style try: _global_style = Style(style, **overrides) if overrides else style yield finally:",
"this widget's parents. :param key: The style name. :type key: str :return: The",
"explicitly given a ``Style`` object already. :param style: The style to apply. :type",
"\"\"\" Tkinter named font with these properties: - size: 10 - family: \"Helvetica\"",
"\"\"\"The widget's current ``Style``.\"\"\" self._overrides = None \"\"\"A dictionary of the widget's currently-overridden",
"in said ``Style``'s own styles, the style is looked for in its ancestors,",
"\"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"]",
"non-ttk widgets; - a collection of colour constants; - and reasonable cross-platform named",
"styles. (Priority 4) styles_dict.update(self._overrides) # Before we actually configure the widget, save any",
"to use. \"\"\" global _global_style try: _global_style = Style(style, **overrides) if overrides else",
"None to clear the current style (if ``keep_style`` is False). :type style: Style",
"to mimic the tkinter widget constructors. :type cnf: dict :param args: Additional args",
"\"highlightthickness\", \"relief\", \"overrelief\", \"justify\"] class Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable version of ``tkinter.Canvas``.\"\"\" STYLED_OPTS =",
"style name or None if it could not be found. \"\"\" ret =",
"font. \"\"\" # Backup copies of \"normal\" tkinter widgets: _tkButton = tk.Button _tkCanvas",
"tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL =",
"from. When a style is requested from a ``Style`` and cannot be found",
"if it could not be found. \"\"\" return self._get_style(key) or self.__class__.DEFAULTS.get(key) def _get_style(self,",
"given dictionary of overrides \"\"\" STYLED_OPTS = [] \"\"\" A list of strings",
":param style: An initial style to employ. :type style: Style :param overrides: Style",
"a ``Style`` and cannot be found in said ``Style``'s own styles, the style",
"The tkinter widget to find styles for. :return: All the styles recognized by",
"8 - family: \"Times\" ``init_fonts`` must be called to initialize this font. \"\"\"",
"any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" self._parents = parents \"\"\"A list",
"Does nothing if ``style`` is given. :type keep_style: bool :param keep_overrides: Whether to",
"STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Style: \"\"\" A dictionary",
"MUTE_RED = \"#663333\" MUTE_YELLOW = \"#888833\" MUTE_TURQUOISE = \"#335555\" MUTE_PURPLE = \"#553377\" MUTE_PINK",
"Entry tk.Frame = Frame tk.Label = Label tk.LabelFrame = LabelFrame tk.Listbox = Listbox",
"strings specifying all the widget options (i.e. the ones that would normally be",
"\"\"\" :param master: The master tkinter widget. :param cnf: A dictionary of configuration",
"styleable: The styleable widget to unregister. :type styleable: StyleableMixin \"\"\" # This will",
"- weight: BOLD ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SERIF_NORMAL",
"this style changes. This should not be called by user code. :param styleable:",
"tk.Scrollbar = _tkScrollbar tk.Spinbox = _tkSpinbox tk.Text = _tkText tk.Toplevel = _tkToplevel @contextmanager",
"= tk.Menu _tkPanedWindow = tk.PanedWindow _tkRadiobutton = tk.Radiobutton _tkScale = tk.Scale _tkScrollbar =",
"= tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL = tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE",
"# Keep the same naming scheme as tkinter. def configure(self, **kwargs): \"\"\" Configure",
"keep_style: self._style.unregister_styleable(self) self._style = None self.update_style() def update_style(self): \"\"\"Update this widget's styles.\"\"\" #",
"must be called to initialize this font. \"\"\" # Backup copies of \"normal\"",
"in this ``Style`` recognized by the given tkinter widget. :param widget: The tkinter",
"global-level style and some overrides. This global-level style will only be used by",
"GRAY_SCALE_E = \"#EEEEEE\" GRAY_SCALE_F = \"#FFFFFF\" MUTE_BLUE = \"#333355\" MUTE_GREEN = \"#335533\" MUTE_RED",
"Button tk.Canvas = Canvas tk.Checkbutton = Checkbutton tk.Entry = Entry tk.Frame = Frame",
"constants: GRAY_SCALE_0 = \"#000000\" GRAY_SCALE_1 = \"#111111\" GRAY_SCALE_2 = \"#222222\" GRAY_SCALE_3 = \"#333333\"",
"colour constants; - and reasonable cross-platform named fonts. \"\"\" import tkinter as tk",
"STYLED_OPTS = [\"bg\", \"activebackground\", \"activerelief\", \"bd\", \"elementborderwidth\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class",
"= tk.Label _tkLabelFrame = tk.LabelFrame _tkListbox = tk.Listbox _tkMenu = tk.Menu _tkPanedWindow =",
"= None \"\"\" A dictionary of default (platform-specific) styles to revert to if",
"name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE = tkfont.Font(root, size=10,",
"the tkinter widgets with their styleable equivalents.\"\"\" tk.Button = Button tk.Canvas = Canvas",
"tk.Toplevel = _tkToplevel @contextmanager def patch(): \"\"\"Context manager to temporarily monkey patch the",
"initialize this font. \"\"\" # Backup copies of \"normal\" tkinter widgets: _tkButton =",
"any of the given style names are not in this ``Style``. :param styles:",
"_tkScrollbar = tk.Scrollbar _tkSpinbox = tk.Spinbox _tkText = tk.Text _tkToplevel = tk.Toplevel _global_style",
"None \"\"\"A dictionary of the widget's currently-overridden styles.\"\"\" self._assure_default_dicts_exist() # Initialize the widget's",
"\"\"\"Styleable version of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"relief\", \"sashrelief\", \"showhandle\"] class Radiobutton(StyleableMixin,",
"will raise an error if the styleable is not already registered. self._styled.remove(styleable) def",
"in ``Style._signal_style_changed``. \"\"\" for parent in parents: parent._register_child(self) def register_styleable(self, styleable): \"\"\" Called",
"styles, or replace them. :type keep_existing: bool :param defaults: A dictionary of styles.",
"from this ``Style``'s ``Style._dict``. If that fails, recursively search this widget's parents. :param",
"fonts. This must be called prior to attempting to use any of the",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Scale(StyleableMixin, tk.Scale): \"\"\"Styleable",
"font. \"\"\" FONT_SANS_SERIF_NORMAL = None \"\"\" Tkinter named font with these properties: -",
"Mixin class used to make a widget \"styleable\". This class works in cooperation",
"changes made won't be taken into effect on instances of that class until",
"Attempt to retrieve the given style from this ``Style``'s ``Style._dict``. If that fails,",
"master: The master tkinter widget. :param cnf: A dictionary of configuration options. This",
"Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable version of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\",",
"\"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable version of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS",
"MUTE_PURPLE = \"#553377\" MUTE_PINK = \"#663366\" MUTE_ORANGE = \"#774433\" RED_TEAM = \"#992222\" BLUE_TEAM",
"given style name or None if it could not be found. \"\"\" ret",
"A list of strings specifying all the widget options (i.e. the ones that",
"``StyleableMixin`` objects to receive updates on whenever this style changes. This should not",
"\"\"\" A list of registered child ``Style``s. These are signaled of any changes",
"tk.Entry): \"\"\"Styleable version of ``tkinter.Entry``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\",",
"recognized by the given tkinter widget. :param widget: The tkinter widget to find",
"class Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable version of ``tkinter.Canvas``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"selectbackground\", \"selectborderwidth\",",
"\"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Entry(StyleableMixin,",
"= v # Directly apply the functional options self.configure(functional) if keep_overrides: self._overrides.update(styled) else:",
"``overrides`` to the already existing overridden styles, or replace them. :type keep_overrides: bool",
"tk_defaults) self.configure(styles_dict) @classmethod def _assure_default_dicts_exist(cls): \"\"\" Make sure that this class's ``StyleableMixin.TK_DEFAULT_STYLES`` and",
"This will raise a ``KeyError`` if any of the given style names are",
"def get_style(self, key): \"\"\" Return the style corresponding to the given style name,",
"tk.Button _tkCanvas = tk.Canvas _tkCheckbutton = tk.Checkbutton _tkEntry = tk.Entry _tkFrame = tk.Frame",
"apply_style(self, style=None, *, keep_style=False, keep_overrides=False, **overrides): \"\"\" Apply the given style with the",
"found. \"\"\" ret = self._dict.get(key) if ret is None: for p in self._parents:",
"are of lowest priority (1). We # will update the dict with increasing",
"employ. :type style: Style :param overrides: Style overrides to use. \"\"\" super().__init__(master, cnf,",
"= tk.Entry _tkFrame = tk.Frame _tkLabel = tk.Label _tkLabelFrame = tk.LabelFrame _tkListbox =",
"cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults # TODO: Styleable Tk (root)? class Button(StyleableMixin, tk.Button):",
"keep_overrides: bool :param overrides: Style overrides to use. \"\"\" # Sort out the",
"_global_style, **overrides) def apply_style(self, style=None, *, keep_style=False, keep_overrides=False, **overrides): \"\"\" Apply the given",
"_tkFrame = tk.Frame _tkLabel = tk.Label _tkLabelFrame = tk.LabelFrame _tkListbox = tk.Listbox _tkMenu",
"find styles for. :return: All the styles recognized by the given tkinter widget.",
"recursively search this widget's parents. :param key: The style name. :type key: str",
"with the given overrides. :param style: The style to employ, or None to",
"A given ``Style`` instance 4. A given dictionary of overrides \"\"\" STYLED_OPTS =",
"or replace them. :type keep_existing: bool :param defaults: A dictionary of default styles.",
"[\"bg\", \"bd\", \"relief\", \"sashrelief\", \"showhandle\"] class Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable version of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS",
"(platform-specific) styles to revert to if an initially explicitly given style option is",
"keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults def patch_tk_widgets(): \"\"\"Monkey patch the tkinter widgets",
"tkinter root widget. :type root: tkinter.Tk \"\"\" global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE,",
"widget styles. ``StyleableMixin``s register themselves to ``Style``s so that whenever a ``Style`` is",
"\"insertbackground\", \"insertborderwidth\"] class Text(StyleableMixin, tk.Text): \"\"\"Styleable version of ``tkinter.Text``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"if any of the given style names are not in this ``Style``. :param",
"given tkinter widget. :param widget: The tkinter widget to find styles for. :return:",
"keep_existing: bool :param defaults: A dictionary of default styles. \"\"\" cls._assure_default_dicts_exist() if keep_existing:",
"updated to reflect the changes. ``Style``s employ a parent-child system in which a",
"checking this ``Style`` and its parents, then resorting to the global default styles",
"= _tkRadiobutton tk.Scale = _tkScale tk.Scrollbar = _tkScrollbar tk.Spinbox = _tkSpinbox tk.Text =",
"and they work on a priority system (higher number means higher priority): 1.",
"and reasonable cross-platform named fonts. \"\"\" import tkinter as tk import tkinter.font as",
"keep_style: If ``style`` is None, setting this will keep the previous style. Does",
"it changes from its default). \"\"\" DEFAULT_STYLES = None \"\"\" A dictionary of",
"(Priority 3) styles_dict.update(self._style.get_relevant_styles(self)) # Update the dict with the overridden styles. (Priority 4)",
"\"relief\", \"labelanchor\"] class Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable version of ``tkinter.Listbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"with ``patch_tk_widgets``.\"\"\" tk.Button = _tkButton tk.Canvas = _tkCanvas tk.Checkbutton = _tkCheckbutton tk.Entry =",
"called to initialize this font. \"\"\" # Backup copies of \"normal\" tkinter widgets:",
"bool :param keep_overrides: Whether to append the given ``overrides`` to the already existing",
"\"\"\" def __init__(self, master=None, cnf={}, *args, style=None, **overrides): \"\"\" :param master: The master",
"try: patch_tk_widgets() yield finally: unpatch_tk_widgets() @contextmanager def stylize(style, **overrides): \"\"\" Context manager to",
"DEFAULTS = {} \"\"\"Global default styles for all ``Style`` objects. This should be",
"= \"#555555\" GRAY_SCALE_6 = \"#666666\" GRAY_SCALE_7 = \"#777777\" GRAY_SCALE_8 = \"#888888\" GRAY_SCALE_9 =",
"styles. \"\"\" if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults def patch_tk_widgets(): \"\"\"Monkey patch",
"named font with these properties: - size: 8 - family: \"Times\" ``init_fonts`` must",
"number means higher priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES`` 3. A given ``Style`` instance",
"\"activeforeground\", \"disabledforeground\", \"bd\", \"selectcolor\", \"relief\", \"activeborderwidth\"] class PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable version of ``tkinter.PanedWindow``.\"\"\"",
"an error if the styleable is not already registered. self._styled.remove(styleable) def _register_child(self, style):",
"tk.Frame = _tkFrame tk.Label = _tkLabel tk.LabelFrame = _tkLabelFrame tk.Listbox = _tkListbox tk.Menu",
"\"offrelief\", \"selectcolor\"] class Scale(StyleableMixin, tk.Scale): \"\"\"Styleable version of ``tkinter.Scale``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"may define this. One may also set this at runtime through ``StyleableMixin.set_defaults``, but",
"keep_style=False, keep_overrides=False, **overrides): \"\"\" Apply the given style with the given overrides. :param",
"@classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update the default styles",
"- size: 10 - family: \"Helvetica\" - weight: BOLD ``init_fonts`` must be called",
"\"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Scale(StyleableMixin, tk.Scale): \"\"\"Styleable version of ``tkinter.Scale``.\"\"\" STYLED_OPTS",
"= tk.Button _tkCanvas = tk.Canvas _tkCheckbutton = tk.Checkbutton _tkEntry = tk.Entry _tkFrame =",
"styleable widget to register. :type styleable: StyleableMixin \"\"\" self._styled.append(styleable) def unregister_styleable(self, styleable): \"\"\"",
"keep_existing: Whether to keep the already existing default styles, or replace them. :type",
"a style is requested from a ``Style`` and cannot be found in said",
"not in tk_defaults) self.configure(styles_dict) @classmethod def _assure_default_dicts_exist(cls): \"\"\" Make sure that this class's",
"= tk.Scale _tkScrollbar = tk.Scrollbar _tkSpinbox = tk.Spinbox _tkText = tk.Text _tkToplevel =",
"_tkSpinbox = tk.Spinbox _tkText = tk.Text _tkToplevel = tk.Toplevel _global_style = None \"\"\"A",
"tk.Spinbox): \"\"\"Styleable version of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\",",
"\"#335533\" MUTE_RED = \"#663333\" MUTE_YELLOW = \"#888833\" MUTE_TURQUOISE = \"#335555\" MUTE_PURPLE = \"#553377\"",
"\"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\"] class LabelFrame(StyleableMixin, tk.LabelFrame):",
"style, which may be set by the stylize context # manger. self.apply_style(style or",
"None \"\"\" Tkinter named font with these properties: - size: 10 - family:",
"4) styles_dict.update(self._overrides) # Before we actually configure the widget, save any of the",
"widgets registered to this ``Style`` and its children. \"\"\" for s in self._styled:",
"\"\"\"Styleable version of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\",",
"= [] \"\"\" A list of registered child ``Style``s. These are signaled of",
"widget by default so we may return # to them if an explicit",
"unpatch_tk_widgets() @contextmanager def stylize(style, **overrides): \"\"\" Context manager to temporarily apply a global-level",
"family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SANS_SERIF_TITLE\",",
"The child ``Style``. :type style: Style \"\"\" self._children.append(style) # Keep the same naming",
"called by user code. :param styleable: The styleable widget to register. :type styleable:",
"raise a ``KeyError`` if any of the given style names are not in",
"_tkCheckbutton = tk.Checkbutton _tkEntry = tk.Entry _tkFrame = tk.Frame _tkLabel = tk.Label _tkLabelFrame",
"options encountered are considered \"functional\" and hence won't be regulated in any way",
"``Style``'s styles. :param kwargs: The styles to add/edit. \"\"\" self._dict.update(kwargs) self._signal_style_changed() config =",
"ret = p._get_style(key) if ret is not None: break return ret @classmethod def",
"self._dict.update(kwargs) self._signal_style_changed() config = configure \"\"\"Alias for ``Style.configure``.\"\"\" def remove_styles(self, *styles): \"\"\" Remove",
"None \"\"\"A global ``Style`` object used by the ``stylize`` context manager.\"\"\" class StyleableMixin:",
"configuration options. This is here to mimic the tkinter widget constructors. :type cnf:",
"root widget. :type root: tkinter.Tk \"\"\" global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL",
"None \"\"\" Tkinter named font with these properties: - size: 8 - family:",
"styles through ``widget.configure`` is perfect fine.) There are four sources of style options",
"*args) self._style = None \"\"\"The widget's current ``Style``.\"\"\" self._overrides = None \"\"\"A dictionary",
"to this ``Style`` and its children. \"\"\" for s in self._styled: s.update_style() for",
"the global default styles (``Style.DEFAULTS``). :param key: The style name. :type key: str",
":type root: tkinter.Tk \"\"\" global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE =",
"style changes. :param style: The child ``Style``. :type style: Style \"\"\" self._children.append(style) #",
"self.update_style() def update_style(self): \"\"\"Update this widget's styles.\"\"\" # Alias TK_DEFAULT_STYLES for conciseness. tk_defaults",
"this font. \"\"\" FONT_SERIF_TITLE = None \"\"\" Tkinter named font with these properties:",
"= Toplevel def unpatch_tk_widgets(): \"\"\"Revert the tkinter widgets back to their defaults after",
"tk_defaults, since those styles are of lowest priority (1). We # will update",
"= None \"\"\" Tkinter named font with these properties: - size: 8 -",
"class Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable version of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS = [\"bg\", \"activebackground\", \"activerelief\", \"bd\",",
"\"fg\", \"disabledforeground\", \"bd\", \"relief\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Menu(StyleableMixin, tk.Menu):",
"k: (k, self.get_style(k)), widget.keys()) if v is not None} def get_style(self, key): \"\"\"",
"child ``Style``s of the changed ``Style`` are recursively informed of the change. \"\"\"",
"with these properties: - size: 10 - family: \"Times\" - weight: BOLD ``init_fonts``",
"This class works in cooperation with the ``Style`` class. Styleable widgets should never",
"to inherit styles from. :param styles: Styles to use. \"\"\" self._dict = styles",
"FONT_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SANS_SERIF_TITLE\", family=\"Helvetica\", weight=tkfont.BOLD)",
"regulated in any way by this class. Subclasses should define this. \"\"\" TK_DEFAULT_STYLES",
"break return ret @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update",
"the given style name, first checking this ``Style`` and its parents, then resorting",
"= \"#666666\" GRAY_SCALE_7 = \"#777777\" GRAY_SCALE_8 = \"#888888\" GRAY_SCALE_9 = \"#999999\" GRAY_SCALE_A =",
"these properties: - size: 10 - family: \"Times\" - weight: BOLD ``init_fonts`` must",
"of the styles specific to this ``Style``.\"\"\" self._styled = [] \"\"\" A list",
"A given dictionary of overrides \"\"\" STYLED_OPTS = [] \"\"\" A list of",
"version of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\",",
"called to initialize this font. \"\"\" FONT_SANS_SERIF_TITLE = None \"\"\" Tkinter named font",
"(Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style: # Update the dict with the styles from",
"def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update the global default styles",
"style to apply. :type style: Style :param overrides: Style overrides to use. \"\"\"",
"@classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update the global default",
"family: \"Courier\" - weight: BOLD ``init_fonts`` must be called to initialize this font.",
"styling system for the non-ttk widgets; - a collection of colour constants; -",
"styles will get overridden. styles_dict = tk_defaults.copy() # Update the dict with the",
"return {k: v for k, v in map(lambda k: (k, self.get_style(k)), widget.keys()) if",
":type styleable: StyleableMixin \"\"\" self._styled.append(styleable) def unregister_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects",
"tk.Listbox _tkMenu = tk.Menu _tkPanedWindow = tk.PanedWindow _tkRadiobutton = tk.Radiobutton _tkScale = tk.Scale",
"widget. :param widget: The tkinter widget to find styles for. :return: All the",
"StyleableMixin \"\"\" self._styled.append(styleable) def unregister_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to stop",
"default styles, or replace them. :type keep_existing: bool :param defaults: A dictionary of",
"# This will raise an error if the styleable is not already registered.",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable version of",
"= None self.update_style() def update_style(self): \"\"\"Update this widget's styles.\"\"\" # Alias TK_DEFAULT_STYLES for",
"may also set this at runtime through ``StyleableMixin.set_defaults``, but any changes made won't",
"effect on instances of that class until ``StyleableMixin.update_style`` is called. \"\"\" def __init__(self,",
"\"#FFFFFF\" MUTE_BLUE = \"#333355\" MUTE_GREEN = \"#335533\" MUTE_RED = \"#663333\" MUTE_YELLOW = \"#888833\"",
"add/edit. \"\"\" self._dict.update(kwargs) self._signal_style_changed() config = configure \"\"\"Alias for ``Style.configure``.\"\"\" def remove_styles(self, *styles):",
"tk.Radiobutton _tkScale = tk.Scale _tkScrollbar = tk.Scrollbar _tkSpinbox = tk.Spinbox _tkText = tk.Text",
"This will raise an error if the styleable is not already registered. self._styled.remove(styleable)",
"super().__init__(master, cnf, *args) self._style = None \"\"\"The widget's current ``Style``.\"\"\" self._overrides = None",
"are not in this ``Style``. :param styles: Style names to remove. \"\"\" for",
"return ret @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update the",
"this font. \"\"\" FONT_SERIF_NORMAL = None \"\"\" Tkinter named font with these properties:",
"scheme as tkinter. def configure(self, **kwargs): \"\"\" Configure this ``Style``'s styles. :param kwargs:",
"to an empty dict in ``StyleableMixin`` then all classes would share the same",
"= styled if style: if self._style: self._style.unregister_styleable(self) self._style = style style.register_styleable(self) elif self._style",
"the changed ``Style`` are recursively informed of the change. \"\"\" DEFAULTS = {}",
"\"\"\" TK_DEFAULT_STYLES = None \"\"\" A dictionary of default (platform-specific) styles to revert",
"is looked for in its ancestors, prioritizing the first ones specified in the",
"def remove_styles(self, *styles): \"\"\" Remove the given styles from this ``Style``. This will",
"if v is not None} def get_style(self, key): \"\"\" Return the style corresponding",
"its parents, then resorting to the global default styles (``Style.DEFAULTS``). :param key: The",
"- weight: BOLD ``init_fonts`` must be called to initialize this font. \"\"\" FONT_MONOSPACE_NORMAL",
"``Style``s. These are signaled of any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\"",
"tk.Frame = Frame tk.Label = Label tk.LabelFrame = LabelFrame tk.Listbox = Listbox tk.Menu",
"tk.PanedWindow = PanedWindow tk.Radiobutton = Radiobutton tk.Scale = Scale tk.Scrollbar = Scrollbar tk.Spinbox",
"__init__(self, master=None, cnf={}, *args, style=None, **overrides): \"\"\" :param master: The master tkinter widget.",
"through ``widget.configure`` is perfect fine.) There are four sources of style options and",
"are recursively informed of the change. \"\"\" DEFAULTS = {} \"\"\"Global default styles",
"its default). \"\"\" DEFAULT_STYLES = None \"\"\" A dictionary of default user-defined styles",
"existing overridden styles, or replace them. :type keep_overrides: bool :param overrides: Style overrides",
"*parents, **styles): \"\"\" :param parents: ``Style``s to inherit styles from. :param styles: Styles",
"initialize this font. \"\"\" FONT_SERIF_NORMAL = None \"\"\" Tkinter named font with these",
"\"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\"] class LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable version of",
"``tkinter.PanedWindow``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"relief\", \"sashrelief\", \"showhandle\"] class Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable version",
"first ones specified in the constructor. When a ``Style`` is updated, all child",
":type style: Style \"\"\" self._children.append(style) # Keep the same naming scheme as tkinter.",
"widget constructor. :param style: An initial style to employ. :type style: Style :param",
"update the default styles for this class. :param keep_existing: Whether to keep the",
"[\"bg\", \"activebackground\", \"activerelief\", \"bd\", \"elementborderwidth\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Spinbox(StyleableMixin, tk.Spinbox):",
"defaults after monkey patching them with ``patch_tk_widgets``.\"\"\" tk.Button = _tkButton tk.Canvas = _tkCanvas",
"lazily built for each unique styled class (i.e. a style is added to",
"of ``tkinter.Entry``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\",",
"tk.Frame _tkLabel = tk.Label _tkLabelFrame = tk.LabelFrame _tkListbox = tk.Listbox _tkMenu = tk.Menu",
"TK_DEFAULT_STYLES for conciseness. tk_defaults = self.__class__.TK_DEFAULT_STYLES # Start off the styles_dict with a",
"cls.DEFAULT_STYLES is None: cls.DEFAULT_STYLES = {} @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience",
"dict with the class-specific user-provided defaults. (Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style: # Update",
"try: _global_style = Style(style, **overrides) if overrides else style yield finally: _global_style =",
"for each unique styled class (i.e. a style is added to this dictionary",
"k, v in map(lambda k: (k, self.get_style(k)), widget.keys()) if v is not None}",
"explicitly given style option is revoked. This dictionary is lazily built for each",
"k not in tk_defaults) self.configure(styles_dict) @classmethod def _assure_default_dicts_exist(cls): \"\"\" Make sure that this",
"attempting to use any of the named fonts. :param root: The tkinter root",
"\"\"\" Mixin class used to make a widget \"styleable\". This class works in",
"\"\"\" Convenience method to update the global default styles (``Style.DEFAULTS``). :param keep_existing: Whether",
"``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES`` 3. A given ``Style`` instance 4. A given dictionary of",
"FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE = tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL =",
"dictionary of default (platform-specific) styles to revert to if an initially explicitly given",
"A dictionary proxy for tkinter widget styles. ``StyleableMixin``s register themselves to ``Style``s so",
"family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL = tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\",",
"parent-child system in which a ``Style`` can have one or more parents to",
"global ``Style`` object used by the ``stylize`` context manager.\"\"\" class StyleableMixin: \"\"\" Mixin",
"3. A given ``Style`` instance 4. A given dictionary of overrides \"\"\" STYLED_OPTS",
"self._style: # Update the dict with the styles from the Style object. (Priority",
"method to update the global default styles (``Style.DEFAULTS``). :param keep_existing: Whether to keep",
"MUTE_GREEN = \"#335533\" MUTE_RED = \"#663333\" MUTE_YELLOW = \"#888833\" MUTE_TURQUOISE = \"#335555\" MUTE_PURPLE",
"on a priority system (higher number means higher priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES``",
"not be called by user code. :param styleable: The styleable widget to unregister.",
"\"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"labelanchor\"] class Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable version of ``tkinter.Listbox``.\"\"\"",
"style (if ``keep_style`` is False). :type style: Style :param keep_style: If ``style`` is",
"\"\"\" FONT_SANS_SERIF_NORMAL = None \"\"\" Tkinter named font with these properties: - size:",
"GRAY_SCALE_2 = \"#222222\" GRAY_SCALE_3 = \"#333333\" GRAY_SCALE_4 = \"#444444\" GRAY_SCALE_5 = \"#555555\" GRAY_SCALE_6",
"them with ``patch_tk_widgets``.\"\"\" tk.Button = _tkButton tk.Canvas = _tkCanvas tk.Checkbutton = _tkCheckbutton tk.Entry",
"this ``Style``'s parent ``Style``s.\"\"\" self._children = [] \"\"\" A list of registered child",
"not be found. \"\"\" ret = self._dict.get(key) if ret is None: for p",
"a widget \"styleable\". This class works in cooperation with the ``Style`` class. Styleable",
"made won't be taken into effect on instances of that class until ``StyleableMixin.update_style``",
"parents: ``Style``s to inherit styles from. :param styles: Styles to use. \"\"\" self._dict",
"with these properties: - size: 10 - family: \"Courier\" - weight: BOLD ``init_fonts``",
"tk.Label = Label tk.LabelFrame = LabelFrame tk.Listbox = Listbox tk.Menu = Menu tk.PanedWindow",
"= _tkPanedWindow tk.Radiobutton = _tkRadiobutton tk.Scale = _tkScale tk.Scrollbar = _tkScrollbar tk.Spinbox =",
"FONT_MONOSPACE_NORMAL = tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD)",
"they're not explicitly given a ``Style`` object already. :param style: The style to",
"def patch_tk_widgets(): \"\"\"Monkey patch the tkinter widgets with their styleable equivalents.\"\"\" tk.Button =",
"\"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\",",
"{} @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update the default",
"\"#663366\" MUTE_ORANGE = \"#774433\" RED_TEAM = \"#992222\" BLUE_TEAM = \"#222299\" UNKNOWN_TEAM = GRAY_SCALE_B",
"_tkSpinbox tk.Text = _tkText tk.Toplevel = _tkToplevel @contextmanager def patch(): \"\"\"Context manager to",
"- a collection of colour constants; - and reasonable cross-platform named fonts. \"\"\"",
"= tk.LabelFrame _tkListbox = tk.Listbox _tkMenu = tk.Menu _tkPanedWindow = tk.PanedWindow _tkRadiobutton =",
"font. \"\"\" FONT_MONOSPACE_NORMAL = None \"\"\" Tkinter named font with these properties: -",
":param widget: The tkinter widget to find styles for. :return: All the styles",
"then all classes would share the same dictionaries). \"\"\" if cls.TK_DEFAULT_STYLES is None:",
"\"activeborderwidth\"] class PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable version of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"relief\",",
"None: cls.DEFAULT_STYLES = {} @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to",
"class Entry(StyleableMixin, tk.Entry): \"\"\"Styleable version of ``tkinter.Entry``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\",",
"``tkinter.Menu``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"selectcolor\", \"relief\", \"activeborderwidth\"]",
"``Style``.\"\"\" self._styled = [] \"\"\" A list of registered ``StyleableMixin``s. These are signaled",
"in self._children: child._signal_style_changed() def get_relevant_styles(self, widget): \"\"\" Determine and return all the styles",
"= _tkScale tk.Scrollbar = _tkScrollbar tk.Spinbox = _tkSpinbox tk.Text = _tkText tk.Toplevel =",
"_tkToplevel @contextmanager def patch(): \"\"\"Context manager to temporarily monkey patch the tkinter widgets",
"tk.Scrollbar _tkSpinbox = tk.Spinbox _tkText = tk.Text _tkToplevel = tk.Toplevel _global_style = None",
"and not keep_style: self._style.unregister_styleable(self) self._style = None self.update_style() def update_style(self): \"\"\"Update this widget's",
"\"showhandle\"] class Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable version of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\",",
"root: tkinter.Tk \"\"\" global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE = tkfont.Font(root,",
"styles. \"\"\" cls._assure_default_dicts_exist() if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults # TODO: Styleable",
"tk_defaults.copy() # Update the dict with the class-specific user-provided defaults. (Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES)",
"until ``StyleableMixin.update_style`` is called. \"\"\" def __init__(self, master=None, cnf={}, *args, style=None, **overrides): \"\"\"",
"styles. ``StyleableMixin``s register themselves to ``Style``s so that whenever a ``Style`` is updated,",
"code. :param styleable: The styleable widget to unregister. :type styleable: StyleableMixin \"\"\" #",
"won't be regulated in any way by this class. Subclasses should define this.",
"args for the widget constructor. :param style: An initial style to employ. :type",
"widgets should never use their ``widget.configure`` method to set styles in their ``StyleableMixin.STYLED_OPTS``;",
"styles recognized by the given tkinter widget. \"\"\" return {k: v for k,",
"styles in their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should be used instead. (Although configuring \"functional\" styles",
"key): \"\"\" Return the style corresponding to the given style name, first checking",
"style changes. This should not be called by user code. :param styleable: The",
"options from the styled ones. functional, styled = {}, {} for k, v",
"= tk.Radiobutton _tkScale = tk.Scale _tkScrollbar = tk.Scrollbar _tkSpinbox = tk.Spinbox _tkText =",
"self._dict.get(key) if ret is None: for p in self._parents: ret = p._get_style(key) if",
"weight=tkfont.BOLD) FONT_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SANS_SERIF_TITLE\", family=\"Helvetica\",",
"list of this ``Style``'s parent ``Style``s.\"\"\" self._children = [] \"\"\" A list of",
"ret is not None: break return ret @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\"",
"tk.LabelFrame = _tkLabelFrame tk.Listbox = _tkListbox tk.Menu = _tkMenu tk.PanedWindow = _tkPanedWindow tk.Radiobutton",
"self.apply_style(style or _global_style, **overrides) def apply_style(self, style=None, *, keep_style=False, keep_overrides=False, **overrides): \"\"\" Apply",
"(Priority 4) styles_dict.update(self._overrides) # Before we actually configure the widget, save any of",
"\"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"selectcolor\", \"relief\", \"activeborderwidth\"] class PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable",
"``tkinter.Spinbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"def unregister_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to stop receiving updates on",
"to update all the ``StyleableMixin`` widgets registered to this ``Style`` and its children.",
"self._style = None \"\"\"The widget's current ``Style``.\"\"\" self._overrides = None \"\"\"A dictionary of",
"tkinter widgets: _tkButton = tk.Button _tkCanvas = tk.Canvas _tkCheckbutton = tk.Checkbutton _tkEntry =",
"\"bd\", \"relief\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Menu(StyleableMixin, tk.Menu): \"\"\"Styleable version",
"styled class (i.e. a style is added to this dictionary the first time",
"This should not be called by user code. :param styleable: The styleable widget",
"Keep the same naming scheme as tkinter. def configure(self, **kwargs): \"\"\" Configure this",
"should be used instead. (Although configuring \"functional\" styles through ``widget.configure`` is perfect fine.)",
"be called to initialize this font. \"\"\" FONT_MONOSPACE_NORMAL = None \"\"\" Tkinter named",
"style yield finally: _global_style = None def init_fonts(root): \"\"\" Initialize all the named",
"in their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should be used instead. (Although configuring \"functional\" styles through",
"self._overrides.update(styled) else: self._overrides = styled if style: if self._style: self._style.unregister_styleable(self) self._style = style",
"font with these properties: - size: 10 - family: \"Helvetica\" - weight: BOLD",
"\"fg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"labelanchor\"] class Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable version of",
"be considered for styling; any other options encountered are considered \"functional\" and hence",
"\"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Scale(StyleableMixin, tk.Scale): \"\"\"Styleable version of",
"\"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable version of",
"Listbox tk.Menu = Menu tk.PanedWindow = PanedWindow tk.Radiobutton = Radiobutton tk.Scale = Scale",
"styles_dict = tk_defaults.copy() # Update the dict with the class-specific user-provided defaults. (Priority",
"Spinbox tk.Text = Text tk.Toplevel = Toplevel def unpatch_tk_widgets(): \"\"\"Revert the tkinter widgets",
"receive updates on whenever this style changes. This should not be called by",
"\"\"\"Styleable version of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\",",
"\"normal\" tkinter widgets: _tkButton = tk.Button _tkCanvas = tk.Canvas _tkCheckbutton = tk.Checkbutton _tkEntry",
"parents to inherit styles from. When a style is requested from a ``Style``",
"- family: \"Helvetica\" ``init_fonts`` must be called to initialize this font. \"\"\" #",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Entry(StyleableMixin, tk.Entry): \"\"\"Styleable",
"style from this ``Style``'s ``Style._dict``. If that fails, recursively search this widget's parents.",
"save any of the styles set to this widget by default so we",
"\"highlightbackground\", \"highlightthickness\", \"relief\"] class Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable version of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS = [\"font\",",
"When a ``Style`` is updated, all child ``Style``s of the changed ``Style`` are",
"@contextmanager def patch(): \"\"\"Context manager to temporarily monkey patch the tkinter widgets with",
"\"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\",",
"class Frame(StyleableMixin, tk.Frame): \"\"\"Styleable version of ``tkinter.Frame``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\",",
"Backup copies of \"normal\" tkinter widgets: _tkButton = tk.Button _tkCanvas = tk.Canvas _tkCheckbutton",
"apply. :type style: Style :param overrides: Style overrides to use. \"\"\" global _global_style",
"\"\"\"Styleable version of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class",
"the Style object. (Priority 3) styles_dict.update(self._style.get_relevant_styles(self)) # Update the dict with the overridden",
"[\"font\", \"bg\", \"fg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"labelanchor\"] class Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable",
"= Menu tk.PanedWindow = PanedWindow tk.Radiobutton = Radiobutton tk.Scale = Scale tk.Scrollbar =",
"method to set styles in their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should be used instead. (Although",
"called. \"\"\" def __init__(self, master=None, cnf={}, *args, style=None, **overrides): \"\"\" :param master: The",
":param styles: Style names to remove. \"\"\" for style in styles: del self._dict[style]",
"- weight: BOLD ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SANS_SERIF_NORMAL",
":param key: The style name. :type key: str :return: The style corresponding to",
"``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should be used instead. (Although configuring \"functional\" styles through ``widget.configure`` is",
"weight: BOLD ``init_fonts`` must be called to initialize this font. \"\"\" FONT_MONOSPACE_NORMAL =",
"class Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable version of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\",",
"the widget options (i.e. the ones that would normally be passed to ``widget.configure(...)``)",
"\"highlightthickness\", \"relief\"] class Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable version of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"\"relief\", \"sashrelief\", \"showhandle\"] class Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable version of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS = [\"font\",",
"Text tk.Toplevel = Toplevel def unpatch_tk_widgets(): \"\"\"Revert the tkinter widgets back to their",
"The styleable widget to register. :type styleable: StyleableMixin \"\"\" self._styled.append(styleable) def unregister_styleable(self, styleable):",
"\"selectborderwidth\", \"selectforeground\", \"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"] class Text(StyleableMixin, tk.Text): \"\"\"Styleable version of",
"these properties: - size: 8 - family: \"Courier\" ``init_fonts`` must be called to",
"is called. \"\"\" def __init__(self, master=None, cnf={}, *args, style=None, **overrides): \"\"\" :param master:",
"= [\"bg\", \"bd\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Checkbutton(StyleableMixin, tk.Checkbutton):",
":param master: The master tkinter widget. :param cnf: A dictionary of configuration options.",
"any other options encountered are considered \"functional\" and hence won't be regulated in",
"called to initialize this font. \"\"\" FONT_SANS_SERIF_NORMAL = None \"\"\" Tkinter named font",
"style: An initial style to employ. :type style: Style :param overrides: Style overrides",
"with these properties: - size: 8 - family: \"Courier\" ``init_fonts`` must be called",
"= tk.Toplevel _global_style = None \"\"\"A global ``Style`` object used by the ``stylize``",
"Initialize all the named fonts. This must be called prior to attempting to",
"styleable): \"\"\" Called by ``StyleableMixin`` objects to receive updates on whenever this style",
"these properties: - size: 10 - family: \"Courier\" - weight: BOLD ``init_fonts`` must",
"ret is None: for p in self._parents: ret = p._get_style(key) if ret is",
"stylize(style, **overrides): \"\"\" Context manager to temporarily apply a global-level style and some",
"instance 4. A given dictionary of overrides \"\"\" STYLED_OPTS = [] \"\"\" A",
"tk.Scrollbar = Scrollbar tk.Spinbox = Spinbox tk.Text = Text tk.Toplevel = Toplevel def",
"_tkLabelFrame tk.Listbox = _tkListbox tk.Menu = _tkMenu tk.PanedWindow = _tkPanedWindow tk.Radiobutton = _tkRadiobutton",
"be called to initialize this font. \"\"\" FONT_SERIF_NORMAL = None \"\"\" Tkinter named",
"ret = self._dict.get(key) if ret is None: for p in self._parents: ret =",
"\"selectforeground\"] class Frame(StyleableMixin, tk.Frame): \"\"\"Styleable version of ``tkinter.Frame``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\",",
"\"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\"] class Canvas(StyleableMixin, tk.Canvas):",
"we may return # to them if an explicit style option on this",
"initialize this font. \"\"\" FONT_SERIF_TITLE = None \"\"\" Tkinter named font with these",
"as tkinter. def configure(self, **kwargs): \"\"\" Configure this ``Style``'s styles. :param kwargs: The",
"the named fonts. :param root: The tkinter root widget. :type root: tkinter.Tk \"\"\"",
"to attempting to use any of the named fonts. :param root: The tkinter",
"def patch(): \"\"\"Context manager to temporarily monkey patch the tkinter widgets with their",
"priority so that lower priority styles will get overridden. styles_dict = tk_defaults.copy() #",
"(Although configuring \"functional\" styles through ``widget.configure`` is perfect fine.) There are four sources",
"revoked. This dictionary is lazily built for each unique styled class (i.e. a",
"the dict with the class-specific user-provided defaults. (Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style: #",
"= [\"font\", \"bg\", \"fg\", \"bd\", \"insertbackground\", \"insertborderwidth\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"selectbackground\", \"selectborderwidth\",",
"= Scrollbar tk.Spinbox = Spinbox tk.Text = Text tk.Toplevel = Toplevel def unpatch_tk_widgets():",
"class PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable version of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"relief\", \"sashrelief\",",
"dict with the overridden styles. (Priority 4) styles_dict.update(self._overrides) # Before we actually configure",
"utilities for tkinter widgets. Some features include: - a hierarchical styling system for",
"= MUTE_GREEN BOOL_FALSE = MUTE_RED # Named fonts: FONT_MONOSPACE_TITLE = None \"\"\" Tkinter",
"style is added to this dictionary the first time it changes from its",
"this. One may also set this at runtime through ``StyleableMixin.set_defaults``, but any changes",
"to them if an explicit style option on this widget is removed. tk_defaults.update((k,",
"tk.Label): \"\"\"Styleable version of ``tkinter.Label``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\",",
"GRAY_SCALE_C = \"#CCCCCC\" GRAY_SCALE_D = \"#DDDDDD\" GRAY_SCALE_E = \"#EEEEEE\" GRAY_SCALE_F = \"#FFFFFF\" MUTE_BLUE",
"_tkText = tk.Text _tkToplevel = tk.Toplevel _global_style = None \"\"\"A global ``Style`` object",
"import tkinter.font as tkfont from contextlib import contextmanager # Colour constants: GRAY_SCALE_0 =",
"properties: - size: 10 - family: \"Courier\" - weight: BOLD ``init_fonts`` must be",
"by this class. Subclasses should define this. \"\"\" TK_DEFAULT_STYLES = None \"\"\" A",
"it could not be found. \"\"\" ret = self._dict.get(key) if ret is None:",
"tkinter widget to find styles for. :return: All the styles recognized by the",
"is lazily built for each unique styled class (i.e. a style is added",
"constants; - and reasonable cross-platform named fonts. \"\"\" import tkinter as tk import",
"own version of these; if they were initialized to an empty dict in",
"which a ``Style`` can have one or more parents to inherit styles from.",
"= Entry tk.Frame = Frame tk.Label = Label tk.LabelFrame = LabelFrame tk.Listbox =",
"(``Style.DEFAULTS``). :param key: The style name. :type key: str :return: The style corresponding",
"be found. \"\"\" ret = self._dict.get(key) if ret is None: for p in",
"by ``StyleableMixin`` objects to stop receiving updates on whenever this style changes. This",
"default user-defined styles for a given class. Subclasses may define this. One may",
"STYLED_OPTS = [\"font\", \"bg\", \"activestyle\", \"fg\", \"disabledforeground\", \"bd\", \"relief\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"selectbackground\",",
"class LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable version of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\",",
"Called by ``StyleableMixin`` objects to receive updates on whenever this style changes. This",
"\"disabledforeground\", \"bd\", \"selectcolor\", \"relief\", \"activeborderwidth\"] class PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable version of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS",
"GRAY_SCALE_9 = \"#999999\" GRAY_SCALE_A = \"#AAAAAA\" GRAY_SCALE_B = \"#BBBBBB\" GRAY_SCALE_C = \"#CCCCCC\" GRAY_SCALE_D",
"= Checkbutton tk.Entry = Entry tk.Frame = Frame tk.Label = Label tk.LabelFrame =",
"``Style`` object used by the ``stylize`` context manager.\"\"\" class StyleableMixin: \"\"\" Mixin class",
"BOOL_TRUE = MUTE_GREEN BOOL_FALSE = MUTE_RED # Named fonts: FONT_MONOSPACE_TITLE = None \"\"\"",
"self.configure(styles_dict) @classmethod def _assure_default_dicts_exist(cls): \"\"\" Make sure that this class's ``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES``",
"GRAY_SCALE_7 = \"#777777\" GRAY_SCALE_8 = \"#888888\" GRAY_SCALE_9 = \"#999999\" GRAY_SCALE_A = \"#AAAAAA\" GRAY_SCALE_B",
"lowest priority (1). We # will update the dict with increasing style priority",
"current style (if ``keep_style`` is False). :type style: Style :param keep_style: If ``style``",
"[] \"\"\" A list of registered child ``Style``s. These are signaled of any",
"clear the current style (if ``keep_style`` is False). :type style: Style :param keep_style:",
"default styles (``Style.DEFAULTS``). :param keep_existing: Whether to keep the already existing default styles,",
"size: 10 - family: \"Courier\" - weight: BOLD ``init_fonts`` must be called to",
"**overrides) if overrides else style yield finally: _global_style = None def init_fonts(root): \"\"\"",
"higher priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES`` 3. A given ``Style`` instance 4. A",
"STYLED_OPTS = [] \"\"\" A list of strings specifying all the widget options",
"cls.DEFAULTS = defaults # TODO: Styleable Tk (root)? class Button(StyleableMixin, tk.Button): \"\"\"Styleable version",
"temporarily monkey patch the tkinter widgets with their styleable equivalents.\"\"\" try: patch_tk_widgets() yield",
"= Scale tk.Scrollbar = Scrollbar tk.Spinbox = Spinbox tk.Text = Text tk.Toplevel =",
"for all ``Style`` objects. This should be set through ``Style.set_defaults``.\"\"\" def __init__(self, *parents,",
"\"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable version of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS = [\"bg\",",
"style. Does nothing if ``style`` is given. :type keep_style: bool :param keep_overrides: Whether",
"- family: \"Times\" - weight: BOLD ``init_fonts`` must be called to initialize this",
"initial style to employ. :type style: Style :param overrides: Style overrides to use.",
"not explicitly given a ``Style`` object already. :param style: The style to apply.",
"classes would share the same dictionaries). \"\"\" if cls.TK_DEFAULT_STYLES is None: cls.TK_DEFAULT_STYLES =",
"\"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"] class Text(StyleableMixin,",
"\"\"\"Update this widget's styles.\"\"\" # Alias TK_DEFAULT_STYLES for conciseness. tk_defaults = self.__class__.TK_DEFAULT_STYLES #",
"of the tk_defaults, since those styles are of lowest priority (1). We #",
"widgets: _tkButton = tk.Button _tkCanvas = tk.Canvas _tkCheckbutton = tk.Checkbutton _tkEntry = tk.Entry",
"all classes would share the same dictionaries). \"\"\" if cls.TK_DEFAULT_STYLES is None: cls.TK_DEFAULT_STYLES",
"properties: - size: 8 - family: \"Helvetica\" ``init_fonts`` must be called to initialize",
"= \"#333333\" GRAY_SCALE_4 = \"#444444\" GRAY_SCALE_5 = \"#555555\" GRAY_SCALE_6 = \"#666666\" GRAY_SCALE_7 =",
"\"Times\" - weight: BOLD ``init_fonts`` must be called to initialize this font. \"\"\"",
"_tkLabel = tk.Label _tkLabelFrame = tk.LabelFrame _tkListbox = tk.Listbox _tkMenu = tk.Menu _tkPanedWindow",
"\"\"\"Styleable version of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\",",
"\"relief\", \"justify\"] class LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable version of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"register. :type styleable: StyleableMixin \"\"\" self._styled.append(styleable) def unregister_styleable(self, styleable): \"\"\" Called by ``StyleableMixin``",
"to temporarily monkey patch the tkinter widgets with their styleable equivalents.\"\"\" try: patch_tk_widgets()",
"\"\"\" Internal method to update all the ``StyleableMixin`` widgets registered to this ``Style``",
"given style with the given overrides. :param style: The style to employ, or",
"[\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"selectcolor\", \"relief\", \"activeborderwidth\"] class PanedWindow(StyleableMixin, tk.PanedWindow):",
"``Style``s so that whenever a ``Style`` is updated, any registered ``StyleableMixin``s are automatically",
"\"showvalue\", \"sliderrelief\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable version of",
"that lower priority styles will get overridden. styles_dict = tk_defaults.copy() # Update the",
"whenever this style changes. This should not be called by user code. :param",
"``tkinter.Label``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"= _tkScrollbar tk.Spinbox = _tkSpinbox tk.Text = _tkText tk.Toplevel = _tkToplevel @contextmanager def",
"for k, v in overrides.items(): if k in self.STYLED_OPTS: styled[k] = v else:",
"widget: The tkinter widget to find styles for. :return: All the styles recognized",
"\"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Scale(StyleableMixin, tk.Scale):",
"already existing default styles, or replace them. :type keep_existing: bool :param defaults: A",
"this ``Style`` in ``Style._signal_style_changed``. \"\"\" self._parents = parents \"\"\"A list of this ``Style``'s",
"*styles): \"\"\" Remove the given styles from this ``Style``. This will raise a",
"8 - family: \"Courier\" ``init_fonts`` must be called to initialize this font. \"\"\"",
":type keep_existing: bool :param defaults: A dictionary of styles. \"\"\" if keep_existing: cls.DEFAULTS.update(defaults)",
"is updated, any registered ``StyleableMixin``s are automatically updated to reflect the changes. ``Style``s",
"used to make a widget \"styleable\". This class works in cooperation with the",
"the changes. ``Style``s employ a parent-child system in which a ``Style`` can have",
"map(lambda k: (k, self.get_style(k)), widget.keys()) if v is not None} def get_style(self, key):",
"The master tkinter widget. :param cnf: A dictionary of configuration options. This is",
"default styles (``Style.DEFAULTS``). :param key: The style name. :type key: str :return: The",
"tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SANS_SERIF_TITLE\", family=\"Helvetica\", weight=tkfont.BOLD) FONT_SANS_SERIF_NORMAL =",
"\"\"\" Remove the given styles from this ``Style``. This will raise a ``KeyError``",
"def _assure_default_dicts_exist(cls): \"\"\" Make sure that this class's ``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES`` are defined",
"= None \"\"\" A dictionary of default user-defined styles for a given class.",
"said ``Style``'s own styles, the style is looked for in its ancestors, prioritizing",
"\"#AAAAAA\" GRAY_SCALE_B = \"#BBBBBB\" GRAY_SCALE_C = \"#CCCCCC\" GRAY_SCALE_D = \"#DDDDDD\" GRAY_SCALE_E = \"#EEEEEE\"",
"this font. \"\"\" FONT_MONOSPACE_NORMAL = None \"\"\" Tkinter named font with these properties:",
"style: The style to apply. :type style: Style :param overrides: Style overrides to",
"be called to initialize this font. \"\"\" # Backup copies of \"normal\" tkinter",
"v for k, v in map(lambda k: (k, self.get_style(k)), widget.keys()) if v is",
"self._get_style(key) or self.__class__.DEFAULTS.get(key) def _get_style(self, key): \"\"\" Attempt to retrieve the given style",
"are four sources of style options and they work on a priority system",
"Style :param overrides: Style overrides to use. \"\"\" global _global_style try: _global_style =",
"v in overrides.items(): if k in self.STYLED_OPTS: styled[k] = v else: functional[k] =",
"styles from the Style object. (Priority 3) styles_dict.update(self._style.get_relevant_styles(self)) # Update the dict with",
"the styles from the Style object. (Priority 3) styles_dict.update(self._style.get_relevant_styles(self)) # Update the dict",
"# TODO: Styleable Tk (root)? class Button(StyleableMixin, tk.Button): \"\"\"Styleable version of ``tkinter.Button``.\"\"\" STYLED_OPTS",
"if k in self.STYLED_OPTS: styled[k] = v else: functional[k] = v # Directly",
"``Style`` is updated, any registered ``StyleableMixin``s are automatically updated to reflect the changes.",
"tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL = tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE =",
"style: Style :param keep_style: If ``style`` is None, setting this will keep the",
"default styles for this class. :param keep_existing: Whether to keep the already existing",
"styles.\"\"\" self._assure_default_dicts_exist() # Initialize the widget's style to the given style or the",
"define this. One may also set this at runtime through ``StyleableMixin.set_defaults``, but any",
"any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" for parent in parents: parent._register_child(self)",
"\"styleable\". This class works in cooperation with the ``Style`` class. Styleable widgets should",
"from its default). \"\"\" DEFAULT_STYLES = None \"\"\" A dictionary of default user-defined",
"GRAY_SCALE_F = \"#FFFFFF\" MUTE_BLUE = \"#333355\" MUTE_GREEN = \"#335533\" MUTE_RED = \"#663333\" MUTE_YELLOW",
"to make a widget \"styleable\". This class works in cooperation with the ``Style``",
"``Style``. :type style: Style \"\"\" self._children.append(style) # Keep the same naming scheme as",
"context manager.\"\"\" class StyleableMixin: \"\"\" Mixin class used to make a widget \"styleable\".",
"style corresponding to the given style name, first checking this ``Style`` and its",
"MUTE_GREEN BOOL_FALSE = MUTE_RED # Named fonts: FONT_MONOSPACE_TITLE = None \"\"\" Tkinter named",
"tkinter widget styles. ``StyleableMixin``s register themselves to ``Style``s so that whenever a ``Style``",
"styleable equivalents.\"\"\" try: patch_tk_widgets() yield finally: unpatch_tk_widgets() @contextmanager def stylize(style, **overrides): \"\"\" Context",
"can have one or more parents to inherit styles from. When a style",
"children. \"\"\" for s in self._styled: s.update_style() for child in self._children: child._signal_style_changed() def",
"= _tkSpinbox tk.Text = _tkText tk.Toplevel = _tkToplevel @contextmanager def patch(): \"\"\"Context manager",
"dictionary proxy for tkinter widget styles. ``StyleableMixin``s register themselves to ``Style``s so that",
"include: - a hierarchical styling system for the non-ttk widgets; - a collection",
"return all the styles in this ``Style`` recognized by the given tkinter widget.",
"class Label(StyleableMixin, tk.Label): \"\"\"Styleable version of ``tkinter.Label``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\",",
"widget's styles.\"\"\" # Alias TK_DEFAULT_STYLES for conciseness. tk_defaults = self.__class__.TK_DEFAULT_STYLES # Start off",
"\"\"\" self._dict.update(kwargs) self._signal_style_changed() config = configure \"\"\"Alias for ``Style.configure``.\"\"\" def remove_styles(self, *styles): \"\"\"",
"s.update_style() for child in self._children: child._signal_style_changed() def get_relevant_styles(self, widget): \"\"\" Determine and return",
"to set styles in their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should be used instead. (Although configuring",
"of styles. \"\"\" if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults def patch_tk_widgets(): \"\"\"Monkey",
"\"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\"] class Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable version",
"self._styled.remove(styleable) def _register_child(self, style): \"\"\" Called by child ``Style``s to receive updates on",
"dictionary of configuration options. This is here to mimic the tkinter widget constructors.",
":param overrides: Style overrides to use. \"\"\" # Sort out the functional options",
"share the same dictionaries). \"\"\" if cls.TK_DEFAULT_STYLES is None: cls.TK_DEFAULT_STYLES = {} if",
"\"#222299\" UNKNOWN_TEAM = GRAY_SCALE_B BOOL_TRUE = MUTE_GREEN BOOL_FALSE = MUTE_RED # Named fonts:",
"this font. \"\"\" FONT_SANS_SERIF_TITLE = None \"\"\" Tkinter named font with these properties:",
"are defined (every class needs its own version of these; if they were",
"= [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Label(StyleableMixin, tk.Label): \"\"\"Styleable version of",
"``StyleableMixin`` then all classes would share the same dictionaries). \"\"\" if cls.TK_DEFAULT_STYLES is",
"All the styles recognized by the given tkinter widget. \"\"\" return {k: v",
"= Frame tk.Label = Label tk.LabelFrame = LabelFrame tk.Listbox = Listbox tk.Menu =",
"set this at runtime through ``StyleableMixin.set_defaults``, but any changes made won't be taken",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\"] class Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable version of ``tkinter.Canvas``.\"\"\"",
"of any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" for parent in parents:",
"through ``StyleableMixin.set_defaults``, but any changes made won't be taken into effect on instances",
"tk.PanedWindow): \"\"\"Styleable version of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"relief\", \"sashrelief\", \"showhandle\"] class",
"finally: unpatch_tk_widgets() @contextmanager def stylize(style, **overrides): \"\"\" Context manager to temporarily apply a",
"for k in styles_dict if k not in tk_defaults) self.configure(styles_dict) @classmethod def _assure_default_dicts_exist(cls):",
"by the stylize context # manger. self.apply_style(style or _global_style, **overrides) def apply_style(self, style=None,",
"for style in styles: del self._dict[style] self._signal_style_changed() def _signal_style_changed(self): \"\"\" Internal method to",
"\"\"\" if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults def patch_tk_widgets(): \"\"\"Monkey patch the",
"of configuration options. This is here to mimic the tkinter widget constructors. :type",
"so that whenever a ``Style`` is updated, any registered ``StyleableMixin``s are automatically updated",
"FONT_MONOSPACE_TITLE = tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL = tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\")",
"\"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable version of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS",
"Directly apply the functional options self.configure(functional) if keep_overrides: self._overrides.update(styled) else: self._overrides = styled",
"use. \"\"\" # Sort out the functional options from the styled ones. functional,",
"are automatically updated to reflect the changes. ``Style``s employ a parent-child system in",
"if they're not explicitly given a ``Style`` object already. :param style: The style",
"weight: BOLD ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SERIF_NORMAL =",
"explicit style option on this widget is removed. tk_defaults.update((k, self.cget(k)) for k in",
"registered to this ``Style`` and its children. \"\"\" for s in self._styled: s.update_style()",
"tk.Radiobutton = _tkRadiobutton tk.Scale = _tkScale tk.Scrollbar = _tkScrollbar tk.Spinbox = _tkSpinbox tk.Text",
"Checkbutton tk.Entry = Entry tk.Frame = Frame tk.Label = Label tk.LabelFrame = LabelFrame",
"self._children = [] \"\"\" A list of registered child ``Style``s. These are signaled",
":type keep_style: bool :param keep_overrides: Whether to append the given ``overrides`` to the",
"name or None if it could not be found. \"\"\" return self._get_style(key) or",
"the first ones specified in the constructor. When a ``Style`` is updated, all",
"not keep_style: self._style.unregister_styleable(self) self._style = None self.update_style() def update_style(self): \"\"\"Update this widget's styles.\"\"\"",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\"] class LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable version of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS",
"of registered ``StyleableMixin``s. These are signaled of any changes to this ``Style`` in",
"if self._style: self._style.unregister_styleable(self) self._style = style style.register_styleable(self) elif self._style and not keep_style: self._style.unregister_styleable(self)",
"raise an error if the styleable is not already registered. self._styled.remove(styleable) def _register_child(self,",
"self.__class__.DEFAULTS.get(key) def _get_style(self, key): \"\"\" Attempt to retrieve the given style from this",
"name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SANS_SERIF_TITLE\", family=\"Helvetica\", weight=tkfont.BOLD) FONT_SANS_SERIF_NORMAL = tkfont.Font(root, size=8,",
"contextlib import contextmanager # Colour constants: GRAY_SCALE_0 = \"#000000\" GRAY_SCALE_1 = \"#111111\" GRAY_SCALE_2",
"to append the given ``overrides`` to the already existing overridden styles, or replace",
"= defaults def patch_tk_widgets(): \"\"\"Monkey patch the tkinter widgets with their styleable equivalents.\"\"\"",
"= [] \"\"\" A list of strings specifying all the widget options (i.e.",
"overrides to use. \"\"\" # Sort out the functional options from the styled",
"3) styles_dict.update(self._style.get_relevant_styles(self)) # Update the dict with the overridden styles. (Priority 4) styles_dict.update(self._overrides)",
"not None: break return ret @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method",
"may return # to them if an explicit style option on this widget",
"``Style.configure``.\"\"\" def remove_styles(self, *styles): \"\"\" Remove the given styles from this ``Style``. This",
"\"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Scale(StyleableMixin, tk.Scale): \"\"\"Styleable version of ``tkinter.Scale``.\"\"\"",
"this widget is removed. tk_defaults.update((k, self.cget(k)) for k in styles_dict if k not",
"\"#333333\" GRAY_SCALE_4 = \"#444444\" GRAY_SCALE_5 = \"#555555\" GRAY_SCALE_6 = \"#666666\" GRAY_SCALE_7 = \"#777777\"",
"STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\",",
"or replace them. :type keep_existing: bool :param defaults: A dictionary of styles. \"\"\"",
"= _tkFrame tk.Label = _tkLabel tk.LabelFrame = _tkLabelFrame tk.Listbox = _tkListbox tk.Menu =",
"# Directly apply the functional options self.configure(functional) if keep_overrides: self._overrides.update(styled) else: self._overrides =",
"styles.\"\"\" # Alias TK_DEFAULT_STYLES for conciseness. tk_defaults = self.__class__.TK_DEFAULT_STYLES # Start off the",
"conciseness. tk_defaults = self.__class__.TK_DEFAULT_STYLES # Start off the styles_dict with a copy of",
"GRAY_SCALE_4 = \"#444444\" GRAY_SCALE_5 = \"#555555\" GRAY_SCALE_6 = \"#666666\" GRAY_SCALE_7 = \"#777777\" GRAY_SCALE_8",
"\"activestyle\", \"fg\", \"disabledforeground\", \"bd\", \"relief\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Menu(StyleableMixin,",
"could not be found. \"\"\" return self._get_style(key) or self.__class__.DEFAULTS.get(key) def _get_style(self, key): \"\"\"",
"not already registered. self._styled.remove(styleable) def _register_child(self, style): \"\"\" Called by child ``Style``s to",
"Label tk.LabelFrame = LabelFrame tk.Listbox = Listbox tk.Menu = Menu tk.PanedWindow = PanedWindow",
"taken into effect on instances of that class until ``StyleableMixin.update_style`` is called. \"\"\"",
"dictionary of the widget's currently-overridden styles.\"\"\" self._assure_default_dicts_exist() # Initialize the widget's style to",
"\"highlightbackground\", \"highlightthickness\", \"relief\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable version of ``tkinter.Toplevel``.\"\"\"",
"to use. \"\"\" self._dict = styles \"\"\"A dictionary of the styles specific to",
"\"Helvetica\" ``init_fonts`` must be called to initialize this font. \"\"\" # Backup copies",
"widget to register. :type styleable: StyleableMixin \"\"\" self._styled.append(styleable) def unregister_styleable(self, styleable): \"\"\" Called",
"_global_style = None \"\"\"A global ``Style`` object used by the ``stylize`` context manager.\"\"\"",
"or _global_style, **overrides) def apply_style(self, style=None, *, keep_style=False, keep_overrides=False, **overrides): \"\"\" Apply the",
"style with the given overrides. :param style: The style to employ, or None",
"font. \"\"\" FONT_SERIF_TITLE = None \"\"\" Tkinter named font with these properties: -",
"append the given ``overrides`` to the already existing overridden styles, or replace them.",
"of the widget's currently-overridden styles.\"\"\" self._assure_default_dicts_exist() # Initialize the widget's style to the",
"Menu tk.PanedWindow = PanedWindow tk.Radiobutton = Radiobutton tk.Scale = Scale tk.Scrollbar = Scrollbar",
"style.register_styleable(self) elif self._style and not keep_style: self._style.unregister_styleable(self) self._style = None self.update_style() def update_style(self):",
"style to the given style or the global style, which may be set",
"to the already existing overridden styles, or replace them. :type keep_overrides: bool :param",
"= \"#000000\" GRAY_SCALE_1 = \"#111111\" GRAY_SCALE_2 = \"#222222\" GRAY_SCALE_3 = \"#333333\" GRAY_SCALE_4 =",
"(i.e. a style is added to this dictionary the first time it changes",
"False). :type style: Style :param keep_style: If ``style`` is None, setting this will",
"Tkinter named font with these properties: - size: 10 - family: \"Times\" -",
"\"\"\" self._styled.append(styleable) def unregister_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to stop receiving",
"\"\"\"Styleable version of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"this style changes. :param style: The child ``Style``. :type style: Style \"\"\" self._children.append(style)",
"Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable version of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\",",
"or None if it could not be found. \"\"\" return self._get_style(key) or self.__class__.DEFAULTS.get(key)",
"\"#774433\" RED_TEAM = \"#992222\" BLUE_TEAM = \"#222299\" UNKNOWN_TEAM = GRAY_SCALE_B BOOL_TRUE = MUTE_GREEN",
"tk.Button = Button tk.Canvas = Canvas tk.Checkbutton = Checkbutton tk.Entry = Entry tk.Frame",
"None \"\"\" A dictionary of default user-defined styles for a given class. Subclasses",
"widget options (i.e. the ones that would normally be passed to ``widget.configure(...)``) to",
"\"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"] class Text(StyleableMixin, tk.Text): \"\"\"Styleable version",
"FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE = tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL = tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\",",
"the current style (if ``keep_style`` is False). :type style: Style :param keep_style: If",
"set to this widget by default so we may return # to them",
"be called to initialize this font. \"\"\" FONT_SERIF_TITLE = None \"\"\" Tkinter named",
"named font with these properties: - size: 8 - family: \"Helvetica\" ``init_fonts`` must",
"family: \"Courier\" ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SERIF_TITLE =",
"for the widget constructor. :param style: An initial style to employ. :type style:",
"themselves to ``Style``s so that whenever a ``Style`` is updated, any registered ``StyleableMixin``s",
"\"elementborderwidth\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable version of ``tkinter.Spinbox``.\"\"\"",
"class works in cooperation with the ``Style`` class. Styleable widgets should never use",
"given style name, first checking this ``Style`` and its parents, then resorting to",
"tk.Checkbutton = Checkbutton tk.Entry = Entry tk.Frame = Frame tk.Label = Label tk.LabelFrame",
"tk.Radiobutton = Radiobutton tk.Scale = Scale tk.Scrollbar = Scrollbar tk.Spinbox = Spinbox tk.Text",
"tk.Scrollbar): \"\"\"Styleable version of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS = [\"bg\", \"activebackground\", \"activerelief\", \"bd\", \"elementborderwidth\", \"troughcolor\",",
"BOOL_FALSE = MUTE_RED # Named fonts: FONT_MONOSPACE_TITLE = None \"\"\" Tkinter named font",
"removed. tk_defaults.update((k, self.cget(k)) for k in styles_dict if k not in tk_defaults) self.configure(styles_dict)",
"\"highlightbackground\", \"highlightthickness\", \"relief\"] class Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable version of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS = [\"font\",",
"cnf, *args) self._style = None \"\"\"The widget's current ``Style``.\"\"\" self._overrides = None \"\"\"A",
"\"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Frame(StyleableMixin,",
"stylize context # manger. self.apply_style(style or _global_style, **overrides) def apply_style(self, style=None, *, keep_style=False,",
"k in styles_dict if k not in tk_defaults) self.configure(styles_dict) @classmethod def _assure_default_dicts_exist(cls): \"\"\"",
"or None if it could not be found. \"\"\" ret = self._dict.get(key) if",
"= \"#444444\" GRAY_SCALE_5 = \"#555555\" GRAY_SCALE_6 = \"#666666\" GRAY_SCALE_7 = \"#777777\" GRAY_SCALE_8 =",
"of colour constants; - and reasonable cross-platform named fonts. \"\"\" import tkinter as",
"``StyleableMixin``s if they're not explicitly given a ``Style`` object already. :param style: The",
"\"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\"] class LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable",
"name, first checking this ``Style`` and its parents, then resorting to the global",
"[\"font\", \"bg\", \"fg\", \"bd\", \"insertbackground\", \"insertborderwidth\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"]",
"class needs its own version of these; if they were initialized to an",
"to employ, or None to clear the current style (if ``keep_style`` is False).",
"[\"font\", \"bg\", \"activestyle\", \"fg\", \"disabledforeground\", \"bd\", \"relief\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"]",
"considered \"functional\" and hence won't be regulated in any way by this class.",
"keep_existing=True, **defaults): \"\"\" Convenience method to update the global default styles (``Style.DEFAULTS``). :param",
"family=\"Courier\") FONT_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\",",
"\"Helvetica\" - weight: BOLD ``init_fonts`` must be called to initialize this font. \"\"\"",
"here to mimic the tkinter widget constructors. :type cnf: dict :param args: Additional",
"tk.Menu): \"\"\"Styleable version of ``tkinter.Menu``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\",",
"four sources of style options and they work on a priority system (higher",
"*args, style=None, **overrides): \"\"\" :param master: The master tkinter widget. :param cnf: A",
"Style object. (Priority 3) styles_dict.update(self._style.get_relevant_styles(self)) # Update the dict with the overridden styles.",
"\"justify\"] class Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable version of ``tkinter.Canvas``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"selectbackground\",",
"is not None: break return ret @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience",
"\"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\"] class Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable version of",
"None: break return ret @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to",
"tkinter widgets with their styleable equivalents.\"\"\" try: patch_tk_widgets() yield finally: unpatch_tk_widgets() @contextmanager def",
"overridden styles. (Priority 4) styles_dict.update(self._overrides) # Before we actually configure the widget, save",
"them. :type keep_overrides: bool :param overrides: Style overrides to use. \"\"\" # Sort",
"``Style``s to inherit styles from. :param styles: Styles to use. \"\"\" self._dict =",
"time it changes from its default). \"\"\" DEFAULT_STYLES = None \"\"\" A dictionary",
"styles \"\"\"A dictionary of the styles specific to this ``Style``.\"\"\" self._styled = []",
"\"selectforeground\"] class Menu(StyleableMixin, tk.Menu): \"\"\"Styleable version of ``tkinter.Menu``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\",",
"or the global style, which may be set by the stylize context #",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable version of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS =",
"given style names are not in this ``Style``. :param styles: Style names to",
"= tk.Spinbox _tkText = tk.Text _tkToplevel = tk.Toplevel _global_style = None \"\"\"A global",
"FONT_SANS_SERIF_NORMAL = None \"\"\" Tkinter named font with these properties: - size: 8",
"fonts: FONT_MONOSPACE_TITLE = None \"\"\" Tkinter named font with these properties: - size:",
"overrides: Style overrides to use. \"\"\" super().__init__(master, cnf, *args) self._style = None \"\"\"The",
"styles from. When a style is requested from a ``Style`` and cannot be",
"of overrides \"\"\" STYLED_OPTS = [] \"\"\" A list of strings specifying all",
"\"Courier\" - weight: BOLD ``init_fonts`` must be called to initialize this font. \"\"\"",
"tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE =",
"defined (every class needs its own version of these; if they were initialized",
"font with these properties: - size: 8 - family: \"Courier\" ``init_fonts`` must be",
"get_style(self, key): \"\"\" Return the style corresponding to the given style name, first",
"Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable version of ``tkinter.Listbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activestyle\", \"fg\", \"disabledforeground\",",
"context # manger. self.apply_style(style or _global_style, **overrides) def apply_style(self, style=None, *, keep_style=False, keep_overrides=False,",
"The style to apply. :type style: Style :param overrides: Style overrides to use.",
"\"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"buttonbackground\", \"buttondownrelief\",",
"them if an explicit style option on this widget is removed. tk_defaults.update((k, self.cget(k))",
"family=\"Times\") FONT_SANS_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SANS_SERIF_TITLE\", family=\"Helvetica\", weight=tkfont.BOLD) FONT_SANS_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SANS_SERIF_NORMAL\",",
"to this ``Style``.\"\"\" self._styled = [] \"\"\" A list of registered ``StyleableMixin``s. These",
"= \"#888833\" MUTE_TURQUOISE = \"#335555\" MUTE_PURPLE = \"#553377\" MUTE_PINK = \"#663366\" MUTE_ORANGE =",
"in parents: parent._register_child(self) def register_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to receive",
"= v else: functional[k] = v # Directly apply the functional options self.configure(functional)",
"unique styled class (i.e. a style is added to this dictionary the first",
"elif self._style and not keep_style: self._style.unregister_styleable(self) self._style = None self.update_style() def update_style(self): \"\"\"Update",
"won't be taken into effect on instances of that class until ``StyleableMixin.update_style`` is",
"of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"labelanchor\"]",
"Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable version of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"_register_child(self, style): \"\"\" Called by child ``Style``s to receive updates on whenever this",
"\"\"\"Monkey patch the tkinter widgets with their styleable equivalents.\"\"\" tk.Button = Button tk.Canvas",
"on instances of that class until ``StyleableMixin.update_style`` is called. \"\"\" def __init__(self, master=None,",
"def _register_child(self, style): \"\"\" Called by child ``Style``s to receive updates on whenever",
"replace them. :type keep_overrides: bool :param overrides: Style overrides to use. \"\"\" #",
"the constructor. When a ``Style`` is updated, all child ``Style``s of the changed",
"# Before we actually configure the widget, save any of the styles set",
"style: Style :param overrides: Style overrides to use. \"\"\" global _global_style try: _global_style",
"\"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Entry(StyleableMixin, tk.Entry): \"\"\"Styleable version of ``tkinter.Entry``.\"\"\" STYLED_OPTS",
"if the styleable is not already registered. self._styled.remove(styleable) def _register_child(self, style): \"\"\" Called",
"an explicit style option on this widget is removed. tk_defaults.update((k, self.cget(k)) for k",
"= [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\"]",
"style: The child ``Style``. :type style: Style \"\"\" self._children.append(style) # Keep the same",
"None: cls.TK_DEFAULT_STYLES = {} if cls.DEFAULT_STYLES is None: cls.DEFAULT_STYLES = {} @classmethod def",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Style: \"\"\" A dictionary proxy for tkinter widget",
"style to employ. :type style: Style :param overrides: Style overrides to use. \"\"\"",
"\"relief\"] class Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable version of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\",",
"\"relief\", \"activeborderwidth\"] class PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable version of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\",",
"these; if they were initialized to an empty dict in ``StyleableMixin`` then all",
"master tkinter widget. :param cnf: A dictionary of configuration options. This is here",
"called to initialize this font. \"\"\" FONT_MONOSPACE_NORMAL = None \"\"\" Tkinter named font",
"keep_overrides=False, **overrides): \"\"\" Apply the given style with the given overrides. :param style:",
"for ``Style.configure``.\"\"\" def remove_styles(self, *styles): \"\"\" Remove the given styles from this ``Style``.",
"\"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class",
"``tkinter.Scrollbar``.\"\"\" STYLED_OPTS = [\"bg\", \"activebackground\", \"activerelief\", \"bd\", \"elementborderwidth\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"]",
"= \"#663366\" MUTE_ORANGE = \"#774433\" RED_TEAM = \"#992222\" BLUE_TEAM = \"#222299\" UNKNOWN_TEAM =",
"Update the dict with the class-specific user-provided defaults. (Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style:",
"styled = {}, {} for k, v in overrides.items(): if k in self.STYLED_OPTS:",
"defaults. (Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style: # Update the dict with the styles",
"``Style`` is updated, all child ``Style``s of the changed ``Style`` are recursively informed",
"\"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Entry(StyleableMixin, tk.Entry): \"\"\"Styleable version of",
"Alias TK_DEFAULT_STYLES for conciseness. tk_defaults = self.__class__.TK_DEFAULT_STYLES # Start off the styles_dict with",
"or more parents to inherit styles from. When a style is requested from",
"tk.Text _tkToplevel = tk.Toplevel _global_style = None \"\"\"A global ``Style`` object used by",
"style option on this widget is removed. tk_defaults.update((k, self.cget(k)) for k in styles_dict",
"cnf: A dictionary of configuration options. This is here to mimic the tkinter",
"is added to this dictionary the first time it changes from its default).",
"\"fg\", \"bd\", \"insertbackground\", \"insertborderwidth\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Toplevel(StyleableMixin,",
"FONT_SERIF_NORMAL = None \"\"\" Tkinter named font with these properties: - size: 8",
"to remove. \"\"\" for style in styles: del self._dict[style] self._signal_style_changed() def _signal_style_changed(self): \"\"\"",
"any of the named fonts. :param root: The tkinter root widget. :type root:",
"parents: parent._register_child(self) def register_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to receive updates",
"tk.Menu = _tkMenu tk.PanedWindow = _tkPanedWindow tk.Radiobutton = _tkRadiobutton tk.Scale = _tkScale tk.Scrollbar",
"= LabelFrame tk.Listbox = Listbox tk.Menu = Menu tk.PanedWindow = PanedWindow tk.Radiobutton =",
"automatically updated to reflect the changes. ``Style``s employ a parent-child system in which",
"\"bg\", \"fg\", \"bd\", \"insertbackground\", \"insertborderwidth\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class",
"``widget.configure`` method to set styles in their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should be used instead.",
"the widget's style to the given style or the global style, which may",
"_tkListbox = tk.Listbox _tkMenu = tk.Menu _tkPanedWindow = tk.PanedWindow _tkRadiobutton = tk.Radiobutton _tkScale",
"version of ``tkinter.Frame``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Label(StyleableMixin,",
"weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL = tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\",",
"patching them with ``patch_tk_widgets``.\"\"\" tk.Button = _tkButton tk.Canvas = _tkCanvas tk.Checkbutton = _tkCheckbutton",
"\"\"\" FONT_SERIF_TITLE = None \"\"\" Tkinter named font with these properties: - size:",
"would normally be passed to ``widget.configure(...)``) to be considered for styling; any other",
"\"\"\" Tkinter named font with these properties: - size: 8 - family: \"Helvetica\"",
"of ``tkinter.Menu``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"selectcolor\", \"relief\",",
"[] \"\"\" A list of strings specifying all the widget options (i.e. the",
"\"\"\" A list of strings specifying all the widget options (i.e. the ones",
"a ``Style`` can have one or more parents to inherit styles from. When",
":param keep_overrides: Whether to append the given ``overrides`` to the already existing overridden",
"= \"#222299\" UNKNOWN_TEAM = GRAY_SCALE_B BOOL_TRUE = MUTE_GREEN BOOL_FALSE = MUTE_RED # Named",
"STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"labelanchor\"] class Listbox(StyleableMixin,",
"\"insertbackground\", \"insertborderwidth\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable",
"\"sashrelief\", \"showhandle\"] class Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable version of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"overrides: Style overrides to use. \"\"\" global _global_style try: _global_style = Style(style, **overrides)",
"be taken into effect on instances of that class until ``StyleableMixin.update_style`` is called.",
"is here to mimic the tkinter widget constructors. :type cnf: dict :param args:",
"_assure_default_dicts_exist(cls): \"\"\" Make sure that this class's ``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES`` are defined (every",
"to ``Style``s so that whenever a ``Style`` is updated, any registered ``StyleableMixin``s are",
"keep the previous style. Does nothing if ``style`` is given. :type keep_style: bool",
"tkinter widgets. Some features include: - a hierarchical styling system for the non-ttk",
"\"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Scale(StyleableMixin, tk.Scale): \"\"\"Styleable version",
"\"selectborderwidth\", \"selectforeground\"] class Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable version of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\",",
"= tk.Text _tkToplevel = tk.Toplevel _global_style = None \"\"\"A global ``Style`` object used",
":type styleable: StyleableMixin \"\"\" # This will raise an error if the styleable",
"replace them. :type keep_existing: bool :param defaults: A dictionary of styles. \"\"\" if",
"If that fails, recursively search this widget's parents. :param key: The style name.",
"manger. self.apply_style(style or _global_style, **overrides) def apply_style(self, style=None, *, keep_style=False, keep_overrides=False, **overrides): \"\"\"",
"sources of style options and they work on a priority system (higher number",
"to use. \"\"\" super().__init__(master, cnf, *args) self._style = None \"\"\"The widget's current ``Style``.\"\"\"",
"GRAY_SCALE_5 = \"#555555\" GRAY_SCALE_6 = \"#666666\" GRAY_SCALE_7 = \"#777777\" GRAY_SCALE_8 = \"#888888\" GRAY_SCALE_9",
"styles from. :param styles: Styles to use. \"\"\" self._dict = styles \"\"\"A dictionary",
"Style :param overrides: Style overrides to use. \"\"\" super().__init__(master, cnf, *args) self._style =",
"= [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\",",
"overrides \"\"\" STYLED_OPTS = [] \"\"\" A list of strings specifying all the",
"keep_style: bool :param keep_overrides: Whether to append the given ``overrides`` to the already",
"``Style`` objects. This should be set through ``Style.set_defaults``.\"\"\" def __init__(self, *parents, **styles): \"\"\"",
"already existing overridden styles, or replace them. :type keep_overrides: bool :param overrides: Style",
"\"\"\" Called by ``StyleableMixin`` objects to stop receiving updates on whenever this style",
"``Style``s employ a parent-child system in which a ``Style`` can have one or",
"be regulated in any way by this class. Subclasses should define this. \"\"\"",
"the dict with the styles from the Style object. (Priority 3) styles_dict.update(self._style.get_relevant_styles(self)) #",
"cls.DEFAULT_STYLES = {} @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update",
"if k not in tk_defaults) self.configure(styles_dict) @classmethod def _assure_default_dicts_exist(cls): \"\"\" Make sure that",
"of default user-defined styles for a given class. Subclasses may define this. One",
"of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Style: \"\"\"",
"overrides. :param style: The style to employ, or None to clear the current",
"self._style.unregister_styleable(self) self._style = style style.register_styleable(self) elif self._style and not keep_style: self._style.unregister_styleable(self) self._style =",
"mimic the tkinter widget constructors. :type cnf: dict :param args: Additional args for",
"\"highlightthickness\", \"relief\"] class Style: \"\"\" A dictionary proxy for tkinter widget styles. ``StyleableMixin``s",
"same naming scheme as tkinter. def configure(self, **kwargs): \"\"\" Configure this ``Style``'s styles.",
"tk.Scale = Scale tk.Scrollbar = Scrollbar tk.Spinbox = Spinbox tk.Text = Text tk.Toplevel",
"= _tkText tk.Toplevel = _tkToplevel @contextmanager def patch(): \"\"\"Context manager to temporarily monkey",
"and return all the styles in this ``Style`` recognized by the given tkinter",
"use. \"\"\" self._dict = styles \"\"\"A dictionary of the styles specific to this",
"the styles in this ``Style`` recognized by the given tkinter widget. :param widget:",
"FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE = tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL = tkfont.Font(root, size=8,",
"retrieve the given style from this ``Style``'s ``Style._dict``. If that fails, recursively search",
"LabelFrame tk.Listbox = Listbox tk.Menu = Menu tk.PanedWindow = PanedWindow tk.Radiobutton = Radiobutton",
"\"\"\" # Sort out the functional options from the styled ones. functional, styled",
"overrides else style yield finally: _global_style = None def init_fonts(root): \"\"\" Initialize all",
"used by the ``stylize`` context manager.\"\"\" class StyleableMixin: \"\"\" Mixin class used to",
"\"selectcolor\"] class Scale(StyleableMixin, tk.Scale): \"\"\"Styleable version of ``tkinter.Scale``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\",",
"the stylize context # manger. self.apply_style(style or _global_style, **overrides) def apply_style(self, style=None, *,",
"equivalents.\"\"\" tk.Button = Button tk.Canvas = Canvas tk.Checkbutton = Checkbutton tk.Entry = Entry",
"not be found. \"\"\" return self._get_style(key) or self.__class__.DEFAULTS.get(key) def _get_style(self, key): \"\"\" Attempt",
"``Style`` in ``Style._signal_style_changed``. \"\"\" self._parents = parents \"\"\"A list of this ``Style``'s parent",
"that fails, recursively search this widget's parents. :param key: The style name. :type",
"styles: Styles to use. \"\"\" self._dict = styles \"\"\"A dictionary of the styles",
"_tkRadiobutton tk.Scale = _tkScale tk.Scrollbar = _tkScrollbar tk.Spinbox = _tkSpinbox tk.Text = _tkText",
"else: cls.DEFAULTS = defaults def patch_tk_widgets(): \"\"\"Monkey patch the tkinter widgets with their",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Menu(StyleableMixin, tk.Menu): \"\"\"Styleable version of ``tkinter.Menu``.\"\"\"",
"must be called to initialize this font. \"\"\" FONT_SERIF_TITLE = None \"\"\" Tkinter",
"= tk.Checkbutton _tkEntry = tk.Entry _tkFrame = tk.Frame _tkLabel = tk.Label _tkLabelFrame =",
"``init_fonts`` must be called to initialize this font. \"\"\" FONT_SANS_SERIF_NORMAL = None \"\"\"",
"kwargs: The styles to add/edit. \"\"\" self._dict.update(kwargs) self._signal_style_changed() config = configure \"\"\"Alias for",
"\"#000000\" GRAY_SCALE_1 = \"#111111\" GRAY_SCALE_2 = \"#222222\" GRAY_SCALE_3 = \"#333333\" GRAY_SCALE_4 = \"#444444\"",
"a collection of colour constants; - and reasonable cross-platform named fonts. \"\"\" import",
"``tkinter.Entry``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"\"\"\" :param parents: ``Style``s to inherit styles from. :param styles: Styles to use.",
"tk.Canvas = Canvas tk.Checkbutton = Checkbutton tk.Entry = Entry tk.Frame = Frame tk.Label",
"to find styles for. :return: All the styles recognized by the given tkinter",
"= parents \"\"\"A list of this ``Style``'s parent ``Style``s.\"\"\" self._children = [] \"\"\"",
"should not be called by user code. :param styleable: The styleable widget to",
"\"\"\" self._children.append(style) # Keep the same naming scheme as tkinter. def configure(self, **kwargs):",
"the given ``overrides`` to the already existing overridden styles, or replace them. :type",
"tk.LabelFrame = LabelFrame tk.Listbox = Listbox tk.Menu = Menu tk.PanedWindow = PanedWindow tk.Radiobutton",
"[] \"\"\" A list of registered ``StyleableMixin``s. These are signaled of any changes",
"\"selectborderwidth\", \"selectforeground\"] class Menu(StyleableMixin, tk.Menu): \"\"\"Styleable version of ``tkinter.Menu``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"\"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"selectcolor\", \"relief\", \"activeborderwidth\"] class PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable version",
"copies of \"normal\" tkinter widgets: _tkButton = tk.Button _tkCanvas = tk.Canvas _tkCheckbutton =",
"\"\"\"Styleable version of ``tkinter.Listbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activestyle\", \"fg\", \"disabledforeground\", \"bd\", \"relief\",",
"class Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable version of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\",",
"widget): \"\"\" Determine and return all the styles in this ``Style`` recognized by",
"\"\"\" self._dict = styles \"\"\"A dictionary of the styles specific to this ``Style``.\"\"\"",
"_tkEntry tk.Frame = _tkFrame tk.Label = _tkLabel tk.LabelFrame = _tkLabelFrame tk.Listbox = _tkListbox",
"initialized to an empty dict in ``StyleableMixin`` then all classes would share the",
"and its children. \"\"\" for s in self._styled: s.update_style() for child in self._children:",
"Some features include: - a hierarchical styling system for the non-ttk widgets; -",
"reflect the changes. ``Style``s employ a parent-child system in which a ``Style`` can",
":type cnf: dict :param args: Additional args for the widget constructor. :param style:",
"= _tkMenu tk.PanedWindow = _tkPanedWindow tk.Radiobutton = _tkRadiobutton tk.Scale = _tkScale tk.Scrollbar =",
":param args: Additional args for the widget constructor. :param style: An initial style",
"functional, styled = {}, {} for k, v in overrides.items(): if k in",
"\"highlightthickness\", \"relief\"] class Label(StyleableMixin, tk.Label): \"\"\"Styleable version of ``tkinter.Label``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"FONT_SERIF_TITLE = None \"\"\" Tkinter named font with these properties: - size: 10",
"Style overrides to use. \"\"\" global _global_style try: _global_style = Style(style, **overrides) if",
"one or more parents to inherit styles from. When a style is requested",
"option on this widget is removed. tk_defaults.update((k, self.cget(k)) for k in styles_dict if",
"FONT_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\")",
"of the named fonts. :param root: The tkinter root widget. :type root: tkinter.Tk",
"to if an initially explicitly given style option is revoked. This dictionary is",
"``StyleableMixin``s. These are signaled of any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\"",
"given ``overrides`` to the already existing overridden styles, or replace them. :type keep_overrides:",
"be set by the stylize context # manger. self.apply_style(style or _global_style, **overrides) def",
":param keep_style: If ``style`` is None, setting this will keep the previous style.",
"from. :param styles: Styles to use. \"\"\" self._dict = styles \"\"\"A dictionary of",
"or replace them. :type keep_overrides: bool :param overrides: Style overrides to use. \"\"\"",
"on whenever this style changes. This should not be called by user code.",
"= tk.Canvas _tkCheckbutton = tk.Checkbutton _tkEntry = tk.Entry _tkFrame = tk.Frame _tkLabel =",
"for child in self._children: child._signal_style_changed() def get_relevant_styles(self, widget): \"\"\" Determine and return all",
"= {} @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update the",
"10 - family: \"Courier\" - weight: BOLD ``init_fonts`` must be called to initialize",
"- size: 8 - family: \"Times\" ``init_fonts`` must be called to initialize this",
"name. :type key: str :return: The style corresponding to the given style name",
"= \"#999999\" GRAY_SCALE_A = \"#AAAAAA\" GRAY_SCALE_B = \"#BBBBBB\" GRAY_SCALE_C = \"#CCCCCC\" GRAY_SCALE_D =",
"apply the functional options self.configure(functional) if keep_overrides: self._overrides.update(styled) else: self._overrides = styled if",
"of ``tkinter.Canvas``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"]",
"self.STYLED_OPTS: styled[k] = v else: functional[k] = v # Directly apply the functional",
"styleable: The styleable widget to register. :type styleable: StyleableMixin \"\"\" self._styled.append(styleable) def unregister_styleable(self,",
"parent._register_child(self) def register_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to receive updates on",
"class. Styleable widgets should never use their ``widget.configure`` method to set styles in",
"def __init__(self, *parents, **styles): \"\"\" :param parents: ``Style``s to inherit styles from. :param",
"p._get_style(key) if ret is not None: break return ret @classmethod def set_defaults(cls, keep_existing=True,",
"widget \"styleable\". This class works in cooperation with the ``Style`` class. Styleable widgets",
"= tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE",
"GRAY_SCALE_B BOOL_TRUE = MUTE_GREEN BOOL_FALSE = MUTE_RED # Named fonts: FONT_MONOSPACE_TITLE = None",
"ones that would normally be passed to ``widget.configure(...)``) to be considered for styling;",
"nothing if ``style`` is given. :type keep_style: bool :param keep_overrides: Whether to append",
"``StyleableMixin.DEFAULT_STYLES`` are defined (every class needs its own version of these; if they",
"changed ``Style`` are recursively informed of the change. \"\"\" DEFAULTS = {} \"\"\"Global",
"of ``tkinter.Button``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\",",
"\"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class",
"be called to initialize this font. \"\"\" FONT_SANS_SERIF_NORMAL = None \"\"\" Tkinter named",
"class. Subclasses should define this. \"\"\" TK_DEFAULT_STYLES = None \"\"\" A dictionary of",
"\"#666666\" GRAY_SCALE_7 = \"#777777\" GRAY_SCALE_8 = \"#888888\" GRAY_SCALE_9 = \"#999999\" GRAY_SCALE_A = \"#AAAAAA\"",
"``Style`` and its parents, then resorting to the global default styles (``Style.DEFAULTS``). :param",
"version of ``tkinter.Scale``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"bd\", \"showvalue\", \"sliderrelief\", \"troughcolor\",",
"\"\"\" self._parents = parents \"\"\"A list of this ``Style``'s parent ``Style``s.\"\"\" self._children =",
"GRAY_SCALE_0 = \"#000000\" GRAY_SCALE_1 = \"#111111\" GRAY_SCALE_2 = \"#222222\" GRAY_SCALE_3 = \"#333333\" GRAY_SCALE_4",
"on this widget is removed. tk_defaults.update((k, self.cget(k)) for k in styles_dict if k",
"= _tkToplevel @contextmanager def patch(): \"\"\"Context manager to temporarily monkey patch the tkinter",
"the widget, save any of the styles set to this widget by default",
"\"\"\" # Backup copies of \"normal\" tkinter widgets: _tkButton = tk.Button _tkCanvas =",
"this. \"\"\" TK_DEFAULT_STYLES = None \"\"\" A dictionary of default (platform-specific) styles to",
"method to update the default styles for this class. :param keep_existing: Whether to",
"cnf={}, *args, style=None, **overrides): \"\"\" :param master: The master tkinter widget. :param cnf:",
"will get overridden. styles_dict = tk_defaults.copy() # Update the dict with the class-specific",
"style: if self._style: self._style.unregister_styleable(self) self._style = style style.register_styleable(self) elif self._style and not keep_style:",
"cnf: dict :param args: Additional args for the widget constructor. :param style: An",
"the ``Style`` class. Styleable widgets should never use their ``widget.configure`` method to set",
"called by user code. :param styleable: The styleable widget to unregister. :type styleable:",
"``tkinter.Scale``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"bd\", \"showvalue\", \"sliderrelief\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\",",
"= tk.PanedWindow _tkRadiobutton = tk.Radiobutton _tkScale = tk.Scale _tkScrollbar = tk.Scrollbar _tkSpinbox =",
"for tkinter widget styles. ``StyleableMixin``s register themselves to ``Style``s so that whenever a",
"a ``Style`` is updated, all child ``Style``s of the changed ``Style`` are recursively",
"\"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\"] class LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable version of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS =",
"widget's currently-overridden styles.\"\"\" self._assure_default_dicts_exist() # Initialize the widget's style to the given style",
"Style overrides to use. \"\"\" super().__init__(master, cnf, *args) self._style = None \"\"\"The widget's",
"for parent in parents: parent._register_child(self) def register_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects",
"the change. \"\"\" DEFAULTS = {} \"\"\"Global default styles for all ``Style`` objects.",
"FONT_SANS_SERIF_TITLE = None \"\"\" Tkinter named font with these properties: - size: 10",
"v in map(lambda k: (k, self.get_style(k)), widget.keys()) if v is not None} def",
"= Label tk.LabelFrame = LabelFrame tk.Listbox = Listbox tk.Menu = Menu tk.PanedWindow =",
"{} if cls.DEFAULT_STYLES is None: cls.DEFAULT_STYLES = {} @classmethod def set_defaults(cls, keep_existing=True, **defaults):",
"Whether to keep the already existing default styles, or replace them. :type keep_existing:",
"def apply_style(self, style=None, *, keep_style=False, keep_overrides=False, **overrides): \"\"\" Apply the given style with",
"\"bd\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable version",
"style or the global style, which may be set by the stylize context",
"the non-ttk widgets; - a collection of colour constants; - and reasonable cross-platform",
"_tkListbox tk.Menu = _tkMenu tk.PanedWindow = _tkPanedWindow tk.Radiobutton = _tkRadiobutton tk.Scale = _tkScale",
"constructors. :type cnf: dict :param args: Additional args for the widget constructor. :param",
"other options encountered are considered \"functional\" and hence won't be regulated in any",
"\"bd\", \"showvalue\", \"sliderrelief\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable version",
"self._signal_style_changed() def _signal_style_changed(self): \"\"\" Internal method to update all the ``StyleableMixin`` widgets registered",
"_tkLabel tk.LabelFrame = _tkLabelFrame tk.Listbox = _tkListbox tk.Menu = _tkMenu tk.PanedWindow = _tkPanedWindow",
"style will only be used by ``StyleableMixin``s if they're not explicitly given a",
"None if it could not be found. \"\"\" ret = self._dict.get(key) if ret",
"tk.Checkbutton _tkEntry = tk.Entry _tkFrame = tk.Frame _tkLabel = tk.Label _tkLabelFrame = tk.LabelFrame",
"named font with these properties: - size: 10 - family: \"Helvetica\" - weight:",
"- family: \"Courier\" - weight: BOLD ``init_fonts`` must be called to initialize this",
"= None \"\"\"A dictionary of the widget's currently-overridden styles.\"\"\" self._assure_default_dicts_exist() # Initialize the",
"self._style: self._style.unregister_styleable(self) self._style = style style.register_styleable(self) elif self._style and not keep_style: self._style.unregister_styleable(self) self._style",
"\"\"\" Context manager to temporarily apply a global-level style and some overrides. This",
"to use any of the named fonts. :param root: The tkinter root widget.",
"size: 8 - family: \"Times\" ``init_fonts`` must be called to initialize this font.",
"with the styles from the Style object. (Priority 3) styles_dict.update(self._style.get_relevant_styles(self)) # Update the",
"dictionary the first time it changes from its default). \"\"\" DEFAULT_STYLES = None",
"remove. \"\"\" for style in styles: del self._dict[style] self._signal_style_changed() def _signal_style_changed(self): \"\"\" Internal",
"STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\",",
"their styleable equivalents.\"\"\" tk.Button = Button tk.Canvas = Canvas tk.Checkbutton = Checkbutton tk.Entry",
"of ``tkinter.Listbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activestyle\", \"fg\", \"disabledforeground\", \"bd\", \"relief\", \"highlightcolor\", \"highlightbackground\",",
"``init_fonts`` must be called to initialize this font. \"\"\" FONT_MONOSPACE_NORMAL = None \"\"\"",
"A dictionary of default (platform-specific) styles to revert to if an initially explicitly",
"\"highlightbackground\", \"highlightthickness\", \"relief\"] class Label(StyleableMixin, tk.Label): \"\"\"Styleable version of ``tkinter.Label``.\"\"\" STYLED_OPTS = [\"font\",",
"priority system (higher number means higher priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES`` 3. A",
":param keep_existing: Whether to keep the already existing default styles, or replace them.",
"\"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Frame(StyleableMixin, tk.Frame):",
"ret @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update the global",
"_tkPanedWindow tk.Radiobutton = _tkRadiobutton tk.Scale = _tkScale tk.Scrollbar = _tkScrollbar tk.Spinbox = _tkSpinbox",
"their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should be used instead. (Although configuring \"functional\" styles through ``widget.configure``",
"a style is added to this dictionary the first time it changes from",
"a parent-child system in which a ``Style`` can have one or more parents",
"[\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\"]",
"\"#888888\" GRAY_SCALE_9 = \"#999999\" GRAY_SCALE_A = \"#AAAAAA\" GRAY_SCALE_B = \"#BBBBBB\" GRAY_SCALE_C = \"#CCCCCC\"",
"styles: Style names to remove. \"\"\" for style in styles: del self._dict[style] self._signal_style_changed()",
"changes. ``Style``s employ a parent-child system in which a ``Style`` can have one",
"this ``Style`` recognized by the given tkinter widget. :param widget: The tkinter widget",
"= Spinbox tk.Text = Text tk.Toplevel = Toplevel def unpatch_tk_widgets(): \"\"\"Revert the tkinter",
"Update the dict with the overridden styles. (Priority 4) styles_dict.update(self._overrides) # Before we",
"be called by user code. :param styleable: The styleable widget to register. :type",
"properties: - size: 8 - family: \"Courier\" ``init_fonts`` must be called to initialize",
"\"\"\" Tkinter named font with these properties: - size: 8 - family: \"Courier\"",
"Tkinter named font with these properties: - size: 8 - family: \"Helvetica\" ``init_fonts``",
"style name. :type key: str :return: The style corresponding to the given style",
"= _tkLabel tk.LabelFrame = _tkLabelFrame tk.Listbox = _tkListbox tk.Menu = _tkMenu tk.PanedWindow =",
"self._style = style style.register_styleable(self) elif self._style and not keep_style: self._style.unregister_styleable(self) self._style = None",
"existing default styles, or replace them. :type keep_existing: bool :param defaults: A dictionary",
"back to their defaults after monkey patching them with ``patch_tk_widgets``.\"\"\" tk.Button = _tkButton",
"# Initialize the widget's style to the given style or the global style,",
"bool :param defaults: A dictionary of default styles. \"\"\" cls._assure_default_dicts_exist() if keep_existing: cls.DEFAULTS.update(defaults)",
"\"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\",",
"dictionary of overrides \"\"\" STYLED_OPTS = [] \"\"\" A list of strings specifying",
":param style: The child ``Style``. :type style: Style \"\"\" self._children.append(style) # Keep the",
"an initially explicitly given style option is revoked. This dictionary is lazily built",
"since those styles are of lowest priority (1). We # will update the",
"error if the styleable is not already registered. self._styled.remove(styleable) def _register_child(self, style): \"\"\"",
"\"selectforeground\", \"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"] class Text(StyleableMixin, tk.Text): \"\"\"Styleable version of ``tkinter.Text``.\"\"\"",
"tk.Canvas): \"\"\"Styleable version of ``tkinter.Canvas``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"highlightcolor\",",
"currently-overridden styles.\"\"\" self._assure_default_dicts_exist() # Initialize the widget's style to the given style or",
"class Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable version of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\",",
"__init__(self, *parents, **styles): \"\"\" :param parents: ``Style``s to inherit styles from. :param styles:",
"Tkinter named font with these properties: - size: 10 - family: \"Helvetica\" -",
"the functional options from the styled ones. functional, styled = {}, {} for",
"= \"#774433\" RED_TEAM = \"#992222\" BLUE_TEAM = \"#222299\" UNKNOWN_TEAM = GRAY_SCALE_B BOOL_TRUE =",
"will update the dict with increasing style priority so that lower priority styles",
"child ``Style``. :type style: Style \"\"\" self._children.append(style) # Keep the same naming scheme",
"PanedWindow tk.Radiobutton = Radiobutton tk.Scale = Scale tk.Scrollbar = Scrollbar tk.Spinbox = Spinbox",
"version of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Style:",
"Make sure that this class's ``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES`` are defined (every class needs",
"styleable: StyleableMixin \"\"\" self._styled.append(styleable) def unregister_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to",
"the given styles from this ``Style``. This will raise a ``KeyError`` if any",
"to this ``Style`` in ``Style._signal_style_changed``. \"\"\" self._parents = parents \"\"\"A list of this",
"the widget's currently-overridden styles.\"\"\" self._assure_default_dicts_exist() # Initialize the widget's style to the given",
"Styleable Tk (root)? class Button(StyleableMixin, tk.Button): \"\"\"Styleable version of ``tkinter.Button``.\"\"\" STYLED_OPTS = [\"font\",",
"\"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Scale(StyleableMixin, tk.Scale): \"\"\"Styleable version of ``tkinter.Scale``.\"\"\" STYLED_OPTS =",
"by child ``Style``s to receive updates on whenever this style changes. :param style:",
"to initialize this font. \"\"\" # Backup copies of \"normal\" tkinter widgets: _tkButton",
"should never use their ``widget.configure`` method to set styles in their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style``",
"for p in self._parents: ret = p._get_style(key) if ret is not None: break",
"set by the stylize context # manger. self.apply_style(style or _global_style, **overrides) def apply_style(self,",
"``tkinter.LabelFrame``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"labelanchor\"] class",
"= \"#FFFFFF\" MUTE_BLUE = \"#333355\" MUTE_GREEN = \"#335533\" MUTE_RED = \"#663333\" MUTE_YELLOW =",
"\"\"\" Return the style corresponding to the given style name, first checking this",
":param style: The style to employ, or None to clear the current style",
"a priority system (higher number means higher priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES`` 3.",
"\"\"\" Tkinter named font with these properties: - size: 8 - family: \"Times\"",
"FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE = tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD)",
"recognized by the given tkinter widget. \"\"\" return {k: v for k, v",
"``widget.configure`` is perfect fine.) There are four sources of style options and they",
"version of ``tkinter.Entry``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\", \"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\",",
"= Style(style, **overrides) if overrides else style yield finally: _global_style = None def",
"\"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Entry(StyleableMixin, tk.Entry):",
"signaled of any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" self._parents = parents",
"found. \"\"\" return self._get_style(key) or self.__class__.DEFAULTS.get(key) def _get_style(self, key): \"\"\" Attempt to retrieve",
"tk.Listbox = _tkListbox tk.Menu = _tkMenu tk.PanedWindow = _tkPanedWindow tk.Radiobutton = _tkRadiobutton tk.Scale",
"is removed. tk_defaults.update((k, self.cget(k)) for k in styles_dict if k not in tk_defaults)",
"to the given style or the global style, which may be set by",
"\"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"] class Text(StyleableMixin, tk.Text): \"\"\"Styleable version of ``tkinter.Text``.\"\"\" STYLED_OPTS = [\"font\",",
"self.__class__.TK_DEFAULT_STYLES # Start off the styles_dict with a copy of the tk_defaults, since",
"self._children: child._signal_style_changed() def get_relevant_styles(self, widget): \"\"\" Determine and return all the styles in",
"object. (Priority 3) styles_dict.update(self._style.get_relevant_styles(self)) # Update the dict with the overridden styles. (Priority",
"child in self._children: child._signal_style_changed() def get_relevant_styles(self, widget): \"\"\" Determine and return all the",
"\"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Entry(StyleableMixin, tk.Entry): \"\"\"Styleable version",
"\"#111111\" GRAY_SCALE_2 = \"#222222\" GRAY_SCALE_3 = \"#333333\" GRAY_SCALE_4 = \"#444444\" GRAY_SCALE_5 = \"#555555\"",
"given ``Style`` instance 4. A given dictionary of overrides \"\"\" STYLED_OPTS = []",
"cross-platform named fonts. \"\"\" import tkinter as tk import tkinter.font as tkfont from",
"names are not in this ``Style``. :param styles: Style names to remove. \"\"\"",
"\"\"\" STYLED_OPTS = [] \"\"\" A list of strings specifying all the widget",
"styles are of lowest priority (1). We # will update the dict with",
"``keep_style`` is False). :type style: Style :param keep_style: If ``style`` is None, setting",
"unregister. :type styleable: StyleableMixin \"\"\" # This will raise an error if the",
"styles_dict.update(self._overrides) # Before we actually configure the widget, save any of the styles",
"# Sort out the functional options from the styled ones. functional, styled =",
"PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable version of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"relief\", \"sashrelief\", \"showhandle\"]",
"stop receiving updates on whenever this style changes. This should not be called",
"the styles specific to this ``Style``.\"\"\" self._styled = [] \"\"\" A list of",
"given a ``Style`` object already. :param style: The style to apply. :type style:",
"\"#999999\" GRAY_SCALE_A = \"#AAAAAA\" GRAY_SCALE_B = \"#BBBBBB\" GRAY_SCALE_C = \"#CCCCCC\" GRAY_SCALE_D = \"#DDDDDD\"",
"keep_overrides: self._overrides.update(styled) else: self._overrides = styled if style: if self._style: self._style.unregister_styleable(self) self._style =",
"if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults def patch_tk_widgets(): \"\"\"Monkey patch the tkinter",
":type key: str :return: The style corresponding to the given style name or",
"\"\"\" global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE = tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\",",
"them. :type keep_existing: bool :param defaults: A dictionary of styles. \"\"\" if keep_existing:",
"BOLD ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SERIF_NORMAL = None",
"to the given style name or None if it could not be found.",
"in this ``Style``. :param styles: Style names to remove. \"\"\" for style in",
"Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable version of ``tkinter.Canvas``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\",",
"\"overrelief\", \"justify\"] class Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable version of ``tkinter.Canvas``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\",",
"\"fg\", \"disabledforeground\", \"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"buttonbackground\",",
"default so we may return # to them if an explicit style option",
"style is looked for in its ancestors, prioritizing the first ones specified in",
"of the changed ``Style`` are recursively informed of the change. \"\"\" DEFAULTS =",
"*, keep_style=False, keep_overrides=False, **overrides): \"\"\" Apply the given style with the given overrides.",
"= style style.register_styleable(self) elif self._style and not keep_style: self._style.unregister_styleable(self) self._style = None self.update_style()",
"code. :param styleable: The styleable widget to register. :type styleable: StyleableMixin \"\"\" self._styled.append(styleable)",
"font with these properties: - size: 10 - family: \"Times\" - weight: BOLD",
"\"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"] class Text(StyleableMixin, tk.Text):",
"widget. :param cnf: A dictionary of configuration options. This is here to mimic",
"parents. :param key: The style name. :type key: str :return: The style corresponding",
"this widget by default so we may return # to them if an",
"[\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\"] class",
"set through ``Style.set_defaults``.\"\"\" def __init__(self, *parents, **styles): \"\"\" :param parents: ``Style``s to inherit",
":param root: The tkinter root widget. :type root: tkinter.Tk \"\"\" global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\",
"= \"#335555\" MUTE_PURPLE = \"#553377\" MUTE_PINK = \"#663366\" MUTE_ORANGE = \"#774433\" RED_TEAM =",
"to apply. :type style: Style :param overrides: Style overrides to use. \"\"\" global",
"None \"\"\"The widget's current ``Style``.\"\"\" self._overrides = None \"\"\"A dictionary of the widget's",
"\"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\"] class Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable",
"the global default styles (``Style.DEFAULTS``). :param keep_existing: Whether to keep the already existing",
"self._style = None self.update_style() def update_style(self): \"\"\"Update this widget's styles.\"\"\" # Alias TK_DEFAULT_STYLES",
"tk.Text = Text tk.Toplevel = Toplevel def unpatch_tk_widgets(): \"\"\"Revert the tkinter widgets back",
"Style \"\"\" self._children.append(style) # Keep the same naming scheme as tkinter. def configure(self,",
"\"\"\" return self._get_style(key) or self.__class__.DEFAULTS.get(key) def _get_style(self, key): \"\"\" Attempt to retrieve the",
"This is here to mimic the tkinter widget constructors. :type cnf: dict :param",
"\"Times\" ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SANS_SERIF_TITLE = None",
"- family: \"Times\" ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SANS_SERIF_TITLE",
"must be called to initialize this font. \"\"\" FONT_SANS_SERIF_TITLE = None \"\"\" Tkinter",
"\"highlightbackground\", \"highlightthickness\", \"relief\"] class Style: \"\"\" A dictionary proxy for tkinter widget styles.",
"of registered child ``Style``s. These are signaled of any changes to this ``Style``",
"GRAY_SCALE_3 = \"#333333\" GRAY_SCALE_4 = \"#444444\" GRAY_SCALE_5 = \"#555555\" GRAY_SCALE_6 = \"#666666\" GRAY_SCALE_7",
"\"#663333\" MUTE_YELLOW = \"#888833\" MUTE_TURQUOISE = \"#335555\" MUTE_PURPLE = \"#553377\" MUTE_PINK = \"#663366\"",
"with their styleable equivalents.\"\"\" tk.Button = Button tk.Canvas = Canvas tk.Checkbutton = Checkbutton",
"if ret is not None: break return ret @classmethod def set_defaults(cls, keep_existing=True, **defaults):",
"\"disabledforeground\", \"bd\", \"relief\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Menu(StyleableMixin, tk.Menu): \"\"\"Styleable",
"``style`` is None, setting this will keep the previous style. Does nothing if",
"manager to temporarily monkey patch the tkinter widgets with their styleable equivalents.\"\"\" try:",
"temporarily apply a global-level style and some overrides. This global-level style will only",
"``Style`` object already. :param style: The style to apply. :type style: Style :param",
"= [\"font\", \"bg\", \"activestyle\", \"fg\", \"disabledforeground\", \"bd\", \"relief\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"selectbackground\", \"selectborderwidth\",",
"\"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"] class Entry(StyleableMixin, tk.Entry): \"\"\"Styleable version of ``tkinter.Entry``.\"\"\"",
"prior to attempting to use any of the named fonts. :param root: The",
"GRAY_SCALE_B = \"#BBBBBB\" GRAY_SCALE_C = \"#CCCCCC\" GRAY_SCALE_D = \"#DDDDDD\" GRAY_SCALE_E = \"#EEEEEE\" GRAY_SCALE_F",
"as tk import tkinter.font as tkfont from contextlib import contextmanager # Colour constants:",
"the given overrides. :param style: The style to employ, or None to clear",
"_get_style(self, key): \"\"\" Attempt to retrieve the given style from this ``Style``'s ``Style._dict``.",
"= \"#777777\" GRAY_SCALE_8 = \"#888888\" GRAY_SCALE_9 = \"#999999\" GRAY_SCALE_A = \"#AAAAAA\" GRAY_SCALE_B =",
"inherit styles from. When a style is requested from a ``Style`` and cannot",
"tkinter widget. :param cnf: A dictionary of configuration options. This is here to",
"class Button(StyleableMixin, tk.Button): \"\"\"Styleable version of ``tkinter.Button``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\",",
"inherit styles from. :param styles: Styles to use. \"\"\" self._dict = styles \"\"\"A",
"\"activerelief\", \"bd\", \"elementborderwidth\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable version",
"\"\"\" Tkinter named font with these properties: - size: 10 - family: \"Courier\"",
"for. :return: All the styles recognized by the given tkinter widget. \"\"\" return",
"key: The style name. :type key: str :return: The style corresponding to the",
"_tkButton tk.Canvas = _tkCanvas tk.Checkbutton = _tkCheckbutton tk.Entry = _tkEntry tk.Frame = _tkFrame",
"tk.Entry = _tkEntry tk.Frame = _tkFrame tk.Label = _tkLabel tk.LabelFrame = _tkLabelFrame tk.Listbox",
"finally: _global_style = None def init_fonts(root): \"\"\" Initialize all the named fonts. This",
"\"#CCCCCC\" GRAY_SCALE_D = \"#DDDDDD\" GRAY_SCALE_E = \"#EEEEEE\" GRAY_SCALE_F = \"#FFFFFF\" MUTE_BLUE = \"#333355\"",
"tk.Spinbox = _tkSpinbox tk.Text = _tkText tk.Toplevel = _tkToplevel @contextmanager def patch(): \"\"\"Context",
"\"\"\"A dictionary of the styles specific to this ``Style``.\"\"\" self._styled = [] \"\"\"",
"An initial style to employ. :type style: Style :param overrides: Style overrides to",
"- size: 8 - family: \"Helvetica\" ``init_fonts`` must be called to initialize this",
"``stylize`` context manager.\"\"\" class StyleableMixin: \"\"\" Mixin class used to make a widget",
"default (platform-specific) styles to revert to if an initially explicitly given style option",
"str :return: The style corresponding to the given style name or None if",
"child ``Style``s. These are signaled of any changes to this ``Style`` in ``Style._signal_style_changed``.",
"the dict with the overridden styles. (Priority 4) styles_dict.update(self._overrides) # Before we actually",
"``StyleableMixin`` objects to stop receiving updates on whenever this style changes. This should",
"overrides to use. \"\"\" super().__init__(master, cnf, *args) self._style = None \"\"\"The widget's current",
"= Listbox tk.Menu = Menu tk.PanedWindow = PanedWindow tk.Radiobutton = Radiobutton tk.Scale =",
"styles to revert to if an initially explicitly given style option is revoked.",
"self._overrides = styled if style: if self._style: self._style.unregister_styleable(self) self._style = style style.register_styleable(self) elif",
"_tkButton = tk.Button _tkCanvas = tk.Canvas _tkCheckbutton = tk.Checkbutton _tkEntry = tk.Entry _tkFrame",
"- and reasonable cross-platform named fonts. \"\"\" import tkinter as tk import tkinter.font",
"priority styles will get overridden. styles_dict = tk_defaults.copy() # Update the dict with",
"size: 10 - family: \"Helvetica\" - weight: BOLD ``init_fonts`` must be called to",
"self.get_style(k)), widget.keys()) if v is not None} def get_style(self, key): \"\"\" Return the",
"``widget.configure(...)``) to be considered for styling; any other options encountered are considered \"functional\"",
"the styles set to this widget by default so we may return #",
"styles, or replace them. :type keep_overrides: bool :param overrides: Style overrides to use.",
"\"insertborderwidth\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable version",
"del self._dict[style] self._signal_style_changed() def _signal_style_changed(self): \"\"\" Internal method to update all the ``StyleableMixin``",
"dict in ``StyleableMixin`` then all classes would share the same dictionaries). \"\"\" if",
"is False). :type style: Style :param keep_style: If ``style`` is None, setting this",
"revert to if an initially explicitly given style option is revoked. This dictionary",
"off the styles_dict with a copy of the tk_defaults, since those styles are",
"empty dict in ``StyleableMixin`` then all classes would share the same dictionaries). \"\"\"",
"None if it could not be found. \"\"\" return self._get_style(key) or self.__class__.DEFAULTS.get(key) def",
"\"\"\" FONT_SANS_SERIF_TITLE = None \"\"\" Tkinter named font with these properties: - size:",
"tk.Canvas = _tkCanvas tk.Checkbutton = _tkCheckbutton tk.Entry = _tkEntry tk.Frame = _tkFrame tk.Label",
"\"justify\"] class LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable version of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\",",
"to receive updates on whenever this style changes. This should not be called",
"FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE = tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL",
"BLUE_TEAM = \"#222299\" UNKNOWN_TEAM = GRAY_SCALE_B BOOL_TRUE = MUTE_GREEN BOOL_FALSE = MUTE_RED #",
"if ``style`` is given. :type keep_style: bool :param keep_overrides: Whether to append the",
"given styles from this ``Style``. This will raise a ``KeyError`` if any of",
":type keep_existing: bool :param defaults: A dictionary of default styles. \"\"\" cls._assure_default_dicts_exist() if",
"\"\"\"Context manager to temporarily monkey patch the tkinter widgets with their styleable equivalents.\"\"\"",
"given. :type keep_style: bool :param keep_overrides: Whether to append the given ``overrides`` to",
"fine.) There are four sources of style options and they work on a",
"of strings specifying all the widget options (i.e. the ones that would normally",
"to use. \"\"\" # Sort out the functional options from the styled ones.",
"TODO: Styleable Tk (root)? class Button(StyleableMixin, tk.Button): \"\"\"Styleable version of ``tkinter.Button``.\"\"\" STYLED_OPTS =",
"any changes made won't be taken into effect on instances of that class",
"class StyleableMixin: \"\"\" Mixin class used to make a widget \"styleable\". This class",
"styles (``Style.DEFAULTS``). :param key: The style name. :type key: str :return: The style",
"\"selectborderwidth\", \"selectforeground\"] class Frame(StyleableMixin, tk.Frame): \"\"\"Styleable version of ``tkinter.Frame``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\",",
"update_style(self): \"\"\"Update this widget's styles.\"\"\" # Alias TK_DEFAULT_STYLES for conciseness. tk_defaults = self.__class__.TK_DEFAULT_STYLES",
"it could not be found. \"\"\" return self._get_style(key) or self.__class__.DEFAULTS.get(key) def _get_style(self, key):",
"\"bg\", \"activestyle\", \"fg\", \"disabledforeground\", \"bd\", \"relief\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class",
"properties: - size: 10 - family: \"Times\" - weight: BOLD ``init_fonts`` must be",
"\"\"\" for parent in parents: parent._register_child(self) def register_styleable(self, styleable): \"\"\" Called by ``StyleableMixin``",
"be passed to ``widget.configure(...)``) to be considered for styling; any other options encountered",
"self._dict = styles \"\"\"A dictionary of the styles specific to this ``Style``.\"\"\" self._styled",
"Whether to append the given ``overrides`` to the already existing overridden styles, or",
"Label(StyleableMixin, tk.Label): \"\"\"Styleable version of ``tkinter.Label``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\",",
"this font. \"\"\" # Backup copies of \"normal\" tkinter widgets: _tkButton = tk.Button",
"Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable version of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\",",
"``Style`` and its children. \"\"\" for s in self._styled: s.update_style() for child in",
"we actually configure the widget, save any of the styles set to this",
"initially explicitly given style option is revoked. This dictionary is lazily built for",
"if it could not be found. \"\"\" ret = self._dict.get(key) if ret is",
"= p._get_style(key) if ret is not None: break return ret @classmethod def set_defaults(cls,",
"proxy for tkinter widget styles. ``StyleableMixin``s register themselves to ``Style``s so that whenever",
"= {} if cls.DEFAULT_STYLES is None: cls.DEFAULT_STYLES = {} @classmethod def set_defaults(cls, keep_existing=True,",
"this ``Style`` in ``Style._signal_style_changed``. \"\"\" for parent in parents: parent._register_child(self) def register_styleable(self, styleable):",
"tkinter widgets back to their defaults after monkey patching them with ``patch_tk_widgets``.\"\"\" tk.Button",
"def configure(self, **kwargs): \"\"\" Configure this ``Style``'s styles. :param kwargs: The styles to",
"for conciseness. tk_defaults = self.__class__.TK_DEFAULT_STYLES # Start off the styles_dict with a copy",
"for s in self._styled: s.update_style() for child in self._children: child._signal_style_changed() def get_relevant_styles(self, widget):",
"as tkfont from contextlib import contextmanager # Colour constants: GRAY_SCALE_0 = \"#000000\" GRAY_SCALE_1",
"= _tkButton tk.Canvas = _tkCanvas tk.Checkbutton = _tkCheckbutton tk.Entry = _tkEntry tk.Frame =",
"functional options self.configure(functional) if keep_overrides: self._overrides.update(styled) else: self._overrides = styled if style: if",
"if cls.TK_DEFAULT_STYLES is None: cls.TK_DEFAULT_STYLES = {} if cls.DEFAULT_STYLES is None: cls.DEFAULT_STYLES =",
"= Canvas tk.Checkbutton = Checkbutton tk.Entry = Entry tk.Frame = Frame tk.Label =",
"= tk.Listbox _tkMenu = tk.Menu _tkPanedWindow = tk.PanedWindow _tkRadiobutton = tk.Radiobutton _tkScale =",
"out the functional options from the styled ones. functional, styled = {}, {}",
"make a widget \"styleable\". This class works in cooperation with the ``Style`` class.",
"MUTE_TURQUOISE = \"#335555\" MUTE_PURPLE = \"#553377\" MUTE_PINK = \"#663366\" MUTE_ORANGE = \"#774433\" RED_TEAM",
"styling; any other options encountered are considered \"functional\" and hence won't be regulated",
"and cannot be found in said ``Style``'s own styles, the style is looked",
"self._children.append(style) # Keep the same naming scheme as tkinter. def configure(self, **kwargs): \"\"\"",
"a copy of the tk_defaults, since those styles are of lowest priority (1).",
"global style, which may be set by the stylize context # manger. self.apply_style(style",
"the styles recognized by the given tkinter widget. \"\"\" return {k: v for",
"\"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Frame(StyleableMixin, tk.Frame): \"\"\"Styleable",
"system in which a ``Style`` can have one or more parents to inherit",
"Additional args for the widget constructor. :param style: An initial style to employ.",
"default). \"\"\" DEFAULT_STYLES = None \"\"\" A dictionary of default user-defined styles for",
"instead. (Although configuring \"functional\" styles through ``widget.configure`` is perfect fine.) There are four",
"the style corresponding to the given style name, first checking this ``Style`` and",
"BOLD ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SANS_SERIF_NORMAL = None",
"\"#EEEEEE\" GRAY_SCALE_F = \"#FFFFFF\" MUTE_BLUE = \"#333355\" MUTE_GREEN = \"#335533\" MUTE_RED = \"#663333\"",
"setting this will keep the previous style. Does nothing if ``style`` is given.",
"register themselves to ``Style``s so that whenever a ``Style`` is updated, any registered",
"= defaults # TODO: Styleable Tk (root)? class Button(StyleableMixin, tk.Button): \"\"\"Styleable version of",
"args: Additional args for the widget constructor. :param style: An initial style to",
"version of these; if they were initialized to an empty dict in ``StyleableMixin``",
"manager to temporarily apply a global-level style and some overrides. This global-level style",
"this will keep the previous style. Does nothing if ``style`` is given. :type",
"version of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\",",
"name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL = tkfont.Font(root, size=8,",
"\"relief\"] class Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable version of ``tkinter.Spinbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"disabledbackground\",",
"search this widget's parents. :param key: The style name. :type key: str :return:",
"= MUTE_RED # Named fonts: FONT_MONOSPACE_TITLE = None \"\"\" Tkinter named font with",
"name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL = tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE = tkfont.Font(root, size=10,",
"tk.Button): \"\"\"Styleable version of ``tkinter.Button``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\",",
"\"highlightbackground\", \"highlightthickness\", \"relief\"] class Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable version of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS = [\"bg\",",
"styles, or replace them. :type keep_existing: bool :param defaults: A dictionary of default",
"of that class until ``StyleableMixin.update_style`` is called. \"\"\" def __init__(self, master=None, cnf={}, *args,",
"[\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Style: \"\"\" A dictionary proxy for",
"= \"#CCCCCC\" GRAY_SCALE_D = \"#DDDDDD\" GRAY_SCALE_E = \"#EEEEEE\" GRAY_SCALE_F = \"#FFFFFF\" MUTE_BLUE =",
"the style is looked for in its ancestors, prioritizing the first ones specified",
"this at runtime through ``StyleableMixin.set_defaults``, but any changes made won't be taken into",
"the given tkinter widget. \"\"\" return {k: v for k, v in map(lambda",
"keep_existing=True, **defaults): \"\"\" Convenience method to update the default styles for this class.",
"# Start off the styles_dict with a copy of the tk_defaults, since those",
"\"\"\"A global ``Style`` object used by the ``stylize`` context manager.\"\"\" class StyleableMixin: \"\"\"",
"increasing style priority so that lower priority styles will get overridden. styles_dict =",
"\"\"\" for s in self._styled: s.update_style() for child in self._children: child._signal_style_changed() def get_relevant_styles(self,",
"= None \"\"\"The widget's current ``Style``.\"\"\" self._overrides = None \"\"\"A dictionary of the",
"Toplevel def unpatch_tk_widgets(): \"\"\"Revert the tkinter widgets back to their defaults after monkey",
"\"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\"] class Canvas(StyleableMixin,",
"Remove the given styles from this ``Style``. This will raise a ``KeyError`` if",
"parents, then resorting to the global default styles (``Style.DEFAULTS``). :param key: The style",
"\"relief\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable version of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS =",
"class-specific user-provided defaults. (Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style: # Update the dict with",
"\"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Frame(StyleableMixin, tk.Frame): \"\"\"Styleable version of",
"(``Style.DEFAULTS``). :param keep_existing: Whether to keep the already existing default styles, or replace",
"None def init_fonts(root): \"\"\" Initialize all the named fonts. This must be called",
"self._styled: s.update_style() for child in self._children: child._signal_style_changed() def get_relevant_styles(self, widget): \"\"\" Determine and",
"in the constructor. When a ``Style`` is updated, all child ``Style``s of the",
"size: 10 - family: \"Times\" - weight: BOLD ``init_fonts`` must be called to",
"and ``StyleableMixin.DEFAULT_STYLES`` are defined (every class needs its own version of these; if",
"considered for styling; any other options encountered are considered \"functional\" and hence won't",
"update the dict with increasing style priority so that lower priority styles will",
"Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable version of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS = [\"bg\", \"activebackground\", \"activerelief\", \"bd\", \"elementborderwidth\",",
"version of ``tkinter.Listbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activestyle\", \"fg\", \"disabledforeground\", \"bd\", \"relief\", \"highlightcolor\",",
"these properties: - size: 8 - family: \"Times\" ``init_fonts`` must be called to",
"# Update the dict with the overridden styles. (Priority 4) styles_dict.update(self._overrides) # Before",
"widgets back to their defaults after monkey patching them with ``patch_tk_widgets``.\"\"\" tk.Button =",
"patch the tkinter widgets with their styleable equivalents.\"\"\" tk.Button = Button tk.Canvas =",
"given class. Subclasses may define this. One may also set this at runtime",
"_tkMenu = tk.Menu _tkPanedWindow = tk.PanedWindow _tkRadiobutton = tk.Radiobutton _tkScale = tk.Scale _tkScrollbar",
"\"\"\" Tkinter named font with these properties: - size: 10 - family: \"Times\"",
"named fonts. :param root: The tkinter root widget. :type root: tkinter.Tk \"\"\" global",
"tk.Listbox): \"\"\"Styleable version of ``tkinter.Listbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activestyle\", \"fg\", \"disabledforeground\", \"bd\",",
"yield finally: _global_style = None def init_fonts(root): \"\"\" Initialize all the named fonts.",
"_tkMenu tk.PanedWindow = _tkPanedWindow tk.Radiobutton = _tkRadiobutton tk.Scale = _tkScale tk.Scrollbar = _tkScrollbar",
"have one or more parents to inherit styles from. When a style is",
"tk.LabelFrame _tkListbox = tk.Listbox _tkMenu = tk.Menu _tkPanedWindow = tk.PanedWindow _tkRadiobutton = tk.Radiobutton",
"to inherit styles from. When a style is requested from a ``Style`` and",
"with their styleable equivalents.\"\"\" try: patch_tk_widgets() yield finally: unpatch_tk_widgets() @contextmanager def stylize(style, **overrides):",
"for a given class. Subclasses may define this. One may also set this",
"A dictionary of default user-defined styles for a given class. Subclasses may define",
"version of ``tkinter.Text``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"insertbackground\", \"insertborderwidth\", \"highlightcolor\", \"highlightbackground\",",
"widget.keys()) if v is not None} def get_style(self, key): \"\"\" Return the style",
"\"indicatoron\", \"offrelief\", \"selectcolor\"] class Scale(StyleableMixin, tk.Scale): \"\"\"Styleable version of ``tkinter.Scale``.\"\"\" STYLED_OPTS = [\"font\",",
"Style names to remove. \"\"\" for style in styles: del self._dict[style] self._signal_style_changed() def",
"self._signal_style_changed() config = configure \"\"\"Alias for ``Style.configure``.\"\"\" def remove_styles(self, *styles): \"\"\" Remove the",
"get overridden. styles_dict = tk_defaults.copy() # Update the dict with the class-specific user-provided",
"tkinter.font as tkfont from contextlib import contextmanager # Colour constants: GRAY_SCALE_0 = \"#000000\"",
"called to initialize this font. \"\"\" FONT_SERIF_TITLE = None \"\"\" Tkinter named font",
"{} for k, v in overrides.items(): if k in self.STYLED_OPTS: styled[k] = v",
"STYLED_OPTS = [\"bg\", \"bd\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Checkbutton(StyleableMixin,",
"Canvas tk.Checkbutton = Checkbutton tk.Entry = Entry tk.Frame = Frame tk.Label = Label",
"(1). We # will update the dict with increasing style priority so that",
"by the ``stylize`` context manager.\"\"\" class StyleableMixin: \"\"\" Mixin class used to make",
"overridden styles, or replace them. :type keep_overrides: bool :param overrides: Style overrides to",
"styled if style: if self._style: self._style.unregister_styleable(self) self._style = style style.register_styleable(self) elif self._style and",
"those styles are of lowest priority (1). We # will update the dict",
"def register_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to receive updates on whenever",
"is not already registered. self._styled.remove(styleable) def _register_child(self, style): \"\"\" Called by child ``Style``s",
"``Style``. :param styles: Style names to remove. \"\"\" for style in styles: del",
"get_relevant_styles(self, widget): \"\"\" Determine and return all the styles in this ``Style`` recognized",
"patch_tk_widgets() yield finally: unpatch_tk_widgets() @contextmanager def stylize(style, **overrides): \"\"\" Context manager to temporarily",
"LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable version of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"highlightcolor\",",
"s in self._styled: s.update_style() for child in self._children: child._signal_style_changed() def get_relevant_styles(self, widget): \"\"\"",
"``tkinter.Frame``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Label(StyleableMixin, tk.Label): \"\"\"Styleable",
"\"selectborderwidth\", \"selectforeground\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable version of ``tkinter.Checkbutton``.\"\"\"",
"version of ``tkinter.Canvas``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"_tkCheckbutton tk.Entry = _tkEntry tk.Frame = _tkFrame tk.Label = _tkLabel tk.LabelFrame = _tkLabelFrame",
"= [] \"\"\" A list of registered ``StyleableMixin``s. These are signaled of any",
"styling utilities for tkinter widgets. Some features include: - a hierarchical styling system",
"return self._get_style(key) or self.__class__.DEFAULTS.get(key) def _get_style(self, key): \"\"\" Attempt to retrieve the given",
"\"\"\"Styleable version of ``tkinter.Canvas``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"highlightcolor\", \"highlightbackground\",",
"if ret is None: for p in self._parents: ret = p._get_style(key) if ret",
"must be called to initialize this font. \"\"\" FONT_SERIF_NORMAL = None \"\"\" Tkinter",
"of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS = [\"bg\", \"activebackground\", \"activerelief\", \"bd\", \"elementborderwidth\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"def stylize(style, **overrides): \"\"\" Context manager to temporarily apply a global-level style and",
"would share the same dictionaries). \"\"\" if cls.TK_DEFAULT_STYLES is None: cls.TK_DEFAULT_STYLES = {}",
"initialize this font. \"\"\" FONT_SANS_SERIF_TITLE = None \"\"\" Tkinter named font with these",
"= GRAY_SCALE_B BOOL_TRUE = MUTE_GREEN BOOL_FALSE = MUTE_RED # Named fonts: FONT_MONOSPACE_TITLE =",
"widgets. Some features include: - a hierarchical styling system for the non-ttk widgets;",
"in ``Style._signal_style_changed``. \"\"\" self._parents = parents \"\"\"A list of this ``Style``'s parent ``Style``s.\"\"\"",
"with the overridden styles. (Priority 4) styles_dict.update(self._overrides) # Before we actually configure the",
"in self._styled: s.update_style() for child in self._children: child._signal_style_changed() def get_relevant_styles(self, widget): \"\"\" Determine",
"\"relief\"] class Label(StyleableMixin, tk.Label): \"\"\"Styleable version of ``tkinter.Label``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\",",
"the same naming scheme as tkinter. def configure(self, **kwargs): \"\"\" Configure this ``Style``'s",
"root: The tkinter root widget. :type root: tkinter.Tk \"\"\" global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE,",
"GRAY_SCALE_1 = \"#111111\" GRAY_SCALE_2 = \"#222222\" GRAY_SCALE_3 = \"#333333\" GRAY_SCALE_4 = \"#444444\" GRAY_SCALE_5",
"\"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\"] class Canvas(StyleableMixin, tk.Canvas): \"\"\"Styleable version of ``tkinter.Canvas``.\"\"\" STYLED_OPTS",
"any registered ``StyleableMixin``s are automatically updated to reflect the changes. ``Style``s employ a",
":param defaults: A dictionary of styles. \"\"\" if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS =",
"The tkinter root widget. :type root: tkinter.Tk \"\"\" global FONT_MONOSPACE_TITLE, FONT_MONOSPACE_NORMAL,\\ FONT_SERIF_TITLE, FONT_SERIF_NORMAL,\\",
"\"readonlybackground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\",",
"_tkScale = tk.Scale _tkScrollbar = tk.Scrollbar _tkSpinbox = tk.Spinbox _tkText = tk.Text _tkToplevel",
"\"\"\"Styleable version of ``tkinter.Label``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\",",
"The styles to add/edit. \"\"\" self._dict.update(kwargs) self._signal_style_changed() config = configure \"\"\"Alias for ``Style.configure``.\"\"\"",
"given overrides. :param style: The style to employ, or None to clear the",
"``Style`` can have one or more parents to inherit styles from. When a",
"``StyleableMixin.set_defaults``, but any changes made won't be taken into effect on instances of",
"all the ``StyleableMixin`` widgets registered to this ``Style`` and its children. \"\"\" for",
"receiving updates on whenever this style changes. This should not be called by",
"style in styles: del self._dict[style] self._signal_style_changed() def _signal_style_changed(self): \"\"\" Internal method to update",
"widgets with their styleable equivalents.\"\"\" tk.Button = Button tk.Canvas = Canvas tk.Checkbutton =",
"None \"\"\" A dictionary of default (platform-specific) styles to revert to if an",
"\"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Menu(StyleableMixin, tk.Menu): \"\"\"Styleable version of ``tkinter.Menu``.\"\"\" STYLED_OPTS = [\"font\",",
"the dict with increasing style priority so that lower priority styles will get",
"first checking this ``Style`` and its parents, then resorting to the global default",
"\"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\"] class",
"monkey patch the tkinter widgets with their styleable equivalents.\"\"\" try: patch_tk_widgets() yield finally:",
"Frame(StyleableMixin, tk.Frame): \"\"\"Styleable version of ``tkinter.Frame``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"to reflect the changes. ``Style``s employ a parent-child system in which a ``Style``",
"this ``Style``. :param styles: Style names to remove. \"\"\" for style in styles:",
"``Style._signal_style_changed``. \"\"\" self._parents = parents \"\"\"A list of this ``Style``'s parent ``Style``s.\"\"\" self._children",
"Internal method to update all the ``StyleableMixin`` widgets registered to this ``Style`` and",
"cannot be found in said ``Style``'s own styles, the style is looked for",
"8 - family: \"Helvetica\" ``init_fonts`` must be called to initialize this font. \"\"\"",
"``init_fonts`` must be called to initialize this font. \"\"\" FONT_SERIF_TITLE = None \"\"\"",
"``Style.set_defaults``.\"\"\" def __init__(self, *parents, **styles): \"\"\" :param parents: ``Style``s to inherit styles from.",
"fails, recursively search this widget's parents. :param key: The style name. :type key:",
"by the given tkinter widget. :param widget: The tkinter widget to find styles",
"If ``style`` is None, setting this will keep the previous style. Does nothing",
"= \"#335533\" MUTE_RED = \"#663333\" MUTE_YELLOW = \"#888833\" MUTE_TURQUOISE = \"#335555\" MUTE_PURPLE =",
"\"\"\" for style in styles: del self._dict[style] self._signal_style_changed() def _signal_style_changed(self): \"\"\" Internal method",
"_tkRadiobutton = tk.Radiobutton _tkScale = tk.Scale _tkScrollbar = tk.Scrollbar _tkSpinbox = tk.Spinbox _tkText",
"is None: for p in self._parents: ret = p._get_style(key) if ret is not",
"\"\"\"Alias for ``Style.configure``.\"\"\" def remove_styles(self, *styles): \"\"\" Remove the given styles from this",
"styleable equivalents.\"\"\" tk.Button = Button tk.Canvas = Canvas tk.Checkbutton = Checkbutton tk.Entry =",
"updated, any registered ``StyleableMixin``s are automatically updated to reflect the changes. ``Style``s employ",
"by default so we may return # to them if an explicit style",
"\"#777777\" GRAY_SCALE_8 = \"#888888\" GRAY_SCALE_9 = \"#999999\" GRAY_SCALE_A = \"#AAAAAA\" GRAY_SCALE_B = \"#BBBBBB\"",
"passed to ``widget.configure(...)``) to be considered for styling; any other options encountered are",
"k in self.STYLED_OPTS: styled[k] = v else: functional[k] = v # Directly apply",
"with the ``Style`` class. Styleable widgets should never use their ``widget.configure`` method to",
"``tkinter.Radiobutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"\"selectcolor\", \"relief\", \"activeborderwidth\"] class PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable version of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS = [\"bg\",",
"of style options and they work on a priority system (higher number means",
"STYLED_OPTS = [\"bg\", \"bd\", \"relief\", \"sashrelief\", \"showhandle\"] class Radiobutton(StyleableMixin, tk.Radiobutton): \"\"\"Styleable version of",
"widget's current ``Style``.\"\"\" self._overrides = None \"\"\"A dictionary of the widget's currently-overridden styles.\"\"\"",
"tk.Text): \"\"\"Styleable version of ``tkinter.Text``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"insertbackground\", \"insertborderwidth\",",
"This dictionary is lazily built for each unique styled class (i.e. a style",
"with increasing style priority so that lower priority styles will get overridden. styles_dict",
"them. :type keep_existing: bool :param defaults: A dictionary of default styles. \"\"\" cls._assure_default_dicts_exist()",
"version of ``tkinter.LabelFrame``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\",",
"defaults: A dictionary of styles. \"\"\" if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults",
"widget, save any of the styles set to this widget by default so",
"dict :param args: Additional args for the widget constructor. :param style: An initial",
"monkey patching them with ``patch_tk_widgets``.\"\"\" tk.Button = _tkButton tk.Canvas = _tkCanvas tk.Checkbutton =",
"styles in this ``Style`` recognized by the given tkinter widget. :param widget: The",
"\"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\",",
"to this dictionary the first time it changes from its default). \"\"\" DEFAULT_STYLES",
"A list of registered child ``Style``s. These are signaled of any changes to",
"\"#553377\" MUTE_PINK = \"#663366\" MUTE_ORANGE = \"#774433\" RED_TEAM = \"#992222\" BLUE_TEAM = \"#222299\"",
"Convenience method to update the default styles for this class. :param keep_existing: Whether",
"widget is removed. tk_defaults.update((k, self.cget(k)) for k in styles_dict if k not in",
"These are signaled of any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" for",
"styles for a given class. Subclasses may define this. One may also set",
"styles, the style is looked for in its ancestors, prioritizing the first ones",
"to this ``Style`` in ``Style._signal_style_changed``. \"\"\" for parent in parents: parent._register_child(self) def register_styleable(self,",
"= _tkCanvas tk.Checkbutton = _tkCheckbutton tk.Entry = _tkEntry tk.Frame = _tkFrame tk.Label =",
"**styles): \"\"\" :param parents: ``Style``s to inherit styles from. :param styles: Styles to",
"``Style`` are recursively informed of the change. \"\"\" DEFAULTS = {} \"\"\"Global default",
"STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"bd\", \"showvalue\", \"sliderrelief\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"given style from this ``Style``'s ``Style._dict``. If that fails, recursively search this widget's",
"Tkinter named font with these properties: - size: 8 - family: \"Times\" ``init_fonts``",
"to temporarily apply a global-level style and some overrides. This global-level style will",
"styled ones. functional, styled = {}, {} for k, v in overrides.items(): if",
"= self.__class__.TK_DEFAULT_STYLES # Start off the styles_dict with a copy of the tk_defaults,",
"= _tkEntry tk.Frame = _tkFrame tk.Label = _tkLabel tk.LabelFrame = _tkLabelFrame tk.Listbox =",
"\"\"\" ret = self._dict.get(key) if ret is None: for p in self._parents: ret",
"set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update the global default styles (``Style.DEFAULTS``).",
"\"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Style: \"\"\" A dictionary proxy for tkinter",
"names to remove. \"\"\" for style in styles: del self._dict[style] self._signal_style_changed() def _signal_style_changed(self):",
"options (i.e. the ones that would normally be passed to ``widget.configure(...)``) to be",
"STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Label(StyleableMixin, tk.Label): \"\"\"Styleable version",
"``patch_tk_widgets``.\"\"\" tk.Button = _tkButton tk.Canvas = _tkCanvas tk.Checkbutton = _tkCheckbutton tk.Entry = _tkEntry",
"hence won't be regulated in any way by this class. Subclasses should define",
"the already existing default styles, or replace them. :type keep_existing: bool :param defaults:",
"of ``tkinter.Scale``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"bd\", \"showvalue\", \"sliderrelief\", \"troughcolor\", \"highlightcolor\",",
"= configure \"\"\"Alias for ``Style.configure``.\"\"\" def remove_styles(self, *styles): \"\"\" Remove the given styles",
"styled[k] = v else: functional[k] = v # Directly apply the functional options",
"\"fg\", \"bd\", \"showvalue\", \"sliderrelief\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Scrollbar(StyleableMixin, tk.Scrollbar): \"\"\"Styleable",
"= \"#EEEEEE\" GRAY_SCALE_F = \"#FFFFFF\" MUTE_BLUE = \"#333355\" MUTE_GREEN = \"#335533\" MUTE_RED =",
"their ``widget.configure`` method to set styles in their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should be used",
"constructor. When a ``Style`` is updated, all child ``Style``s of the changed ``Style``",
"\"\"\" FONT_SERIF_NORMAL = None \"\"\" Tkinter named font with these properties: - size:",
"is not None} def get_style(self, key): \"\"\" Return the style corresponding to the",
"to ``widget.configure(...)``) to be considered for styling; any other options encountered are considered",
"these properties: - size: 10 - family: \"Helvetica\" - weight: BOLD ``init_fonts`` must",
"may be set by the stylize context # manger. self.apply_style(style or _global_style, **overrides)",
"be used by ``StyleableMixin``s if they're not explicitly given a ``Style`` object already.",
"for the non-ttk widgets; - a collection of colour constants; - and reasonable",
"this font. \"\"\" FONT_SANS_SERIF_NORMAL = None \"\"\" Tkinter named font with these properties:",
"unregister_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to stop receiving updates on whenever",
"class. Subclasses may define this. One may also set this at runtime through",
"\"selectforeground\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Checkbutton(StyleableMixin, tk.Checkbutton): \"\"\"Styleable version of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS",
"_global_style = Style(style, **overrides) if overrides else style yield finally: _global_style = None",
"\"highlightthickness\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Menu(StyleableMixin, tk.Menu): \"\"\"Styleable version of ``tkinter.Menu``.\"\"\" STYLED_OPTS =",
"Return the style corresponding to the given style name, first checking this ``Style``",
"tk import tkinter.font as tkfont from contextlib import contextmanager # Colour constants: GRAY_SCALE_0",
"style options and they work on a priority system (higher number means higher",
"\"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"] class Text(StyleableMixin, tk.Text): \"\"\"Styleable version of ``tkinter.Text``.\"\"\" STYLED_OPTS",
"``StyleableMixin.DEFAULT_STYLES`` 3. A given ``Style`` instance 4. A given dictionary of overrides \"\"\"",
"``Style``. This will raise a ``KeyError`` if any of the given style names",
"\"insertborderwidth\"] class Text(StyleableMixin, tk.Text): \"\"\"Styleable version of ``tkinter.Text``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\",",
":type style: Style :param overrides: Style overrides to use. \"\"\" global _global_style try:",
"key: str :return: The style corresponding to the given style name or None",
"\"highlightbackground\", \"highlightthickness\", \"relief\", \"labelanchor\"] class Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable version of ``tkinter.Listbox``.\"\"\" STYLED_OPTS =",
"\"\"\"A list of this ``Style``'s parent ``Style``s.\"\"\" self._children = [] \"\"\" A list",
"from this ``Style``. This will raise a ``KeyError`` if any of the given",
"**overrides): \"\"\" :param master: The master tkinter widget. :param cnf: A dictionary of",
"needs its own version of these; if they were initialized to an empty",
"update all the ``StyleableMixin`` widgets registered to this ``Style`` and its children. \"\"\"",
"\"offrelief\", \"selectcolor\"] class Entry(StyleableMixin, tk.Entry): \"\"\"Styleable version of ``tkinter.Entry``.\"\"\" STYLED_OPTS = [\"font\", \"bg\",",
"master=None, cnf={}, *args, style=None, **overrides): \"\"\" :param master: The master tkinter widget. :param",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Frame(StyleableMixin, tk.Frame): \"\"\"Styleable version",
"``Style._dict``. If that fails, recursively search this widget's parents. :param key: The style",
"This global-level style will only be used by ``StyleableMixin``s if they're not explicitly",
":param kwargs: The styles to add/edit. \"\"\" self._dict.update(kwargs) self._signal_style_changed() config = configure \"\"\"Alias",
"{k: v for k, v in map(lambda k: (k, self.get_style(k)), widget.keys()) if v",
"dictionary of styles. \"\"\" if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults def patch_tk_widgets():",
"= tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SANS_SERIF_TITLE\", family=\"Helvetica\", weight=tkfont.BOLD) FONT_SANS_SERIF_NORMAL",
"the given style or the global style, which may be set by the",
"manager.\"\"\" class StyleableMixin: \"\"\" Mixin class used to make a widget \"styleable\". This",
"\"highlightbackground\", \"highlightthickness\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Menu(StyleableMixin, tk.Menu): \"\"\"Styleable version of ``tkinter.Menu``.\"\"\" STYLED_OPTS",
"A dictionary of default styles. \"\"\" cls._assure_default_dicts_exist() if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS =",
"\"\"\" A dictionary proxy for tkinter widget styles. ``StyleableMixin``s register themselves to ``Style``s",
"this dictionary the first time it changes from its default). \"\"\" DEFAULT_STYLES =",
"A dictionary of styles. \"\"\" if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults def",
"dictionaries). \"\"\" if cls.TK_DEFAULT_STYLES is None: cls.TK_DEFAULT_STYLES = {} if cls.DEFAULT_STYLES is None:",
"on whenever this style changes. :param style: The child ``Style``. :type style: Style",
"will only be used by ``StyleableMixin``s if they're not explicitly given a ``Style``",
"styleable is not already registered. self._styled.remove(styleable) def _register_child(self, style): \"\"\" Called by child",
"self._assure_default_dicts_exist() # Initialize the widget's style to the given style or the global",
"the tkinter widgets with their styleable equivalents.\"\"\" try: patch_tk_widgets() yield finally: unpatch_tk_widgets() @contextmanager",
"an empty dict in ``StyleableMixin`` then all classes would share the same dictionaries).",
"``Style``s.\"\"\" self._children = [] \"\"\" A list of registered child ``Style``s. These are",
"system for the non-ttk widgets; - a collection of colour constants; - and",
"encountered are considered \"functional\" and hence won't be regulated in any way by",
"receive updates on whenever this style changes. :param style: The child ``Style``. :type",
"were initialized to an empty dict in ``StyleableMixin`` then all classes would share",
"``Style._signal_style_changed``. \"\"\" for parent in parents: parent._register_child(self) def register_styleable(self, styleable): \"\"\" Called by",
"dict with the styles from the Style object. (Priority 3) styles_dict.update(self._style.get_relevant_styles(self)) # Update",
"if cls.DEFAULT_STYLES is None: cls.DEFAULT_STYLES = {} @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\"",
"is None: cls.DEFAULT_STYLES = {} @classmethod def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method",
"MUTE_PINK = \"#663366\" MUTE_ORANGE = \"#774433\" RED_TEAM = \"#992222\" BLUE_TEAM = \"#222299\" UNKNOWN_TEAM",
"# manger. self.apply_style(style or _global_style, **overrides) def apply_style(self, style=None, *, keep_style=False, keep_overrides=False, **overrides):",
"(i.e. the ones that would normally be passed to ``widget.configure(...)``) to be considered",
"styles_dict with a copy of the tk_defaults, since those styles are of lowest",
"some overrides. This global-level style will only be used by ``StyleableMixin``s if they're",
"\"buttondownrelief\", \"buttonuprelief\", \"insertbackground\", \"insertborderwidth\"] class Text(StyleableMixin, tk.Text): \"\"\"Styleable version of ``tkinter.Text``.\"\"\" STYLED_OPTS =",
"MUTE_RED # Named fonts: FONT_MONOSPACE_TITLE = None \"\"\" Tkinter named font with these",
"all the styles in this ``Style`` recognized by the given tkinter widget. :param",
"\"\"\" Attempt to retrieve the given style from this ``Style``'s ``Style._dict``. If that",
"= Text tk.Toplevel = Toplevel def unpatch_tk_widgets(): \"\"\"Revert the tkinter widgets back to",
"that class until ``StyleableMixin.update_style`` is called. \"\"\" def __init__(self, master=None, cnf={}, *args, style=None,",
"changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" for parent in parents: parent._register_child(self) def",
"[\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Label(StyleableMixin, tk.Label): \"\"\"Styleable version of ``tkinter.Label``.\"\"\"",
"_tkFrame tk.Label = _tkLabel tk.LabelFrame = _tkLabelFrame tk.Listbox = _tkListbox tk.Menu = _tkMenu",
"else: functional[k] = v # Directly apply the functional options self.configure(functional) if keep_overrides:",
"\"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"selectcolor\", \"relief\", \"activeborderwidth\"] class PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable version of",
"Configure this ``Style``'s styles. :param kwargs: The styles to add/edit. \"\"\" self._dict.update(kwargs) self._signal_style_changed()",
"that this class's ``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES`` are defined (every class needs its own",
"``Style``s of the changed ``Style`` are recursively informed of the change. \"\"\" DEFAULTS",
"MUTE_BLUE = \"#333355\" MUTE_GREEN = \"#335533\" MUTE_RED = \"#663333\" MUTE_YELLOW = \"#888833\" MUTE_TURQUOISE",
"Style :param keep_style: If ``style`` is None, setting this will keep the previous",
"overrides: Style overrides to use. \"\"\" # Sort out the functional options from",
"this class. :param keep_existing: Whether to keep the already existing default styles, or",
"of this ``Style``'s parent ``Style``s.\"\"\" self._children = [] \"\"\" A list of registered",
"family: \"Helvetica\" - weight: BOLD ``init_fonts`` must be called to initialize this font.",
"\"bg\", \"activebackground\", \"fg\", \"bd\", \"showvalue\", \"sliderrelief\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Scrollbar(StyleableMixin,",
"keep the already existing default styles, or replace them. :type keep_existing: bool :param",
"to keep the already existing default styles, or replace them. :type keep_existing: bool",
"family: \"Times\" ``init_fonts`` must be called to initialize this font. \"\"\" FONT_SANS_SERIF_TITLE =",
"\"\"\" if cls.TK_DEFAULT_STYLES is None: cls.TK_DEFAULT_STYLES = {} if cls.DEFAULT_STYLES is None: cls.DEFAULT_STYLES",
"\"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Label(StyleableMixin, tk.Label): \"\"\"Styleable version of ``tkinter.Label``.\"\"\" STYLED_OPTS =",
"yield finally: unpatch_tk_widgets() @contextmanager def stylize(style, **overrides): \"\"\" Context manager to temporarily apply",
"the tk_defaults, since those styles are of lowest priority (1). We # will",
"FONT_MONOSPACE_TITLE = None \"\"\" Tkinter named font with these properties: - size: 10",
"size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE = tkfont.Font(root,",
"user-provided defaults. (Priority 2) styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style: # Update the dict with the",
"(higher number means higher priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES`` 2. ``StyleableMixin.DEFAULT_STYLES`` 3. A given ``Style``",
"= [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"selectcolor\", \"relief\", \"activeborderwidth\"] class PanedWindow(StyleableMixin,",
"registered. self._styled.remove(styleable) def _register_child(self, style): \"\"\" Called by child ``Style``s to receive updates",
"of default styles. \"\"\" cls._assure_default_dicts_exist() if keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults #",
"_signal_style_changed(self): \"\"\" Internal method to update all the ``StyleableMixin`` widgets registered to this",
"``tkinter.Button``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"all ``Style`` objects. This should be set through ``Style.set_defaults``.\"\"\" def __init__(self, *parents, **styles):",
"given tkinter widget. \"\"\" return {k: v for k, v in map(lambda k:",
"widget. \"\"\" return {k: v for k, v in map(lambda k: (k, self.get_style(k)),",
"key): \"\"\" Attempt to retrieve the given style from this ``Style``'s ``Style._dict``. If",
"Convenience method to update the global default styles (``Style.DEFAULTS``). :param keep_existing: Whether to",
"self._style and not keep_style: self._style.unregister_styleable(self) self._style = None self.update_style() def update_style(self): \"\"\"Update this",
"self._styled = [] \"\"\" A list of registered ``StyleableMixin``s. These are signaled of",
"``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES`` are defined (every class needs its own version of these;",
"a hierarchical styling system for the non-ttk widgets; - a collection of colour",
"style corresponding to the given style name or None if it could not",
"v is not None} def get_style(self, key): \"\"\" Return the style corresponding to",
"be called by user code. :param styleable: The styleable widget to unregister. :type",
":param parents: ``Style``s to inherit styles from. :param styles: Styles to use. \"\"\"",
"its children. \"\"\" for s in self._styled: s.update_style() for child in self._children: child._signal_style_changed()",
"Scale(StyleableMixin, tk.Scale): \"\"\"Styleable version of ``tkinter.Scale``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"bd\",",
"but any changes made won't be taken into effect on instances of that",
"sure that this class's ``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES`` are defined (every class needs its",
"A list of registered ``StyleableMixin``s. These are signaled of any changes to this",
"This should be set through ``Style.set_defaults``.\"\"\" def __init__(self, *parents, **styles): \"\"\" :param parents:",
"is updated, all child ``Style``s of the changed ``Style`` are recursively informed of",
"of the change. \"\"\" DEFAULTS = {} \"\"\"Global default styles for all ``Style``",
"dict with increasing style priority so that lower priority styles will get overridden.",
"return # to them if an explicit style option on this widget is",
"the given style with the given overrides. :param style: The style to employ,",
"\"\"\"Styleable version of ``tkinter.Scrollbar``.\"\"\" STYLED_OPTS = [\"bg\", \"activebackground\", \"activerelief\", \"bd\", \"elementborderwidth\", \"troughcolor\", \"highlightcolor\",",
"to update the global default styles (``Style.DEFAULTS``). :param keep_existing: Whether to keep the",
"name or None if it could not be found. \"\"\" ret = self._dict.get(key)",
"styles to add/edit. \"\"\" self._dict.update(kwargs) self._signal_style_changed() config = configure \"\"\"Alias for ``Style.configure``.\"\"\" def",
"(k, self.get_style(k)), widget.keys()) if v is not None} def get_style(self, key): \"\"\" Return",
"resorting to the global default styles (``Style.DEFAULTS``). :param key: The style name. :type",
"the already existing overridden styles, or replace them. :type keep_overrides: bool :param overrides:",
"style and some overrides. This global-level style will only be used by ``StyleableMixin``s",
"they work on a priority system (higher number means higher priority): 1. ``StyleableMixin.TK_DEFAULT_STYLES``",
"Style: \"\"\" A dictionary proxy for tkinter widget styles. ``StyleableMixin``s register themselves to",
"TK_DEFAULT_STYLES = None \"\"\" A dictionary of default (platform-specific) styles to revert to",
"the given style from this ``Style``'s ``Style._dict``. If that fails, recursively search this",
"= None def init_fonts(root): \"\"\" Initialize all the named fonts. This must be",
"options and they work on a priority system (higher number means higher priority):",
"def update_style(self): \"\"\"Update this widget's styles.\"\"\" # Alias TK_DEFAULT_STYLES for conciseness. tk_defaults =",
"from contextlib import contextmanager # Colour constants: GRAY_SCALE_0 = \"#000000\" GRAY_SCALE_1 = \"#111111\"",
":param styleable: The styleable widget to register. :type styleable: StyleableMixin \"\"\" self._styled.append(styleable) def",
"``KeyError`` if any of the given style names are not in this ``Style``.",
"the ones that would normally be passed to ``widget.configure(...)``) to be considered for",
"- size: 10 - family: \"Times\" - weight: BOLD ``init_fonts`` must be called",
"\"bg\", \"fg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"labelanchor\"] class Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable version",
"options. This is here to mimic the tkinter widget constructors. :type cnf: dict",
"parent in parents: parent._register_child(self) def register_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to",
"else style yield finally: _global_style = None def init_fonts(root): \"\"\" Initialize all the",
"Subclasses should define this. \"\"\" TK_DEFAULT_STYLES = None \"\"\" A dictionary of default",
"= \"#992222\" BLUE_TEAM = \"#222299\" UNKNOWN_TEAM = GRAY_SCALE_B BOOL_TRUE = MUTE_GREEN BOOL_FALSE =",
"equivalents.\"\"\" try: patch_tk_widgets() yield finally: unpatch_tk_widgets() @contextmanager def stylize(style, **overrides): \"\"\" Context manager",
"by user code. :param styleable: The styleable widget to register. :type styleable: StyleableMixin",
"\"bd\", \"selectcolor\", \"relief\", \"activeborderwidth\"] class PanedWindow(StyleableMixin, tk.PanedWindow): \"\"\"Styleable version of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS =",
"= [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\",",
"of the styles set to this widget by default so we may return",
"The style name. :type key: str :return: The style corresponding to the given",
"None} def get_style(self, key): \"\"\" Return the style corresponding to the given style",
"STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"selectcolor\", \"relief\", \"activeborderwidth\"] class",
"for in its ancestors, prioritizing the first ones specified in the constructor. When",
"to add/edit. \"\"\" self._dict.update(kwargs) self._signal_style_changed() config = configure \"\"\"Alias for ``Style.configure``.\"\"\" def remove_styles(self,",
"this ``Style``'s ``Style._dict``. If that fails, recursively search this widget's parents. :param key:",
"use any of the named fonts. :param root: The tkinter root widget. :type",
"= {}, {} for k, v in overrides.items(): if k in self.STYLED_OPTS: styled[k]",
"= tk_defaults.copy() # Update the dict with the class-specific user-provided defaults. (Priority 2)",
"self.configure(functional) if keep_overrides: self._overrides.update(styled) else: self._overrides = styled if style: if self._style: self._style.unregister_styleable(self)",
"to initialize this font. \"\"\" FONT_SERIF_NORMAL = None \"\"\" Tkinter named font with",
"copy of the tk_defaults, since those styles are of lowest priority (1). We",
"child ``Style``s to receive updates on whenever this style changes. :param style: The",
"global default styles (``Style.DEFAULTS``). :param keep_existing: Whether to keep the already existing default",
"tkfont from contextlib import contextmanager # Colour constants: GRAY_SCALE_0 = \"#000000\" GRAY_SCALE_1 =",
"Apply the given style with the given overrides. :param style: The style to",
"object used by the ``stylize`` context manager.\"\"\" class StyleableMixin: \"\"\" Mixin class used",
"parent ``Style``s.\"\"\" self._children = [] \"\"\" A list of registered child ``Style``s. These",
"def _signal_style_changed(self): \"\"\" Internal method to update all the ``StyleableMixin`` widgets registered to",
"corresponding to the given style name or None if it could not be",
"user code. :param styleable: The styleable widget to register. :type styleable: StyleableMixin \"\"\"",
"``Style`` instance 4. A given dictionary of overrides \"\"\" STYLED_OPTS = [] \"\"\"",
"with a copy of the tk_defaults, since those styles are of lowest priority",
"to initialize this font. \"\"\" FONT_MONOSPACE_NORMAL = None \"\"\" Tkinter named font with",
"def set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update the default styles for",
"any way by this class. Subclasses should define this. \"\"\" TK_DEFAULT_STYLES = None",
"size=8, name=\"FONT_SERIF_NORMAL\", family=\"Times\") FONT_SANS_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SANS_SERIF_TITLE\", family=\"Helvetica\", weight=tkfont.BOLD) FONT_SANS_SERIF_NORMAL = tkfont.Font(root,",
"ones. functional, styled = {}, {} for k, v in overrides.items(): if k",
"more parents to inherit styles from. When a style is requested from a",
"(every class needs its own version of these; if they were initialized to",
"to initialize this font. \"\"\" FONT_SANS_SERIF_TITLE = None \"\"\" Tkinter named font with",
"the overridden styles. (Priority 4) styles_dict.update(self._overrides) # Before we actually configure the widget,",
"the widget constructor. :param style: An initial style to employ. :type style: Style",
"and its parents, then resorting to the global default styles (``Style.DEFAULTS``). :param key:",
"called prior to attempting to use any of the named fonts. :param root:",
"a given class. Subclasses may define this. One may also set this at",
"tk.Toplevel _global_style = None \"\"\"A global ``Style`` object used by the ``stylize`` context",
"\"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Frame(StyleableMixin, tk.Frame): \"\"\"Styleable version of ``tkinter.Frame``.\"\"\"",
"dictionary of default user-defined styles for a given class. Subclasses may define this.",
"never use their ``widget.configure`` method to set styles in their ``StyleableMixin.STYLED_OPTS``; ``StyleableMixin.apply_style`` should",
"is None: cls.TK_DEFAULT_STYLES = {} if cls.DEFAULT_STYLES is None: cls.DEFAULT_STYLES = {} @classmethod",
"changes from its default). \"\"\" DEFAULT_STYLES = None \"\"\" A dictionary of default",
"``tkinter.Checkbutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\",",
"``style`` is given. :type keep_style: bool :param keep_overrides: Whether to append the given",
"``init_fonts`` must be called to initialize this font. \"\"\" FONT_SANS_SERIF_TITLE = None \"\"\"",
"given style option is revoked. This dictionary is lazily built for each unique",
"style=None, **overrides): \"\"\" :param master: The master tkinter widget. :param cnf: A dictionary",
"\"labelanchor\"] class Listbox(StyleableMixin, tk.Listbox): \"\"\"Styleable version of ``tkinter.Listbox``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activestyle\",",
"class Style: \"\"\" A dictionary proxy for tkinter widget styles. ``StyleableMixin``s register themselves",
"style style.register_styleable(self) elif self._style and not keep_style: self._style.unregister_styleable(self) self._style = None self.update_style() def",
"\"bd\", \"elementborderwidth\", \"troughcolor\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Spinbox(StyleableMixin, tk.Spinbox): \"\"\"Styleable version of",
"The styleable widget to unregister. :type styleable: StyleableMixin \"\"\" # This will raise",
"each unique styled class (i.e. a style is added to this dictionary the",
"\"selectforeground\"] class Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable version of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\",",
"widget constructors. :type cnf: dict :param args: Additional args for the widget constructor.",
"\"functional\" and hence won't be regulated in any way by this class. Subclasses",
"they were initialized to an empty dict in ``StyleableMixin`` then all classes would",
"version of ``tkinter.Label``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\",",
"named fonts. \"\"\" import tkinter as tk import tkinter.font as tkfont from contextlib",
"and some overrides. This global-level style will only be used by ``StyleableMixin``s if",
"with these properties: - size: 8 - family: \"Times\" ``init_fonts`` must be called",
"None, setting this will keep the previous style. Does nothing if ``style`` is",
"signaled of any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" for parent in",
"Styles to use. \"\"\" self._dict = styles \"\"\"A dictionary of the styles specific",
"FONT_SERIF_NORMAL,\\ FONT_SANS_SERIF_TITLE, FONT_SANS_SERIF_NORMAL FONT_MONOSPACE_TITLE = tkfont.Font(root, size=10, name=\"FONT_MONOSPACE_TITLE\", family=\"Courier\", weight=tkfont.BOLD) FONT_MONOSPACE_NORMAL = tkfont.Font(root,",
"in its ancestors, prioritizing the first ones specified in the constructor. When a",
"all the widget options (i.e. the ones that would normally be passed to",
"widget's style to the given style or the global style, which may be",
"prioritizing the first ones specified in the constructor. When a ``Style`` is updated,",
"styleable): \"\"\" Called by ``StyleableMixin`` objects to stop receiving updates on whenever this",
"= \"#888888\" GRAY_SCALE_9 = \"#999999\" GRAY_SCALE_A = \"#AAAAAA\" GRAY_SCALE_B = \"#BBBBBB\" GRAY_SCALE_C =",
"the first time it changes from its default). \"\"\" DEFAULT_STYLES = None \"\"\"",
"style is requested from a ``Style`` and cannot be found in said ``Style``'s",
"\"\"\"Styleable version of ``tkinter.Button``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\",",
"\"\"\" Make sure that this class's ``StyleableMixin.TK_DEFAULT_STYLES`` and ``StyleableMixin.DEFAULT_STYLES`` are defined (every class",
"``Style``s to receive updates on whenever this style changes. :param style: The child",
"= tkfont.Font(root, size=8, name=\"FONT_MONOSPACE_NORMAL\", family=\"Courier\") FONT_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SERIF_TITLE\", family=\"Times\", weight=tkfont.BOLD) FONT_SERIF_NORMAL",
":param overrides: Style overrides to use. \"\"\" super().__init__(master, cnf, *args) self._style = None",
"updates on whenever this style changes. This should not be called by user",
"None self.update_style() def update_style(self): \"\"\"Update this widget's styles.\"\"\" # Alias TK_DEFAULT_STYLES for conciseness.",
"style): \"\"\" Called by child ``Style``s to receive updates on whenever this style",
"the same dictionaries). \"\"\" if cls.TK_DEFAULT_STYLES is None: cls.TK_DEFAULT_STYLES = {} if cls.DEFAULT_STYLES",
"works in cooperation with the ``Style`` class. Styleable widgets should never use their",
"family: \"Times\" - weight: BOLD ``init_fonts`` must be called to initialize this font.",
"lower priority styles will get overridden. styles_dict = tk_defaults.copy() # Update the dict",
"of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\",",
"to register. :type styleable: StyleableMixin \"\"\" self._styled.append(styleable) def unregister_styleable(self, styleable): \"\"\" Called by",
":return: All the styles recognized by the given tkinter widget. \"\"\" return {k:",
"fonts. :param root: The tkinter root widget. :type root: tkinter.Tk \"\"\" global FONT_MONOSPACE_TITLE,",
"this widget's styles.\"\"\" # Alias TK_DEFAULT_STYLES for conciseness. tk_defaults = self.__class__.TK_DEFAULT_STYLES # Start",
"**kwargs): \"\"\" Configure this ``Style``'s styles. :param kwargs: The styles to add/edit. \"\"\"",
"Initialize the widget's style to the given style or the global style, which",
"styles set to this widget by default so we may return # to",
"register_styleable(self, styleable): \"\"\" Called by ``StyleableMixin`` objects to receive updates on whenever this",
"to retrieve the given style from this ``Style``'s ``Style._dict``. If that fails, recursively",
"all child ``Style``s of the changed ``Style`` are recursively informed of the change.",
"keep_existing: cls.DEFAULTS.update(defaults) else: cls.DEFAULTS = defaults # TODO: Styleable Tk (root)? class Button(StyleableMixin,",
"k, v in overrides.items(): if k in self.STYLED_OPTS: styled[k] = v else: functional[k]",
"or self.__class__.DEFAULTS.get(key) def _get_style(self, key): \"\"\" Attempt to retrieve the given style from",
"``tkinter.Toplevel``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Style: \"\"\" A",
"in any way by this class. Subclasses should define this. \"\"\" TK_DEFAULT_STYLES =",
"\"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"] class Label(StyleableMixin, tk.Label): \"\"\"Styleable version of ``tkinter.Label``.\"\"\" STYLED_OPTS",
"same dictionaries). \"\"\" if cls.TK_DEFAULT_STYLES is None: cls.TK_DEFAULT_STYLES = {} if cls.DEFAULT_STYLES is",
"\"\"\"Global default styles for all ``Style`` objects. This should be set through ``Style.set_defaults``.\"\"\"",
"tk_defaults = self.__class__.TK_DEFAULT_STYLES # Start off the styles_dict with a copy of the",
"Text(StyleableMixin, tk.Text): \"\"\"Styleable version of ``tkinter.Text``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"fg\", \"bd\", \"insertbackground\",",
"\"highlightthickness\", \"relief\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\"] class Toplevel(StyleableMixin, tk.Toplevel): \"\"\"Styleable version of ``tkinter.Toplevel``.\"\"\" STYLED_OPTS",
"size: 8 - family: \"Helvetica\" ``init_fonts`` must be called to initialize this font.",
"if an explicit style option on this widget is removed. tk_defaults.update((k, self.cget(k)) for",
"this ``Style`` and its parents, then resorting to the global default styles (``Style.DEFAULTS``).",
"def init_fonts(root): \"\"\" Initialize all the named fonts. This must be called prior",
":param cnf: A dictionary of configuration options. This is here to mimic the",
"cls.DEFAULTS = defaults def patch_tk_widgets(): \"\"\"Monkey patch the tkinter widgets with their styleable",
"GRAY_SCALE_A = \"#AAAAAA\" GRAY_SCALE_B = \"#BBBBBB\" GRAY_SCALE_C = \"#CCCCCC\" GRAY_SCALE_D = \"#DDDDDD\" GRAY_SCALE_E",
"styles from this ``Style``. This will raise a ``KeyError`` if any of the",
"to unregister. :type styleable: StyleableMixin \"\"\" # This will raise an error if",
"widget to unregister. :type styleable: StyleableMixin \"\"\" # This will raise an error",
"tkinter widget constructors. :type cnf: dict :param args: Additional args for the widget",
"= styles \"\"\"A dictionary of the styles specific to this ``Style``.\"\"\" self._styled =",
"parents \"\"\"A list of this ``Style``'s parent ``Style``s.\"\"\" self._children = [] \"\"\" A",
"Determine and return all the styles in this ``Style`` recognized by the given",
"Frame tk.Label = Label tk.LabelFrame = LabelFrame tk.Listbox = Listbox tk.Menu = Menu",
"cls.TK_DEFAULT_STYLES = {} if cls.DEFAULT_STYLES is None: cls.DEFAULT_STYLES = {} @classmethod def set_defaults(cls,",
"= _tkListbox tk.Menu = _tkMenu tk.PanedWindow = _tkPanedWindow tk.Radiobutton = _tkRadiobutton tk.Scale =",
"if keep_overrides: self._overrides.update(styled) else: self._overrides = styled if style: if self._style: self._style.unregister_styleable(self) self._style",
"import contextmanager # Colour constants: GRAY_SCALE_0 = \"#000000\" GRAY_SCALE_1 = \"#111111\" GRAY_SCALE_2 =",
"version of ``tkinter.PanedWindow``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"relief\", \"sashrelief\", \"showhandle\"] class Radiobutton(StyleableMixin, tk.Radiobutton):",
"style priority so that lower priority styles will get overridden. styles_dict = tk_defaults.copy()",
":type keep_overrides: bool :param overrides: Style overrides to use. \"\"\" # Sort out",
"normally be passed to ``widget.configure(...)``) to be considered for styling; any other options",
"these properties: - size: 8 - family: \"Helvetica\" ``init_fonts`` must be called to",
"to employ. :type style: Style :param overrides: Style overrides to use. \"\"\" super().__init__(master,",
"set_defaults(cls, keep_existing=True, **defaults): \"\"\" Convenience method to update the default styles for this",
"\"\"\" FONT_MONOSPACE_NORMAL = None \"\"\" Tkinter named font with these properties: - size:",
"4. A given dictionary of overrides \"\"\" STYLED_OPTS = [] \"\"\" A list",
"a ``Style`` is updated, any registered ``StyleableMixin``s are automatically updated to reflect the",
"font with these properties: - size: 10 - family: \"Courier\" - weight: BOLD",
"styles for all ``Style`` objects. This should be set through ``Style.set_defaults``.\"\"\" def __init__(self,",
"way by this class. Subclasses should define this. \"\"\" TK_DEFAULT_STYLES = None \"\"\"",
"\"\"\"A dictionary of the widget's currently-overridden styles.\"\"\" self._assure_default_dicts_exist() # Initialize the widget's style",
"Named fonts: FONT_MONOSPACE_TITLE = None \"\"\" Tkinter named font with these properties: -",
"# Colour constants: GRAY_SCALE_0 = \"#000000\" GRAY_SCALE_1 = \"#111111\" GRAY_SCALE_2 = \"#222222\" GRAY_SCALE_3",
"# Update the dict with the styles from the Style object. (Priority 3)",
"\"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\"] class LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable version",
"\"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\"] class LabelFrame(StyleableMixin, tk.LabelFrame): \"\"\"Styleable version of ``tkinter.LabelFrame``.\"\"\"",
"own styles, the style is looked for in its ancestors, prioritizing the first",
"from the Style object. (Priority 3) styles_dict.update(self._style.get_relevant_styles(self)) # Update the dict with the",
"in self.STYLED_OPTS: styled[k] = v else: functional[k] = v # Directly apply the",
"tk.Label _tkLabelFrame = tk.LabelFrame _tkListbox = tk.Listbox _tkMenu = tk.Menu _tkPanedWindow = tk.PanedWindow",
"that would normally be passed to ``widget.configure(...)``) to be considered for styling; any",
"Called by ``StyleableMixin`` objects to stop receiving updates on whenever this style changes.",
"from the styled ones. functional, styled = {}, {} for k, v in",
"option is revoked. This dictionary is lazily built for each unique styled class",
"styles: del self._dict[style] self._signal_style_changed() def _signal_style_changed(self): \"\"\" Internal method to update all the",
"contextmanager # Colour constants: GRAY_SCALE_0 = \"#000000\" GRAY_SCALE_1 = \"#111111\" GRAY_SCALE_2 = \"#222222\"",
"also set this at runtime through ``StyleableMixin.set_defaults``, but any changes made won't be",
"styles_dict.update(self._style.get_relevant_styles(self)) # Update the dict with the overridden styles. (Priority 4) styles_dict.update(self._overrides) #",
"class. :param keep_existing: Whether to keep the already existing default styles, or replace",
"FONT_SANS_SERIF_TITLE = tkfont.Font(root, size=10, name=\"FONT_SANS_SERIF_TITLE\", family=\"Helvetica\", weight=tkfont.BOLD) FONT_SANS_SERIF_NORMAL = tkfont.Font(root, size=8, name=\"FONT_SANS_SERIF_NORMAL\", family=\"Helvetica\")",
"styles_dict.update(self.__class__.DEFAULT_STYLES) if self._style: # Update the dict with the styles from the Style",
"given style name or None if it could not be found. \"\"\" return",
"self._parents = parents \"\"\"A list of this ``Style``'s parent ``Style``s.\"\"\" self._children = []",
"initialize this font. \"\"\" FONT_MONOSPACE_NORMAL = None \"\"\" Tkinter named font with these",
"tk.Text = _tkText tk.Toplevel = _tkToplevel @contextmanager def patch(): \"\"\"Context manager to temporarily",
"Subclasses may define this. One may also set this at runtime through ``StyleableMixin.set_defaults``,",
"These are signaled of any changes to this ``Style`` in ``Style._signal_style_changed``. \"\"\" self._parents",
"by ``StyleableMixin`` objects to receive updates on whenever this style changes. This should",
"\"\"\"Revert the tkinter widgets back to their defaults after monkey patching them with",
"= None \"\"\"A global ``Style`` object used by the ``stylize`` context manager.\"\"\" class",
"patch the tkinter widgets with their styleable equivalents.\"\"\" try: patch_tk_widgets() yield finally: unpatch_tk_widgets()",
"employ, or None to clear the current style (if ``keep_style`` is False). :type",
"this class. Subclasses should define this. \"\"\" TK_DEFAULT_STYLES = None \"\"\" A dictionary",
"\"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"justify\", \"selectbackground\", \"selectborderwidth\", \"selectforeground\", \"buttonbackground\", \"buttondownrelief\", \"buttonuprelief\", \"insertbackground\",",
"define this. \"\"\" TK_DEFAULT_STYLES = None \"\"\" A dictionary of default (platform-specific) styles",
"previous style. Does nothing if ``style`` is given. :type keep_style: bool :param keep_overrides:",
"Styleable widgets should never use their ``widget.configure`` method to set styles in their",
"if an initially explicitly given style option is revoked. This dictionary is lazily",
"tk.Checkbutton): \"\"\"Styleable version of ``tkinter.Checkbutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\",",
"styles_dict if k not in tk_defaults) self.configure(styles_dict) @classmethod def _assure_default_dicts_exist(cls): \"\"\" Make sure",
"version of ``tkinter.Button``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\",",
"v else: functional[k] = v # Directly apply the functional options self.configure(functional) if",
"tk.Frame): \"\"\"Styleable version of ``tkinter.Frame``.\"\"\" STYLED_OPTS = [\"bg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\"]",
"tk.Spinbox = Spinbox tk.Text = Text tk.Toplevel = Toplevel def unpatch_tk_widgets(): \"\"\"Revert the",
"used by ``StyleableMixin``s if they're not explicitly given a ``Style`` object already. :param",
"tk.Radiobutton): \"\"\"Styleable version of ``tkinter.Radiobutton``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\", \"disabledforeground\",",
"tk.Canvas _tkCheckbutton = tk.Checkbutton _tkEntry = tk.Entry _tkFrame = tk.Frame _tkLabel = tk.Label",
"= [\"font\", \"bg\", \"fg\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"labelanchor\"] class Listbox(StyleableMixin, tk.Listbox):",
"found in said ``Style``'s own styles, the style is looked for in its",
"tkinter as tk import tkinter.font as tkfont from contextlib import contextmanager # Colour",
"then resorting to the global default styles (``Style.DEFAULTS``). :param key: The style name.",
"tk.Toplevel = Toplevel def unpatch_tk_widgets(): \"\"\"Revert the tkinter widgets back to their defaults",
"\"#444444\" GRAY_SCALE_5 = \"#555555\" GRAY_SCALE_6 = \"#666666\" GRAY_SCALE_7 = \"#777777\" GRAY_SCALE_8 = \"#888888\"",
"= \"#663333\" MUTE_YELLOW = \"#888833\" MUTE_TURQUOISE = \"#335555\" MUTE_PURPLE = \"#553377\" MUTE_PINK =",
"Contains styling utilities for tkinter widgets. Some features include: - a hierarchical styling",
"if self._style: # Update the dict with the styles from the Style object.",
"\"fg\", \"activeforeground\", \"disabledforeground\", \"bd\", \"highlightcolor\", \"highlightbackground\", \"highlightthickness\", \"relief\", \"overrelief\", \"justify\", \"indicatoron\", \"offrelief\", \"selectcolor\"]",
"so that lower priority styles will get overridden. styles_dict = tk_defaults.copy() # Update",
"\"#333355\" MUTE_GREEN = \"#335533\" MUTE_RED = \"#663333\" MUTE_YELLOW = \"#888833\" MUTE_TURQUOISE = \"#335555\"",
"widgets; - a collection of colour constants; - and reasonable cross-platform named fonts.",
"# to them if an explicit style option on this widget is removed.",
"will keep the previous style. Does nothing if ``style`` is given. :type keep_style:",
"apply a global-level style and some overrides. This global-level style will only be",
"\"\"\" A dictionary of default user-defined styles for a given class. Subclasses may",
"RED_TEAM = \"#992222\" BLUE_TEAM = \"#222299\" UNKNOWN_TEAM = GRAY_SCALE_B BOOL_TRUE = MUTE_GREEN BOOL_FALSE",
"properties: - size: 10 - family: \"Helvetica\" - weight: BOLD ``init_fonts`` must be",
"Button(StyleableMixin, tk.Button): \"\"\"Styleable version of ``tkinter.Button``.\"\"\" STYLED_OPTS = [\"font\", \"bg\", \"activebackground\", \"fg\", \"activeforeground\",",
":return: The style corresponding to the given style name or None if it"
] |
[
"assert monty_c.count() == mongo_c.count() def test_qop_not_2(monty_find, mongo_find): docs = [ {\"a\": 6}, {\"a\":",
"mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_3(monty_find, mongo_find): docs = [",
"monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 0 assert monty_c.count() ==",
"{\"a\": {\"$not\": re.compile(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count()",
"{\"$not\": {\"$in\": [6]}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count()",
"0 assert monty_c.count() == mongo_c.count() def test_qop_not_4(monty_find, mongo_find): docs = [ {\"a\": \"apple\"},",
"mongo_c.count() def test_qop_not_2(monty_find, mongo_find): docs = [ {\"a\": 6}, {\"a\": [6]} ] spec",
"monty_c.count() == mongo_c.count() def test_qop_not_5(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, {\"a\": \"banana\"},",
"= {\"a\": {\"$not\": re.compile(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert",
"mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 1 assert monty_c.count() == mongo_c.count() assert",
"= [ {\"a\": 4}, {\"x\": 8} ] spec = {\"a\": {\"$not\": {\"$eq\": 8}}}",
"spec = {\"a\": {\"$not\": Regex(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec)",
"docs = [ {\"a\": \"apple\"}, {\"a\": \"banana\"}, ] spec = {\"a\": {\"$not\": re.compile(\"^a\")}}",
"def test_qop_not_1(monty_find, mongo_find): docs = [ {\"a\": 4}, {\"x\": 8} ] spec =",
"[6]}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 0",
"mongo_c.count() def test_qop_not_4(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, ] spec = {\"a\":",
"{\"$in\": [6]}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() ==",
"mongo_find): docs = [ {\"a\": \"apple\"}, {\"a\": \"banana\"}, ] spec = {\"a\": {\"$not\":",
"{\"a\": \"apple\"}, {\"a\": \"banana\"}, ] spec = {\"a\": {\"$not\": re.compile(\"^a\")}} monty_c = monty_find(docs,",
"= monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 1 assert monty_c.count()",
"test_qop_not_3(monty_find, mongo_find): docs = [ {\"a\": [{\"b\": 8}, {\"b\": 6}]}, ] spec =",
"6}, {\"a\": [6]} ] spec = {\"a\": {\"$not\": {\"$eq\": 6}}} monty_c = monty_find(docs,",
"spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_5(monty_find, mongo_find): docs",
"mongo_c.count() def test_qop_not_5(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, {\"a\": \"banana\"}, ] spec",
"] spec = {\"a\": {\"$not\": {\"$eq\": 8}}} monty_c = monty_find(docs, spec) mongo_c =",
"== mongo_c.count() def test_qop_not_5(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, {\"a\": \"banana\"}, ]",
"spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count()",
"== mongo_c.count() def test_qop_not_2(monty_find, mongo_find): docs = [ {\"a\": 6}, {\"a\": [6]} ]",
"== 2 assert monty_c.count() == mongo_c.count() def test_qop_not_2(monty_find, mongo_find): docs = [ {\"a\":",
"6}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 0",
"{\"b\": 6}]}, ] spec = {\"a.b\": {\"$not\": {\"$in\": [6]}}} monty_c = monty_find(docs, spec)",
"\"apple\"}, {\"a\": \"banana\"}, ] spec = {\"a\": {\"$not\": re.compile(\"^a\")}} monty_c = monty_find(docs, spec)",
"monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 0 assert",
"{\"a.b\": {\"$not\": {\"$in\": [6]}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert",
"\"apple\"}, ] spec = {\"a\": {\"$not\": Regex(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c =",
"spec) assert mongo_c.count() == 1 assert monty_c.count() == mongo_c.count() assert next(monty_c) == next(mongo_c)",
"= {\"a\": {\"$not\": {\"$eq\": 6}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec)",
"mongo_find): docs = [ {\"a\": 4}, {\"x\": 8} ] spec = {\"a\": {\"$not\":",
"= [ {\"a\": [{\"b\": 8}, {\"b\": 6}]}, ] spec = {\"a.b\": {\"$not\": {\"$in\":",
"= [ {\"a\": \"apple\"}, ] spec = {\"a\": {\"$not\": Regex(\"^a\")}} monty_c = monty_find(docs,",
"docs = [ {\"a\": 6}, {\"a\": [6]} ] spec = {\"a\": {\"$not\": {\"$eq\":",
"mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_4(monty_find, mongo_find): docs = [",
"mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_5(monty_find, mongo_find): docs = [",
"spec = {\"a\": {\"$not\": re.compile(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec)",
"= [ {\"a\": 6}, {\"a\": [6]} ] spec = {\"a\": {\"$not\": {\"$eq\": 6}}}",
"mongo_find): docs = [ {\"a\": [{\"b\": 8}, {\"b\": 6}]}, ] spec = {\"a.b\":",
"{\"a\": [6]} ] spec = {\"a\": {\"$not\": {\"$eq\": 6}}} monty_c = monty_find(docs, spec)",
"8} ] spec = {\"a\": {\"$not\": {\"$eq\": 8}}} monty_c = monty_find(docs, spec) mongo_c",
"mongo_find): docs = [ {\"a\": \"apple\"}, ] spec = {\"a\": {\"$not\": Regex(\"^a\")}} monty_c",
"def test_qop_not_2(monty_find, mongo_find): docs = [ {\"a\": 6}, {\"a\": [6]} ] spec =",
"re from bson.regex import Regex def test_qop_not_1(monty_find, mongo_find): docs = [ {\"a\": 4},",
"== 0 assert monty_c.count() == mongo_c.count() def test_qop_not_4(monty_find, mongo_find): docs = [ {\"a\":",
"monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 1 assert monty_c.count() ==",
"monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 2 assert",
"monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 2 assert monty_c.count() ==",
"[6]} ] spec = {\"a\": {\"$not\": {\"$eq\": 6}}} monty_c = monty_find(docs, spec) mongo_c",
"mongo_find): docs = [ {\"a\": 6}, {\"a\": [6]} ] spec = {\"a\": {\"$not\":",
"assert monty_c.count() == mongo_c.count() def test_qop_not_5(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, {\"a\":",
"{\"a\": {\"$not\": {\"$eq\": 8}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert",
"spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 2 assert monty_c.count() == mongo_c.count()",
"mongo_find(docs, spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_5(monty_find, mongo_find):",
"{\"a\": 6}, {\"a\": [6]} ] spec = {\"a\": {\"$not\": {\"$eq\": 6}}} monty_c =",
"test_qop_not_2(monty_find, mongo_find): docs = [ {\"a\": 6}, {\"a\": [6]} ] spec = {\"a\":",
"import re from bson.regex import Regex def test_qop_not_1(monty_find, mongo_find): docs = [ {\"a\":",
"spec) assert mongo_c.count() == 2 assert monty_c.count() == mongo_c.count() def test_qop_not_2(monty_find, mongo_find): docs",
"= {\"a\": {\"$not\": {\"$eq\": 8}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec)",
"{\"$eq\": 6}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() ==",
"assert mongo_c.count() == 2 assert monty_c.count() == mongo_c.count() def test_qop_not_2(monty_find, mongo_find): docs =",
"= mongo_find(docs, spec) assert mongo_c.count() == 2 assert monty_c.count() == mongo_c.count() def test_qop_not_2(monty_find,",
"= mongo_find(docs, spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_4(monty_find,",
"test_qop_not_4(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, ] spec = {\"a\": {\"$not\": Regex(\"^a\")}}",
"def test_qop_not_3(monty_find, mongo_find): docs = [ {\"a\": [{\"b\": 8}, {\"b\": 6}]}, ] spec",
"mongo_find(docs, spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_3(monty_find, mongo_find):",
"{\"x\": 8} ] spec = {\"a\": {\"$not\": {\"$eq\": 8}}} monty_c = monty_find(docs, spec)",
"mongo_c.count() def test_qop_not_3(monty_find, mongo_find): docs = [ {\"a\": [{\"b\": 8}, {\"b\": 6}]}, ]",
"Regex(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 0",
"= {\"a.b\": {\"$not\": {\"$in\": [6]}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec)",
"def test_qop_not_5(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, {\"a\": \"banana\"}, ] spec =",
"monty_c.count() == mongo_c.count() def test_qop_not_4(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, ] spec",
"assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_5(monty_find, mongo_find): docs =",
"mongo_c.count() == 2 assert monty_c.count() == mongo_c.count() def test_qop_not_2(monty_find, mongo_find): docs = [",
"{\"$eq\": 8}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() ==",
"{\"a\": [{\"b\": 8}, {\"b\": 6}]}, ] spec = {\"a.b\": {\"$not\": {\"$in\": [6]}}} monty_c",
"= [ {\"a\": \"apple\"}, {\"a\": \"banana\"}, ] spec = {\"a\": {\"$not\": re.compile(\"^a\")}} monty_c",
"[ {\"a\": \"apple\"}, {\"a\": \"banana\"}, ] spec = {\"a\": {\"$not\": re.compile(\"^a\")}} monty_c =",
"] spec = {\"a\": {\"$not\": {\"$eq\": 6}}} monty_c = monty_find(docs, spec) mongo_c =",
"[ {\"a\": 6}, {\"a\": [6]} ] spec = {\"a\": {\"$not\": {\"$eq\": 6}}} monty_c",
"assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_3(monty_find, mongo_find): docs =",
"{\"a\": {\"$not\": Regex(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count()",
"mongo_find(docs, spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_4(monty_find, mongo_find):",
"assert monty_c.count() == mongo_c.count() def test_qop_not_4(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, ]",
"mongo_find(docs, spec) assert mongo_c.count() == 2 assert monty_c.count() == mongo_c.count() def test_qop_not_2(monty_find, mongo_find):",
"re.compile(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 1",
"[ {\"a\": \"apple\"}, ] spec = {\"a\": {\"$not\": Regex(\"^a\")}} monty_c = monty_find(docs, spec)",
"spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 1 assert monty_c.count() == mongo_c.count()",
"assert monty_c.count() == mongo_c.count() def test_qop_not_3(monty_find, mongo_find): docs = [ {\"a\": [{\"b\": 8},",
"[{\"b\": 8}, {\"b\": 6}]}, ] spec = {\"a.b\": {\"$not\": {\"$in\": [6]}}} monty_c =",
"docs = [ {\"a\": [{\"b\": 8}, {\"b\": 6}]}, ] spec = {\"a.b\": {\"$not\":",
"{\"a\": \"apple\"}, ] spec = {\"a\": {\"$not\": Regex(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c",
"[ {\"a\": [{\"b\": 8}, {\"b\": 6}]}, ] spec = {\"a.b\": {\"$not\": {\"$in\": [6]}}}",
"spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_4(monty_find, mongo_find): docs",
"= mongo_find(docs, spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_5(monty_find,",
"docs = [ {\"a\": \"apple\"}, ] spec = {\"a\": {\"$not\": Regex(\"^a\")}} monty_c =",
"2 assert monty_c.count() == mongo_c.count() def test_qop_not_2(monty_find, mongo_find): docs = [ {\"a\": 6},",
"4}, {\"x\": 8} ] spec = {\"a\": {\"$not\": {\"$eq\": 8}}} monty_c = monty_find(docs,",
"{\"$not\": re.compile(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() ==",
"spec = {\"a\": {\"$not\": {\"$eq\": 6}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs,",
"test_qop_not_5(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, {\"a\": \"banana\"}, ] spec = {\"a\":",
"{\"$not\": {\"$eq\": 8}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count()",
"mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def",
"import Regex def test_qop_not_1(monty_find, mongo_find): docs = [ {\"a\": 4}, {\"x\": 8} ]",
"monty_c.count() == mongo_c.count() def test_qop_not_3(monty_find, mongo_find): docs = [ {\"a\": [{\"b\": 8}, {\"b\":",
"\"banana\"}, ] spec = {\"a\": {\"$not\": re.compile(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c =",
"spec = {\"a.b\": {\"$not\": {\"$in\": [6]}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs,",
"{\"$not\": Regex(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() ==",
"== 0 assert monty_c.count() == mongo_c.count() def test_qop_not_5(monty_find, mongo_find): docs = [ {\"a\":",
"8}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 2",
"mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 2 assert monty_c.count() == mongo_c.count() def",
"test_qop_not_1(monty_find, mongo_find): docs = [ {\"a\": 4}, {\"x\": 8} ] spec = {\"a\":",
"docs = [ {\"a\": 4}, {\"x\": 8} ] spec = {\"a\": {\"$not\": {\"$eq\":",
"bson.regex import Regex def test_qop_not_1(monty_find, mongo_find): docs = [ {\"a\": 4}, {\"x\": 8}",
"] spec = {\"a\": {\"$not\": re.compile(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs,",
"monty_c.count() == mongo_c.count() def test_qop_not_2(monty_find, mongo_find): docs = [ {\"a\": 6}, {\"a\": [6]}",
"{\"a\": \"banana\"}, ] spec = {\"a\": {\"$not\": re.compile(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c",
"= mongo_find(docs, spec) assert mongo_c.count() == 1 assert monty_c.count() == mongo_c.count() assert next(monty_c)",
"== mongo_c.count() def test_qop_not_4(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, ] spec =",
"== mongo_c.count() def test_qop_not_3(monty_find, mongo_find): docs = [ {\"a\": [{\"b\": 8}, {\"b\": 6}]},",
"] spec = {\"a\": {\"$not\": Regex(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs,",
"= mongo_find(docs, spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_3(monty_find,",
"8}, {\"b\": 6}]}, ] spec = {\"a.b\": {\"$not\": {\"$in\": [6]}}} monty_c = monty_find(docs,",
"def test_qop_not_4(monty_find, mongo_find): docs = [ {\"a\": \"apple\"}, ] spec = {\"a\": {\"$not\":",
"from bson.regex import Regex def test_qop_not_1(monty_find, mongo_find): docs = [ {\"a\": 4}, {\"x\":",
"mongo_find(docs, spec) assert mongo_c.count() == 1 assert monty_c.count() == mongo_c.count() assert next(monty_c) ==",
"= {\"a\": {\"$not\": Regex(\"^a\")}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert",
"{\"a\": {\"$not\": {\"$eq\": 6}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert",
"0 assert monty_c.count() == mongo_c.count() def test_qop_not_3(monty_find, mongo_find): docs = [ {\"a\": [{\"b\":",
"= monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 0 assert monty_c.count()",
"monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 1 assert",
"= monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count() == 2 assert monty_c.count()",
"[ {\"a\": 4}, {\"x\": 8} ] spec = {\"a\": {\"$not\": {\"$eq\": 8}}} monty_c",
"spec) assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_3(monty_find, mongo_find): docs",
"{\"a\": 4}, {\"x\": 8} ] spec = {\"a\": {\"$not\": {\"$eq\": 8}}} monty_c =",
"assert mongo_c.count() == 0 assert monty_c.count() == mongo_c.count() def test_qop_not_4(monty_find, mongo_find): docs =",
"] spec = {\"a.b\": {\"$not\": {\"$in\": [6]}}} monty_c = monty_find(docs, spec) mongo_c =",
"6}]}, ] spec = {\"a.b\": {\"$not\": {\"$in\": [6]}}} monty_c = monty_find(docs, spec) mongo_c",
"Regex def test_qop_not_1(monty_find, mongo_find): docs = [ {\"a\": 4}, {\"x\": 8} ] spec",
"{\"$not\": {\"$eq\": 6}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs, spec) assert mongo_c.count()",
"spec = {\"a\": {\"$not\": {\"$eq\": 8}}} monty_c = monty_find(docs, spec) mongo_c = mongo_find(docs,",
"0 assert monty_c.count() == mongo_c.count() def test_qop_not_5(monty_find, mongo_find): docs = [ {\"a\": \"apple\"},",
"== 0 assert monty_c.count() == mongo_c.count() def test_qop_not_3(monty_find, mongo_find): docs = [ {\"a\":"
] |
[
"__init__(self, file): self.path = file self.ptr = None self.name = re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '')",
"create_macro(self): return f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def create_autoclean(self): return f'autoclean {self.ptr}\\n' def patch_routine(self, rom:",
"return f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def create_autoclean(self): return f'autoclean {self.ptr}\\n' def patch_routine(self, rom: Rom):",
"'w') as f: f.write(str(self)) (success, rom_data) = asar.patch(f'tmp_{self.name}.asm', rom.data) if success: rom.data =",
"ptrs[0] print(f'Routine {self.name} was applied correctly') else: print(asar.geterrors()) raise PatchException(f'Routine {self.name} encountered an",
"{self.name} was applied correctly') else: print(asar.geterrors()) raise PatchException(f'Routine {self.name} encountered an error while",
"import re class Routine: incsrc = 'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n' def __init__(self, file): self.path",
"(success, rom_data) = asar.patch(f'tmp_{self.name}.asm', rom.data) if success: rom.data = rom_data ptrs = asar.getprints()",
"os import re class Routine: incsrc = 'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n' def __init__(self, file):",
"open(self.path, 'r') as r: self.routine = f'print \"$\",pc\\n{r.read()}\\n\\n' def __str__(self): return self.incsrc +",
"= file self.ptr = None self.name = re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '') with open(self.path, 'r')",
"def patch_routine(self, rom: Rom): with open(f'tmp_{self.name}.asm', 'w') as f: f.write(str(self)) (success, rom_data) =",
"with open(self.path, 'r') as r: self.routine = f'print \"$\",pc\\n{r.read()}\\n\\n' def __str__(self): return self.incsrc",
"file)[-1].replace('.asm', '') with open(self.path, 'r') as r: self.routine = f'print \"$\",pc\\n{r.read()}\\n\\n' def __str__(self):",
"f'autoclean {self.ptr}\\n' def patch_routine(self, rom: Rom): with open(f'tmp_{self.name}.asm', 'w') as f: f.write(str(self)) (success,",
"rom_data ptrs = asar.getprints() self.ptr = ptrs[0] print(f'Routine {self.name} was applied correctly') else:",
"self.routine def create_macro(self): return f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def create_autoclean(self): return f'autoclean {self.ptr}\\n' def",
"Routine: incsrc = 'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n' def __init__(self, file): self.path = file self.ptr",
"patchexception import PatchException import os import re class Routine: incsrc = 'incsrc global_ow_code/defines.asm\\nfreecode",
"re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '') with open(self.path, 'r') as r: self.routine = f'print \"$\",pc\\n{r.read()}\\n\\n' def",
"asar from rom import Rom from patchexception import PatchException import os import re",
"self.incsrc + 'parent:\\n' + self.routine def create_macro(self): return f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def create_autoclean(self):",
"= f'print \"$\",pc\\n{r.read()}\\n\\n' def __str__(self): return self.incsrc + 'parent:\\n' + self.routine def create_macro(self):",
"asar.getprints() self.ptr = ptrs[0] print(f'Routine {self.name} was applied correctly') else: print(asar.geterrors()) raise PatchException(f'Routine",
"= rom_data ptrs = asar.getprints() self.ptr = ptrs[0] print(f'Routine {self.name} was applied correctly')",
"rom_data) = asar.patch(f'tmp_{self.name}.asm', rom.data) if success: rom.data = rom_data ptrs = asar.getprints() self.ptr",
"def create_autoclean(self): return f'autoclean {self.ptr}\\n' def patch_routine(self, rom: Rom): with open(f'tmp_{self.name}.asm', 'w') as",
"create_autoclean(self): return f'autoclean {self.ptr}\\n' def patch_routine(self, rom: Rom): with open(f'tmp_{self.name}.asm', 'w') as f:",
"'') with open(self.path, 'r') as r: self.routine = f'print \"$\",pc\\n{r.read()}\\n\\n' def __str__(self): return",
"global_ow_code/defines.asm\\nfreecode cleaned\\n' def __init__(self, file): self.path = file self.ptr = None self.name =",
"patch_routine(self, rom: Rom): with open(f'tmp_{self.name}.asm', 'w') as f: f.write(str(self)) (success, rom_data) = asar.patch(f'tmp_{self.name}.asm',",
"rom.data) if success: rom.data = rom_data ptrs = asar.getprints() self.ptr = ptrs[0] print(f'Routine",
"{self.ptr}\\n' def patch_routine(self, rom: Rom): with open(f'tmp_{self.name}.asm', 'w') as f: f.write(str(self)) (success, rom_data)",
"def create_macro(self): return f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def create_autoclean(self): return f'autoclean {self.ptr}\\n' def patch_routine(self,",
"f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def create_autoclean(self): return f'autoclean {self.ptr}\\n' def patch_routine(self, rom: Rom): with",
"was applied correctly') else: print(asar.geterrors()) raise PatchException(f'Routine {self.name} encountered an error while patching')",
"{self.ptr}\\nendmacro\\n' def create_autoclean(self): return f'autoclean {self.ptr}\\n' def patch_routine(self, rom: Rom): with open(f'tmp_{self.name}.asm', 'w')",
"def __init__(self, file): self.path = file self.ptr = None self.name = re.findall(r'\\w+\\.asm', file)[-1].replace('.asm',",
"self.name = re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '') with open(self.path, 'r') as r: self.routine = f'print",
"\"$\",pc\\n{r.read()}\\n\\n' def __str__(self): return self.incsrc + 'parent:\\n' + self.routine def create_macro(self): return f'macro",
"class Routine: incsrc = 'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n' def __init__(self, file): self.path = file",
"rom: Rom): with open(f'tmp_{self.name}.asm', 'w') as f: f.write(str(self)) (success, rom_data) = asar.patch(f'tmp_{self.name}.asm', rom.data)",
"import os import re class Routine: incsrc = 'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n' def __init__(self,",
"import Rom from patchexception import PatchException import os import re class Routine: incsrc",
"as r: self.routine = f'print \"$\",pc\\n{r.read()}\\n\\n' def __str__(self): return self.incsrc + 'parent:\\n' +",
"file self.ptr = None self.name = re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '') with open(self.path, 'r') as",
"file): self.path = file self.ptr = None self.name = re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '') with",
"{self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def create_autoclean(self): return f'autoclean {self.ptr}\\n' def patch_routine(self, rom: Rom): with open(f'tmp_{self.name}.asm',",
"+ self.routine def create_macro(self): return f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def create_autoclean(self): return f'autoclean {self.ptr}\\n'",
"from rom import Rom from patchexception import PatchException import os import re class",
"= 'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n' def __init__(self, file): self.path = file self.ptr = None",
"f.write(str(self)) (success, rom_data) = asar.patch(f'tmp_{self.name}.asm', rom.data) if success: rom.data = rom_data ptrs =",
"from patchexception import PatchException import os import re class Routine: incsrc = 'incsrc",
"self.ptr = None self.name = re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '') with open(self.path, 'r') as r:",
"f: f.write(str(self)) (success, rom_data) = asar.patch(f'tmp_{self.name}.asm', rom.data) if success: rom.data = rom_data ptrs",
"self.path = file self.ptr = None self.name = re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '') with open(self.path,",
"+ 'parent:\\n' + self.routine def create_macro(self): return f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def create_autoclean(self): return",
"success: rom.data = rom_data ptrs = asar.getprints() self.ptr = ptrs[0] print(f'Routine {self.name} was",
"Rom from patchexception import PatchException import os import re class Routine: incsrc =",
"re class Routine: incsrc = 'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n' def __init__(self, file): self.path =",
"rom import Rom from patchexception import PatchException import os import re class Routine:",
"f'print \"$\",pc\\n{r.read()}\\n\\n' def __str__(self): return self.incsrc + 'parent:\\n' + self.routine def create_macro(self): return",
"ptrs = asar.getprints() self.ptr = ptrs[0] print(f'Routine {self.name} was applied correctly') else: print(asar.geterrors())",
"= asar.getprints() self.ptr = ptrs[0] print(f'Routine {self.name} was applied correctly') else: print(asar.geterrors()) raise",
"= asar.patch(f'tmp_{self.name}.asm', rom.data) if success: rom.data = rom_data ptrs = asar.getprints() self.ptr =",
"= re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '') with open(self.path, 'r') as r: self.routine = f'print \"$\",pc\\n{r.read()}\\n\\n'",
"print(f'Routine {self.name} was applied correctly') else: print(asar.geterrors()) raise PatchException(f'Routine {self.name} encountered an error",
"r: self.routine = f'print \"$\",pc\\n{r.read()}\\n\\n' def __str__(self): return self.incsrc + 'parent:\\n' + self.routine",
"return self.incsrc + 'parent:\\n' + self.routine def create_macro(self): return f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def",
"None self.name = re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '') with open(self.path, 'r') as r: self.routine =",
"= None self.name = re.findall(r'\\w+\\.asm', file)[-1].replace('.asm', '') with open(self.path, 'r') as r: self.routine",
"'r') as r: self.routine = f'print \"$\",pc\\n{r.read()}\\n\\n' def __str__(self): return self.incsrc + 'parent:\\n'",
"open(f'tmp_{self.name}.asm', 'w') as f: f.write(str(self)) (success, rom_data) = asar.patch(f'tmp_{self.name}.asm', rom.data) if success: rom.data",
"import asar from rom import Rom from patchexception import PatchException import os import",
"Rom): with open(f'tmp_{self.name}.asm', 'w') as f: f.write(str(self)) (success, rom_data) = asar.patch(f'tmp_{self.name}.asm', rom.data) if",
"asar.patch(f'tmp_{self.name}.asm', rom.data) if success: rom.data = rom_data ptrs = asar.getprints() self.ptr = ptrs[0]",
"self.routine = f'print \"$\",pc\\n{r.read()}\\n\\n' def __str__(self): return self.incsrc + 'parent:\\n' + self.routine def",
"cleaned\\n' def __init__(self, file): self.path = file self.ptr = None self.name = re.findall(r'\\w+\\.asm',",
"'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n' def __init__(self, file): self.path = file self.ptr = None self.name",
"with open(f'tmp_{self.name}.asm', 'w') as f: f.write(str(self)) (success, rom_data) = asar.patch(f'tmp_{self.name}.asm', rom.data) if success:",
"rom.data = rom_data ptrs = asar.getprints() self.ptr = ptrs[0] print(f'Routine {self.name} was applied",
"__str__(self): return self.incsrc + 'parent:\\n' + self.routine def create_macro(self): return f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n'",
"self.ptr = ptrs[0] print(f'Routine {self.name} was applied correctly') else: print(asar.geterrors()) raise PatchException(f'Routine {self.name}",
"= ptrs[0] print(f'Routine {self.name} was applied correctly') else: print(asar.geterrors()) raise PatchException(f'Routine {self.name} encountered",
"return f'autoclean {self.ptr}\\n' def patch_routine(self, rom: Rom): with open(f'tmp_{self.name}.asm', 'w') as f: f.write(str(self))",
"applied correctly') else: print(asar.geterrors()) raise PatchException(f'Routine {self.name} encountered an error while patching') os.remove(f'tmp_{self.name}.asm')",
"import PatchException import os import re class Routine: incsrc = 'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n'",
"incsrc = 'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n' def __init__(self, file): self.path = file self.ptr =",
"def __str__(self): return self.incsrc + 'parent:\\n' + self.routine def create_macro(self): return f'macro {self.name}()\\n\\tJSL",
"'parent:\\n' + self.routine def create_macro(self): return f'macro {self.name}()\\n\\tJSL {self.ptr}\\nendmacro\\n' def create_autoclean(self): return f'autoclean",
"PatchException import os import re class Routine: incsrc = 'incsrc global_ow_code/defines.asm\\nfreecode cleaned\\n' def",
"if success: rom.data = rom_data ptrs = asar.getprints() self.ptr = ptrs[0] print(f'Routine {self.name}",
"as f: f.write(str(self)) (success, rom_data) = asar.patch(f'tmp_{self.name}.asm', rom.data) if success: rom.data = rom_data"
] |
[
"context = \"paper\") plt.rc('text', usetex=True) plt.rc('font', family='serif') def poipmf(start, stop, lamb): k =",
"import scipy from scipy.stats import poisson from scipy.stats import norm from math import",
"def poipmf(start, stop, lamb): k = np.arange(start, stop, 1) pmf = scipy.stats.poisson.pmf(k, lamb)",
"100) plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma), color = '#353131') plt.stem(k, pmf, '--', bottom=0) plt.title(r\"Poisson",
"import seaborn as sns import collections import scipy from scipy.stats import poisson from",
"numpy as np import matplotlib.pyplot as plt import seaborn as sns import collections",
"= [1, 5, 10, 200] poipmf(0, 13, lamb[0]) poipmf(0, 17, lamb[1]) poipmf(0, 25,",
"lamb = [1, 5, 10, 200] poipmf(0, 13, lamb[0]) poipmf(0, 17, lamb[1]) poipmf(0,",
"matplotlib.pyplot as plt import seaborn as sns import collections import scipy from scipy.stats",
"import sqrt sns.set(style = \"darkgrid\", context = \"paper\") plt.rc('text', usetex=True) plt.rc('font', family='serif') def",
"'--', bottom=0) plt.title(r\"Poisson Normal Appr. with $\\lambda$ = %d\" % (lamb)) plt.show() lamb",
"1) pmf = scipy.stats.poisson.pmf(k, lamb) mu = lamb sigma = sqrt(lamb) x =",
"as plt import seaborn as sns import collections import scipy from scipy.stats import",
"5, 10, 200] poipmf(0, 13, lamb[0]) poipmf(0, 17, lamb[1]) poipmf(0, 25, lamb[2]) poipmf(0,",
"import matplotlib.pyplot as plt import seaborn as sns import collections import scipy from",
"lamb sigma = sqrt(lamb) x = np.linspace(mu - 5*sigma, mu + 5*sigma, 100)",
"'#353131') plt.stem(k, pmf, '--', bottom=0) plt.title(r\"Poisson Normal Appr. with $\\lambda$ = %d\" %",
"stop, lamb): k = np.arange(start, stop, 1) pmf = scipy.stats.poisson.pmf(k, lamb) mu =",
"5*sigma, 100) plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma), color = '#353131') plt.stem(k, pmf, '--', bottom=0)",
"= np.linspace(mu - 5*sigma, mu + 5*sigma, 100) plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma), color",
"% (lamb)) plt.show() lamb = [1, 5, 10, 200] poipmf(0, 13, lamb[0]) poipmf(0,",
"5*sigma, mu + 5*sigma, 100) plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma), color = '#353131') plt.stem(k,",
"collections import scipy from scipy.stats import poisson from scipy.stats import norm from math",
"mu = lamb sigma = sqrt(lamb) x = np.linspace(mu - 5*sigma, mu +",
"np.linspace(mu - 5*sigma, mu + 5*sigma, 100) plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma), color =",
"sns import collections import scipy from scipy.stats import poisson from scipy.stats import norm",
"import norm from math import sqrt sns.set(style = \"darkgrid\", context = \"paper\") plt.rc('text',",
"\"darkgrid\", context = \"paper\") plt.rc('text', usetex=True) plt.rc('font', family='serif') def poipmf(start, stop, lamb): k",
"color = '#353131') plt.stem(k, pmf, '--', bottom=0) plt.title(r\"Poisson Normal Appr. with $\\lambda$ =",
"pmf = scipy.stats.poisson.pmf(k, lamb) mu = lamb sigma = sqrt(lamb) x = np.linspace(mu",
"sqrt sns.set(style = \"darkgrid\", context = \"paper\") plt.rc('text', usetex=True) plt.rc('font', family='serif') def poipmf(start,",
"plt.rc('font', family='serif') def poipmf(start, stop, lamb): k = np.arange(start, stop, 1) pmf =",
"+ 5*sigma, 100) plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma), color = '#353131') plt.stem(k, pmf, '--',",
"norm from math import sqrt sns.set(style = \"darkgrid\", context = \"paper\") plt.rc('text', usetex=True)",
"seaborn as sns import collections import scipy from scipy.stats import poisson from scipy.stats",
"plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma), color = '#353131') plt.stem(k, pmf, '--', bottom=0) plt.title(r\"Poisson Normal",
"<gh_stars>0 import numpy as np import matplotlib.pyplot as plt import seaborn as sns",
"plt.rc('text', usetex=True) plt.rc('font', family='serif') def poipmf(start, stop, lamb): k = np.arange(start, stop, 1)",
"%d\" % (lamb)) plt.show() lamb = [1, 5, 10, 200] poipmf(0, 13, lamb[0])",
"x = np.linspace(mu - 5*sigma, mu + 5*sigma, 100) plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma),",
"scipy.stats.norm.pdf(x, mu, sigma), color = '#353131') plt.stem(k, pmf, '--', bottom=0) plt.title(r\"Poisson Normal Appr.",
"pmf, '--', bottom=0) plt.title(r\"Poisson Normal Appr. with $\\lambda$ = %d\" % (lamb)) plt.show()",
"import collections import scipy from scipy.stats import poisson from scipy.stats import norm from",
"as sns import collections import scipy from scipy.stats import poisson from scipy.stats import",
"\"paper\") plt.rc('text', usetex=True) plt.rc('font', family='serif') def poipmf(start, stop, lamb): k = np.arange(start, stop,",
"from math import sqrt sns.set(style = \"darkgrid\", context = \"paper\") plt.rc('text', usetex=True) plt.rc('font',",
"poisson from scipy.stats import norm from math import sqrt sns.set(style = \"darkgrid\", context",
"200] poipmf(0, 13, lamb[0]) poipmf(0, 17, lamb[1]) poipmf(0, 25, lamb[2]) poipmf(0, 200, lamb[3])",
"mu, sigma), color = '#353131') plt.stem(k, pmf, '--', bottom=0) plt.title(r\"Poisson Normal Appr. with",
"plt import seaborn as sns import collections import scipy from scipy.stats import poisson",
"plt.stem(k, pmf, '--', bottom=0) plt.title(r\"Poisson Normal Appr. with $\\lambda$ = %d\" % (lamb))",
"math import sqrt sns.set(style = \"darkgrid\", context = \"paper\") plt.rc('text', usetex=True) plt.rc('font', family='serif')",
"from scipy.stats import norm from math import sqrt sns.set(style = \"darkgrid\", context =",
"np import matplotlib.pyplot as plt import seaborn as sns import collections import scipy",
"plt.title(r\"Poisson Normal Appr. with $\\lambda$ = %d\" % (lamb)) plt.show() lamb = [1,",
"= sqrt(lamb) x = np.linspace(mu - 5*sigma, mu + 5*sigma, 100) plt.plot(x, scipy.stats.norm.pdf(x,",
"as np import matplotlib.pyplot as plt import seaborn as sns import collections import",
"= %d\" % (lamb)) plt.show() lamb = [1, 5, 10, 200] poipmf(0, 13,",
"10, 200] poipmf(0, 13, lamb[0]) poipmf(0, 17, lamb[1]) poipmf(0, 25, lamb[2]) poipmf(0, 200,",
"= np.arange(start, stop, 1) pmf = scipy.stats.poisson.pmf(k, lamb) mu = lamb sigma =",
"scipy.stats.poisson.pmf(k, lamb) mu = lamb sigma = sqrt(lamb) x = np.linspace(mu - 5*sigma,",
"- 5*sigma, mu + 5*sigma, 100) plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma), color = '#353131')",
"scipy.stats import poisson from scipy.stats import norm from math import sqrt sns.set(style =",
"= lamb sigma = sqrt(lamb) x = np.linspace(mu - 5*sigma, mu + 5*sigma,",
"scipy.stats import norm from math import sqrt sns.set(style = \"darkgrid\", context = \"paper\")",
"lamb): k = np.arange(start, stop, 1) pmf = scipy.stats.poisson.pmf(k, lamb) mu = lamb",
"$\\lambda$ = %d\" % (lamb)) plt.show() lamb = [1, 5, 10, 200] poipmf(0,",
"stop, 1) pmf = scipy.stats.poisson.pmf(k, lamb) mu = lamb sigma = sqrt(lamb) x",
"= scipy.stats.poisson.pmf(k, lamb) mu = lamb sigma = sqrt(lamb) x = np.linspace(mu -",
"sigma = sqrt(lamb) x = np.linspace(mu - 5*sigma, mu + 5*sigma, 100) plt.plot(x,",
"lamb) mu = lamb sigma = sqrt(lamb) x = np.linspace(mu - 5*sigma, mu",
"family='serif') def poipmf(start, stop, lamb): k = np.arange(start, stop, 1) pmf = scipy.stats.poisson.pmf(k,",
"import poisson from scipy.stats import norm from math import sqrt sns.set(style = \"darkgrid\",",
"mu + 5*sigma, 100) plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma), color = '#353131') plt.stem(k, pmf,",
"Normal Appr. with $\\lambda$ = %d\" % (lamb)) plt.show() lamb = [1, 5,",
"k = np.arange(start, stop, 1) pmf = scipy.stats.poisson.pmf(k, lamb) mu = lamb sigma",
"bottom=0) plt.title(r\"Poisson Normal Appr. with $\\lambda$ = %d\" % (lamb)) plt.show() lamb =",
"= '#353131') plt.stem(k, pmf, '--', bottom=0) plt.title(r\"Poisson Normal Appr. with $\\lambda$ = %d\"",
"sigma), color = '#353131') plt.stem(k, pmf, '--', bottom=0) plt.title(r\"Poisson Normal Appr. with $\\lambda$",
"with $\\lambda$ = %d\" % (lamb)) plt.show() lamb = [1, 5, 10, 200]",
"= \"paper\") plt.rc('text', usetex=True) plt.rc('font', family='serif') def poipmf(start, stop, lamb): k = np.arange(start,",
"from scipy.stats import poisson from scipy.stats import norm from math import sqrt sns.set(style",
"np.arange(start, stop, 1) pmf = scipy.stats.poisson.pmf(k, lamb) mu = lamb sigma = sqrt(lamb)",
"plt.show() lamb = [1, 5, 10, 200] poipmf(0, 13, lamb[0]) poipmf(0, 17, lamb[1])",
"(lamb)) plt.show() lamb = [1, 5, 10, 200] poipmf(0, 13, lamb[0]) poipmf(0, 17,",
"Appr. with $\\lambda$ = %d\" % (lamb)) plt.show() lamb = [1, 5, 10,",
"[1, 5, 10, 200] poipmf(0, 13, lamb[0]) poipmf(0, 17, lamb[1]) poipmf(0, 25, lamb[2])",
"= \"darkgrid\", context = \"paper\") plt.rc('text', usetex=True) plt.rc('font', family='serif') def poipmf(start, stop, lamb):",
"sqrt(lamb) x = np.linspace(mu - 5*sigma, mu + 5*sigma, 100) plt.plot(x, scipy.stats.norm.pdf(x, mu,",
"poipmf(start, stop, lamb): k = np.arange(start, stop, 1) pmf = scipy.stats.poisson.pmf(k, lamb) mu",
"import numpy as np import matplotlib.pyplot as plt import seaborn as sns import",
"scipy from scipy.stats import poisson from scipy.stats import norm from math import sqrt",
"sns.set(style = \"darkgrid\", context = \"paper\") plt.rc('text', usetex=True) plt.rc('font', family='serif') def poipmf(start, stop,",
"usetex=True) plt.rc('font', family='serif') def poipmf(start, stop, lamb): k = np.arange(start, stop, 1) pmf"
] |
[
"BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for",
"in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER",
"= 20 BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)]",
"[True] for batch in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM = [[len(row) for row in batch] for",
"test_should_correctly_calculate_the_batch_length(self): partition = DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert partition.x == BATCHED_INPUTS_SMALL assert partition.y ==",
"range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for",
"5 NUM_BATCHES_MEDIUM = 1000 NUM_ROWS_MEDIUM = 100 ROW_LEN_MEDIUM = 20 BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER",
"batch] for batch in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for",
"row in batch] for batch in BATCHED_INPUTS_MEDIUM] class TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self): partition =",
"BATCHED_INPUTS_MEDIUM] class TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self): partition = DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert partition.x ==",
"in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ = [[True] + [len(row) for row in batch] + [True]",
"assert partition.num_batches == NUM_BATCHES_SMALL partition = DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert partition.x == BATCHED_INPUTS_MEDIUM",
"BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch",
"* INPUT_PLACEHOLDER = 1 OUTPUT_PLACEHOLDER = 2 NUM_BATCHES_SMALL = 10 NUM_ROWS_SMALL = 10",
"BATCHED_INPUTS_SMALL assert partition.y == BATCHED_OUTPUTS_SMALL assert partition.sizes == BATCHED_SIZES_SMALL assert partition.num_batches == NUM_BATCHES_SMALL",
"row in batch] + [True] for batch in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL = [[len(row) for",
"for batch in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row",
"= 10 ROW_LEN_SMALL = 5 NUM_BATCHES_MEDIUM = 1000 NUM_ROWS_MEDIUM = 100 ROW_LEN_MEDIUM =",
"row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ = [[True] + [len(row) for",
"for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ = [[True] + [len(row)",
"batch in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM = [[len(row) for row in batch] for batch in",
"for timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL",
"BATCHED_SIZES_SMALL = [[len(row) for row in batch] for batch in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM =",
"def test_should_correctly_calculate_the_batch_length(self): partition = DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert partition.x == BATCHED_INPUTS_SMALL assert partition.y",
"BATCHED_SIZES_SMALL assert partition.num_batches == NUM_BATCHES_SMALL partition = DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert partition.x ==",
"= 2 NUM_BATCHES_SMALL = 10 NUM_ROWS_SMALL = 10 ROW_LEN_SMALL = 5 NUM_BATCHES_MEDIUM =",
"in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)]",
"in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ = [[True]",
"from tf_rnn.dataset import * INPUT_PLACEHOLDER = 1 OUTPUT_PLACEHOLDER = 2 NUM_BATCHES_SMALL = 10",
"for row in batch] for batch in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep",
"timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM =",
"[True] for batch in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL = [[len(row) for row in batch] for",
"batch in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row in",
"for batch in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM = [[len(row) for row in batch] for batch",
"DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert partition.x == BATCHED_INPUTS_MEDIUM assert partition.y == BATCHED_OUTPUTS_MEDIUM assert partition.sizes",
"for batch in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row",
"class TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self): partition = DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert partition.x == BATCHED_INPUTS_SMALL",
"range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ = [[True] + [len(row) for row in",
"for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ = [[True] + [len(row) for row in batch]",
"in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ = [[True] + [len(row) for row",
"for timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM",
"partition.num_batches == NUM_BATCHES_SMALL partition = DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert partition.x == BATCHED_INPUTS_MEDIUM assert",
"partition.x == BATCHED_INPUTS_MEDIUM assert partition.y == BATCHED_OUTPUTS_MEDIUM assert partition.sizes == BATCHED_SIZES_MEDIUM assert partition.num_batches",
"for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep",
"[[len(row) for row in batch] for batch in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for",
"for timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_",
"in batch] + [True] for batch in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL = [[len(row) for row",
"BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch",
"1 OUTPUT_PLACEHOLDER = 2 NUM_BATCHES_SMALL = 10 NUM_ROWS_SMALL = 10 ROW_LEN_SMALL = 5",
"+ [True] for batch in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM = [[len(row) for row in batch]",
"in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)]",
"range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for",
"== NUM_BATCHES_SMALL partition = DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert partition.x == BATCHED_INPUTS_MEDIUM assert partition.y",
"in batch] + [True] for batch in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM = [[len(row) for row",
"in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)]",
"batch in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ = [[True] + [len(row) for row in batch] +",
"TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self): partition = DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert partition.x == BATCHED_INPUTS_SMALL assert",
"+ [True] for batch in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL = [[len(row) for row in batch]",
"= [[True] + [len(row) for row in batch] + [True] for batch in",
"BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL = [[len(row) for row in batch] for batch in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM",
"batch in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL = [[len(row) for row in batch] for batch in",
"import * INPUT_PLACEHOLDER = 1 OUTPUT_PLACEHOLDER = 2 NUM_BATCHES_SMALL = 10 NUM_ROWS_SMALL =",
"= DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert partition.x == BATCHED_INPUTS_MEDIUM assert partition.y == BATCHED_OUTPUTS_MEDIUM assert",
"+ [len(row) for row in batch] + [True] for batch in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM",
"range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ = [[True] +",
"= DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert partition.x == BATCHED_INPUTS_SMALL assert partition.y == BATCHED_OUTPUTS_SMALL assert",
"row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ = [[True] + [len(row) for",
"timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL =",
"2 NUM_BATCHES_SMALL = 10 NUM_ROWS_SMALL = 10 ROW_LEN_SMALL = 5 NUM_BATCHES_MEDIUM = 1000",
"== BATCHED_INPUTS_SMALL assert partition.y == BATCHED_OUTPUTS_SMALL assert partition.sizes == BATCHED_SIZES_SMALL assert partition.num_batches ==",
"for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep",
"= [[len(row) for row in batch] for batch in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER",
"batch in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row in",
"in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM = [[len(row) for row in batch] for batch in BATCHED_INPUTS_MEDIUM]",
"timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ =",
"batch in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ = [[True] + [len(row) for row in batch] +",
"assert partition.x == BATCHED_INPUTS_SMALL assert partition.y == BATCHED_OUTPUTS_SMALL assert partition.sizes == BATCHED_SIZES_SMALL assert",
"BATCHED_SIZES_MEDIUM_ = [[True] + [len(row) for row in batch] + [True] for batch",
"BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert partition.x == BATCHED_INPUTS_SMALL assert partition.y == BATCHED_OUTPUTS_SMALL assert partition.sizes ==",
"= 10 NUM_ROWS_SMALL = 10 ROW_LEN_SMALL = 5 NUM_BATCHES_MEDIUM = 1000 NUM_ROWS_MEDIUM =",
"BATCHED_SIZES_SMALL_) assert partition.x == BATCHED_INPUTS_SMALL assert partition.y == BATCHED_OUTPUTS_SMALL assert partition.sizes == BATCHED_SIZES_SMALL",
"== BATCHED_SIZES_SMALL assert partition.num_batches == NUM_BATCHES_SMALL partition = DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert partition.x",
"row in batch] for batch in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in",
"INPUT_PLACEHOLDER = 1 OUTPUT_PLACEHOLDER = 2 NUM_BATCHES_SMALL = 10 NUM_ROWS_SMALL = 10 ROW_LEN_SMALL",
"for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row",
"in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)]",
"in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER",
"BATCHED_INPUTS_MEDIUM assert partition.y == BATCHED_OUTPUTS_MEDIUM assert partition.sizes == BATCHED_SIZES_MEDIUM assert partition.num_batches == NUM_BATCHES_MEDIUM",
"in batch] for batch in BATCHED_INPUTS_SMALL] BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)]",
"[len(row) for row in batch] + [True] for batch in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM =",
"= 1000 NUM_ROWS_MEDIUM = 100 ROW_LEN_MEDIUM = 20 BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep",
"partition.sizes == BATCHED_SIZES_SMALL assert partition.num_batches == NUM_BATCHES_SMALL partition = DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert",
"for row in batch] for batch in BATCHED_INPUTS_MEDIUM] class TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self): partition",
"range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ = [[True] + [len(row) for row in batch] + [True] for",
"batch in BATCHED_INPUTS_MEDIUM] class TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self): partition = DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert",
"batch] for batch in BATCHED_INPUTS_MEDIUM] class TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self): partition = DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL,",
"partition = DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert partition.x == BATCHED_INPUTS_MEDIUM assert partition.y == BATCHED_OUTPUTS_MEDIUM",
"BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert partition.x == BATCHED_INPUTS_MEDIUM assert partition.y == BATCHED_OUTPUTS_MEDIUM assert partition.sizes ==",
"= [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch in",
"tf_rnn.dataset import * INPUT_PLACEHOLDER = 1 OUTPUT_PLACEHOLDER = 2 NUM_BATCHES_SMALL = 10 NUM_ROWS_SMALL",
"import pytest from tf_rnn.dataset import * INPUT_PLACEHOLDER = 1 OUTPUT_PLACEHOLDER = 2 NUM_BATCHES_SMALL",
"10 ROW_LEN_SMALL = 5 NUM_BATCHES_MEDIUM = 1000 NUM_ROWS_MEDIUM = 100 ROW_LEN_MEDIUM = 20",
"range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER for",
"NUM_ROWS_MEDIUM = 100 ROW_LEN_MEDIUM = 20 BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)]",
"for batch in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL = [[len(row) for row in batch] for batch",
"in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)]",
"for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ = [[True] + [len(row)",
"range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ = [[True] +",
"partition.x == BATCHED_INPUTS_SMALL assert partition.y == BATCHED_OUTPUTS_SMALL assert partition.sizes == BATCHED_SIZES_SMALL assert partition.num_batches",
"= [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch in",
"BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM = [[len(row) for row in batch] for batch in BATCHED_INPUTS_MEDIUM] class",
"in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ = [[True] + [len(row) for row",
"range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ = [[True] + [len(row) for row in batch] + [True] for",
"== BATCHED_INPUTS_MEDIUM assert partition.y == BATCHED_OUTPUTS_MEDIUM assert partition.sizes == BATCHED_SIZES_MEDIUM assert partition.num_batches ==",
"batch in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row in",
"for batch in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ = [[True] + [len(row) for row in batch]",
"NUM_BATCHES_SMALL partition = DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_) assert partition.x == BATCHED_INPUTS_MEDIUM assert partition.y ==",
"[[len(row) for row in batch] for batch in BATCHED_INPUTS_MEDIUM] class TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self):",
"assert partition.y == BATCHED_OUTPUTS_SMALL assert partition.sizes == BATCHED_SIZES_SMALL assert partition.num_batches == NUM_BATCHES_SMALL partition",
"BATCHED_SIZES_MEDIUM = [[len(row) for row in batch] for batch in BATCHED_INPUTS_MEDIUM] class TestDataPartition():",
"NUM_BATCHES_SMALL = 10 NUM_ROWS_SMALL = 10 ROW_LEN_SMALL = 5 NUM_BATCHES_MEDIUM = 1000 NUM_ROWS_MEDIUM",
"= 1 OUTPUT_PLACEHOLDER = 2 NUM_BATCHES_SMALL = 10 NUM_ROWS_SMALL = 10 ROW_LEN_SMALL =",
"[len(row) for row in batch] + [True] for batch in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL =",
"ROW_LEN_SMALL = 5 NUM_BATCHES_MEDIUM = 1000 NUM_ROWS_MEDIUM = 100 ROW_LEN_MEDIUM = 20 BATCHED_INPUTS_SMALL",
"range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for",
"in BATCHED_INPUTS_MEDIUM] class TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self): partition = DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert partition.x",
"batch] + [True] for batch in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL = [[len(row) for row in",
"DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert partition.x == BATCHED_INPUTS_SMALL assert partition.y == BATCHED_OUTPUTS_SMALL assert partition.sizes",
"range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for",
"partition = DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_) assert partition.x == BATCHED_INPUTS_SMALL assert partition.y == BATCHED_OUTPUTS_SMALL",
"20 BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for",
"pytest from tf_rnn.dataset import * INPUT_PLACEHOLDER = 1 OUTPUT_PLACEHOLDER = 2 NUM_BATCHES_SMALL =",
"BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch",
"in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ = [[True] + [len(row) for row in batch] + [True]",
"[[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)]",
"BATCHED_INPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch",
"assert partition.x == BATCHED_INPUTS_MEDIUM assert partition.y == BATCHED_OUTPUTS_MEDIUM assert partition.sizes == BATCHED_SIZES_MEDIUM assert",
"[[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)]",
"OUTPUT_PLACEHOLDER = 2 NUM_BATCHES_SMALL = 10 NUM_ROWS_SMALL = 10 ROW_LEN_SMALL = 5 NUM_BATCHES_MEDIUM",
"= 100 ROW_LEN_MEDIUM = 20 BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for",
"= 5 NUM_BATCHES_MEDIUM = 1000 NUM_ROWS_MEDIUM = 100 ROW_LEN_MEDIUM = 20 BATCHED_INPUTS_SMALL =",
"10 NUM_ROWS_SMALL = 10 ROW_LEN_SMALL = 5 NUM_BATCHES_MEDIUM = 1000 NUM_ROWS_MEDIUM = 100",
"+ [len(row) for row in batch] + [True] for batch in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL",
"NUM_BATCHES_MEDIUM = 1000 NUM_ROWS_MEDIUM = 100 ROW_LEN_MEDIUM = 20 BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER for",
"[[True] + [len(row) for row in batch] + [True] for batch in BATCHED_INPUTS_SMALL]",
"for batch in BATCHED_INPUTS_MEDIUM] class TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self): partition = DataPartition(BATCHED_INPUTS_SMALL, BATCHED_OUTPUTS_SMALL, BATCHED_SIZES_SMALL_)",
"range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ = [[True] + [len(row) for row in",
"[[True] + [len(row) for row in batch] + [True] for batch in BATCHED_INPUTS_MEDIUM]",
"for timestep in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_",
"row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in",
"timestep in range(ROW_LEN_MEDIUM)] for row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_SIZES_MEDIUM_ =",
"batch] + [True] for batch in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM = [[len(row) for row in",
"1000 NUM_ROWS_MEDIUM = 100 ROW_LEN_MEDIUM = 20 BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in",
"BATCHED_SIZES_MEDIUM_) assert partition.x == BATCHED_INPUTS_MEDIUM assert partition.y == BATCHED_OUTPUTS_MEDIUM assert partition.sizes == BATCHED_SIZES_MEDIUM",
"for row in batch] + [True] for batch in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM = [[len(row)",
"assert partition.sizes == BATCHED_SIZES_SMALL assert partition.num_batches == NUM_BATCHES_SMALL partition = DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM, BATCHED_SIZES_MEDIUM_)",
"partition.y == BATCHED_OUTPUTS_SMALL assert partition.sizes == BATCHED_SIZES_SMALL assert partition.num_batches == NUM_BATCHES_SMALL partition =",
"in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL = [[len(row) for row in batch] for batch in BATCHED_INPUTS_SMALL]",
"NUM_ROWS_SMALL = 10 ROW_LEN_SMALL = 5 NUM_BATCHES_MEDIUM = 1000 NUM_ROWS_MEDIUM = 100 ROW_LEN_MEDIUM",
"in batch] for batch in BATCHED_INPUTS_MEDIUM] class TestDataPartition(): def test_should_correctly_calculate_the_batch_length(self): partition = DataPartition(BATCHED_INPUTS_SMALL,",
"== BATCHED_OUTPUTS_SMALL assert partition.sizes == BATCHED_SIZES_SMALL assert partition.num_batches == NUM_BATCHES_SMALL partition = DataPartition(BATCHED_INPUTS_MEDIUM,",
"row in range(NUM_ROWS_MEDIUM)] for batch in range(NUM_BATCHES_MEDIUM)] BATCHED_OUTPUTS_MEDIUM = [[[INPUT_PLACEHOLDER for timestep in",
"BATCHED_OUTPUTS_SMALL assert partition.sizes == BATCHED_SIZES_SMALL assert partition.num_batches == NUM_BATCHES_SMALL partition = DataPartition(BATCHED_INPUTS_MEDIUM, BATCHED_OUTPUTS_MEDIUM,",
"ROW_LEN_MEDIUM = 20 BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row in",
"100 ROW_LEN_MEDIUM = 20 BATCHED_INPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for row",
"row in batch] + [True] for batch in BATCHED_INPUTS_MEDIUM] BATCHED_SIZES_MEDIUM = [[len(row) for",
"for row in batch] + [True] for batch in BATCHED_INPUTS_SMALL] BATCHED_SIZES_SMALL = [[len(row)",
"range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_OUTPUTS_SMALL = [[[INPUT_PLACEHOLDER for timestep in range(ROW_LEN_SMALL)] for",
"= [[len(row) for row in batch] for batch in BATCHED_INPUTS_MEDIUM] class TestDataPartition(): def",
"BATCHED_SIZES_SMALL_ = [[True] + [len(row) for row in batch] + [True] for batch",
"in range(ROW_LEN_SMALL)] for row in range(NUM_ROWS_SMALL)] for batch in range(NUM_BATCHES_SMALL)] BATCHED_SIZES_SMALL_ = [[True]"
] |
[
"d = Taxi(args) return d, d.task elif name == \"higgs\": d = Higgs(args)",
"= Covtype(args) return d, d.task elif name == \"airline\": d = Airline(args) return",
"import Covtype from .airline import Airline from .epsilon import Epsilon from .generated import",
"from .covtype import Covtype from .airline import Airline from .epsilon import Epsilon from",
"name.startswith(\"mortgage\"): d: DataSet = Mortgage(args) return d, d.task elif name == \"taxi\": d",
"-> Tuple[DataSet, str]: if name.startswith(\"mortgage\"): d: DataSet = Mortgage(args) return d, d.task elif",
"str, args: argparse.Namespace) -> Tuple[DataSet, str]: if name.startswith(\"mortgage\"): d: DataSet = Mortgage(args) return",
"d.task elif name == \"higgs\": d = Higgs(args) return d, d.task elif name",
"DataSet = Mortgage(args) return d, d.task elif name == \"taxi\": d = Taxi(args)",
"import Higgs from .year import YearPrediction from .covtype import Covtype from .airline import",
"d, d.task elif name == \"year\": d = YearPrediction(args) return d, d.task elif",
"import Mortgage from .taxi import Taxi from .higgs import Higgs from .year import",
"== \"covtype\": d = Covtype(args) return d, d.task elif name == \"airline\": d",
".higgs import Higgs from .year import YearPrediction from .covtype import Covtype from .airline",
"== \"taxi\": d = Taxi(args) return d, d.task elif name == \"higgs\": d",
"Mortgage from .taxi import Taxi from .higgs import Higgs from .year import YearPrediction",
"\"airline\": d = Airline(args) return d, d.task elif name == \"epsilon\": d =",
"from typing import Tuple from dxgb_bench.utils import DataSet def factory(name: str, args: argparse.Namespace)",
"Epsilon from .generated import Generated import argparse from typing import Tuple from dxgb_bench.utils",
"from .taxi import Taxi from .higgs import Higgs from .year import YearPrediction from",
"d.task elif name == \"epsilon\": d = Epsilon(args) return d, d.task elif name",
"elif name == \"covtype\": d = Covtype(args) return d, d.task elif name ==",
"def factory(name: str, args: argparse.Namespace) -> Tuple[DataSet, str]: if name.startswith(\"mortgage\"): d: DataSet =",
"d = Higgs(args) return d, d.task elif name == \"year\": d = YearPrediction(args)",
"== \"higgs\": d = Higgs(args) return d, d.task elif name == \"year\": d",
"import Taxi from .higgs import Higgs from .year import YearPrediction from .covtype import",
"if name.startswith(\"mortgage\"): d: DataSet = Mortgage(args) return d, d.task elif name == \"taxi\":",
"from .epsilon import Epsilon from .generated import Generated import argparse from typing import",
".covtype import Covtype from .airline import Airline from .epsilon import Epsilon from .generated",
"= Mortgage(args) return d, d.task elif name == \"taxi\": d = Taxi(args) return",
"Generated import argparse from typing import Tuple from dxgb_bench.utils import DataSet def factory(name:",
"d, d.task elif name == \"epsilon\": d = Epsilon(args) return d, d.task elif",
"return d, d.task elif name == \"taxi\": d = Taxi(args) return d, d.task",
"== \"airline\": d = Airline(args) return d, d.task elif name == \"epsilon\": d",
"DataSet def factory(name: str, args: argparse.Namespace) -> Tuple[DataSet, str]: if name.startswith(\"mortgage\"): d: DataSet",
"\"year\": d = YearPrediction(args) return d, d.task elif name == \"covtype\": d =",
"d, d.task elif name == \"airline\": d = Airline(args) return d, d.task elif",
"d, d.task elif name == \"generated\": d = Generated(args) return d, d.task else:",
"elif name == \"taxi\": d = Taxi(args) return d, d.task elif name ==",
"Higgs from .year import YearPrediction from .covtype import Covtype from .airline import Airline",
"return d, d.task elif name == \"generated\": d = Generated(args) return d, d.task",
"Covtype from .airline import Airline from .epsilon import Epsilon from .generated import Generated",
"\"epsilon\": d = Epsilon(args) return d, d.task elif name == \"generated\": d =",
"d, d.task elif name == \"higgs\": d = Higgs(args) return d, d.task elif",
"d.task elif name == \"generated\": d = Generated(args) return d, d.task else: raise",
"d, d.task elif name == \"covtype\": d = Covtype(args) return d, d.task elif",
"import Tuple from dxgb_bench.utils import DataSet def factory(name: str, args: argparse.Namespace) -> Tuple[DataSet,",
"from .higgs import Higgs from .year import YearPrediction from .covtype import Covtype from",
"= Airline(args) return d, d.task elif name == \"epsilon\": d = Epsilon(args) return",
"return d, d.task elif name == \"airline\": d = Airline(args) return d, d.task",
".mortgage import Mortgage from .taxi import Taxi from .higgs import Higgs from .year",
"import DataSet def factory(name: str, args: argparse.Namespace) -> Tuple[DataSet, str]: if name.startswith(\"mortgage\"): d:",
"from .year import YearPrediction from .covtype import Covtype from .airline import Airline from",
"Taxi(args) return d, d.task elif name == \"higgs\": d = Higgs(args) return d,",
"d.task elif name == \"taxi\": d = Taxi(args) return d, d.task elif name",
"= Higgs(args) return d, d.task elif name == \"year\": d = YearPrediction(args) return",
"elif name == \"epsilon\": d = Epsilon(args) return d, d.task elif name ==",
"import Airline from .epsilon import Epsilon from .generated import Generated import argparse from",
"Airline(args) return d, d.task elif name == \"epsilon\": d = Epsilon(args) return d,",
"\"covtype\": d = Covtype(args) return d, d.task elif name == \"airline\": d =",
"elif name == \"year\": d = YearPrediction(args) return d, d.task elif name ==",
"d = Airline(args) return d, d.task elif name == \"epsilon\": d = Epsilon(args)",
"args: argparse.Namespace) -> Tuple[DataSet, str]: if name.startswith(\"mortgage\"): d: DataSet = Mortgage(args) return d,",
"factory(name: str, args: argparse.Namespace) -> Tuple[DataSet, str]: if name.startswith(\"mortgage\"): d: DataSet = Mortgage(args)",
".airline import Airline from .epsilon import Epsilon from .generated import Generated import argparse",
"name == \"year\": d = YearPrediction(args) return d, d.task elif name == \"covtype\":",
"name == \"airline\": d = Airline(args) return d, d.task elif name == \"epsilon\":",
".taxi import Taxi from .higgs import Higgs from .year import YearPrediction from .covtype",
"name == \"covtype\": d = Covtype(args) return d, d.task elif name == \"airline\":",
"dxgb_bench.utils import DataSet def factory(name: str, args: argparse.Namespace) -> Tuple[DataSet, str]: if name.startswith(\"mortgage\"):",
"from .generated import Generated import argparse from typing import Tuple from dxgb_bench.utils import",
"Covtype(args) return d, d.task elif name == \"airline\": d = Airline(args) return d,",
"\"higgs\": d = Higgs(args) return d, d.task elif name == \"year\": d =",
"import Epsilon from .generated import Generated import argparse from typing import Tuple from",
"Tuple from dxgb_bench.utils import DataSet def factory(name: str, args: argparse.Namespace) -> Tuple[DataSet, str]:",
"d = Epsilon(args) return d, d.task elif name == \"generated\": d = Generated(args)",
"import Generated import argparse from typing import Tuple from dxgb_bench.utils import DataSet def",
"YearPrediction(args) return d, d.task elif name == \"covtype\": d = Covtype(args) return d,",
"argparse.Namespace) -> Tuple[DataSet, str]: if name.startswith(\"mortgage\"): d: DataSet = Mortgage(args) return d, d.task",
"name == \"taxi\": d = Taxi(args) return d, d.task elif name == \"higgs\":",
"YearPrediction from .covtype import Covtype from .airline import Airline from .epsilon import Epsilon",
"import argparse from typing import Tuple from dxgb_bench.utils import DataSet def factory(name: str,",
"name == \"epsilon\": d = Epsilon(args) return d, d.task elif name == \"generated\":",
"Epsilon(args) return d, d.task elif name == \"generated\": d = Generated(args) return d,",
"Taxi from .higgs import Higgs from .year import YearPrediction from .covtype import Covtype",
"d.task elif name == \"airline\": d = Airline(args) return d, d.task elif name",
"typing import Tuple from dxgb_bench.utils import DataSet def factory(name: str, args: argparse.Namespace) ->",
"from .mortgage import Mortgage from .taxi import Taxi from .higgs import Higgs from",
"== \"year\": d = YearPrediction(args) return d, d.task elif name == \"covtype\": d",
"Mortgage(args) return d, d.task elif name == \"taxi\": d = Taxi(args) return d,",
"\"taxi\": d = Taxi(args) return d, d.task elif name == \"higgs\": d =",
"d = YearPrediction(args) return d, d.task elif name == \"covtype\": d = Covtype(args)",
"Tuple[DataSet, str]: if name.startswith(\"mortgage\"): d: DataSet = Mortgage(args) return d, d.task elif name",
"return d, d.task elif name == \"epsilon\": d = Epsilon(args) return d, d.task",
"== \"generated\": d = Generated(args) return d, d.task else: raise ValueError(\"Unknown dataset:\", name)",
"argparse from typing import Tuple from dxgb_bench.utils import DataSet def factory(name: str, args:",
".generated import Generated import argparse from typing import Tuple from dxgb_bench.utils import DataSet",
"elif name == \"generated\": d = Generated(args) return d, d.task else: raise ValueError(\"Unknown",
"elif name == \"airline\": d = Airline(args) return d, d.task elif name ==",
"Airline from .epsilon import Epsilon from .generated import Generated import argparse from typing",
"return d, d.task elif name == \"covtype\": d = Covtype(args) return d, d.task",
"name == \"generated\": d = Generated(args) return d, d.task else: raise ValueError(\"Unknown dataset:\",",
"= Taxi(args) return d, d.task elif name == \"higgs\": d = Higgs(args) return",
"d.task elif name == \"covtype\": d = Covtype(args) return d, d.task elif name",
"from .airline import Airline from .epsilon import Epsilon from .generated import Generated import",
"from dxgb_bench.utils import DataSet def factory(name: str, args: argparse.Namespace) -> Tuple[DataSet, str]: if",
".epsilon import Epsilon from .generated import Generated import argparse from typing import Tuple",
"elif name == \"higgs\": d = Higgs(args) return d, d.task elif name ==",
"d: DataSet = Mortgage(args) return d, d.task elif name == \"taxi\": d =",
"d, d.task elif name == \"taxi\": d = Taxi(args) return d, d.task elif",
"= YearPrediction(args) return d, d.task elif name == \"covtype\": d = Covtype(args) return",
"return d, d.task elif name == \"higgs\": d = Higgs(args) return d, d.task",
"return d, d.task elif name == \"year\": d = YearPrediction(args) return d, d.task",
".year import YearPrediction from .covtype import Covtype from .airline import Airline from .epsilon",
"name == \"higgs\": d = Higgs(args) return d, d.task elif name == \"year\":",
"str]: if name.startswith(\"mortgage\"): d: DataSet = Mortgage(args) return d, d.task elif name ==",
"d = Covtype(args) return d, d.task elif name == \"airline\": d = Airline(args)",
"d.task elif name == \"year\": d = YearPrediction(args) return d, d.task elif name",
"Higgs(args) return d, d.task elif name == \"year\": d = YearPrediction(args) return d,",
"import YearPrediction from .covtype import Covtype from .airline import Airline from .epsilon import",
"= Epsilon(args) return d, d.task elif name == \"generated\": d = Generated(args) return",
"== \"epsilon\": d = Epsilon(args) return d, d.task elif name == \"generated\": d"
] |
[
"0.05, seed: int = 42, device: str = 'cpu', batch_size: int = 5,",
"import ClipGradNorm, CommitScalarByMean, Evaluation from houttuynia.triggers import Periodic from houttuynia.utils import ensure_output_dir, experiment_hash,",
"number device: device id batch_size: the size of each batch num_epochs: the total",
"device: device id batch_size: the size of each batch num_epochs: the total numbers",
"from houttuynia.utils import ensure_output_dir, experiment_hash, options_dump class IrisEstimator(Classifier): def __init__(self, in_features: int, num_classes:",
"out_dir: the root path of output monitor: the type of monitor \"\"\" options",
"'tensorboard') = 'tensorboard'): \"\"\" train iris classifier Args: hidden_features: the size of hidden",
"= 42, device: str = 'cpu', batch_size: int = 5, num_epochs: int =",
"hidden_features: the size of hidden layers dropout: the dropout ratio bias: whether or",
"from torch import nn, optim from houttuynia.monitors import get_monitor from houttuynia.schedules import EpochalSchedule",
"= in_features self.num_classes = num_classes self.hidden_features = hidden_features self.negative_slope = negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential(",
"ratio bias: whether or not use the bias in hidden layers negative_slope: the",
"out_dir / experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir => {experiment_dir}') manual_seed(seed) log_system.notice(f'seed => {seed}')",
"Periodic from houttuynia.utils import ensure_output_dir, experiment_hash, options_dump class IrisEstimator(Classifier): def __init__(self, in_features: int,",
"'criterion', 'acc', chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion', 'acc', chapter='test'),",
"Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion', 'acc', chapter='test'), )) return schedule.run(train, num_epochs) if __name__ == '__main__':",
"nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, num_classes, bias), )) app =",
"schedule = EpochalSchedule(estimator, optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion', 'acc', chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.))",
"= 'tensorboard'): \"\"\" train iris classifier Args: hidden_features: the size of hidden layers",
"{seed}') train, test = prepare_iris_dataset(batch_size) estimator = IrisEstimator( in_features=4, dropout=dropout, num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope,",
"nn.Linear(in_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, num_classes, bias),",
"the random seed number device: device id batch_size: the size of each batch",
"experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir => {experiment_dir}') manual_seed(seed) log_system.notice(f'seed => {seed}') train, test",
"bias: bool, negative_slope: float) -> None: self.dropout = dropout self.in_features = in_features self.num_classes",
"import aku from torch import nn, optim from houttuynia.monitors import get_monitor from houttuynia.schedules",
"float, bias: bool, negative_slope: float) -> None: self.dropout = dropout self.in_features = in_features",
"of output monitor: the type of monitor \"\"\" options = locals() experiment_dir =",
"self.negative_slope = negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, hidden_features,",
"bias=bias ) optimizer = optim.Adam(estimator.parameters()) monitor = get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator) schedule = EpochalSchedule(estimator,",
"Path import aku from torch import nn, optim from houttuynia.monitors import get_monitor from",
"dropout: float = 0.05, bias: bool = True, negative_slope: float = 0.05, seed:",
"monitor: the type of monitor \"\"\" options = locals() experiment_dir = out_dir /",
"= aku.App(__file__) @app.register def train(hidden_features: int = 100, dropout: float = 0.05, bias:",
"Path = Path('../out_dir'), monitor: ('filesystem', 'tensorboard') = 'tensorboard'): \"\"\" train iris classifier Args:",
"use the bias in hidden layers negative_slope: the ratio of negative part seed:",
"/ experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir => {experiment_dir}') manual_seed(seed) log_system.notice(f'seed => {seed}') train,",
"train(hidden_features: int = 100, dropout: float = 0.05, bias: bool = True, negative_slope:",
") optimizer = optim.Adam(estimator.parameters()) monitor = get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator) schedule = EpochalSchedule(estimator, optimizer,",
"torch import nn, optim from houttuynia.monitors import get_monitor from houttuynia.schedules import EpochalSchedule from",
"= hidden_features self.negative_slope = negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True),",
"\"\"\" train iris classifier Args: hidden_features: the size of hidden layers dropout: the",
"monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion', 'acc', chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'),",
"inplace=True), nn.Linear(hidden_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, num_classes, bias), )) app = aku.App(__file__)",
"monitor = get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator) schedule = EpochalSchedule(estimator, optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion',",
"import EpochalSchedule from houttuynia.nn import Classifier from houttuynia import log_system, manual_seed, to_device from",
"import Classifier from houttuynia import log_system, manual_seed, to_device from houttuynia.datasets import prepare_iris_dataset from",
"CommitScalarByMean, Evaluation from houttuynia.triggers import Periodic from houttuynia.utils import ensure_output_dir, experiment_hash, options_dump class",
"seed: the random seed number device: device id batch_size: the size of each",
"100, dropout: float = 0.05, bias: bool = True, negative_slope: float = 0.05,",
"id batch_size: the size of each batch num_epochs: the total numbers of epochs",
"ratio of negative part seed: the random seed number device: device id batch_size:",
"ensure_output_dir, experiment_hash, options_dump class IrisEstimator(Classifier): def __init__(self, in_features: int, num_classes: int, hidden_features: int,",
"in_features: int, num_classes: int, hidden_features: int, dropout: float, bias: bool, negative_slope: float) ->",
"**options) log_system.notice(f'experiment_dir => {experiment_dir}') manual_seed(seed) log_system.notice(f'seed => {seed}') train, test = prepare_iris_dataset(batch_size) estimator",
"get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator) schedule = EpochalSchedule(estimator, optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion', 'acc', chapter='train',",
"hidden_features: int, dropout: float, bias: bool, negative_slope: float) -> None: self.dropout = dropout",
"houttuynia.schedule import Moment, Pipeline from houttuynia.extensions import ClipGradNorm, CommitScalarByMean, Evaluation from houttuynia.triggers import",
"Pipeline from houttuynia.extensions import ClipGradNorm, CommitScalarByMean, Evaluation from houttuynia.triggers import Periodic from houttuynia.utils",
"seed: int = 42, device: str = 'cpu', batch_size: int = 5, num_epochs:",
"or not use the bias in hidden layers negative_slope: the ratio of negative",
"ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir => {experiment_dir}') manual_seed(seed) log_system.notice(f'seed => {seed}') train, test =",
"negative part seed: the random seed number device: device id batch_size: the size",
"num_epochs: int = 50, out_dir: Path = Path('../out_dir'), monitor: ('filesystem', 'tensorboard') = 'tensorboard'):",
"whether or not use the bias in hidden layers negative_slope: the ratio of",
"iteration=5))(CommitScalarByMean( 'criterion', 'acc', chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion', 'acc',",
"{experiment_dir}') manual_seed(seed) log_system.notice(f'seed => {seed}') train, test = prepare_iris_dataset(batch_size) estimator = IrisEstimator( in_features=4,",
"float) -> None: self.dropout = dropout self.in_features = in_features self.num_classes = num_classes self.hidden_features",
"log_system, manual_seed, to_device from houttuynia.datasets import prepare_iris_dataset from houttuynia.schedule import Moment, Pipeline from",
"manual_seed, to_device from houttuynia.datasets import prepare_iris_dataset from houttuynia.schedule import Moment, Pipeline from houttuynia.extensions",
"Evaluation from houttuynia.triggers import Periodic from houttuynia.utils import ensure_output_dir, experiment_hash, options_dump class IrisEstimator(Classifier):",
"hidden layers dropout: the dropout ratio bias: whether or not use the bias",
"import get_monitor from houttuynia.schedules import EpochalSchedule from houttuynia.nn import Classifier from houttuynia import",
"=> {seed}') train, test = prepare_iris_dataset(batch_size) estimator = IrisEstimator( in_features=4, dropout=dropout, num_classes=3, hidden_features=hidden_features,",
"num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope, bias=bias ) optimizer = optim.Adam(estimator.parameters()) monitor = get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator)",
"num_classes self.hidden_features = hidden_features self.negative_slope = negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features, hidden_features, bias),",
"train, test = prepare_iris_dataset(batch_size) estimator = IrisEstimator( in_features=4, dropout=dropout, num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope, bias=bias",
"chapter='test'), CommitScalarByMean('criterion', 'acc', chapter='test'), )) return schedule.run(train, num_epochs) if __name__ == '__main__': app.run()",
"of epochs out_dir: the root path of output monitor: the type of monitor",
"epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion', 'acc', chapter='test'), )) return schedule.run(train, num_epochs) if __name__ ==",
"of hidden layers dropout: the dropout ratio bias: whether or not use the",
"optim from houttuynia.monitors import get_monitor from houttuynia.schedules import EpochalSchedule from houttuynia.nn import Classifier",
"from houttuynia.nn import Classifier from houttuynia import log_system, manual_seed, to_device from houttuynia.datasets import",
"= EpochalSchedule(estimator, optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion', 'acc', chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH,",
"0.05, bias: bool = True, negative_slope: float = 0.05, seed: int = 42,",
"def __init__(self, in_features: int, num_classes: int, hidden_features: int, dropout: float, bias: bool, negative_slope:",
"from pathlib import Path import aku from torch import nn, optim from houttuynia.monitors",
"iris classifier Args: hidden_features: the size of hidden layers dropout: the dropout ratio",
"42, device: str = 'cpu', batch_size: int = 5, num_epochs: int = 50,",
"train iris classifier Args: hidden_features: the size of hidden layers dropout: the dropout",
"size of each batch num_epochs: the total numbers of epochs out_dir: the root",
"of monitor \"\"\" options = locals() experiment_dir = out_dir / experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir,",
"app = aku.App(__file__) @app.register def train(hidden_features: int = 100, dropout: float = 0.05,",
"random seed number device: device id batch_size: the size of each batch num_epochs:",
"path of output monitor: the type of monitor \"\"\" options = locals() experiment_dir",
"self.num_classes = num_classes self.hidden_features = hidden_features self.negative_slope = negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features,",
"import log_system, manual_seed, to_device from houttuynia.datasets import prepare_iris_dataset from houttuynia.schedule import Moment, Pipeline",
"import prepare_iris_dataset from houttuynia.schedule import Moment, Pipeline from houttuynia.extensions import ClipGradNorm, CommitScalarByMean, Evaluation",
"in_features self.num_classes = num_classes self.hidden_features = hidden_features self.negative_slope = negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout),",
"import Periodic from houttuynia.utils import ensure_output_dir, experiment_hash, options_dump class IrisEstimator(Classifier): def __init__(self, in_features:",
"chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion', 'acc', chapter='test'), )) return",
"epochs out_dir: the root path of output monitor: the type of monitor \"\"\"",
"bool, negative_slope: float) -> None: self.dropout = dropout self.in_features = in_features self.num_classes =",
"dropout: float, bias: bool, negative_slope: float) -> None: self.dropout = dropout self.in_features =",
"import nn, optim from houttuynia.monitors import get_monitor from houttuynia.schedules import EpochalSchedule from houttuynia.nn",
"aku.App(__file__) @app.register def train(hidden_features: int = 100, dropout: float = 0.05, bias: bool",
"iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion', 'acc', chapter='test'), )) return schedule.run(train, num_epochs) if",
"int = 100, dropout: float = 0.05, bias: bool = True, negative_slope: float",
"batch_size: the size of each batch num_epochs: the total numbers of epochs out_dir:",
"estimator = IrisEstimator( in_features=4, dropout=dropout, num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope, bias=bias ) optimizer = optim.Adam(estimator.parameters())",
"from houttuynia.schedule import Moment, Pipeline from houttuynia.extensions import ClipGradNorm, CommitScalarByMean, Evaluation from houttuynia.triggers",
"Path('../out_dir'), monitor: ('filesystem', 'tensorboard') = 'tensorboard'): \"\"\" train iris classifier Args: hidden_features: the",
"schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion', 'acc', chapter='test'), )) return schedule.run(train, num_epochs)",
"= get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator) schedule = EpochalSchedule(estimator, optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion', 'acc',",
"= True, negative_slope: float = 0.05, seed: int = 42, device: str =",
"'cpu', batch_size: int = 5, num_epochs: int = 50, out_dir: Path = Path('../out_dir'),",
"from houttuynia.datasets import prepare_iris_dataset from houttuynia.schedule import Moment, Pipeline from houttuynia.extensions import ClipGradNorm,",
"classifier Args: hidden_features: the size of hidden layers dropout: the dropout ratio bias:",
"= locals() experiment_dir = out_dir / experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir => {experiment_dir}')",
"def train(hidden_features: int = 100, dropout: float = 0.05, bias: bool = True,",
"batch_size: int = 5, num_epochs: int = 50, out_dir: Path = Path('../out_dir'), monitor:",
"optimizer = optim.Adam(estimator.parameters()) monitor = get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator) schedule = EpochalSchedule(estimator, optimizer, monitor)",
"optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion', 'acc', chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test,",
"Moment, Pipeline from houttuynia.extensions import ClipGradNorm, CommitScalarByMean, Evaluation from houttuynia.triggers import Periodic from",
"the dropout ratio bias: whether or not use the bias in hidden layers",
"super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True),",
"the ratio of negative part seed: the random seed number device: device id",
"in hidden layers negative_slope: the ratio of negative part seed: the random seed",
"self.hidden_features = hidden_features self.negative_slope = negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope,",
"class IrisEstimator(Classifier): def __init__(self, in_features: int, num_classes: int, hidden_features: int, dropout: float, bias:",
"Args: hidden_features: the size of hidden layers dropout: the dropout ratio bias: whether",
"bias: bool = True, negative_slope: float = 0.05, seed: int = 42, device:",
"= dropout self.in_features = in_features self.num_classes = num_classes self.hidden_features = hidden_features self.negative_slope =",
"int, hidden_features: int, dropout: float, bias: bool, negative_slope: float) -> None: self.dropout =",
"root path of output monitor: the type of monitor \"\"\" options = locals()",
"the size of each batch num_epochs: the total numbers of epochs out_dir: the",
"to_device from houttuynia.datasets import prepare_iris_dataset from houttuynia.schedule import Moment, Pipeline from houttuynia.extensions import",
"int, dropout: float, bias: bool, negative_slope: float) -> None: self.dropout = dropout self.in_features",
"get_monitor from houttuynia.schedules import EpochalSchedule from houttuynia.nn import Classifier from houttuynia import log_system,",
"('filesystem', 'tensorboard') = 'tensorboard'): \"\"\" train iris classifier Args: hidden_features: the size of",
"of negative part seed: the random seed number device: device id batch_size: the",
"@app.register def train(hidden_features: int = 100, dropout: float = 0.05, bias: bool =",
"dropout ratio bias: whether or not use the bias in hidden layers negative_slope:",
"= 100, dropout: float = 0.05, bias: bool = True, negative_slope: float =",
"houttuynia.monitors import get_monitor from houttuynia.schedules import EpochalSchedule from houttuynia.nn import Classifier from houttuynia",
"num_epochs: the total numbers of epochs out_dir: the root path of output monitor:",
"options_dump class IrisEstimator(Classifier): def __init__(self, in_features: int, num_classes: int, hidden_features: int, dropout: float,",
"monitor: ('filesystem', 'tensorboard') = 'tensorboard'): \"\"\" train iris classifier Args: hidden_features: the size",
"__init__(self, in_features: int, num_classes: int, hidden_features: int, dropout: float, bias: bool, negative_slope: float)",
"negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope,",
"bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, num_classes, bias), )) app = aku.App(__file__) @app.register def train(hidden_features:",
"negative_slope: float) -> None: self.dropout = dropout self.in_features = in_features self.num_classes = num_classes",
"= prepare_iris_dataset(batch_size) estimator = IrisEstimator( in_features=4, dropout=dropout, num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope, bias=bias ) optimizer",
"pathlib import Path import aku from torch import nn, optim from houttuynia.monitors import",
"nn.Linear(hidden_features, num_classes, bias), )) app = aku.App(__file__) @app.register def train(hidden_features: int = 100,",
"= negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, hidden_features, bias),",
"'tensorboard'): \"\"\" train iris classifier Args: hidden_features: the size of hidden layers dropout:",
"int, num_classes: int, hidden_features: int, dropout: float, bias: bool, negative_slope: float) -> None:",
"optim.Adam(estimator.parameters()) monitor = get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator) schedule = EpochalSchedule(estimator, optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean(",
"negative_slope=negative_slope, bias=bias ) optimizer = optim.Adam(estimator.parameters()) monitor = get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator) schedule =",
"log_system.notice(f'seed => {seed}') train, test = prepare_iris_dataset(batch_size) estimator = IrisEstimator( in_features=4, dropout=dropout, num_classes=3,",
"= optim.Adam(estimator.parameters()) monitor = get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator) schedule = EpochalSchedule(estimator, optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION,",
"out_dir: Path = Path('../out_dir'), monitor: ('filesystem', 'tensorboard') = 'tensorboard'): \"\"\" train iris classifier",
"layers negative_slope: the ratio of negative part seed: the random seed number device:",
"50, out_dir: Path = Path('../out_dir'), monitor: ('filesystem', 'tensorboard') = 'tensorboard'): \"\"\" train iris",
"inplace=True), nn.Linear(hidden_features, num_classes, bias), )) app = aku.App(__file__) @app.register def train(hidden_features: int =",
"type of monitor \"\"\" options = locals() experiment_dir = out_dir / experiment_hash(**options) ensure_output_dir(experiment_dir)",
"IrisEstimator(Classifier): def __init__(self, in_features: int, num_classes: int, hidden_features: int, dropout: float, bias: bool,",
"nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, num_classes, bias), )) app = aku.App(__file__) @app.register def train(hidden_features: int",
"bool = True, negative_slope: float = 0.05, seed: int = 42, device: str",
"import Moment, Pipeline from houttuynia.extensions import ClipGradNorm, CommitScalarByMean, Evaluation from houttuynia.triggers import Periodic",
")) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion', 'acc', chapter='test'), )) return schedule.run(train,",
"houttuynia.utils import ensure_output_dir, experiment_hash, options_dump class IrisEstimator(Classifier): def __init__(self, in_features: int, num_classes: int,",
"bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, num_classes, bias), )) app",
"= 50, out_dir: Path = Path('../out_dir'), monitor: ('filesystem', 'tensorboard') = 'tensorboard'): \"\"\" train",
"from houttuynia.triggers import Periodic from houttuynia.utils import ensure_output_dir, experiment_hash, options_dump class IrisEstimator(Classifier): def",
"from houttuynia.schedules import EpochalSchedule from houttuynia.nn import Classifier from houttuynia import log_system, manual_seed,",
"negative_slope: float = 0.05, seed: int = 42, device: str = 'cpu', batch_size:",
"int = 5, num_epochs: int = 50, out_dir: Path = Path('../out_dir'), monitor: ('filesystem',",
"dropout self.in_features = in_features self.num_classes = num_classes self.hidden_features = hidden_features self.negative_slope = negative_slope",
"self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features,",
"in_features=4, dropout=dropout, num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope, bias=bias ) optimizer = optim.Adam(estimator.parameters()) monitor = get_monitor(monitor)(log_dir=experiment_dir)",
"locals() experiment_dir = out_dir / experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir => {experiment_dir}') manual_seed(seed)",
"houttuynia.extensions import ClipGradNorm, CommitScalarByMean, Evaluation from houttuynia.triggers import Periodic from houttuynia.utils import ensure_output_dir,",
"self.dropout = dropout self.in_features = in_features self.num_classes = num_classes self.hidden_features = hidden_features self.negative_slope",
"houttuynia.datasets import prepare_iris_dataset from houttuynia.schedule import Moment, Pipeline from houttuynia.extensions import ClipGradNorm, CommitScalarByMean,",
"= num_classes self.hidden_features = hidden_features self.negative_slope = negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features, hidden_features,",
"device: str = 'cpu', batch_size: int = 5, num_epochs: int = 50, out_dir:",
")) app = aku.App(__file__) @app.register def train(hidden_features: int = 100, dropout: float =",
"houttuynia import log_system, manual_seed, to_device from houttuynia.datasets import prepare_iris_dataset from houttuynia.schedule import Moment,",
"nn.Dropout(dropout), nn.Linear(in_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, num_classes,",
"int = 42, device: str = 'cpu', batch_size: int = 5, num_epochs: int",
"bias in hidden layers negative_slope: the ratio of negative part seed: the random",
"bias), )) app = aku.App(__file__) @app.register def train(hidden_features: int = 100, dropout: float",
"import ensure_output_dir, experiment_hash, options_dump class IrisEstimator(Classifier): def __init__(self, in_features: int, num_classes: int, hidden_features:",
"float = 0.05, seed: int = 42, device: str = 'cpu', batch_size: int",
"nn, optim from houttuynia.monitors import get_monitor from houttuynia.schedules import EpochalSchedule from houttuynia.nn import",
"the root path of output monitor: the type of monitor \"\"\" options =",
"dropout=dropout, num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope, bias=bias ) optimizer = optim.Adam(estimator.parameters()) monitor = get_monitor(monitor)(log_dir=experiment_dir) to_device(device,",
"num_classes: int, hidden_features: int, dropout: float, bias: bool, negative_slope: float) -> None: self.dropout",
"negative_slope: the ratio of negative part seed: the random seed number device: device",
"each batch num_epochs: the total numbers of epochs out_dir: the root path of",
"total numbers of epochs out_dir: the root path of output monitor: the type",
"prepare_iris_dataset(batch_size) estimator = IrisEstimator( in_features=4, dropout=dropout, num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope, bias=bias ) optimizer =",
"schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion', 'acc', chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion',",
"to_device(device, estimator) schedule = EpochalSchedule(estimator, optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion', 'acc', chapter='train', ))",
"aku from torch import nn, optim from houttuynia.monitors import get_monitor from houttuynia.schedules import",
"numbers of epochs out_dir: the root path of output monitor: the type of",
"Classifier from houttuynia import log_system, manual_seed, to_device from houttuynia.datasets import prepare_iris_dataset from houttuynia.schedule",
"experiment_dir = out_dir / experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir => {experiment_dir}') manual_seed(seed) log_system.notice(f'seed",
"= 0.05, bias: bool = True, negative_slope: float = 0.05, seed: int =",
"EpochalSchedule(estimator, optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion', 'acc', chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline(",
"self.in_features = in_features self.num_classes = num_classes self.hidden_features = hidden_features self.negative_slope = negative_slope super(IrisEstimator,",
"'acc', chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD, iteration=1))(ClipGradNorm(max_norm=4.)) schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion', 'acc', chapter='test'), ))",
"5, num_epochs: int = 50, out_dir: Path = Path('../out_dir'), monitor: ('filesystem', 'tensorboard') =",
"houttuynia.nn import Classifier from houttuynia import log_system, manual_seed, to_device from houttuynia.datasets import prepare_iris_dataset",
"int = 50, out_dir: Path = Path('../out_dir'), monitor: ('filesystem', 'tensorboard') = 'tensorboard'): \"\"\"",
"part seed: the random seed number device: device id batch_size: the size of",
"monitor \"\"\" options = locals() experiment_dir = out_dir / experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options)",
"ClipGradNorm, CommitScalarByMean, Evaluation from houttuynia.triggers import Periodic from houttuynia.utils import ensure_output_dir, experiment_hash, options_dump",
"str = 'cpu', batch_size: int = 5, num_epochs: int = 50, out_dir: Path",
"EpochalSchedule from houttuynia.nn import Classifier from houttuynia import log_system, manual_seed, to_device from houttuynia.datasets",
"from houttuynia.extensions import ClipGradNorm, CommitScalarByMean, Evaluation from houttuynia.triggers import Periodic from houttuynia.utils import",
"experiment_hash, options_dump class IrisEstimator(Classifier): def __init__(self, in_features: int, num_classes: int, hidden_features: int, dropout:",
"hidden layers negative_slope: the ratio of negative part seed: the random seed number",
"log_system.notice(f'experiment_dir => {experiment_dir}') manual_seed(seed) log_system.notice(f'seed => {seed}') train, test = prepare_iris_dataset(batch_size) estimator =",
"of each batch num_epochs: the total numbers of epochs out_dir: the root path",
"=> {experiment_dir}') manual_seed(seed) log_system.notice(f'seed => {seed}') train, test = prepare_iris_dataset(batch_size) estimator = IrisEstimator(",
"the bias in hidden layers negative_slope: the ratio of negative part seed: the",
"nn.Linear(hidden_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, num_classes, bias), )) app = aku.App(__file__) @app.register",
"\"\"\" options = locals() experiment_dir = out_dir / experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir",
"schedule.register_extension(Periodic(Moment.AFTER_EPOCH, epoch=1))(Pipeline( Evaluation(data_loader=test, chapter='test'), CommitScalarByMean('criterion', 'acc', chapter='test'), )) return schedule.run(train, num_epochs) if __name__",
"num_classes, bias), )) app = aku.App(__file__) @app.register def train(hidden_features: int = 100, dropout:",
"the total numbers of epochs out_dir: the root path of output monitor: the",
"batch num_epochs: the total numbers of epochs out_dir: the root path of output",
"import Path import aku from torch import nn, optim from houttuynia.monitors import get_monitor",
"= Path('../out_dir'), monitor: ('filesystem', 'tensorboard') = 'tensorboard'): \"\"\" train iris classifier Args: hidden_features:",
"= 5, num_epochs: int = 50, out_dir: Path = Path('../out_dir'), monitor: ('filesystem', 'tensorboard')",
"True, negative_slope: float = 0.05, seed: int = 42, device: str = 'cpu',",
"= 'cpu', batch_size: int = 5, num_epochs: int = 50, out_dir: Path =",
"bias: whether or not use the bias in hidden layers negative_slope: the ratio",
"manual_seed(seed) log_system.notice(f'seed => {seed}') train, test = prepare_iris_dataset(batch_size) estimator = IrisEstimator( in_features=4, dropout=dropout,",
"output monitor: the type of monitor \"\"\" options = locals() experiment_dir = out_dir",
"seed number device: device id batch_size: the size of each batch num_epochs: the",
"hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, num_classes, bias), )) app = aku.App(__file__) @app.register def",
"= out_dir / experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir => {experiment_dir}') manual_seed(seed) log_system.notice(f'seed =>",
"= IrisEstimator( in_features=4, dropout=dropout, num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope, bias=bias ) optimizer = optim.Adam(estimator.parameters()) monitor",
"None: self.dropout = dropout self.in_features = in_features self.num_classes = num_classes self.hidden_features = hidden_features",
"= 0.05, seed: int = 42, device: str = 'cpu', batch_size: int =",
"the size of hidden layers dropout: the dropout ratio bias: whether or not",
"prepare_iris_dataset from houttuynia.schedule import Moment, Pipeline from houttuynia.extensions import ClipGradNorm, CommitScalarByMean, Evaluation from",
"float = 0.05, bias: bool = True, negative_slope: float = 0.05, seed: int",
"dropout: the dropout ratio bias: whether or not use the bias in hidden",
"device id batch_size: the size of each batch num_epochs: the total numbers of",
"test = prepare_iris_dataset(batch_size) estimator = IrisEstimator( in_features=4, dropout=dropout, num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope, bias=bias )",
"houttuynia.triggers import Periodic from houttuynia.utils import ensure_output_dir, experiment_hash, options_dump class IrisEstimator(Classifier): def __init__(self,",
"IrisEstimator( in_features=4, dropout=dropout, num_classes=3, hidden_features=hidden_features, negative_slope=negative_slope, bias=bias ) optimizer = optim.Adam(estimator.parameters()) monitor =",
"estimator) schedule = EpochalSchedule(estimator, optimizer, monitor) schedule.register_extension(Periodic(Moment.AFTER_ITERATION, iteration=5))(CommitScalarByMean( 'criterion', 'acc', chapter='train', )) schedule.register_extension(Periodic(Moment.AFTER_BACKWARD,",
"from houttuynia import log_system, manual_seed, to_device from houttuynia.datasets import prepare_iris_dataset from houttuynia.schedule import",
"not use the bias in hidden layers negative_slope: the ratio of negative part",
"hidden_features self.negative_slope = negative_slope super(IrisEstimator, self).__init__(estimator=nn.Sequential( nn.Dropout(dropout), nn.Linear(in_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features,",
"size of hidden layers dropout: the dropout ratio bias: whether or not use",
"hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, hidden_features, bias), nn.LeakyReLU(negative_slope=negative_slope, inplace=True), nn.Linear(hidden_features, num_classes, bias), ))",
"options = locals() experiment_dir = out_dir / experiment_hash(**options) ensure_output_dir(experiment_dir) options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir =>",
"layers dropout: the dropout ratio bias: whether or not use the bias in",
"the type of monitor \"\"\" options = locals() experiment_dir = out_dir / experiment_hash(**options)",
"from houttuynia.monitors import get_monitor from houttuynia.schedules import EpochalSchedule from houttuynia.nn import Classifier from",
"-> None: self.dropout = dropout self.in_features = in_features self.num_classes = num_classes self.hidden_features =",
"hidden_features=hidden_features, negative_slope=negative_slope, bias=bias ) optimizer = optim.Adam(estimator.parameters()) monitor = get_monitor(monitor)(log_dir=experiment_dir) to_device(device, estimator) schedule",
"options_dump(experiment_dir, **options) log_system.notice(f'experiment_dir => {experiment_dir}') manual_seed(seed) log_system.notice(f'seed => {seed}') train, test = prepare_iris_dataset(batch_size)",
"houttuynia.schedules import EpochalSchedule from houttuynia.nn import Classifier from houttuynia import log_system, manual_seed, to_device"
] |
[
"Enum4linuxParser() def test_parse_os_information(self): result = self.parser.parse_os_information(self.OS_INFORMATION) expected = Enum4linuxOS(domain='CS', os='Windows Server 2012 R2",
"self.parser.parse_shares(self.SHARES) expected = [ Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote Admin'), Enum4linuxShare(name='C$', share_type='Disk', comment='Default share'), Enum4linuxShare(name='IPC$',",
"Enum4linuxShare, Enum4linuxGroup, \\ Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY, OUTPUT, \\ LOCAL_GROUPS,",
"Enum4linuxOS, Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup, \\ Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY, OUTPUT,",
"desc=None) ] self.assertEqual(result, expected) def test_parse_shares(self): result = self.parser.parse_shares(self.SHARES) expected = [ Enum4linuxShare(name='ADMIN$',",
"[set(), {'CS\\krbtgt', 'CS\\Domain Controllers', 'CS\\Enterprise Admins', 'CS\\Read-only Domain Controllers'}] self.assertCountEqual(result, expected) self.assertCountEqual(result_users, expected_users)",
"] self.assertEqual(result, expected) def test_parse_shares(self): result = self.parser.parse_shares(self.SHARES) expected = [ Enum4linuxShare(name='ADMIN$', share_type='Disk',",
"group in result] expected = [ Enum4linuxGroup(name='Cert Publishers', rid='0x205'), Enum4linuxGroup(name='Denied RODC Password Replication",
"account='jkowalski', name='<NAME>', desc=None) ] self.assertEqual(result, expected) def test_parse_shares(self): result = self.parser.parse_shares(self.SHARES) expected =",
"{'CS\\krbtgt', 'CS\\Domain Controllers', 'CS\\Enterprise Admins', 'CS\\Read-only Domain Controllers'}] self.assertCountEqual(result, expected) self.assertCountEqual(result_users, expected_users) def",
"USERS def setUp(self): self.parser = Enum4linuxParser() def test_parse_os_information(self): result = self.parser.parse_os_information(self.OS_INFORMATION) expected =",
"Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup, \\ Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY, OUTPUT, \\",
"self.parser.parse_password_policy(self.PASSWORD_POLICY) expected = Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24', max_age='41 days 23 hours 52 minutes', min_age='1",
"share'), Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon server share'), Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon",
"self.parser.parse_os_information(self.OS_INFORMATION) expected = Enum4linuxOS(domain='CS', os='Windows Server 2012 R2 Standard 9600', server='Windows Server 2012",
"expected) def test_parse_shares(self): result = self.parser.parse_shares(self.SHARES) expected = [ Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote Admin'),",
"= Enum4linuxParser() def test_parse_os_information(self): result = self.parser.parse_os_information(self.OS_INFORMATION) expected = Enum4linuxOS(domain='CS', os='Windows Server 2012",
"\\ LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES, OS_INFORMATION, USERS def setUp(self): self.parser = Enum4linuxParser()",
"23 hours 52 minutes', min_age='1 day', cleartext='0', no_anon_change='0', no_clear_change='0', lockout_admins='0', reset_lockout='30 minutes', lockout_duration='30",
"acb='0x00000210', account='jkowalski', name='<NAME>', desc=None) ] self.assertEqual(result, expected) def test_parse_shares(self): result = self.parser.parse_shares(self.SHARES) expected",
"comment='Logon server share'), Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon server share') ] self.assertCountEqual(result, expected) def test_parse_groups_list(self):",
"Enum4linuxGroup(name='Cert Publishers', rid='0x205'), Enum4linuxGroup(name='Denied RODC Password Replication Group', rid='0x23c') ] expected_users = [set(),",
"class Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY, OUTPUT, \\ LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES,",
"result = self.parser.parse_os_information(self.OS_INFORMATION) expected = Enum4linuxOS(domain='CS', os='Windows Server 2012 R2 Standard 9600', server='Windows",
"9600', server='Windows Server 2012 R2 Standard 6.3') self.assertEqual(result, expected) def test_parse_users(self): result =",
"the computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210', account='jkowalski', name='<NAME>', desc=None) ] self.assertEqual(result, expected) def test_parse_shares(self):",
"Enum4linuxGroup, \\ Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY, OUTPUT, \\ LOCAL_GROUPS, GROUPS,",
"share_type='Disk', comment='Remote Admin'), Enum4linuxShare(name='C$', share_type='Disk', comment='Default share'), Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk',",
"comment='Remote IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon server share'), Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon server share') ]",
"share_type='Disk', comment='Logon server share') ] self.assertCountEqual(result, expected) def test_parse_groups_list(self): result = self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users",
"= self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users = [group.users for group in result] expected = [ Enum4linuxGroup(name='Cert",
"Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon server share') ] self.assertCountEqual(result, expected) def test_parse_groups_list(self): result = self.parser.parse_groups_list(self.LOCAL_GROUPS)",
"self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users = [group.users for group in result] expected = [ Enum4linuxGroup(name='Cert Publishers',",
"comment='Default share'), Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon server share'), Enum4linuxShare(name='SYSVOL', share_type='Disk',",
"name='<NAME>', desc=None) ] self.assertEqual(result, expected) def test_parse_shares(self): result = self.parser.parse_shares(self.SHARES) expected = [",
"Admin'), Enum4linuxShare(name='C$', share_type='Disk', comment='Default share'), Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon server",
"Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon server share'), Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon server",
"name=None, desc='Built-in account for administering the computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210', account='jkowalski', name='<NAME>', desc=None)",
"expected_users) def test_parse_password_policy(self): result = self.parser.parse_password_policy(self.PASSWORD_POLICY) expected = Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24', max_age='41 days",
"import TestCase from tools.acuote_ad.parsers.enum4linux_parser import Enum4linuxParser from tools.acuote_ad.structs import Enum4linuxOS, Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup,",
"TestCase from tools.acuote_ad.parsers.enum4linux_parser import Enum4linuxParser from tools.acuote_ad.structs import Enum4linuxOS, Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup, \\",
"import Enum4linuxParser from tools.acuote_ad.structs import Enum4linuxOS, Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup, \\ Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase):",
"= [set(), {'CS\\krbtgt', 'CS\\Domain Controllers', 'CS\\Enterprise Admins', 'CS\\Read-only Domain Controllers'}] self.assertCountEqual(result, expected) self.assertCountEqual(result_users,",
"result = self.parser.parse_password_policy(self.PASSWORD_POLICY) expected = Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24', max_age='41 days 23 hours 52",
"day', cleartext='0', no_anon_change='0', no_clear_change='0', lockout_admins='0', reset_lockout='30 minutes', lockout_duration='30 minutes', lockout_threshold='None', force_logoff_time='Not Set') self.assertEqual(result,",
"cleartext='0', no_anon_change='0', no_clear_change='0', lockout_admins='0', reset_lockout='30 minutes', lockout_duration='30 minutes', lockout_threshold='None', force_logoff_time='Not Set') self.assertEqual(result, expected)",
"= Enum4linuxOS(domain='CS', os='Windows Server 2012 R2 Standard 9600', server='Windows Server 2012 R2 Standard",
"expected = Enum4linuxOS(domain='CS', os='Windows Server 2012 R2 Standard 9600', server='Windows Server 2012 R2",
"= [ Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote Admin'), Enum4linuxShare(name='C$', share_type='Disk', comment='Default share'), Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote",
"max_age='41 days 23 hours 52 minutes', min_age='1 day', cleartext='0', no_anon_change='0', no_clear_change='0', lockout_admins='0', reset_lockout='30",
"share_type='Disk', comment='Default share'), Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon server share'), Enum4linuxShare(name='SYSVOL',",
"server share'), Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon server share') ] self.assertCountEqual(result, expected) def test_parse_groups_list(self): result",
"] self.assertCountEqual(result, expected) def test_parse_groups_list(self): result = self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users = [group.users for group",
"Enum4linuxShare(name='C$', share_type='Disk', comment='Default share'), Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon server share'),",
"= self.parser.parse_password_policy(self.PASSWORD_POLICY) expected = Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24', max_age='41 days 23 hours 52 minutes',",
"def test_parse_password_policy(self): result = self.parser.parse_password_policy(self.PASSWORD_POLICY) expected = Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24', max_age='41 days 23",
"52 minutes', min_age='1 day', cleartext='0', no_anon_change='0', no_clear_change='0', lockout_admins='0', reset_lockout='30 minutes', lockout_duration='30 minutes', lockout_threshold='None',",
"minutes', min_age='1 day', cleartext='0', no_anon_change='0', no_clear_change='0', lockout_admins='0', reset_lockout='30 minutes', lockout_duration='30 minutes', lockout_threshold='None', force_logoff_time='Not",
"Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010', account='Administrator', name=None, desc='Built-in account for administering the computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451',",
"tools.acuote_ad.parsers.enum4linux_parser import Enum4linuxParser from tools.acuote_ad.structs import Enum4linuxOS, Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup, \\ Enum4linuxPasswordPolicy class",
"R2 Standard 9600', server='Windows Server 2012 R2 Standard 6.3') self.assertEqual(result, expected) def test_parse_users(self):",
"LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES, OS_INFORMATION, USERS def setUp(self): self.parser = Enum4linuxParser() def",
"min_age='1 day', cleartext='0', no_anon_change='0', no_clear_change='0', lockout_admins='0', reset_lockout='30 minutes', lockout_duration='30 minutes', lockout_threshold='None', force_logoff_time='Not Set')",
"Controllers'}] self.assertCountEqual(result, expected) self.assertCountEqual(result_users, expected_users) def test_parse_password_policy(self): result = self.parser.parse_password_policy(self.PASSWORD_POLICY) expected = Enum4linuxPasswordPolicy(min_length='7',",
"PASSWORD_POLICY, OUTPUT, \\ LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES, OS_INFORMATION, USERS def setUp(self): self.parser",
"\\ Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY, OUTPUT, \\ LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS,",
"self.assertEqual(result, expected) def test_parse_users(self): result = self.parser.parse_users(self.USERS) expected = [ Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010',",
"for group in result] expected = [ Enum4linuxGroup(name='Cert Publishers', rid='0x205'), Enum4linuxGroup(name='Denied RODC Password",
"Publishers', rid='0x205'), Enum4linuxGroup(name='Denied RODC Password Replication Group', rid='0x23c') ] expected_users = [set(), {'CS\\krbtgt',",
"Enum4linuxGroup(name='Denied RODC Password Replication Group', rid='0x23c') ] expected_users = [set(), {'CS\\krbtgt', 'CS\\Domain Controllers',",
"self.parser.parse_users(self.USERS) expected = [ Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010', account='Administrator', name=None, desc='Built-in account for administering",
"share_type='Disk', comment='Logon server share'), Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon server share') ] self.assertCountEqual(result, expected) def",
"rid='0x205'), Enum4linuxGroup(name='Denied RODC Password Replication Group', rid='0x23c') ] expected_users = [set(), {'CS\\krbtgt', 'CS\\Domain",
"result] expected = [ Enum4linuxGroup(name='Cert Publishers', rid='0x205'), Enum4linuxGroup(name='Denied RODC Password Replication Group', rid='0x23c')",
"BUILTIN_GROUPS, SHARES, OS_INFORMATION, USERS def setUp(self): self.parser = Enum4linuxParser() def test_parse_os_information(self): result =",
"share') ] self.assertCountEqual(result, expected) def test_parse_groups_list(self): result = self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users = [group.users for",
"from tools.acuote_ad.structs import Enum4linuxOS, Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup, \\ Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input",
"def test_parse_shares(self): result = self.parser.parse_shares(self.SHARES) expected = [ Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote Admin'), Enum4linuxShare(name='C$',",
"comment='Logon server share') ] self.assertCountEqual(result, expected) def test_parse_groups_list(self): result = self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users =",
"self.parser = Enum4linuxParser() def test_parse_os_information(self): result = self.parser.parse_os_information(self.OS_INFORMATION) expected = Enum4linuxOS(domain='CS', os='Windows Server",
"unittest import TestCase from tools.acuote_ad.parsers.enum4linux_parser import Enum4linuxParser from tools.acuote_ad.structs import Enum4linuxOS, Enum4linuxUser, Enum4linuxShare,",
"Password Replication Group', rid='0x23c') ] expected_users = [set(), {'CS\\krbtgt', 'CS\\Domain Controllers', 'CS\\Enterprise Admins',",
"= Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24', max_age='41 days 23 hours 52 minutes', min_age='1 day', cleartext='0',",
"'CS\\Enterprise Admins', 'CS\\Read-only Domain Controllers'}] self.assertCountEqual(result, expected) self.assertCountEqual(result_users, expected_users) def test_parse_password_policy(self): result =",
"Server 2012 R2 Standard 6.3') self.assertEqual(result, expected) def test_parse_users(self): result = self.parser.parse_users(self.USERS) expected",
"[ Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010', account='Administrator', name=None, desc='Built-in account for administering the computer/domain'), Enum4linuxUser(index='0x101e',",
"hours 52 minutes', min_age='1 day', cleartext='0', no_anon_change='0', no_clear_change='0', lockout_admins='0', reset_lockout='30 minutes', lockout_duration='30 minutes',",
"desc='Built-in account for administering the computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210', account='jkowalski', name='<NAME>', desc=None) ]",
"Enum4linuxParser from tools.acuote_ad.structs import Enum4linuxOS, Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup, \\ Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase): from",
"server share') ] self.assertCountEqual(result, expected) def test_parse_groups_list(self): result = self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users = [group.users",
"Domain Controllers'}] self.assertCountEqual(result, expected) self.assertCountEqual(result_users, expected_users) def test_parse_password_policy(self): result = self.parser.parse_password_policy(self.PASSWORD_POLICY) expected =",
"= [ Enum4linuxGroup(name='Cert Publishers', rid='0x205'), Enum4linuxGroup(name='Denied RODC Password Replication Group', rid='0x23c') ] expected_users",
"in result] expected = [ Enum4linuxGroup(name='Cert Publishers', rid='0x205'), Enum4linuxGroup(name='Denied RODC Password Replication Group',",
"self.assertCountEqual(result, expected) self.assertCountEqual(result_users, expected_users) def test_parse_password_policy(self): result = self.parser.parse_password_policy(self.PASSWORD_POLICY) expected = Enum4linuxPasswordPolicy(min_length='7', complexity='1',",
"expected = Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24', max_age='41 days 23 hours 52 minutes', min_age='1 day',",
"GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES, OS_INFORMATION, USERS def setUp(self): self.parser = Enum4linuxParser() def test_parse_os_information(self):",
"self.assertEqual(result, expected) def test_parse_shares(self): result = self.parser.parse_shares(self.SHARES) expected = [ Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote",
"from tools.acuote_ad.parsers.enum4linux_parser import Enum4linuxParser from tools.acuote_ad.structs import Enum4linuxOS, Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup, \\ Enum4linuxPasswordPolicy",
"Standard 6.3') self.assertEqual(result, expected) def test_parse_users(self): result = self.parser.parse_users(self.USERS) expected = [ Enum4linuxUser(index='0xf4d',",
"for administering the computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210', account='jkowalski', name='<NAME>', desc=None) ] self.assertEqual(result, expected)",
"'CS\\Domain Controllers', 'CS\\Enterprise Admins', 'CS\\Read-only Domain Controllers'}] self.assertCountEqual(result, expected) self.assertCountEqual(result_users, expected_users) def test_parse_password_policy(self):",
"result = self.parser.parse_users(self.USERS) expected = [ Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010', account='Administrator', name=None, desc='Built-in account",
"tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY, OUTPUT, \\ LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES, OS_INFORMATION, USERS def",
"def test_parse_users(self): result = self.parser.parse_users(self.USERS) expected = [ Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010', account='Administrator', name=None,",
"2012 R2 Standard 9600', server='Windows Server 2012 R2 Standard 6.3') self.assertEqual(result, expected) def",
"server='Windows Server 2012 R2 Standard 6.3') self.assertEqual(result, expected) def test_parse_users(self): result = self.parser.parse_users(self.USERS)",
"administering the computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210', account='jkowalski', name='<NAME>', desc=None) ] self.assertEqual(result, expected) def",
"Group', rid='0x23c') ] expected_users = [set(), {'CS\\krbtgt', 'CS\\Domain Controllers', 'CS\\Enterprise Admins', 'CS\\Read-only Domain",
"result = self.parser.parse_shares(self.SHARES) expected = [ Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote Admin'), Enum4linuxShare(name='C$', share_type='Disk', comment='Default",
"rid='0x23c') ] expected_users = [set(), {'CS\\krbtgt', 'CS\\Domain Controllers', 'CS\\Enterprise Admins', 'CS\\Read-only Domain Controllers'}]",
"[ Enum4linuxGroup(name='Cert Publishers', rid='0x205'), Enum4linuxGroup(name='Denied RODC Password Replication Group', rid='0x23c') ] expected_users =",
"comment='Remote Admin'), Enum4linuxShare(name='C$', share_type='Disk', comment='Default share'), Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon",
"expected) def test_parse_groups_list(self): result = self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users = [group.users for group in result]",
"] expected_users = [set(), {'CS\\krbtgt', 'CS\\Domain Controllers', 'CS\\Enterprise Admins', 'CS\\Read-only Domain Controllers'}] self.assertCountEqual(result,",
"tools.acuote_ad.structs import Enum4linuxOS, Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup, \\ Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import",
"import Enum4linuxOS, Enum4linuxUser, Enum4linuxShare, Enum4linuxGroup, \\ Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY,",
"test_parse_os_information(self): result = self.parser.parse_os_information(self.OS_INFORMATION) expected = Enum4linuxOS(domain='CS', os='Windows Server 2012 R2 Standard 9600',",
"expected = [ Enum4linuxGroup(name='Cert Publishers', rid='0x205'), Enum4linuxGroup(name='Denied RODC Password Replication Group', rid='0x23c') ]",
"complexity='1', history='24', max_age='41 days 23 hours 52 minutes', min_age='1 day', cleartext='0', no_anon_change='0', no_clear_change='0',",
"Enum4linuxPasswordPolicy class Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY, OUTPUT, \\ LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS,",
"Controllers', 'CS\\Enterprise Admins', 'CS\\Read-only Domain Controllers'}] self.assertCountEqual(result, expected) self.assertCountEqual(result_users, expected_users) def test_parse_password_policy(self): result",
"Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210', account='jkowalski', name='<NAME>', desc=None) ] self.assertEqual(result, expected) def test_parse_shares(self): result =",
"Server 2012 R2 Standard 9600', server='Windows Server 2012 R2 Standard 6.3') self.assertEqual(result, expected)",
"Enum4linuxOS(domain='CS', os='Windows Server 2012 R2 Standard 9600', server='Windows Server 2012 R2 Standard 6.3')",
"= self.parser.parse_shares(self.SHARES) expected = [ Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote Admin'), Enum4linuxShare(name='C$', share_type='Disk', comment='Default share'),",
"expected_users = [set(), {'CS\\krbtgt', 'CS\\Domain Controllers', 'CS\\Enterprise Admins', 'CS\\Read-only Domain Controllers'}] self.assertCountEqual(result, expected)",
"Replication Group', rid='0x23c') ] expected_users = [set(), {'CS\\krbtgt', 'CS\\Domain Controllers', 'CS\\Enterprise Admins', 'CS\\Read-only",
"self.assertCountEqual(result_users, expected_users) def test_parse_password_policy(self): result = self.parser.parse_password_policy(self.PASSWORD_POLICY) expected = Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24', max_age='41",
"<filename>tests/test_tools/test_aucote_ad/test_parsers/test_enum4linux_parser.py<gh_stars>1-10 from unittest import TestCase from tools.acuote_ad.parsers.enum4linux_parser import Enum4linuxParser from tools.acuote_ad.structs import Enum4linuxOS,",
"from unittest import TestCase from tools.acuote_ad.parsers.enum4linux_parser import Enum4linuxParser from tools.acuote_ad.structs import Enum4linuxOS, Enum4linuxUser,",
"6.3') self.assertEqual(result, expected) def test_parse_users(self): result = self.parser.parse_users(self.USERS) expected = [ Enum4linuxUser(index='0xf4d', rid='0x1f4',",
"expected) def test_parse_users(self): result = self.parser.parse_users(self.USERS) expected = [ Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010', account='Administrator',",
"Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon server share'), Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon server share') ] self.assertCountEqual(result, expected)",
"computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210', account='jkowalski', name='<NAME>', desc=None) ] self.assertEqual(result, expected) def test_parse_shares(self): result",
"[group.users for group in result] expected = [ Enum4linuxGroup(name='Cert Publishers', rid='0x205'), Enum4linuxGroup(name='Denied RODC",
"share_type='IPC', comment='Remote IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon server share'), Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon server share')",
"def test_parse_os_information(self): result = self.parser.parse_os_information(self.OS_INFORMATION) expected = Enum4linuxOS(domain='CS', os='Windows Server 2012 R2 Standard",
"setUp(self): self.parser = Enum4linuxParser() def test_parse_os_information(self): result = self.parser.parse_os_information(self.OS_INFORMATION) expected = Enum4linuxOS(domain='CS', os='Windows",
"IPC'), Enum4linuxShare(name='NETLOGON', share_type='Disk', comment='Logon server share'), Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon server share') ] self.assertCountEqual(result,",
"= [ Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010', account='Administrator', name=None, desc='Built-in account for administering the computer/domain'),",
"= [group.users for group in result] expected = [ Enum4linuxGroup(name='Cert Publishers', rid='0x205'), Enum4linuxGroup(name='Denied",
"SHARES, OS_INFORMATION, USERS def setUp(self): self.parser = Enum4linuxParser() def test_parse_os_information(self): result = self.parser.parse_os_information(self.OS_INFORMATION)",
"OS_INFORMATION, USERS def setUp(self): self.parser = Enum4linuxParser() def test_parse_os_information(self): result = self.parser.parse_os_information(self.OS_INFORMATION) expected",
"rid='0x451', acb='0x00000210', account='jkowalski', name='<NAME>', desc=None) ] self.assertEqual(result, expected) def test_parse_shares(self): result = self.parser.parse_shares(self.SHARES)",
"acb='0x00000010', account='Administrator', name=None, desc='Built-in account for administering the computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210', account='jkowalski',",
"share'), Enum4linuxShare(name='SYSVOL', share_type='Disk', comment='Logon server share') ] self.assertCountEqual(result, expected) def test_parse_groups_list(self): result =",
"DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES, OS_INFORMATION, USERS def setUp(self): self.parser = Enum4linuxParser() def test_parse_os_information(self): result",
"rid='0x1f4', acb='0x00000010', account='Administrator', name=None, desc='Built-in account for administering the computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210',",
"account='Administrator', name=None, desc='Built-in account for administering the computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210', account='jkowalski', name='<NAME>',",
"[ Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote Admin'), Enum4linuxShare(name='C$', share_type='Disk', comment='Default share'), Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote IPC'),",
"RODC Password Replication Group', rid='0x23c') ] expected_users = [set(), {'CS\\krbtgt', 'CS\\Domain Controllers', 'CS\\Enterprise",
"result = self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users = [group.users for group in result] expected = [",
"import PASSWORD_POLICY, OUTPUT, \\ LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES, OS_INFORMATION, USERS def setUp(self):",
"OUTPUT, \\ LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES, OS_INFORMATION, USERS def setUp(self): self.parser =",
"Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24', max_age='41 days 23 hours 52 minutes', min_age='1 day', cleartext='0', no_anon_change='0',",
"days 23 hours 52 minutes', min_age='1 day', cleartext='0', no_anon_change='0', no_clear_change='0', lockout_admins='0', reset_lockout='30 minutes',",
"os='Windows Server 2012 R2 Standard 9600', server='Windows Server 2012 R2 Standard 6.3') self.assertEqual(result,",
"expected = [ Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010', account='Administrator', name=None, desc='Built-in account for administering the",
"Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote Admin'), Enum4linuxShare(name='C$', share_type='Disk', comment='Default share'), Enum4linuxShare(name='IPC$', share_type='IPC', comment='Remote IPC'), Enum4linuxShare(name='NETLOGON',",
"expected) self.assertCountEqual(result_users, expected_users) def test_parse_password_policy(self): result = self.parser.parse_password_policy(self.PASSWORD_POLICY) expected = Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24',",
"Standard 9600', server='Windows Server 2012 R2 Standard 6.3') self.assertEqual(result, expected) def test_parse_users(self): result",
"= self.parser.parse_os_information(self.OS_INFORMATION) expected = Enum4linuxOS(domain='CS', os='Windows Server 2012 R2 Standard 9600', server='Windows Server",
"Admins', 'CS\\Read-only Domain Controllers'}] self.assertCountEqual(result, expected) self.assertCountEqual(result_users, expected_users) def test_parse_password_policy(self): result = self.parser.parse_password_policy(self.PASSWORD_POLICY)",
"test_parse_groups_list(self): result = self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users = [group.users for group in result] expected =",
"result_users = [group.users for group in result] expected = [ Enum4linuxGroup(name='Cert Publishers', rid='0x205'),",
"account for administering the computer/domain'), Enum4linuxUser(index='0x101e', rid='0x451', acb='0x00000210', account='jkowalski', name='<NAME>', desc=None) ] self.assertEqual(result,",
"Enum4linuxParserTest(TestCase): from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY, OUTPUT, \\ LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES, OS_INFORMATION,",
"def test_parse_groups_list(self): result = self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users = [group.users for group in result] expected",
"from tests.test_tools.test_aucote_ad.test_parsers.test_enum4linux_parser_input import PASSWORD_POLICY, OUTPUT, \\ LOCAL_GROUPS, GROUPS, DOMAIN_GROUPS, BUILTIN_GROUPS, SHARES, OS_INFORMATION, USERS",
"'CS\\Read-only Domain Controllers'}] self.assertCountEqual(result, expected) self.assertCountEqual(result_users, expected_users) def test_parse_password_policy(self): result = self.parser.parse_password_policy(self.PASSWORD_POLICY) expected",
"def setUp(self): self.parser = Enum4linuxParser() def test_parse_os_information(self): result = self.parser.parse_os_information(self.OS_INFORMATION) expected = Enum4linuxOS(domain='CS',",
"test_parse_shares(self): result = self.parser.parse_shares(self.SHARES) expected = [ Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote Admin'), Enum4linuxShare(name='C$', share_type='Disk',",
"= self.parser.parse_users(self.USERS) expected = [ Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010', account='Administrator', name=None, desc='Built-in account for",
"self.assertCountEqual(result, expected) def test_parse_groups_list(self): result = self.parser.parse_groups_list(self.LOCAL_GROUPS) result_users = [group.users for group in",
"test_parse_users(self): result = self.parser.parse_users(self.USERS) expected = [ Enum4linuxUser(index='0xf4d', rid='0x1f4', acb='0x00000010', account='Administrator', name=None, desc='Built-in",
"2012 R2 Standard 6.3') self.assertEqual(result, expected) def test_parse_users(self): result = self.parser.parse_users(self.USERS) expected =",
"history='24', max_age='41 days 23 hours 52 minutes', min_age='1 day', cleartext='0', no_anon_change='0', no_clear_change='0', lockout_admins='0',",
"R2 Standard 6.3') self.assertEqual(result, expected) def test_parse_users(self): result = self.parser.parse_users(self.USERS) expected = [",
"test_parse_password_policy(self): result = self.parser.parse_password_policy(self.PASSWORD_POLICY) expected = Enum4linuxPasswordPolicy(min_length='7', complexity='1', history='24', max_age='41 days 23 hours",
"expected = [ Enum4linuxShare(name='ADMIN$', share_type='Disk', comment='Remote Admin'), Enum4linuxShare(name='C$', share_type='Disk', comment='Default share'), Enum4linuxShare(name='IPC$', share_type='IPC',"
] |
[
"hidden_size * num_directions) # h_n (num_layers * num_directions, batch, hidden_size) self.gru = nn.GRU(hidden_size,",
"i in range(seq_len): attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) # Normalize energies to weights in",
"= '../data/cmn-eng/' SOS_token = 0 EOS_token = 1 MAX_LENGTH = 10 # 工具函数",
"= max([len(x) for x in zh_sens]) # 借助 NLTK 函数 en_word_counts = FreqDist('",
"=> [1, 1, 10] # print(type(attn_weights)) # print(type(encoder_outputs.transpose(0, 1))) # print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size())",
"seq2seq with attention # np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1, is_cuda=False):",
"LongTensor N = mini-batch # output (N, W, embedding_dim) self.embedded = nn.Embedding(input_size, hidden_size)",
"optim.Adam(decoder.parameters(), lr=lr) criterion = nn.NLLLoss() # 训练函数 def train(input_variable, target_variable, encoder, decoder, encoder_optimizer,",
"decoder_input = Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input) if USE_CUDA: decoder_input = decoder_input.cuda() if max_similar_pos ==",
"500] encoder_hidden = encoder.init_hidden() # 假设 input 为 [1, 4, 5, 7] [1,",
"hidden = self.gru(embedded, hidden) return output, hidden def init_hidden(self): hidden = Variable(torch.zeros(self.n_layers, 1,",
"# int(input_variable.size()) target_variable = Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA: input_variable = input_variable.cuda() target_variable = target_variable.cuda()",
"as_minutes(s): pass def time_since(since, percent): pass # 数据预处理 with open(path + 'cmn.txt') as",
"% print_every == 0: print_loss_avg = print_loss_total / epoch print('epoch {}\\'s avg_loss is",
"raw.strip() letters_only = re.sub(\"[^a-zA-Z]\", \" \", raw) words = letters_only.lower().split() return (\" \".join(words))",
"import numpy as np import pandas as pd import matplotlib.pyplot as plt from",
"max([len(x) for x in en_sens]) zh_max_len = max([len(x) for x in zh_sens]) #",
"[1, 4, 5, 7] [1, 4] # [4, 1, 500] [1, 1, 500]",
"evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False): input_sen2index = sen2index(sentence, 'en') input_variable = Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length =",
"in range(max_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) topv, topi",
"decoder_hidden, encoder_outputs) topv, topi = decoder_output.data.topk(1) ni = topi[0][0] # EOS_token if ni",
"0: decoded_words.append('<EOS>') break else: decoded_words.append(index2word_zh[ni]) decoder_input = Variable(torch.LongTensor([[ni]])) if USE_CUDA: decoder_input = decoder_input.cuda()",
"nn.GRU(hidden_size, hidden_size) def forward(self, word_inputs, hidden): seq_len = len(word_inputs[0]) embedded = self.embedded(word_inputs).view(seq_len, 1,",
"Variable import numpy as np import pandas as pd import matplotlib.pyplot as plt",
"max([len(x) for x in zh_sens]) # 借助 NLTK 函数 en_word_counts = FreqDist(' '.join(en_sens).split('",
"lines] pairs = [[en, zh] for en, zh in zip (en_sens, zh_sens)] en_max_len",
"* direc, batch_s, fea] [1, 1, 500] encoder_hidden = encoder.init_hidden() # 假设 input",
"topi = decoder_output.data.topk(1) ni = topi[0][0] # EOS_token if ni == 0: decoded_words.append('<EOS>')",
"print(target_variable[i].size()) loss += criterion(decoder_output, target_variable[0][i]) topv, topi = decoder_output.data.topk(1) max_similar_pos = topi[0][0] decoder_input",
"input_length = input_variable.size()[1] target_length = target_variable.size()[1] ## encoder # [num_layers * direc, batch_s,",
"n_epochs = 500 print_every = 50 print_loss_total = 0 # 开始训练 for epoch",
"print('epoch {}\\'s avg_loss is {}'.format(epoch, print_loss_avg)) # 查看结果 def evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False): input_sen2index",
"= [word2index_zh[word] for word in list(jieba.cut(sen))] no_eos.append(0) return no_eos def as_minutes(s): pass def",
"encoder_optimizer.step() decoder_optimizer.step() return loss.data[0] / target_length # 训练细节定义 n_epochs = 500 print_every =",
"Normalize energies to weights in range 0 to 1, resize to 1 x",
"\"\", raw) return(letters_only) def wordandindex(vocab): return {word: i + 1 for i, word",
"if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() for i in range(target_length): decoder_output,",
"[1, 1, 20] rnn_input = torch.cat((embedded,last_context), 2) # print(\"decoder's rnn_input is {}\".format(rnn_input)) #",
"= target_variable.size()[1] ## encoder # [num_layers * direc, batch_s, fea] [1, 1, 500]",
"if USE_CUDA: input_variable = input_variable.cuda() target_variable = target_variable.cuda() loss = train(input_variable, target_variable, encoder,",
"encoder.init_hidden() encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) decoder_input = Variable(torch.LongTensor([[0]])) decoder_context = Variable(torch.zeros(1, 1,",
"word2index_en['EOS'] = 0 index2word_en[0] = 'EOS' word2index_zh, index2word_zh = wordandindex(zh_vocab) word2index_zh['EOS'] = 0",
"criterion, False) print_loss_total += loss if epoch % print_every == 0: print_loss_avg =",
"[1, 1, 10] rnn_output, hidden = self.gru(rnn_input, last_hidden) # print(\"decoder's rnn_output is {}\".format(rnn_output))",
"#print(\"decoder's output is {}\".format(output)) return output, context, hidden, attn_weights # 训练 # 500",
"# print(\"decoder's context is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size())) output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1)))",
"= torch.zeros(max_length, max_length) for di in range(max_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input,",
"global word2index_zh if lang == 'en': no_eos = [word2index_en[word] for word in sen.split('",
"= Counter() for sen in zh_sens: for word in list(jieba.cut(sen)): zh_counts[word] += 1",
"lang): global word2index_en global word2index_zh if lang == 'en': no_eos = [word2index_en[word] for",
"'EOS' sen_vector = [[sen2index(pair[0], 'en'), sen2index(pair[1], 'zh')] for pair in filter_pairs] # 模型实现",
"self.n_layers = n_layers self.is_cuda = is_cuda # input (N, W) LongTensor N =",
"encoder_outputs): # embedding 的本来输出是 (n, w, embedding_dim) # [1, 1, 10] embedded =",
"{}\".format(attn_weights)) # [1, 1, 3] bmm [1, 3, 10](转置之前 [3, 1, 10]) =>",
"training_pair = random.choice(sen_vector) input_variable = Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size()) target_variable = Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA:",
"matplotlib.pyplot as plt from nltk import FreqDist import re import jieba import math",
"7 filter_pairs = [pair for pair in pairs if len(pair[0].split(' ')) < MAX_LENGTH",
"def time_since(since, percent): pass # 数据预处理 with open(path + 'cmn.txt') as f: lines",
"for line in lines] zh_sens = [deal_zh_sen(line.split('\\t')[1]) for line in lines] pairs =",
"= self.attn(encoder_output) energy = hidden.dot(energy) return energy class DecoderRNN(nn.Module): def __init__(self, hidden_size, output_size,",
"= nn.Linear(hidden_size * 2, output_size) self.attn = Attn(hidden_size) def forward(self, word_input, last_context, last_hidden,",
"0 # added noto for each word # input_length = input_variable.size()[1] target_length =",
"1): training_pair = random.choice(sen_vector) input_variable = Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size()) target_variable = Variable(torch.LongTensor([training_pair[1]])) if",
"翻译结果 decoded_words = [] # 这块还不是很理解 decoder_attentions = torch.zeros(max_length, max_length) for di in",
"embedded = self.embedded(word_inputs).view(seq_len, 1, -1) output, hidden = self.gru(embedded, hidden) return output, hidden",
"batch, input_size) # h_0 (num_layers * num_directions, batch, hidden_size) # output (seq_len, batch,",
"break else: decoded_words.append(index2word_zh[ni]) decoder_input = Variable(torch.LongTensor([[ni]])) if USE_CUDA: decoder_input = decoder_input.cuda() return ''.join(decoded_words),",
"pandas as pd import matplotlib.pyplot as plt from nltk import FreqDist import re",
"False) if USE_CUDA: encoder.cuda() decoder.cuda() lr = 1e-3 encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer",
"zh_vocab = set(zh_counts) MAX_LENGTH = 7 filter_pairs = [pair for pair in pairs",
"and len(list(jieba.cut(pair[1]))) < MAX_LENGTH] word2index_en, index2word_en = wordandindex(en_vocab) word2index_en['EOS'] = 0 index2word_en[0] =",
"last_hidden, encoder_outputs): # embedding 的本来输出是 (n, w, embedding_dim) # [1, 1, 10] embedded",
"= wordandindex(zh_vocab) word2index_zh['EOS'] = 0 index2word_zh[0] = 'EOS' sen_vector = [[sen2index(pair[0], 'en'), sen2index(pair[1],",
"zh_counts = Counter() for sen in zh_sens: for word in list(jieba.cut(sen)): zh_counts[word] +=",
"self).__init__() # input_size 实际上是 vocab 的size self.input_size = input_size self.hidden_size = hidden_size self.n_layers",
"== 0: decoded_words.append('<EOS>') break else: decoded_words.append(index2word_zh[ni]) decoder_input = Variable(torch.LongTensor([[ni]])) if USE_CUDA: decoder_input =",
"# added noto for each word # input_length = input_variable.size()[1] target_length = target_variable.size()[1]",
"[1, 1, 3] bmm [1, 3, 10](转置之前 [3, 1, 10]) => [1, 1,",
"rnn_output, hidden = self.gru(rnn_input, last_hidden) # print(\"decoder's rnn_output is {}\".format(rnn_output)) # [1, 1,",
"1, 10]) => [1, 1, 10] # print(type(attn_weights)) # print(type(encoder_outputs.transpose(0, 1))) # print(attn_weights.size())",
"output_size self.n_layers = n_layers self.is_cuda = is_cuda # outout_size 为 中文 vocab 的",
"self.gru(rnn_input, last_hidden) # print(\"decoder's rnn_output is {}\".format(rnn_output)) # [1, 1, 3] attn_weights =",
"as f: lines = f.readlines() en_sens = [deal_en_sen(line.split('\\t')[0]) for line in lines] zh_sens",
"/ target_length # 训练细节定义 n_epochs = 500 print_every = 50 print_loss_total = 0",
"letters_only = re.sub(\"[^a-zA-Z]\", \" \", raw) words = letters_only.lower().split() return (\" \".join(words)) def",
"list(jieba.cut(sen)): zh_counts[word] += 1 zh_vocab = set(zh_counts) MAX_LENGTH = 7 filter_pairs = [pair",
"filter_pairs = [pair for pair in pairs if len(pair[0].split(' ')) < MAX_LENGTH and",
"[1, 1] decoder_input = Variable(torch.LongTensor([[0]])) # [1, 1, 500] decoder_context = Variable(torch.zeros(1, 1,",
"self.n_layers = n_layers self.is_cuda = is_cuda # outout_size 为 中文 vocab 的 length",
"= decoder_output.data.topk(1) ni = topi[0][0] # EOS_token if ni == 0: decoded_words.append('<EOS>') break",
"torch.cat((embedded,last_context), 2) # print(\"decoder's rnn_input is {}\".format(rnn_input)) # [1, 1, 10] rnn_output, hidden",
"= decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) topv, topi = decoder_output.data.topk(1) ni = topi[0][0] #",
"# input (seq_len, batch, input_size) # h_0 (num_layers * num_directions, batch, hidden_size) #",
"hidden_size) # input => (N, *, in_features) # output => (N, * ,",
"target_variable.cuda() loss = train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, False) print_loss_total +=",
"n_layers, False) if USE_CUDA: encoder.cuda() decoder.cuda() lr = 1e-3 encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr)",
"torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd",
"global word2index_en global word2index_zh if lang == 'en': no_eos = [word2index_en[word] for word",
"= set(en_word_counts) # zh_vocab = set(zh_word_counts) zh_counts = Counter() for sen in zh_sens:",
"index2word_en = wordandindex(en_vocab) word2index_en['EOS'] = 0 index2word_en[0] = 'EOS' word2index_zh, index2word_zh = wordandindex(zh_vocab)",
"[word2index_zh[word] for word in list(jieba.cut(sen))] no_eos.append(0) return no_eos def as_minutes(s): pass def time_since(since,",
"2)).size())) output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1))) #print(\"decoder's output is {}\".format(output)) return output, context,",
"direc, batch_s, fea] [1, 1, 500] encoder_hidden = encoder.init_hidden() # 假设 input 为",
"encoder_hidden = encoder.init_hidden() # 假设 input 为 [1, 4, 5, 7] [1, 4]",
"def sen2index(sen, lang): global word2index_en global word2index_zh if lang == 'en': no_eos =",
"range(1, n_epochs + 1): training_pair = random.choice(sen_vector) input_variable = Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size()) target_variable",
"topv, topi = decoder_output.data.topk(1) max_similar_pos = topi[0][0] decoder_input = Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input) if",
"sen.split(' ')] else: no_eos = [word2index_zh[word] for word in list(jieba.cut(sen))] no_eos.append(0) return no_eos",
"数据预处理 with open(path + 'cmn.txt') as f: lines = f.readlines() en_sens = [deal_en_sen(line.split('\\t')[0])",
"print_loss_total += loss if epoch % print_every == 0: print_loss_avg = print_loss_total /",
"1, 10] # print(type(attn_weights)) # print(type(encoder_outputs.transpose(0, 1))) # print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size()) context =",
"len(zh_vocab), n_layers, False) if USE_CUDA: encoder.cuda() decoder.cuda() lr = 1e-3 encoder_optimizer = optim.Adam(encoder.parameters(),",
"context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # print(\"decoder's context is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size())) output",
"= random.choice(sen_vector) input_variable = Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size()) target_variable = Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA: input_variable",
"for word in sen.split(' ')] else: no_eos = [word2index_zh[word] for word in list(jieba.cut(sen))]",
"import Counter import random path = '../data/cmn-eng/' SOS_token = 0 EOS_token = 1",
"DecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, n_layers=1, is_cuda=False): super(DecoderRNN, self).__init__() self.hidden_size = hidden_size self.output_size",
"def deal_zh_sen(raw): raw.strip() letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw) return(letters_only) def wordandindex(vocab): return {word:",
"= topi[0][0] # EOS_token if ni == 0: decoded_words.append('<EOS>') break else: decoded_words.append(index2word_zh[ni]) decoder_input",
"decoded_words.append('<EOS>') break else: decoded_words.append(index2word_zh[ni]) decoder_input = Variable(torch.LongTensor([[ni]])) if USE_CUDA: decoder_input = decoder_input.cuda() return",
"word in enumerate(vocab)} def sen2index(sen, lang): global word2index_en global word2index_zh if lang ==",
"en_sens]) zh_max_len = max([len(x) for x in zh_sens]) # 借助 NLTK 函数 en_word_counts",
"# h_0 (num_layers * num_directions, batch, hidden_size) # output (seq_len, batch, hidden_size *",
"# [1, 1, 3] attn_weights = self.attn(rnn_output, encoder_outputs) # print(\"decoder's attn_weights is {}\".format(attn_weights))",
"128 n_layers = 1 MAX_LENGTH = 7 # USE_CUDA = False USE_CUDA =",
"= wordandindex(en_vocab) word2index_en['EOS'] = 0 index2word_en[0] = 'EOS' word2index_zh, index2word_zh = wordandindex(zh_vocab) word2index_zh['EOS']",
"# outout_size 为 中文 vocab 的 length self.embedded = nn.Embedding(output_size, hidden_size) self.gru =",
"n_layers, False) decoder = DecoderRNN(hidden_size, len(zh_vocab), n_layers, False) if USE_CUDA: encoder.cuda() decoder.cuda() lr",
"for x in zh_sens]) # 借助 NLTK 函数 en_word_counts = FreqDist(' '.join(en_sens).split(' '))",
"encoder_outputs 保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden, encoder_output): energy = self.attn(encoder_output) energy =",
"output => (N, * , out_features) self.out = nn.Linear(hidden_size * 2, output_size) self.attn",
"= len(word_inputs[0]) embedded = self.embedded(word_inputs).view(seq_len, 1, -1) output, hidden = self.gru(embedded, hidden) return",
"MAX_LENGTH and len(list(jieba.cut(pair[1]))) < MAX_LENGTH] word2index_en, index2word_en = wordandindex(en_vocab) word2index_en['EOS'] = 0 index2word_en[0]",
"len(list(jieba.cut(pair[1]))) < MAX_LENGTH] word2index_en, index2word_en = wordandindex(en_vocab) word2index_en['EOS'] = 0 index2word_en[0] = 'EOS'",
"## decoder # [1, 1] decoder_input = Variable(torch.LongTensor([[0]])) # [1, 1, 500] decoder_context",
"Variable(torch.zeros(1, 1, decoder.hidden_size)) # [1, 1, 500] decoder_hidden = encoder_hidden if is_cuda: decoder_input",
"Variable(torch.LongTensor([[ni]])) if USE_CUDA: decoder_input = decoder_input.cuda() return ''.join(decoded_words), decoder_attentions[:di+1, :len(encoder_outputs)] print(evaluate('i love you')[0])",
"for pair in pairs if len(pair[0].split(' ')) < MAX_LENGTH and len(list(jieba.cut(pair[1]))) < MAX_LENGTH]",
"def __init__(self, hidden_size, max_length=MAX_LENGTH, is_cuda=False): super(Attn, self).__init__() self.hidden_size = hidden_size self.is_cuda = is_cuda",
"return loss.data[0] / target_length # 训练细节定义 n_epochs = 500 print_every = 50 print_loss_total",
"encoder # [num_layers * direc, batch_s, fea] [1, 1, 500] encoder_hidden = encoder.init_hidden()",
"的本来输出是 (n, w, embedding_dim) # [1, 1, 10] embedded = self.embedded(word_input) # print(\"decoder's",
"< MAX_LENGTH and len(list(jieba.cut(pair[1]))) < MAX_LENGTH] word2index_en, index2word_en = wordandindex(en_vocab) word2index_en['EOS'] = 0",
"hidden, encoder_outputs): seq_len = len(encoder_outputs) attn_energies = Variable(torch.zeros(seq_len)) if self.is_cuda: attn_energies = attn_energies.cuda()",
"20] rnn_input = torch.cat((embedded,last_context), 2) # print(\"decoder's rnn_input is {}\".format(rnn_input)) # [1, 1,",
"en_vocab = set(en_word_counts) # zh_vocab = set(zh_word_counts) zh_counts = Counter() for sen in",
"False) decoder = DecoderRNN(hidden_size, len(zh_vocab), n_layers, False) if USE_CUDA: encoder.cuda() decoder.cuda() lr =",
"hidden_size self.is_cuda = is_cuda # general method self.attn = nn.Linear(self.hidden_size, hidden_size) def forward(self,",
"# [1, 1, 500] decoder_hidden = encoder_hidden if is_cuda: decoder_input = decoder_input.cuda() decoder_context",
"\" \", raw) words = letters_only.lower().split() return (\" \".join(words)) def deal_zh_sen(raw): raw.strip() letters_only",
"attn_weights is {}\".format(attn_weights)) # [1, 1, 3] bmm [1, 3, 10](转置之前 [3, 1,",
"is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() decoder_hidden = encoder_hidden # 翻译结果 decoded_words",
"in en_sens]) zh_max_len = max([len(x) for x in zh_sens]) # 借助 NLTK 函数",
"embedded = self.embedded(word_input) # print(\"decoder's embedded is {}\".format(embedded)) # [1, 1, 20] rnn_input",
"f.readlines() en_sens = [deal_en_sen(line.split('\\t')[0]) for line in lines] zh_sens = [deal_zh_sen(line.split('\\t')[1]) for line",
"return output, context, hidden, attn_weights # 训练 # 500 hidden_size = 128 n_layers",
"EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1, is_cuda=False): super(EncoderRNN, self).__init__() # input_size 实际上是 vocab",
"pass # 数据预处理 with open(path + 'cmn.txt') as f: lines = f.readlines() en_sens",
"for line in lines] pairs = [[en, zh] for en, zh in zip",
"def score(self, hidden, encoder_output): energy = self.attn(encoder_output) energy = hidden.dot(energy) return energy class",
"is {}\".format(attn_weights)) # [1, 1, 3] bmm [1, 3, 10](转置之前 [3, 1, 10])",
"word2index_zh if lang == 'en': no_eos = [word2index_en[word] for word in sen.split(' ')]",
"= hidden_size self.output_size = output_size self.n_layers = n_layers self.is_cuda = is_cuda # outout_size",
"= Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input) if USE_CUDA: decoder_input = decoder_input.cuda() if max_similar_pos == 0:",
"index2word_zh[0] = 'EOS' sen_vector = [[sen2index(pair[0], 'en'), sen2index(pair[1], 'zh')] for pair in filter_pairs]",
"# [1, 1, 3] bmm [1, 3, 10](转置之前 [3, 1, 10]) => [1,",
"torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F",
"sen in zh_sens: for word in list(jieba.cut(sen)): zh_counts[word] += 1 zh_vocab = set(zh_counts)",
"(n, w, embedding_dim) # [1, 1, 10] embedded = self.embedded(word_input) # print(\"decoder's embedded",
"zip (en_sens, zh_sens)] en_max_len = max([len(x) for x in en_sens]) zh_max_len = max([len(x)",
"# 训练细节定义 n_epochs = 500 print_every = 50 print_loss_total = 0 # 开始训练",
"1: word for i, word in enumerate(vocab)} def sen2index(sen, lang): global word2index_en global",
"topi = decoder_output.data.topk(1) max_similar_pos = topi[0][0] decoder_input = Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input) if USE_CUDA:",
"# 梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss = 0 # added noto for each word",
"decoder_optimizer.zero_grad() loss = 0 # added noto for each word # input_length =",
"[1, 1, 10] embedded = self.embedded(word_input) # print(\"decoder's embedded is {}\".format(embedded)) # [1,",
"DecoderRNN(hidden_size, len(zh_vocab), n_layers, False) if USE_CUDA: encoder.cuda() decoder.cuda() lr = 1e-3 encoder_optimizer =",
"raw) words = letters_only.lower().split() return (\" \".join(words)) def deal_zh_sen(raw): raw.strip() letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\",",
"input (seq_len, batch, input_size) # h_0 (num_layers * num_directions, batch, hidden_size) # output",
"{}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size())) output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1))) #print(\"decoder's output is {}\".format(output))",
"1, 500] decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) # [1, 1, 500] decoder_hidden =",
"forward(self, hidden, encoder_outputs): seq_len = len(encoder_outputs) attn_energies = Variable(torch.zeros(seq_len)) if self.is_cuda: attn_energies =",
"for i in range(seq_len): attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) # Normalize energies to weights",
"decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) topv, topi = decoder_output.data.topk(1) ni = topi[0][0] # EOS_token",
"# print(\"decoder's embedded is {}\".format(embedded)) # [1, 1, 20] rnn_input = torch.cat((embedded,last_context), 2)",
"general method class Attn(nn.Module): def __init__(self, hidden_size, max_length=MAX_LENGTH, is_cuda=False): super(Attn, self).__init__() self.hidden_size =",
"hidden_size) # input (seq_len, batch, input_size) # h_0 (num_layers * num_directions, batch, hidden_size)",
"encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, False) print_loss_total += loss if epoch % print_every",
"# [1, 1, 10] embedded = self.embedded(word_input) # print(\"decoder's embedded is {}\".format(embedded)) #",
"encoder_hidden) ## decoder # [1, 1] decoder_input = Variable(torch.LongTensor([[0]])) # [1, 1, 500]",
"decoder_context, decoder_hidden, encoder_outputs) # ??? # print(target_variable[i].size()) loss += criterion(decoder_output, target_variable[0][i]) topv, topi",
"1)) # print(\"decoder's context is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size())) output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)),",
"outout_size 为 中文 vocab 的 length self.embedded = nn.Embedding(output_size, hidden_size) self.gru = nn.GRU(hidden_size",
"= input_variable.size()[1] target_length = target_variable.size()[1] ## encoder # [num_layers * direc, batch_s, fea]",
"USE_CUDA = False USE_CUDA = False encoder = EncoderRNN(len(en_vocab), hidden_size, n_layers, False) decoder",
"'../data/cmn-eng/' SOS_token = 0 EOS_token = 1 MAX_LENGTH = 10 # 工具函数 def",
"[1, 1, 500] encoder_hidden = encoder.init_hidden() # 假设 input 为 [1, 4, 5,",
"input_variable = Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length = input_variable.size()[1] if is_cuda: input_variable = input_variable.cuda() encoder_hidden",
"word2index_zh['EOS'] = 0 index2word_zh[0] = 'EOS' sen_vector = [[sen2index(pair[0], 'en'), sen2index(pair[1], 'zh')] for",
"target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, False) print_loss_total += loss if epoch %",
"range(target_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) # ??? #",
"avg_loss is {}'.format(epoch, print_loss_avg)) # 查看结果 def evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False): input_sen2index = sen2index(sentence,",
"1))) # print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size()) context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # print(\"decoder's context is",
"与 encoder_outputs 保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden, encoder_output): energy = self.attn(encoder_output) energy",
"模型实现 # seq2seq with attention # np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size,",
"self.out = nn.Linear(hidden_size * 2, output_size) self.attn = Attn(hidden_size) def forward(self, word_input, last_context,",
"== 0: print_loss_avg = print_loss_total / epoch print('epoch {}\\'s avg_loss is {}'.format(epoch, print_loss_avg))",
"1, 500] encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) ## decoder # [1, 1] decoder_input",
"hidden_size, output_size, n_layers=1, is_cuda=False): super(DecoderRNN, self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.n_layers",
"= FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab = set(en_word_counts) # zh_vocab = set(zh_word_counts) zh_counts = Counter() for",
"encoder(input_variable, encoder_hidden) ## decoder # [1, 1] decoder_input = Variable(torch.LongTensor([[0]])) # [1, 1,",
"return (\" \".join(words)) def deal_zh_sen(raw): raw.strip() letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw) return(letters_only) def",
"line in lines] zh_sens = [deal_zh_sen(line.split('\\t')[1]) for line in lines] pairs = [[en,",
"= False USE_CUDA = False encoder = EncoderRNN(len(en_vocab), hidden_size, n_layers, False) decoder =",
"2) # print(\"decoder's rnn_input is {}\".format(rnn_input)) # [1, 1, 10] rnn_output, hidden =",
"if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() decoder_hidden = encoder_hidden # 翻译结果",
"= encoder_hidden # 翻译结果 decoded_words = [] # 这块还不是很理解 decoder_attentions = torch.zeros(max_length, max_length)",
"zh] for en, zh in zip (en_sens, zh_sens)] en_max_len = max([len(x) for x",
"weights in range 0 to 1, resize to 1 x 1 x seq_len",
"{}'.format(epoch, print_loss_avg)) # 查看结果 def evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False): input_sen2index = sen2index(sentence, 'en') input_variable",
"max_length) for di in range(max_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden,",
"re.sub(\"[^a-zA-Z]\", \" \", raw) words = letters_only.lower().split() return (\" \".join(words)) def deal_zh_sen(raw): raw.strip()",
"# 开始训练 for epoch in range(1, n_epochs + 1): training_pair = random.choice(sen_vector) input_variable",
"word2index_en global word2index_zh if lang == 'en': no_eos = [word2index_en[word] for word in",
"')) # zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab = set(en_word_counts) # zh_vocab = set(zh_word_counts) zh_counts",
"= mini-batch # output (N, W, embedding_dim) self.embedded = nn.Embedding(input_size, hidden_size) # input",
"time from collections import Counter import random path = '../data/cmn-eng/' SOS_token = 0",
"percent): pass # 数据预处理 with open(path + 'cmn.txt') as f: lines = f.readlines()",
"1, 10] rnn_output, hidden = self.gru(rnn_input, last_hidden) # print(\"decoder's rnn_output is {}\".format(rnn_output)) #",
"input_sen2index = sen2index(sentence, 'en') input_variable = Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length = input_variable.size()[1] if is_cuda:",
"= [] # 这块还不是很理解 decoder_attentions = torch.zeros(max_length, max_length) for di in range(max_length): decoder_output,",
"word in list(jieba.cut(sen))] no_eos.append(0) return no_eos def as_minutes(s): pass def time_since(since, percent): pass",
"resize to 1 x 1 x seq_len # 返回的 是 attn_weigths 维度 与",
"10] embedded = self.embedded(word_input) # print(\"decoder's embedded is {}\".format(embedded)) # [1, 1, 20]",
"decoder_optimizer.step() return loss.data[0] / target_length # 训练细节定义 n_epochs = 500 print_every = 50",
"decoder, encoder_optimizer, decoder_optimizer, criterion, False) print_loss_total += loss if epoch % print_every ==",
"zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab = set(en_word_counts) # zh_vocab = set(zh_word_counts) zh_counts = Counter()",
"{i + 1: word for i, word in enumerate(vocab)} def sen2index(sen, lang): global",
"Attn 中的 general method class Attn(nn.Module): def __init__(self, hidden_size, max_length=MAX_LENGTH, is_cuda=False): super(Attn, self).__init__()",
"output (seq_len, batch, hidden_size * num_directions) # h_n (num_layers * num_directions, batch, hidden_size)",
"*, in_features) # output => (N, * , out_features) self.out = nn.Linear(hidden_size *",
"def forward(self, hidden, encoder_outputs): seq_len = len(encoder_outputs) attn_energies = Variable(torch.zeros(seq_len)) if self.is_cuda: attn_energies",
"# output => (N, * , out_features) self.out = nn.Linear(hidden_size * 2, output_size)",
"self).__init__() self.hidden_size = hidden_size self.is_cuda = is_cuda # general method self.attn = nn.Linear(self.hidden_size,",
"(num_layers * num_directions, batch, hidden_size) # output (seq_len, batch, hidden_size * num_directions) #",
"decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr) criterion = nn.NLLLoss() # 训练函数 def train(input_variable, target_variable, encoder,",
"is_cuda=False): super(EncoderRNN, self).__init__() # input_size 实际上是 vocab 的size self.input_size = input_size self.hidden_size =",
"word # input_length = input_variable.size()[1] target_length = target_variable.size()[1] ## encoder # [num_layers *",
"attn_weights = self.attn(rnn_output, encoder_outputs) # print(\"decoder's attn_weights is {}\".format(attn_weights)) # [1, 1, 3]",
"= [pair for pair in pairs if len(pair[0].split(' ')) < MAX_LENGTH and len(list(jieba.cut(pair[1])))",
"def forward(self, word_inputs, hidden): seq_len = len(word_inputs[0]) embedded = self.embedded(word_inputs).view(seq_len, 1, -1) output,",
"decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) # ??? # print(target_variable[i].size()) loss",
"input_variable.cuda() encoder_hidden = encoder.init_hidden() encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) decoder_input = Variable(torch.LongTensor([[0]])) decoder_context",
"= Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size()) target_variable = Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA: input_variable = input_variable.cuda() target_variable",
"= encoder_hidden if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() for i in",
"deal_en_sen(raw): raw.strip() letters_only = re.sub(\"[^a-zA-Z]\", \" \", raw) words = letters_only.lower().split() return (\"",
"print(encoder_outputs.transpose(0,1).size()) context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # print(\"decoder's context is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size()))",
"+= 1 zh_vocab = set(zh_counts) MAX_LENGTH = 7 filter_pairs = [pair for pair",
"plt from nltk import FreqDist import re import jieba import math import time",
"x in en_sens]) zh_max_len = max([len(x) for x in zh_sens]) # 借助 NLTK",
"= Variable(torch.zeros(seq_len)) if self.is_cuda: attn_energies = attn_energies.cuda() for i in range(seq_len): attn_energies[i] =",
"decoded_words = [] # 这块还不是很理解 decoder_attentions = torch.zeros(max_length, max_length) for di in range(max_length):",
"= hidden_size self.is_cuda = is_cuda # general method self.attn = nn.Linear(self.hidden_size, hidden_size) def",
"import FreqDist import re import jieba import math import time from collections import",
"in enumerate(vocab)}, {i + 1: word for i, word in enumerate(vocab)} def sen2index(sen,",
"#print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size())) output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1))) #print(\"decoder's output is {}\".format(output)) return",
"decoder_output.data.topk(1) ni = topi[0][0] # EOS_token if ni == 0: decoded_words.append('<EOS>') break else:",
"FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab = set(en_word_counts) # zh_vocab = set(zh_word_counts) zh_counts = Counter() for sen",
"= self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) # Normalize energies to weights in range 0 to 1,",
"batch, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size) def forward(self, word_inputs, hidden): seq_len = len(word_inputs[0])",
"in zh_sens]) # 借助 NLTK 函数 en_word_counts = FreqDist(' '.join(en_sens).split(' ')) # zh_word_counts",
"== 'en': no_eos = [word2index_en[word] for word in sen.split(' ')] else: no_eos =",
"collections import Counter import random path = '../data/cmn-eng/' SOS_token = 0 EOS_token =",
"seq_len # 返回的 是 attn_weigths 维度 与 encoder_outputs 保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self,",
"word in sen.split(' ')] else: no_eos = [word2index_zh[word] for word in list(jieba.cut(sen))] no_eos.append(0)",
"n_layers self.is_cuda = is_cuda # input (N, W) LongTensor N = mini-batch #",
"context), 2)).size())) output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1))) #print(\"decoder's output is {}\".format(output)) return output,",
"class Attn(nn.Module): def __init__(self, hidden_size, max_length=MAX_LENGTH, is_cuda=False): super(Attn, self).__init__() self.hidden_size = hidden_size self.is_cuda",
"USE_CUDA = False encoder = EncoderRNN(len(en_vocab), hidden_size, n_layers, False) decoder = DecoderRNN(hidden_size, len(zh_vocab),",
"last_hidden) # print(\"decoder's rnn_output is {}\".format(rnn_output)) # [1, 1, 3] attn_weights = self.attn(rnn_output,",
"h_n (num_layers * num_directions, batch, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size) def forward(self, word_inputs,",
"di in range(max_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) topv,",
"is_cuda=False): # 梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss = 0 # added noto for each",
"<gh_stars>1-10 import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional",
"is {}'.format(epoch, print_loss_avg)) # 查看结果 def evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False): input_sen2index = sen2index(sentence, 'en')",
"10 # 工具函数 def deal_en_sen(raw): raw.strip() letters_only = re.sub(\"[^a-zA-Z]\", \" \", raw) words",
"w, embedding_dim) # [1, 1, 10] embedded = self.embedded(word_input) # print(\"decoder's embedded is",
"= self.attn(rnn_output, encoder_outputs) # print(\"decoder's attn_weights is {}\".format(attn_weights)) # [1, 1, 3] bmm",
"encoder.init_hidden() # 假设 input 为 [1, 4, 5, 7] [1, 4] # [4,",
"self.embedded = nn.Embedding(output_size, hidden_size) self.gru = nn.GRU(hidden_size * 2, hidden_size) # input =>",
"decoder_optimizer, criterion, is_cuda=False): # 梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss = 0 # added noto",
"as np import pandas as pd import matplotlib.pyplot as plt from nltk import",
"as plt from nltk import FreqDist import re import jieba import math import",
"decoder_context = decoder_context.cuda() for i in range(target_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input,",
"[1, 1, 500] decoder_hidden = encoder_hidden if is_cuda: decoder_input = decoder_input.cuda() decoder_context =",
"optim import torch.nn.functional as F from torch.autograd import Variable import numpy as np",
"word in list(jieba.cut(sen)): zh_counts[word] += 1 zh_vocab = set(zh_counts) MAX_LENGTH = 7 filter_pairs",
"500] decoder_hidden = encoder_hidden if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() for",
"0 # 开始训练 for epoch in range(1, n_epochs + 1): training_pair = random.choice(sen_vector)",
"为 中文 vocab 的 length self.embedded = nn.Embedding(output_size, hidden_size) self.gru = nn.GRU(hidden_size *",
"\".join(words)) def deal_zh_sen(raw): raw.strip() letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw) return(letters_only) def wordandindex(vocab): return",
"* 2, hidden_size) # input => (N, *, in_features) # output => (N,",
"??? # print(target_variable[i].size()) loss += criterion(decoder_output, target_variable[0][i]) topv, topi = decoder_output.data.topk(1) max_similar_pos =",
"return hidden # 为了简便 这里实现的是 Attn 中的 general method class Attn(nn.Module): def __init__(self,",
"self.hidden_size = hidden_size self.is_cuda = is_cuda # general method self.attn = nn.Linear(self.hidden_size, hidden_size)",
"to 1 x 1 x seq_len # 返回的 是 attn_weigths 维度 与 encoder_outputs",
"Counter import random path = '../data/cmn-eng/' SOS_token = 0 EOS_token = 1 MAX_LENGTH",
"max_length=MAX_LENGTH, is_cuda=False): super(Attn, self).__init__() self.hidden_size = hidden_size self.is_cuda = is_cuda # general method",
"self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers self.is_cuda = is_cuda #",
"i + 1 for i, word in enumerate(vocab)}, {i + 1: word for",
"as pd import matplotlib.pyplot as plt from nltk import FreqDist import re import",
"= encoder.init_hidden() encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) decoder_input = Variable(torch.LongTensor([[0]])) decoder_context = Variable(torch.zeros(1,",
"= F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1))) #print(\"decoder's output is {}\".format(output)) return output, context, hidden, attn_weights",
"en_word_counts = FreqDist(' '.join(en_sens).split(' ')) # zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab = set(en_word_counts) #",
"letters_only.lower().split() return (\" \".join(words)) def deal_zh_sen(raw): raw.strip() letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw) return(letters_only)",
"def init_hidden(self): hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) if self.is_cuda: hidden = hidden.cuda() return",
"embedded is {}\".format(embedded)) # [1, 1, 20] rnn_input = torch.cat((embedded,last_context), 2) # print(\"decoder's",
"decoder.cuda() lr = 1e-3 encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr) criterion",
"中文 vocab 的 length self.embedded = nn.Embedding(output_size, hidden_size) self.gru = nn.GRU(hidden_size * 2,",
"= 0 EOS_token = 1 MAX_LENGTH = 10 # 工具函数 def deal_en_sen(raw): raw.strip()",
"x seq_len # 返回的 是 attn_weigths 维度 与 encoder_outputs 保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def",
"=> (N, * , out_features) self.out = nn.Linear(hidden_size * 2, output_size) self.attn =",
"# print(target_variable[i].size()) loss += criterion(decoder_output, target_variable[0][i]) topv, topi = decoder_output.data.topk(1) max_similar_pos = topi[0][0]",
"for word in list(jieba.cut(sen))] no_eos.append(0) return no_eos def as_minutes(s): pass def time_since(since, percent):",
"= len(encoder_outputs) attn_energies = Variable(torch.zeros(seq_len)) if self.is_cuda: attn_energies = attn_energies.cuda() for i in",
"epoch % print_every == 0: print_loss_avg = print_loss_total / epoch print('epoch {}\\'s avg_loss",
"= topi[0][0] decoder_input = Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input) if USE_CUDA: decoder_input = decoder_input.cuda() if",
"decoder_input.cuda() if max_similar_pos == 0: break loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss.data[0] / target_length",
"ni == 0: decoded_words.append('<EOS>') break else: decoded_words.append(index2word_zh[ni]) decoder_input = Variable(torch.LongTensor([[ni]])) if USE_CUDA: decoder_input",
"= 128 n_layers = 1 MAX_LENGTH = 7 # USE_CUDA = False USE_CUDA",
"break loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss.data[0] / target_length # 训练细节定义 n_epochs = 500",
"借助 NLTK 函数 en_word_counts = FreqDist(' '.join(en_sens).split(' ')) # zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab",
"= nn.GRU(hidden_size, hidden_size) def forward(self, word_inputs, hidden): seq_len = len(word_inputs[0]) embedded = self.embedded(word_inputs).view(seq_len,",
"nn.Linear(self.hidden_size, hidden_size) def forward(self, hidden, encoder_outputs): seq_len = len(encoder_outputs) attn_energies = Variable(torch.zeros(seq_len)) if",
"[deal_zh_sen(line.split('\\t')[1]) for line in lines] pairs = [[en, zh] for en, zh in",
"in range(target_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) # ???",
"return no_eos def as_minutes(s): pass def time_since(since, percent): pass # 数据预处理 with open(path",
"zh_sens: for word in list(jieba.cut(sen)): zh_counts[word] += 1 zh_vocab = set(zh_counts) MAX_LENGTH =",
"[] # 这块还不是很理解 decoder_attentions = torch.zeros(max_length, max_length) for di in range(max_length): decoder_output, decoder_context,",
"else: decoded_words.append(index2word_zh[ni]) decoder_input = Variable(torch.LongTensor([[ni]])) if USE_CUDA: decoder_input = decoder_input.cuda() return ''.join(decoded_words), decoder_attentions[:di+1,",
"# Normalize energies to weights in range 0 to 1, resize to 1",
"is_cuda # general method self.attn = nn.Linear(self.hidden_size, hidden_size) def forward(self, hidden, encoder_outputs): seq_len",
"decoder, encoder_optimizer, decoder_optimizer, criterion, is_cuda=False): # 梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss = 0 #",
"= [[en, zh] for en, zh in zip (en_sens, zh_sens)] en_max_len = max([len(x)",
"# 为了简便 这里实现的是 Attn 中的 general method class Attn(nn.Module): def __init__(self, hidden_size, max_length=MAX_LENGTH,",
"hidden_size) self.gru = nn.GRU(hidden_size * 2, hidden_size) # input => (N, *, in_features)",
"score(self, hidden, encoder_output): energy = self.attn(encoder_output) energy = hidden.dot(energy) return energy class DecoderRNN(nn.Module):",
"# general method self.attn = nn.Linear(self.hidden_size, hidden_size) def forward(self, hidden, encoder_outputs): seq_len =",
"__init__(self, hidden_size, output_size, n_layers=1, is_cuda=False): super(DecoderRNN, self).__init__() self.hidden_size = hidden_size self.output_size = output_size",
"index2word_en[0] = 'EOS' word2index_zh, index2word_zh = wordandindex(zh_vocab) word2index_zh['EOS'] = 0 index2word_zh[0] = 'EOS'",
"hidden = self.gru(rnn_input, last_hidden) # print(\"decoder's rnn_output is {}\".format(rnn_output)) # [1, 1, 3]",
"1))) #print(\"decoder's output is {}\".format(output)) return output, context, hidden, attn_weights # 训练 #",
"rnn_input is {}\".format(rnn_input)) # [1, 1, 10] rnn_output, hidden = self.gru(rnn_input, last_hidden) #",
"class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1, is_cuda=False): super(EncoderRNN, self).__init__() # input_size 实际上是",
"method self.attn = nn.Linear(self.hidden_size, hidden_size) def forward(self, hidden, encoder_outputs): seq_len = len(encoder_outputs) attn_energies",
"is {}\".format(rnn_output)) # [1, 1, 3] attn_weights = self.attn(rnn_output, encoder_outputs) # print(\"decoder's attn_weights",
"fea] [1, 1, 500] encoder_hidden = encoder.init_hidden() # 假设 input 为 [1, 4,",
"super(EncoderRNN, self).__init__() # input_size 实际上是 vocab 的size self.input_size = input_size self.hidden_size = hidden_size",
"words = letters_only.lower().split() return (\" \".join(words)) def deal_zh_sen(raw): raw.strip() letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\", \"\",",
"+ 1 for i, word in enumerate(vocab)}, {i + 1: word for i,",
"= hidden.cuda() return hidden # 为了简便 这里实现的是 Attn 中的 general method class Attn(nn.Module):",
"out_features) self.out = nn.Linear(hidden_size * 2, output_size) self.attn = Attn(hidden_size) def forward(self, word_input,",
"hidden_size) self.gru = nn.GRU(hidden_size, hidden_size) def forward(self, word_inputs, hidden): seq_len = len(word_inputs[0]) embedded",
"encoder_outputs[i].squeeze(0)) # Normalize energies to weights in range 0 to 1, resize to",
"encoder_optimizer, decoder_optimizer, criterion, False) print_loss_total += loss if epoch % print_every == 0:",
"for i, word in enumerate(vocab)}, {i + 1: word for i, word in",
"print_loss_total = 0 # 开始训练 for epoch in range(1, n_epochs + 1): training_pair",
"= re.sub(\"[^a-zA-Z]\", \" \", raw) words = letters_only.lower().split() return (\" \".join(words)) def deal_zh_sen(raw):",
"# embedding 的本来输出是 (n, w, embedding_dim) # [1, 1, 10] embedded = self.embedded(word_input)",
"target_variable = target_variable.cuda() loss = train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, False)",
"bmm [1, 3, 10](转置之前 [3, 1, 10]) => [1, 1, 10] # print(type(attn_weights))",
"1] decoder_input = Variable(torch.LongTensor([[0]])) # [1, 1, 500] decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size))",
"hidden, encoder_output): energy = self.attn(encoder_output) energy = hidden.dot(energy) return energy class DecoderRNN(nn.Module): def",
"hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) if self.is_cuda: hidden = hidden.cuda() return hidden #",
"= nn.NLLLoss() # 训练函数 def train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, is_cuda=False):",
"= decoder_input.cuda() decoder_context = decoder_context.cuda() for i in range(target_length): decoder_output, decoder_context, decoder_hidden, decoder_attention",
"decoder.hidden_size)) if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() decoder_hidden = encoder_hidden #",
"loss = train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, False) print_loss_total += loss",
"decoder_hidden = encoder_hidden # 翻译结果 decoded_words = [] # 这块还不是很理解 decoder_attentions = torch.zeros(max_length,",
"re import jieba import math import time from collections import Counter import random",
"encoder_hidden if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() for i in range(target_length):",
"= set(zh_word_counts) zh_counts = Counter() for sen in zh_sens: for word in list(jieba.cut(sen)):",
"decoder_input = Variable(torch.LongTensor([[0]])) # [1, 1, 500] decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) #",
"False encoder = EncoderRNN(len(en_vocab), hidden_size, n_layers, False) decoder = DecoderRNN(hidden_size, len(zh_vocab), n_layers, False)",
"= decoder_context.cuda() for i in range(target_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context,",
"1, 500] [1, 1, 500] encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) ## decoder #",
"(\" \".join(words)) def deal_zh_sen(raw): raw.strip() letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw) return(letters_only) def wordandindex(vocab):",
"criterion, is_cuda=False): # 梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss = 0 # added noto for",
"target_length = target_variable.size()[1] ## encoder # [num_layers * direc, batch_s, fea] [1, 1,",
"500 print_every = 50 print_loss_total = 0 # 开始训练 for epoch in range(1,",
"= letters_only.lower().split() return (\" \".join(words)) def deal_zh_sen(raw): raw.strip() letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw)",
"output, hidden def init_hidden(self): hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) if self.is_cuda: hidden =",
"decoded_words.append(index2word_zh[ni]) decoder_input = Variable(torch.LongTensor([[ni]])) if USE_CUDA: decoder_input = decoder_input.cuda() return ''.join(decoded_words), decoder_attentions[:di+1, :len(encoder_outputs)]",
"= input_variable.cuda() target_variable = target_variable.cuda() loss = train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer,",
"1 MAX_LENGTH = 7 # USE_CUDA = False USE_CUDA = False encoder =",
"en_max_len = max([len(x) for x in en_sens]) zh_max_len = max([len(x) for x in",
"print_loss_avg)) # 查看结果 def evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False): input_sen2index = sen2index(sentence, 'en') input_variable =",
"max_similar_pos = topi[0][0] decoder_input = Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input) if USE_CUDA: decoder_input = decoder_input.cuda()",
"target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, is_cuda=False): # 梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss =",
"super(Attn, self).__init__() self.hidden_size = hidden_size self.is_cuda = is_cuda # general method self.attn =",
"decoder_hidden = encoder_hidden if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() for i",
"# print(\"decoder's attn_weights is {}\".format(attn_weights)) # [1, 1, 3] bmm [1, 3, 10](转置之前",
"'EOS' word2index_zh, index2word_zh = wordandindex(zh_vocab) word2index_zh['EOS'] = 0 index2word_zh[0] = 'EOS' sen_vector =",
"hidden) return output, hidden def init_hidden(self): hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) if self.is_cuda:",
"input_variable.size()[1] if is_cuda: input_variable = input_variable.cuda() encoder_hidden = encoder.init_hidden() encoder_outputs, encoder_hidden = encoder(input_variable,",
"encoder_outputs) topv, topi = decoder_output.data.topk(1) ni = topi[0][0] # EOS_token if ni ==",
"# output (seq_len, batch, hidden_size * num_directions) # h_n (num_layers * num_directions, batch,",
"rnn_input = torch.cat((embedded,last_context), 2) # print(\"decoder's rnn_input is {}\".format(rnn_input)) # [1, 1, 10]",
"{}\".format(rnn_input)) # [1, 1, 10] rnn_output, hidden = self.gru(rnn_input, last_hidden) # print(\"decoder's rnn_output",
"self.is_cuda: hidden = hidden.cuda() return hidden # 为了简便 这里实现的是 Attn 中的 general method",
"{}\".format(output)) return output, context, hidden, attn_weights # 训练 # 500 hidden_size = 128",
"output_size) self.attn = Attn(hidden_size) def forward(self, word_input, last_context, last_hidden, encoder_outputs): # embedding 的本来输出是",
"input_variable.size()[1] target_length = target_variable.size()[1] ## encoder # [num_layers * direc, batch_s, fea] [1,",
"in pairs if len(pair[0].split(' ')) < MAX_LENGTH and len(list(jieba.cut(pair[1]))) < MAX_LENGTH] word2index_en, index2word_en",
"encoder = EncoderRNN(len(en_vocab), hidden_size, n_layers, False) decoder = DecoderRNN(hidden_size, len(zh_vocab), n_layers, False) if",
"pairs = [[en, zh] for en, zh in zip (en_sens, zh_sens)] en_max_len =",
"seq_len = len(word_inputs[0]) embedded = self.embedded(word_inputs).view(seq_len, 1, -1) output, hidden = self.gru(embedded, hidden)",
"self.gru = nn.GRU(hidden_size * 2, hidden_size) # input => (N, *, in_features) #",
"else: no_eos = [word2index_zh[word] for word in list(jieba.cut(sen))] no_eos.append(0) return no_eos def as_minutes(s):",
"')] else: no_eos = [word2index_zh[word] for word in list(jieba.cut(sen))] no_eos.append(0) return no_eos def",
"input_size self.hidden_size = hidden_size self.n_layers = n_layers self.is_cuda = is_cuda # input (N,",
"self.output_size = output_size self.n_layers = n_layers self.is_cuda = is_cuda # outout_size 为 中文",
"is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() for i in range(target_length): decoder_output, decoder_context,",
"loss if epoch % print_every == 0: print_loss_avg = print_loss_total / epoch print('epoch",
"range(max_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) topv, topi =",
"decoder_input = Variable(torch.LongTensor([[0]])) decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) if is_cuda: decoder_input = decoder_input.cuda()",
"no_eos = [word2index_zh[word] for word in list(jieba.cut(sen))] no_eos.append(0) return no_eos def as_minutes(s): pass",
"= hidden.dot(energy) return energy class DecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, n_layers=1, is_cuda=False): super(DecoderRNN,",
"seq_len = len(encoder_outputs) attn_energies = Variable(torch.zeros(seq_len)) if self.is_cuda: attn_energies = attn_energies.cuda() for i",
"context.squeeze(0)), 1))) #print(\"decoder's output is {}\".format(output)) return output, context, hidden, attn_weights # 训练",
"4, 5, 7] [1, 4] # [4, 1, 500] [1, 1, 500] encoder_outputs,",
"= Variable(torch.LongTensor([[0]])) decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) if is_cuda: decoder_input = decoder_input.cuda() decoder_context",
"self.embedded = nn.Embedding(input_size, hidden_size) # input (seq_len, batch, input_size) # h_0 (num_layers *",
"for x in en_sens]) zh_max_len = max([len(x) for x in zh_sens]) # 借助",
"3, 10](转置之前 [3, 1, 10]) => [1, 1, 10] # print(type(attn_weights)) # print(type(encoder_outputs.transpose(0,",
"is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size())) output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1))) #print(\"decoder's output is",
"# [4, 1, 500] [1, 1, 500] encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) ##",
"F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1))) #print(\"decoder's output is {}\".format(output)) return output, context, hidden, attn_weights #",
"nn.GRU(hidden_size * 2, hidden_size) # input => (N, *, in_features) # output =>",
"假设 input 为 [1, 4, 5, 7] [1, 4] # [4, 1, 500]",
"import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as",
"# 这块还不是很理解 decoder_attentions = torch.zeros(max_length, max_length) for di in range(max_length): decoder_output, decoder_context, decoder_hidden,",
"print_loss_avg = print_loss_total / epoch print('epoch {}\\'s avg_loss is {}'.format(epoch, print_loss_avg)) # 查看结果",
"def as_minutes(s): pass def time_since(since, percent): pass # 数据预处理 with open(path + 'cmn.txt')",
"__init__(self, input_size, hidden_size, n_layers=1, is_cuda=False): super(EncoderRNN, self).__init__() # input_size 实际上是 vocab 的size self.input_size",
"input_variable = Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size()) target_variable = Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA: input_variable = input_variable.cuda()",
"1, decoder.hidden_size)) if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() decoder_hidden = encoder_hidden",
"0 EOS_token = 1 MAX_LENGTH = 10 # 工具函数 def deal_en_sen(raw): raw.strip() letters_only",
"Variable(torch.LongTensor([[0]])) decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) if is_cuda: decoder_input = decoder_input.cuda() decoder_context =",
"# print(type(encoder_outputs.transpose(0, 1))) # print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size()) context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # print(\"decoder's",
"训练细节定义 n_epochs = 500 print_every = 50 print_loss_total = 0 # 开始训练 for",
"N = mini-batch # output (N, W, embedding_dim) self.embedded = nn.Embedding(input_size, hidden_size) #",
"查看结果 def evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False): input_sen2index = sen2index(sentence, 'en') input_variable = Variable(torch.LongTensor(input_sen2index).view(1, -1))",
"= sen2index(sentence, 'en') input_variable = Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length = input_variable.size()[1] if is_cuda: input_variable",
"hidden): seq_len = len(word_inputs[0]) embedded = self.embedded(word_inputs).view(seq_len, 1, -1) output, hidden = self.gru(embedded,",
"decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) topv, topi = decoder_output.data.topk(1) ni",
"attn_weights # 训练 # 500 hidden_size = 128 n_layers = 1 MAX_LENGTH =",
"# 模型实现 # seq2seq with attention # np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module): def __init__(self, input_size,",
"len(pair[0].split(' ')) < MAX_LENGTH and len(list(jieba.cut(pair[1]))) < MAX_LENGTH] word2index_en, index2word_en = wordandindex(en_vocab) word2index_en['EOS']",
"output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1))) #print(\"decoder's output is {}\".format(output)) return output, context, hidden,",
"维度 与 encoder_outputs 保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden, encoder_output): energy = self.attn(encoder_output)",
"decoder_attentions = torch.zeros(max_length, max_length) for di in range(max_length): decoder_output, decoder_context, decoder_hidden, decoder_attention =",
"## encoder # [num_layers * direc, batch_s, fea] [1, 1, 500] encoder_hidden =",
"as optim import torch.nn.functional as F from torch.autograd import Variable import numpy as",
"in range(1, n_epochs + 1): training_pair = random.choice(sen_vector) input_variable = Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size())",
"decoder_context.cuda() for i in range(target_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden,",
"1, self.hidden_size)) if self.is_cuda: hidden = hidden.cuda() return hidden # 为了简便 这里实现的是 Attn",
"wordandindex(vocab): return {word: i + 1 for i, word in enumerate(vocab)}, {i +",
"self.hidden_size)) if self.is_cuda: hidden = hidden.cuda() return hidden # 为了简便 这里实现的是 Attn 中的",
"hidden # 为了简便 这里实现的是 Attn 中的 general method class Attn(nn.Module): def __init__(self, hidden_size,",
"= is_cuda # general method self.attn = nn.Linear(self.hidden_size, hidden_size) def forward(self, hidden, encoder_outputs):",
"返回的 是 attn_weigths 维度 与 encoder_outputs 保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden, encoder_output):",
"in enumerate(vocab)} def sen2index(sen, lang): global word2index_en global word2index_zh if lang == 'en':",
"decoder_output.data.topk(1) max_similar_pos = topi[0][0] decoder_input = Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input) if USE_CUDA: decoder_input =",
"self.is_cuda = is_cuda # general method self.attn = nn.Linear(self.hidden_size, hidden_size) def forward(self, hidden,",
"print(\"decoder's rnn_input is {}\".format(rnn_input)) # [1, 1, 10] rnn_output, hidden = self.gru(rnn_input, last_hidden)",
"# [1, 1, 10] rnn_output, hidden = self.gru(rnn_input, last_hidden) # print(\"decoder's rnn_output is",
"encoder(input_variable, encoder_hidden) decoder_input = Variable(torch.LongTensor([[0]])) decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) if is_cuda: decoder_input",
"print(\"decoder's embedded is {}\".format(embedded)) # [1, 1, 20] rnn_input = torch.cat((embedded,last_context), 2) #",
"= False encoder = EncoderRNN(len(en_vocab), hidden_size, n_layers, False) decoder = DecoderRNN(hidden_size, len(zh_vocab), n_layers,",
"context is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size())) output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1))) #print(\"decoder's output",
"= Variable(torch.LongTensor([[ni]])) if USE_CUDA: decoder_input = decoder_input.cuda() return ''.join(decoded_words), decoder_attentions[:di+1, :len(encoder_outputs)] print(evaluate('i love",
"(seq_len, batch, hidden_size * num_directions) # h_n (num_layers * num_directions, batch, hidden_size) self.gru",
"= nn.Embedding(input_size, hidden_size) # input (seq_len, batch, input_size) # h_0 (num_layers * num_directions,",
"FreqDist(' '.join(en_sens).split(' ')) # zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab = set(en_word_counts) # zh_vocab =",
"'zh')] for pair in filter_pairs] # 模型实现 # seq2seq with attention # np.array([sen_vector[2][1]]).shape",
"0: print_loss_avg = print_loss_total / epoch print('epoch {}\\'s avg_loss is {}'.format(epoch, print_loss_avg)) #",
"def __init__(self, input_size, hidden_size, n_layers=1, is_cuda=False): super(EncoderRNN, self).__init__() # input_size 实际上是 vocab 的size",
"(N, *, in_features) # output => (N, * , out_features) self.out = nn.Linear(hidden_size",
"1, 10] embedded = self.embedded(word_input) # print(\"decoder's embedded is {}\".format(embedded)) # [1, 1,",
"input_size, hidden_size, n_layers=1, is_cuda=False): super(EncoderRNN, self).__init__() # input_size 实际上是 vocab 的size self.input_size =",
"decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() for i in range(target_length): decoder_output, decoder_context, decoder_hidden,",
"1, 500] decoder_hidden = encoder_hidden if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda()",
"[[sen2index(pair[0], 'en'), sen2index(pair[1], 'zh')] for pair in filter_pairs] # 模型实现 # seq2seq with",
"= 7 # USE_CUDA = False USE_CUDA = False encoder = EncoderRNN(len(en_vocab), hidden_size,",
"encoder_hidden) decoder_input = Variable(torch.LongTensor([[0]])) decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) if is_cuda: decoder_input =",
"print(\"decoder's context is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size())) output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0), context.squeeze(0)), 1))) #print(\"decoder's",
"decoder_input = decoder_input.cuda() if max_similar_pos == 0: break loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss.data[0]",
"self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers self.is_cuda = is_cuda",
"def forward(self, word_input, last_context, last_hidden, encoder_outputs): # embedding 的本来输出是 (n, w, embedding_dim) #",
"energy class DecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, n_layers=1, is_cuda=False): super(DecoderRNN, self).__init__() self.hidden_size =",
"print_every == 0: print_loss_avg = print_loss_total / epoch print('epoch {}\\'s avg_loss is {}'.format(epoch,",
"\", raw) words = letters_only.lower().split() return (\" \".join(words)) def deal_zh_sen(raw): raw.strip() letters_only =",
"random.choice(sen_vector) input_variable = Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size()) target_variable = Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA: input_variable =",
"10]) => [1, 1, 10] # print(type(attn_weights)) # print(type(encoder_outputs.transpose(0, 1))) # print(attn_weights.size()) #",
"= DecoderRNN(hidden_size, len(zh_vocab), n_layers, False) if USE_CUDA: encoder.cuda() decoder.cuda() lr = 1e-3 encoder_optimizer",
"[1, 1, 500] decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) # [1, 1, 500] decoder_hidden",
"for di in range(max_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs)",
"list(jieba.cut(sen))] no_eos.append(0) return no_eos def as_minutes(s): pass def time_since(since, percent): pass # 数据预处理",
"import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from",
"np import pandas as pd import matplotlib.pyplot as plt from nltk import FreqDist",
"= max([len(x) for x in en_sens]) zh_max_len = max([len(x) for x in zh_sens])",
"0 index2word_en[0] = 'EOS' word2index_zh, index2word_zh = wordandindex(zh_vocab) word2index_zh['EOS'] = 0 index2word_zh[0] =",
"= 7 filter_pairs = [pair for pair in pairs if len(pair[0].split(' ')) <",
"# USE_CUDA = False USE_CUDA = False encoder = EncoderRNN(len(en_vocab), hidden_size, n_layers, False)",
"if USE_CUDA: encoder.cuda() decoder.cuda() lr = 1e-3 encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer =",
"self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) # Normalize energies to weights in range 0 to 1, resize",
"for each word # input_length = input_variable.size()[1] target_length = target_variable.size()[1] ## encoder #",
"for sen in zh_sens: for word in list(jieba.cut(sen)): zh_counts[word] += 1 zh_vocab =",
"attn_energies.cuda() for i in range(seq_len): attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) # Normalize energies to",
"EncoderRNN(len(en_vocab), hidden_size, n_layers, False) decoder = DecoderRNN(hidden_size, len(zh_vocab), n_layers, False) if USE_CUDA: encoder.cuda()",
"训练函数 def train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, is_cuda=False): # 梯度初始化 encoder_optimizer.zero_grad()",
"decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) topv, topi = decoder_output.data.topk(1)",
"len(encoder_outputs) attn_energies = Variable(torch.zeros(seq_len)) if self.is_cuda: attn_energies = attn_energies.cuda() for i in range(seq_len):",
"+= criterion(decoder_output, target_variable[0][i]) topv, topi = decoder_output.data.topk(1) max_similar_pos = topi[0][0] decoder_input = Variable(torch.LongTensor([[max_similar_pos]]))",
"[[en, zh] for en, zh in zip (en_sens, zh_sens)] en_max_len = max([len(x) for",
"hidden_size) # output (seq_len, batch, hidden_size * num_directions) # h_n (num_layers * num_directions,",
"实际上是 vocab 的size self.input_size = input_size self.hidden_size = hidden_size self.n_layers = n_layers self.is_cuda",
"batch, hidden_size) # output (seq_len, batch, hidden_size * num_directions) # h_n (num_layers *",
"np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1, is_cuda=False): super(EncoderRNN, self).__init__() # input_size",
"= print_loss_total / epoch print('epoch {}\\'s avg_loss is {}'.format(epoch, print_loss_avg)) # 查看结果 def",
"set(en_word_counts) # zh_vocab = set(zh_word_counts) zh_counts = Counter() for sen in zh_sens: for",
"Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input) if USE_CUDA: decoder_input = decoder_input.cuda() if max_similar_pos == 0: break",
"embedding_dim) self.embedded = nn.Embedding(input_size, hidden_size) # input (seq_len, batch, input_size) # h_0 (num_layers",
"if USE_CUDA: decoder_input = decoder_input.cuda() if max_similar_pos == 0: break loss.backward() encoder_optimizer.step() decoder_optimizer.step()",
"'.join(en_sens).split(' ')) # zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab = set(en_word_counts) # zh_vocab = set(zh_word_counts)",
"= self.embedded(word_inputs).view(seq_len, 1, -1) output, hidden = self.gru(embedded, hidden) return output, hidden def",
"= [deal_zh_sen(line.split('\\t')[1]) for line in lines] pairs = [[en, zh] for en, zh",
"vocab 的 length self.embedded = nn.Embedding(output_size, hidden_size) self.gru = nn.GRU(hidden_size * 2, hidden_size)",
"-1) output, hidden = self.gru(embedded, hidden) return output, hidden def init_hidden(self): hidden =",
"is_cuda=False): super(Attn, self).__init__() self.hidden_size = hidden_size self.is_cuda = is_cuda # general method self.attn",
"1 x 1 x seq_len # 返回的 是 attn_weigths 维度 与 encoder_outputs 保持一致",
"10] rnn_output, hidden = self.gru(rnn_input, last_hidden) # print(\"decoder's rnn_output is {}\".format(rnn_output)) # [1,",
"# 假设 input 为 [1, 4, 5, 7] [1, 4] # [4, 1,",
"lines = f.readlines() en_sens = [deal_en_sen(line.split('\\t')[0]) for line in lines] zh_sens = [deal_zh_sen(line.split('\\t')[1])",
"energy = self.attn(encoder_output) energy = hidden.dot(energy) return energy class DecoderRNN(nn.Module): def __init__(self, hidden_size,",
"(N, * , out_features) self.out = nn.Linear(hidden_size * 2, output_size) self.attn = Attn(hidden_size)",
"+ 'cmn.txt') as f: lines = f.readlines() en_sens = [deal_en_sen(line.split('\\t')[0]) for line in",
"= [deal_en_sen(line.split('\\t')[0]) for line in lines] zh_sens = [deal_zh_sen(line.split('\\t')[1]) for line in lines]",
"topi[0][0] # EOS_token if ni == 0: decoded_words.append('<EOS>') break else: decoded_words.append(index2word_zh[ni]) decoder_input =",
"in zh_sens: for word in list(jieba.cut(sen)): zh_counts[word] += 1 zh_vocab = set(zh_counts) MAX_LENGTH",
"self.attn = Attn(hidden_size) def forward(self, word_input, last_context, last_hidden, encoder_outputs): # embedding 的本来输出是 (n,",
"super(DecoderRNN, self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers self.is_cuda =",
"# print(type(attn_weights)) # print(type(encoder_outputs.transpose(0, 1))) # print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size()) context = attn_weights.bmm(encoder_outputs.transpose(0, 1))",
"为 [1, 4, 5, 7] [1, 4] # [4, 1, 500] [1, 1,",
"500 hidden_size = 128 n_layers = 1 MAX_LENGTH = 7 # USE_CUDA =",
"# 训练 # 500 hidden_size = 128 n_layers = 1 MAX_LENGTH = 7",
"decoder_input = Variable(torch.LongTensor([[ni]])) if USE_CUDA: decoder_input = decoder_input.cuda() return ''.join(decoded_words), decoder_attentions[:di+1, :len(encoder_outputs)] print(evaluate('i",
"MAX_LENGTH] word2index_en, index2word_en = wordandindex(en_vocab) word2index_en['EOS'] = 0 index2word_en[0] = 'EOS' word2index_zh, index2word_zh",
"if max_similar_pos == 0: break loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss.data[0] / target_length #",
"mini-batch # output (N, W, embedding_dim) self.embedded = nn.Embedding(input_size, hidden_size) # input (seq_len,",
"3] attn_weights = self.attn(rnn_output, encoder_outputs) # print(\"decoder's attn_weights is {}\".format(attn_weights)) # [1, 1,",
"F from torch.autograd import Variable import numpy as np import pandas as pd",
"if self.is_cuda: hidden = hidden.cuda() return hidden # 为了简便 这里实现的是 Attn 中的 general",
"# ??? # print(target_variable[i].size()) loss += criterion(decoder_output, target_variable[0][i]) topv, topi = decoder_output.data.topk(1) max_similar_pos",
"# input_length = input_variable.size()[1] target_length = target_variable.size()[1] ## encoder # [num_layers * direc,",
"MAX_LENGTH = 10 # 工具函数 def deal_en_sen(raw): raw.strip() letters_only = re.sub(\"[^a-zA-Z]\", \" \",",
"= 10 # 工具函数 def deal_en_sen(raw): raw.strip() letters_only = re.sub(\"[^a-zA-Z]\", \" \", raw)",
"if self.is_cuda: attn_energies = attn_energies.cuda() for i in range(seq_len): attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0))",
"print(\"decoder's rnn_output is {}\".format(rnn_output)) # [1, 1, 3] attn_weights = self.attn(rnn_output, encoder_outputs) #",
"sen2index(sen, lang): global word2index_en global word2index_zh if lang == 'en': no_eos = [word2index_en[word]",
"{}\\'s avg_loss is {}'.format(epoch, print_loss_avg)) # 查看结果 def evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False): input_sen2index =",
"# output (N, W, embedding_dim) self.embedded = nn.Embedding(input_size, hidden_size) # input (seq_len, batch,",
"sen_vector = [[sen2index(pair[0], 'en'), sen2index(pair[1], 'zh')] for pair in filter_pairs] # 模型实现 #",
"encoder_hidden = encoder(input_variable, encoder_hidden) ## decoder # [1, 1] decoder_input = Variable(torch.LongTensor([[0]])) #",
"= encoder(input_variable, encoder_hidden) ## decoder # [1, 1] decoder_input = Variable(torch.LongTensor([[0]])) # [1,",
"0 index2word_zh[0] = 'EOS' sen_vector = [[sen2index(pair[0], 'en'), sen2index(pair[1], 'zh')] for pair in",
"import Variable import numpy as np import pandas as pd import matplotlib.pyplot as",
"(N, W, embedding_dim) self.embedded = nn.Embedding(input_size, hidden_size) # input (seq_len, batch, input_size) #",
"last_context, last_hidden, encoder_outputs): # embedding 的本来输出是 (n, w, embedding_dim) # [1, 1, 10]",
"max_length=MAX_LENGTH, is_cuda=False): input_sen2index = sen2index(sentence, 'en') input_variable = Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length = input_variable.size()[1]",
"= Variable(torch.zeros(1, 1, decoder.hidden_size)) if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() decoder_hidden",
"= decoder_input.cuda() decoder_context = decoder_context.cuda() decoder_hidden = encoder_hidden # 翻译结果 decoded_words = []",
"if ni == 0: decoded_words.append('<EOS>') break else: decoded_words.append(index2word_zh[ni]) decoder_input = Variable(torch.LongTensor([[ni]])) if USE_CUDA:",
"[pair for pair in pairs if len(pair[0].split(' ')) < MAX_LENGTH and len(list(jieba.cut(pair[1]))) <",
"7] [1, 4] # [4, 1, 500] [1, 1, 500] encoder_outputs, encoder_hidden =",
"为了简便 这里实现的是 Attn 中的 general method class Attn(nn.Module): def __init__(self, hidden_size, max_length=MAX_LENGTH, is_cuda=False):",
"n_epochs + 1): training_pair = random.choice(sen_vector) input_variable = Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size()) target_variable =",
"decoder_hidden, encoder_outputs) # ??? # print(target_variable[i].size()) loss += criterion(decoder_output, target_variable[0][i]) topv, topi =",
"as F from torch.autograd import Variable import numpy as np import pandas as",
"函数 en_word_counts = FreqDist(' '.join(en_sens).split(' ')) # zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab = set(en_word_counts)",
"pairs if len(pair[0].split(' ')) < MAX_LENGTH and len(list(jieba.cut(pair[1]))) < MAX_LENGTH] word2index_en, index2word_en =",
"input_size) # h_0 (num_layers * num_directions, batch, hidden_size) # output (seq_len, batch, hidden_size",
"[deal_en_sen(line.split('\\t')[0]) for line in lines] zh_sens = [deal_zh_sen(line.split('\\t')[1]) for line in lines] pairs",
"i in range(target_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) #",
"decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda()",
"no_eos.append(0) return no_eos def as_minutes(s): pass def time_since(since, percent): pass # 数据预处理 with",
"zh_sens]) # 借助 NLTK 函数 en_word_counts = FreqDist(' '.join(en_sens).split(' ')) # zh_word_counts =",
"if len(pair[0].split(' ')) < MAX_LENGTH and len(list(jieba.cut(pair[1]))) < MAX_LENGTH] word2index_en, index2word_en = wordandindex(en_vocab)",
"500] encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) ## decoder # [1, 1] decoder_input =",
"input_variable.cuda() target_variable = target_variable.cuda() loss = train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion,",
"False) print_loss_total += loss if epoch % print_every == 0: print_loss_avg = print_loss_total",
"pair in pairs if len(pair[0].split(' ')) < MAX_LENGTH and len(list(jieba.cut(pair[1]))) < MAX_LENGTH] word2index_en,",
"hidden_size) def forward(self, word_inputs, hidden): seq_len = len(word_inputs[0]) embedded = self.embedded(word_inputs).view(seq_len, 1, -1)",
"target_length # 训练细节定义 n_epochs = 500 print_every = 50 print_loss_total = 0 #",
"word_input, last_context, last_hidden, encoder_outputs): # embedding 的本来输出是 (n, w, embedding_dim) # [1, 1,",
"from collections import Counter import random path = '../data/cmn-eng/' SOS_token = 0 EOS_token",
"len(word_inputs[0]) embedded = self.embedded(word_inputs).view(seq_len, 1, -1) output, hidden = self.gru(embedded, hidden) return output,",
"= 500 print_every = 50 print_loss_total = 0 # 开始训练 for epoch in",
"= Attn(hidden_size) def forward(self, word_input, last_context, last_hidden, encoder_outputs): # embedding 的本来输出是 (n, w,",
"# np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1, is_cuda=False): super(EncoderRNN, self).__init__() #",
"n_layers=1, is_cuda=False): super(DecoderRNN, self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers",
"print(type(attn_weights)) # print(type(encoder_outputs.transpose(0, 1))) # print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size()) context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) #",
"range 0 to 1, resize to 1 x 1 x seq_len # 返回的",
"hidden.dot(energy) return energy class DecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, n_layers=1, is_cuda=False): super(DecoderRNN, self).__init__()",
"Attn(nn.Module): def __init__(self, hidden_size, max_length=MAX_LENGTH, is_cuda=False): super(Attn, self).__init__() self.hidden_size = hidden_size self.is_cuda =",
"import pandas as pd import matplotlib.pyplot as plt from nltk import FreqDist import",
"no_eos = [word2index_en[word] for word in sen.split(' ')] else: no_eos = [word2index_zh[word] for",
"decoder.hidden_size)) # [1, 1, 500] decoder_hidden = encoder_hidden if is_cuda: decoder_input = decoder_input.cuda()",
"line in lines] pairs = [[en, zh] for en, zh in zip (en_sens,",
"Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA: input_variable = input_variable.cuda() target_variable = target_variable.cuda() loss = train(input_variable, target_variable,",
"1 MAX_LENGTH = 10 # 工具函数 def deal_en_sen(raw): raw.strip() letters_only = re.sub(\"[^a-zA-Z]\", \"",
"print_loss_total / epoch print('epoch {}\\'s avg_loss is {}'.format(epoch, print_loss_avg)) # 查看结果 def evaluate(sentence,",
"SOS_token = 0 EOS_token = 1 MAX_LENGTH = 10 # 工具函数 def deal_en_sen(raw):",
"{word: i + 1 for i, word in enumerate(vocab)}, {i + 1: word",
"self.gru = nn.GRU(hidden_size, hidden_size) def forward(self, word_inputs, hidden): seq_len = len(word_inputs[0]) embedded =",
"attention # np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1, is_cuda=False): super(EncoderRNN, self).__init__()",
"num_directions, batch, hidden_size) # output (seq_len, batch, hidden_size * num_directions) # h_n (num_layers",
"is {}\".format(embedded)) # [1, 1, 20] rnn_input = torch.cat((embedded,last_context), 2) # print(\"decoder's rnn_input",
"[1, 4] # [4, 1, 500] [1, 1, 500] encoder_outputs, encoder_hidden = encoder(input_variable,",
"= n_layers self.is_cuda = is_cuda # outout_size 为 中文 vocab 的 length self.embedded",
"= self.gru(rnn_input, last_hidden) # print(\"decoder's rnn_output is {}\".format(rnn_output)) # [1, 1, 3] attn_weights",
"return output, hidden def init_hidden(self): hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) if self.is_cuda: hidden",
"* 2, output_size) self.attn = Attn(hidden_size) def forward(self, word_input, last_context, last_hidden, encoder_outputs): #",
"+= loss if epoch % print_every == 0: print_loss_avg = print_loss_total / epoch",
"=> (N, *, in_features) # output => (N, * , out_features) self.out =",
"re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw) return(letters_only) def wordandindex(vocab): return {word: i + 1 for i,",
"i, word in enumerate(vocab)}, {i + 1: word for i, word in enumerate(vocab)}",
"500] decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) # [1, 1, 500] decoder_hidden = encoder_hidden",
"USE_CUDA: input_variable = input_variable.cuda() target_variable = target_variable.cuda() loss = train(input_variable, target_variable, encoder, decoder,",
"= optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr) criterion = nn.NLLLoss() # 训练函数 def",
"forward(self, word_inputs, hidden): seq_len = len(word_inputs[0]) embedded = self.embedded(word_inputs).view(seq_len, 1, -1) output, hidden",
"= nn.Embedding(output_size, hidden_size) self.gru = nn.GRU(hidden_size * 2, hidden_size) # input => (N,",
"word2index_en, index2word_en = wordandindex(en_vocab) word2index_en['EOS'] = 0 index2word_en[0] = 'EOS' word2index_zh, index2word_zh =",
"{}\".format(rnn_output)) # [1, 1, 3] attn_weights = self.attn(rnn_output, encoder_outputs) # print(\"decoder's attn_weights is",
"工具函数 def deal_en_sen(raw): raw.strip() letters_only = re.sub(\"[^a-zA-Z]\", \" \", raw) words = letters_only.lower().split()",
"decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) # ??? # print(target_variable[i].size())",
"lang == 'en': no_eos = [word2index_en[word] for word in sen.split(' ')] else: no_eos",
"# [1, 1] decoder_input = Variable(torch.LongTensor([[0]])) # [1, 1, 500] decoder_context = Variable(torch.zeros(1,",
"(seq_len, batch, input_size) # h_0 (num_layers * num_directions, batch, hidden_size) # output (seq_len,",
"-1)) input_length = input_variable.size()[1] if is_cuda: input_variable = input_variable.cuda() encoder_hidden = encoder.init_hidden() encoder_outputs,",
"with attention # np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1, is_cuda=False): super(EncoderRNN,",
"= self.gru(embedded, hidden) return output, hidden def init_hidden(self): hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size))",
"hidden.cuda() return hidden # 为了简便 这里实现的是 Attn 中的 general method class Attn(nn.Module): def",
"encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, is_cuda=False): # 梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss = 0",
"zh_counts[word] += 1 zh_vocab = set(zh_counts) MAX_LENGTH = 7 filter_pairs = [pair for",
"F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden, encoder_output): energy = self.attn(encoder_output) energy = hidden.dot(energy) return energy",
"input_variable = input_variable.cuda() target_variable = target_variable.cuda() loss = train(input_variable, target_variable, encoder, decoder, encoder_optimizer,",
"torch.nn.functional as F from torch.autograd import Variable import numpy as np import pandas",
"# EOS_token if ni == 0: decoded_words.append('<EOS>') break else: decoded_words.append(index2word_zh[ni]) decoder_input = Variable(torch.LongTensor([[ni]]))",
"self.hidden_size = hidden_size self.n_layers = n_layers self.is_cuda = is_cuda # input (N, W)",
"return(letters_only) def wordandindex(vocab): return {word: i + 1 for i, word in enumerate(vocab)},",
"encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) decoder_input = Variable(torch.LongTensor([[0]])) decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size))",
"vocab 的size self.input_size = input_size self.hidden_size = hidden_size self.n_layers = n_layers self.is_cuda =",
"word_inputs, hidden): seq_len = len(word_inputs[0]) embedded = self.embedded(word_inputs).view(seq_len, 1, -1) output, hidden =",
"= hidden_size self.n_layers = n_layers self.is_cuda = is_cuda # input (N, W) LongTensor",
"rnn_output is {}\".format(rnn_output)) # [1, 1, 3] attn_weights = self.attn(rnn_output, encoder_outputs) # print(\"decoder's",
"的 length self.embedded = nn.Embedding(output_size, hidden_size) self.gru = nn.GRU(hidden_size * 2, hidden_size) #",
"return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden, encoder_output): energy = self.attn(encoder_output) energy = hidden.dot(energy) return",
"pd import matplotlib.pyplot as plt from nltk import FreqDist import re import jieba",
"encoder_outputs) # print(\"decoder's attn_weights is {}\".format(attn_weights)) # [1, 1, 3] bmm [1, 3,",
"self.is_cuda = is_cuda # input (N, W) LongTensor N = mini-batch # output",
"False USE_CUDA = False encoder = EncoderRNN(len(en_vocab), hidden_size, n_layers, False) decoder = DecoderRNN(hidden_size,",
"1, 500] encoder_hidden = encoder.init_hidden() # 假设 input 为 [1, 4, 5, 7]",
"input => (N, *, in_features) # output => (N, * , out_features) self.out",
"loss += criterion(decoder_output, target_variable[0][i]) topv, topi = decoder_output.data.topk(1) max_similar_pos = topi[0][0] decoder_input =",
"filter_pairs] # 模型实现 # seq2seq with attention # np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module): def __init__(self,",
"# zh_vocab = set(zh_word_counts) zh_counts = Counter() for sen in zh_sens: for word",
"zh_max_len = max([len(x) for x in zh_sens]) # 借助 NLTK 函数 en_word_counts =",
"# input (N, W) LongTensor N = mini-batch # output (N, W, embedding_dim)",
"energy = hidden.dot(energy) return energy class DecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, n_layers=1, is_cuda=False):",
"训练 # 500 hidden_size = 128 n_layers = 1 MAX_LENGTH = 7 #",
"= 0 # added noto for each word # input_length = input_variable.size()[1] target_length",
"to weights in range 0 to 1, resize to 1 x 1 x",
"= output_size self.n_layers = n_layers self.is_cuda = is_cuda # outout_size 为 中文 vocab",
"= nn.GRU(hidden_size * 2, hidden_size) # input => (N, *, in_features) # output",
"noto for each word # input_length = input_variable.size()[1] target_length = target_variable.size()[1] ## encoder",
"target_variable = Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA: input_variable = input_variable.cuda() target_variable = target_variable.cuda() loss =",
"hidden_size, n_layers=1, is_cuda=False): super(EncoderRNN, self).__init__() # input_size 实际上是 vocab 的size self.input_size = input_size",
"# [num_layers * direc, batch_s, fea] [1, 1, 500] encoder_hidden = encoder.init_hidden() #",
"as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import",
"# 数据预处理 with open(path + 'cmn.txt') as f: lines = f.readlines() en_sens =",
"attn_energies = attn_energies.cuda() for i in range(seq_len): attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) # Normalize",
"import torch.nn.functional as F from torch.autograd import Variable import numpy as np import",
"def evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False): input_sen2index = sen2index(sentence, 'en') input_variable = Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length",
"enumerate(vocab)} def sen2index(sen, lang): global word2index_en global word2index_zh if lang == 'en': no_eos",
"h_0 (num_layers * num_directions, batch, hidden_size) # output (seq_len, batch, hidden_size * num_directions)",
"n_layers=1, is_cuda=False): super(EncoderRNN, self).__init__() # input_size 实际上是 vocab 的size self.input_size = input_size self.hidden_size",
"< MAX_LENGTH] word2index_en, index2word_en = wordandindex(en_vocab) word2index_en['EOS'] = 0 index2word_en[0] = 'EOS' word2index_zh,",
"* num_directions, batch, hidden_size) # output (seq_len, batch, hidden_size * num_directions) # h_n",
"= 0 # 开始训练 for epoch in range(1, n_epochs + 1): training_pair =",
"set(zh_word_counts) zh_counts = Counter() for sen in zh_sens: for word in list(jieba.cut(sen)): zh_counts[word]",
"lr = 1e-3 encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr) criterion =",
"USE_CUDA: encoder.cuda() decoder.cuda() lr = 1e-3 encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer = optim.Adam(decoder.parameters(),",
"def deal_en_sen(raw): raw.strip() letters_only = re.sub(\"[^a-zA-Z]\", \" \", raw) words = letters_only.lower().split() return",
"# print(\"decoder's rnn_output is {}\".format(rnn_output)) # [1, 1, 3] attn_weights = self.attn(rnn_output, encoder_outputs)",
"decoder_context.cuda() decoder_hidden = encoder_hidden # 翻译结果 decoded_words = [] # 这块还不是很理解 decoder_attentions =",
"self.gru(embedded, hidden) return output, hidden def init_hidden(self): hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) if",
"criterion(decoder_output, target_variable[0][i]) topv, topi = decoder_output.data.topk(1) max_similar_pos = topi[0][0] decoder_input = Variable(torch.LongTensor([[max_similar_pos]])) #",
"500] [1, 1, 500] encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) ## decoder # [1,",
"is_cuda: input_variable = input_variable.cuda() encoder_hidden = encoder.init_hidden() encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) decoder_input",
"# 借助 NLTK 函数 en_word_counts = FreqDist(' '.join(en_sens).split(' ')) # zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens))))",
"梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss = 0 # added noto for each word #",
"= Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA: input_variable = input_variable.cuda() target_variable = target_variable.cuda() loss = train(input_variable,",
"encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) ## decoder # [1, 1] decoder_input = Variable(torch.LongTensor([[0]]))",
"MAX_LENGTH = 7 filter_pairs = [pair for pair in pairs if len(pair[0].split(' '))",
"= 'EOS' sen_vector = [[sen2index(pair[0], 'en'), sen2index(pair[1], 'zh')] for pair in filter_pairs] #",
"n_layers = 1 MAX_LENGTH = 7 # USE_CUDA = False USE_CUDA = False",
"= input_size self.hidden_size = hidden_size self.n_layers = n_layers self.is_cuda = is_cuda # input",
"hidden_size, max_length=MAX_LENGTH, is_cuda=False): super(Attn, self).__init__() self.hidden_size = hidden_size self.is_cuda = is_cuda # general",
"W) LongTensor N = mini-batch # output (N, W, embedding_dim) self.embedded = nn.Embedding(input_size,",
"set(zh_counts) MAX_LENGTH = 7 filter_pairs = [pair for pair in pairs if len(pair[0].split('",
"[1, 1, 3] attn_weights = self.attn(rnn_output, encoder_outputs) # print(\"decoder's attn_weights is {}\".format(attn_weights)) #",
"这里实现的是 Attn 中的 general method class Attn(nn.Module): def __init__(self, hidden_size, max_length=MAX_LENGTH, is_cuda=False): super(Attn,",
"zh_vocab = set(zh_word_counts) zh_counts = Counter() for sen in zh_sens: for word in",
"deal_zh_sen(raw): raw.strip() letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw) return(letters_only) def wordandindex(vocab): return {word: i",
"decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) # ??? # print(target_variable[i].size()) loss +=",
"decoder_context, decoder_hidden, encoder_outputs) topv, topi = decoder_output.data.topk(1) ni = topi[0][0] # EOS_token if",
"in lines] zh_sens = [deal_zh_sen(line.split('\\t')[1]) for line in lines] pairs = [[en, zh]",
"FreqDist import re import jieba import math import time from collections import Counter",
"1, 20] rnn_input = torch.cat((embedded,last_context), 2) # print(\"decoder's rnn_input is {}\".format(rnn_input)) # [1,",
"import math import time from collections import Counter import random path = '../data/cmn-eng/'",
"# print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size()) context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # print(\"decoder's context is {}\".format(context))",
"if is_cuda: input_variable = input_variable.cuda() encoder_hidden = encoder.init_hidden() encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden)",
"(N, W) LongTensor N = mini-batch # output (N, W, embedding_dim) self.embedded =",
"n_layers self.is_cuda = is_cuda # outout_size 为 中文 vocab 的 length self.embedded =",
"lines] zh_sens = [deal_zh_sen(line.split('\\t')[1]) for line in lines] pairs = [[en, zh] for",
"pair in filter_pairs] # 模型实现 # seq2seq with attention # np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module):",
"output is {}\".format(output)) return output, context, hidden, attn_weights # 训练 # 500 hidden_size",
"encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr) criterion = nn.NLLLoss() # 训练函数",
"EOS_token if ni == 0: decoded_words.append('<EOS>') break else: decoded_words.append(index2word_zh[ni]) decoder_input = Variable(torch.LongTensor([[ni]])) if",
"hidden_size = 128 n_layers = 1 MAX_LENGTH = 7 # USE_CUDA = False",
"= set(zh_counts) MAX_LENGTH = 7 filter_pairs = [pair for pair in pairs if",
"# print(\"decoder's rnn_input is {}\".format(rnn_input)) # [1, 1, 10] rnn_output, hidden = self.gru(rnn_input,",
"enumerate(vocab)}, {i + 1: word for i, word in enumerate(vocab)} def sen2index(sen, lang):",
"input (N, W) LongTensor N = mini-batch # output (N, W, embedding_dim) self.embedded",
"2, output_size) self.attn = Attn(hidden_size) def forward(self, word_input, last_context, last_hidden, encoder_outputs): # embedding",
"for epoch in range(1, n_epochs + 1): training_pair = random.choice(sen_vector) input_variable = Variable(torch.LongTensor([training_pair[0]]))",
"max_similar_pos == 0: break loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss.data[0] / target_length # 训练细节定义",
"= Variable(torch.zeros(1, 1, decoder.hidden_size)) # [1, 1, 500] decoder_hidden = encoder_hidden if is_cuda:",
"is_cuda=False): input_sen2index = sen2index(sentence, 'en') input_variable = Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length = input_variable.size()[1] if",
"each word # input_length = input_variable.size()[1] target_length = target_variable.size()[1] ## encoder # [num_layers",
"= n_layers self.is_cuda = is_cuda # input (N, W) LongTensor N = mini-batch",
"= FreqDist(' '.join(en_sens).split(' ')) # zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab = set(en_word_counts) # zh_vocab",
"(num_layers * num_directions, batch, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size) def forward(self, word_inputs, hidden):",
"* num_directions, batch, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size) def forward(self, word_inputs, hidden): seq_len",
"nn.Embedding(output_size, hidden_size) self.gru = nn.GRU(hidden_size * 2, hidden_size) # input => (N, *,",
"= decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) # ??? # print(target_variable[i].size()) loss += criterion(decoder_output, target_variable[0][i])",
"self.attn(encoder_output) energy = hidden.dot(energy) return energy class DecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, n_layers=1,",
"attn_weights.bmm(encoder_outputs.transpose(0, 1)) # print(\"decoder's context is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size())) output = F.log_softmax(self.out(torch.cat((rnn_output.squeeze(0),",
"EOS_token = 1 MAX_LENGTH = 10 # 工具函数 def deal_en_sen(raw): raw.strip() letters_only =",
"output, context, hidden, attn_weights # 训练 # 500 hidden_size = 128 n_layers =",
"torch.zeros(max_length, max_length) for di in range(max_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context,",
"encoder.cuda() decoder.cuda() lr = 1e-3 encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr)",
"decoder_context = decoder_context.cuda() decoder_hidden = encoder_hidden # 翻译结果 decoded_words = [] # 这块还不是很理解",
"'cmn.txt') as f: lines = f.readlines() en_sens = [deal_en_sen(line.split('\\t')[0]) for line in lines]",
"nn.NLLLoss() # 训练函数 def train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, is_cuda=False): #",
"method class Attn(nn.Module): def __init__(self, hidden_size, max_length=MAX_LENGTH, is_cuda=False): super(Attn, self).__init__() self.hidden_size = hidden_size",
"path = '../data/cmn-eng/' SOS_token = 0 EOS_token = 1 MAX_LENGTH = 10 #",
"3] bmm [1, 3, 10](转置之前 [3, 1, 10]) => [1, 1, 10] #",
"+ 1: word for i, word in enumerate(vocab)} def sen2index(sen, lang): global word2index_en",
"= 0 index2word_en[0] = 'EOS' word2index_zh, index2word_zh = wordandindex(zh_vocab) word2index_zh['EOS'] = 0 index2word_zh[0]",
"[num_layers * direc, batch_s, fea] [1, 1, 500] encoder_hidden = encoder.init_hidden() # 假设",
"# 500 hidden_size = 128 n_layers = 1 MAX_LENGTH = 7 # USE_CUDA",
"input_length = input_variable.size()[1] if is_cuda: input_variable = input_variable.cuda() encoder_hidden = encoder.init_hidden() encoder_outputs, encoder_hidden",
"decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) # ??? # print(target_variable[i].size()) loss += criterion(decoder_output,",
"numpy as np import pandas as pd import matplotlib.pyplot as plt from nltk",
"= is_cuda # input (N, W) LongTensor N = mini-batch # output (N,",
"= [word2index_en[word] for word in sen.split(' ')] else: no_eos = [word2index_zh[word] for word",
"input_size 实际上是 vocab 的size self.input_size = input_size self.hidden_size = hidden_size self.n_layers = n_layers",
"hidden_size) def forward(self, hidden, encoder_outputs): seq_len = len(encoder_outputs) attn_energies = Variable(torch.zeros(seq_len)) if self.is_cuda:",
"这块还不是很理解 decoder_attentions = torch.zeros(max_length, max_length) for di in range(max_length): decoder_output, decoder_context, decoder_hidden, decoder_attention",
"* , out_features) self.out = nn.Linear(hidden_size * 2, output_size) self.attn = Attn(hidden_size) def",
"encoder_outputs) # ??? # print(target_variable[i].size()) loss += criterion(decoder_output, target_variable[0][i]) topv, topi = decoder_output.data.topk(1)",
"context, hidden, attn_weights # 训练 # 500 hidden_size = 128 n_layers = 1",
"print(type(encoder_outputs.transpose(0, 1))) # print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size()) context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # print(\"decoder's context",
"# zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab = set(en_word_counts) # zh_vocab = set(zh_word_counts) zh_counts =",
"1, decoder.hidden_size)) # [1, 1, 500] decoder_hidden = encoder_hidden if is_cuda: decoder_input =",
"1, -1) output, hidden = self.gru(embedded, hidden) return output, hidden def init_hidden(self): hidden",
"5, 7] [1, 4] # [4, 1, 500] [1, 1, 500] encoder_outputs, encoder_hidden",
"Counter() for sen in zh_sens: for word in list(jieba.cut(sen)): zh_counts[word] += 1 zh_vocab",
"= nn.Linear(self.hidden_size, hidden_size) def forward(self, hidden, encoder_outputs): seq_len = len(encoder_outputs) attn_energies = Variable(torch.zeros(seq_len))",
"input_variable = input_variable.cuda() encoder_hidden = encoder.init_hidden() encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) decoder_input =",
"hidden, attn_weights # 训练 # 500 hidden_size = 128 n_layers = 1 MAX_LENGTH",
"= decoder_input.cuda() if max_similar_pos == 0: break loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss.data[0] /",
"50 print_loss_total = 0 # 开始训练 for epoch in range(1, n_epochs + 1):",
"import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable import",
"decoder_input.cuda() decoder_context = decoder_context.cuda() for i in range(target_length): decoder_output, decoder_context, decoder_hidden, decoder_attention =",
"raw) return(letters_only) def wordandindex(vocab): return {word: i + 1 for i, word in",
"to 1, resize to 1 x 1 x seq_len # 返回的 是 attn_weigths",
"self.attn = nn.Linear(self.hidden_size, hidden_size) def forward(self, hidden, encoder_outputs): seq_len = len(encoder_outputs) attn_energies =",
"is_cuda # input (N, W) LongTensor N = mini-batch # output (N, W,",
"in range 0 to 1, resize to 1 x 1 x seq_len #",
"import time from collections import Counter import random path = '../data/cmn-eng/' SOS_token =",
"print(\"decoder's attn_weights is {}\".format(attn_weights)) # [1, 1, 3] bmm [1, 3, 10](转置之前 [3,",
"for en, zh in zip (en_sens, zh_sens)] en_max_len = max([len(x) for x in",
"1, resize to 1 x 1 x seq_len # 返回的 是 attn_weigths 维度",
"hidden_size, n_layers, False) decoder = DecoderRNN(hidden_size, len(zh_vocab), n_layers, False) if USE_CUDA: encoder.cuda() decoder.cuda()",
"{}\".format(embedded)) # [1, 1, 20] rnn_input = torch.cat((embedded,last_context), 2) # print(\"decoder's rnn_input is",
"general method self.attn = nn.Linear(self.hidden_size, hidden_size) def forward(self, hidden, encoder_outputs): seq_len = len(encoder_outputs)",
"pass def time_since(since, percent): pass # 数据预处理 with open(path + 'cmn.txt') as f:",
"train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, False) print_loss_total += loss if epoch",
"encoder_hidden # 翻译结果 decoded_words = [] # 这块还不是很理解 decoder_attentions = torch.zeros(max_length, max_length) for",
"random path = '../data/cmn-eng/' SOS_token = 0 EOS_token = 1 MAX_LENGTH = 10",
"hidden = hidden.cuda() return hidden # 为了简便 这里实现的是 Attn 中的 general method class",
"is {}\".format(output)) return output, context, hidden, attn_weights # 训练 # 500 hidden_size =",
"f: lines = f.readlines() en_sens = [deal_en_sen(line.split('\\t')[0]) for line in lines] zh_sens =",
"in list(jieba.cut(sen)): zh_counts[word] += 1 zh_vocab = set(zh_counts) MAX_LENGTH = 7 filter_pairs =",
"= encoder.init_hidden() # 假设 input 为 [1, 4, 5, 7] [1, 4] #",
"letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw) return(letters_only) def wordandindex(vocab): return {word: i + 1",
"epoch print('epoch {}\\'s avg_loss is {}'.format(epoch, print_loss_avg)) # 查看结果 def evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False):",
"en, zh in zip (en_sens, zh_sens)] en_max_len = max([len(x) for x in en_sens])",
"in range(seq_len): attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) # Normalize energies to weights in range",
"[1, 3, 10](转置之前 [3, 1, 10]) => [1, 1, 10] # print(type(attn_weights)) #",
"optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr) criterion = nn.NLLLoss() # 训练函数 def train(input_variable,",
"= torch.cat((embedded,last_context), 2) # print(\"decoder's rnn_input is {}\".format(rnn_input)) # [1, 1, 10] rnn_output,",
"Attn(hidden_size) def forward(self, word_input, last_context, last_hidden, encoder_outputs): # embedding 的本来输出是 (n, w, embedding_dim)",
"wordandindex(en_vocab) word2index_en['EOS'] = 0 index2word_en[0] = 'EOS' word2index_zh, index2word_zh = wordandindex(zh_vocab) word2index_zh['EOS'] =",
"= [[sen2index(pair[0], 'en'), sen2index(pair[1], 'zh')] for pair in filter_pairs] # 模型实现 # seq2seq",
"print(decoder_input) if USE_CUDA: decoder_input = decoder_input.cuda() if max_similar_pos == 0: break loss.backward() encoder_optimizer.step()",
"0 to 1, resize to 1 x 1 x seq_len # 返回的 是",
"train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, is_cuda=False): # 梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss",
"ni = topi[0][0] # EOS_token if ni == 0: decoded_words.append('<EOS>') break else: decoded_words.append(index2word_zh[ni])",
"1, 3] attn_weights = self.attn(rnn_output, encoder_outputs) # print(\"decoder's attn_weights is {}\".format(attn_weights)) # [1,",
"zh_sens = [deal_zh_sen(line.split('\\t')[1]) for line in lines] pairs = [[en, zh] for en,",
"= 1 MAX_LENGTH = 10 # 工具函数 def deal_en_sen(raw): raw.strip() letters_only = re.sub(\"[^a-zA-Z]\",",
"index2word_zh = wordandindex(zh_vocab) word2index_zh['EOS'] = 0 index2word_zh[0] = 'EOS' sen_vector = [[sen2index(pair[0], 'en'),",
"encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss = 0 # added noto for each word # input_length",
"+ 1): training_pair = random.choice(sen_vector) input_variable = Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size()) target_variable = Variable(torch.LongTensor([training_pair[1]]))",
"中的 general method class Attn(nn.Module): def __init__(self, hidden_size, max_length=MAX_LENGTH, is_cuda=False): super(Attn, self).__init__() self.hidden_size",
"word in enumerate(vocab)}, {i + 1: word for i, word in enumerate(vocab)} def",
"with open(path + 'cmn.txt') as f: lines = f.readlines() en_sens = [deal_en_sen(line.split('\\t')[0]) for",
"for word in list(jieba.cut(sen)): zh_counts[word] += 1 zh_vocab = set(zh_counts) MAX_LENGTH = 7",
"if epoch % print_every == 0: print_loss_avg = print_loss_total / epoch print('epoch {}\\'s",
"import re import jieba import math import time from collections import Counter import",
"self.is_cuda: attn_energies = attn_energies.cuda() for i in range(seq_len): attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) #",
"en_sens = [deal_en_sen(line.split('\\t')[0]) for line in lines] zh_sens = [deal_zh_sen(line.split('\\t')[1]) for line in",
"Variable(torch.zeros(seq_len)) if self.is_cuda: attn_energies = attn_energies.cuda() for i in range(seq_len): attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0),",
"1e-3 encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr) criterion = nn.NLLLoss() #",
"= is_cuda # outout_size 为 中文 vocab 的 length self.embedded = nn.Embedding(output_size, hidden_size)",
"= Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length = input_variable.size()[1] if is_cuda: input_variable = input_variable.cuda() encoder_hidden =",
"length self.embedded = nn.Embedding(output_size, hidden_size) self.gru = nn.GRU(hidden_size * 2, hidden_size) # input",
"Variable(torch.LongTensor([[0]])) # [1, 1, 500] decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) # [1, 1,",
"__init__(self, hidden_size, max_length=MAX_LENGTH, is_cuda=False): super(Attn, self).__init__() self.hidden_size = hidden_size self.is_cuda = is_cuda #",
"loss.data[0] / target_length # 训练细节定义 n_epochs = 500 print_every = 50 print_loss_total =",
"in zip (en_sens, zh_sens)] en_max_len = max([len(x) for x in en_sens]) zh_max_len =",
"print_every = 50 print_loss_total = 0 # 开始训练 for epoch in range(1, n_epochs",
"= 1 MAX_LENGTH = 7 # USE_CUDA = False USE_CUDA = False encoder",
"output, hidden = self.gru(embedded, hidden) return output, hidden def init_hidden(self): hidden = Variable(torch.zeros(self.n_layers,",
"= target_variable.cuda() loss = train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, False) print_loss_total",
"1, 3] bmm [1, 3, 10](转置之前 [3, 1, 10]) => [1, 1, 10]",
"x in zh_sens]) # 借助 NLTK 函数 en_word_counts = FreqDist(' '.join(en_sens).split(' ')) #",
"[1, 1, 10] # print(type(attn_weights)) # print(type(encoder_outputs.transpose(0, 1))) # print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size()) context",
"attn_energies = Variable(torch.zeros(seq_len)) if self.is_cuda: attn_energies = attn_energies.cuda() for i in range(seq_len): attn_energies[i]",
"= f.readlines() en_sens = [deal_en_sen(line.split('\\t')[0]) for line in lines] zh_sens = [deal_zh_sen(line.split('\\t')[1]) for",
"energies to weights in range 0 to 1, resize to 1 x 1",
"# 返回的 是 attn_weigths 维度 与 encoder_outputs 保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden,",
"USE_CUDA: decoder_input = decoder_input.cuda() if max_similar_pos == 0: break loss.backward() encoder_optimizer.step() decoder_optimizer.step() return",
"print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size()) context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # print(\"decoder's context is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output,",
"self.embedded(word_input) # print(\"decoder's embedded is {}\".format(embedded)) # [1, 1, 20] rnn_input = torch.cat((embedded,last_context),",
"nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable",
"encoder_outputs): seq_len = len(encoder_outputs) attn_energies = Variable(torch.zeros(seq_len)) if self.is_cuda: attn_energies = attn_energies.cuda() for",
"decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() decoder_hidden = encoder_hidden # 翻译结果 decoded_words =",
"= decoder_context.cuda() decoder_hidden = encoder_hidden # 翻译结果 decoded_words = [] # 这块还不是很理解 decoder_attentions",
"1 zh_vocab = set(zh_counts) MAX_LENGTH = 7 filter_pairs = [pair for pair in",
"criterion = nn.NLLLoss() # 训练函数 def train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion,",
"decoder = DecoderRNN(hidden_size, len(zh_vocab), n_layers, False) if USE_CUDA: encoder.cuda() decoder.cuda() lr = 1e-3",
"'en': no_eos = [word2index_en[word] for word in sen.split(' ')] else: no_eos = [word2index_zh[word]",
"is {}\".format(rnn_input)) # [1, 1, 10] rnn_output, hidden = self.gru(rnn_input, last_hidden) # print(\"decoder's",
"0: break loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss.data[0] / target_length # 训练细节定义 n_epochs =",
"是 attn_weigths 维度 与 encoder_outputs 保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden, encoder_output): energy",
"num_directions) # h_n (num_layers * num_directions, batch, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size) def",
"1 x seq_len # 返回的 是 attn_weigths 维度 与 encoder_outputs 保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0)",
"import random path = '../data/cmn-eng/' SOS_token = 0 EOS_token = 1 MAX_LENGTH =",
"output_size, n_layers=1, is_cuda=False): super(DecoderRNN, self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.n_layers =",
"embedding_dim) # [1, 1, 10] embedded = self.embedded(word_input) # print(\"decoder's embedded is {}\".format(embedded))",
"lr=lr) decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr) criterion = nn.NLLLoss() # 训练函数 def train(input_variable, target_variable,",
"[1, 1, 500] encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) ## decoder # [1, 1]",
"jieba import math import time from collections import Counter import random path =",
"= encoder(input_variable, encoder_hidden) decoder_input = Variable(torch.LongTensor([[0]])) decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) if is_cuda:",
"= attn_weights.bmm(encoder_outputs.transpose(0, 1)) # print(\"decoder's context is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context), 2)).size())) output =",
"int(input_variable.size()) target_variable = Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA: input_variable = input_variable.cuda() target_variable = target_variable.cuda() loss",
"[3, 1, 10]) => [1, 1, 10] # print(type(attn_weights)) # print(type(encoder_outputs.transpose(0, 1))) #",
"torch.autograd import Variable import numpy as np import pandas as pd import matplotlib.pyplot",
"x 1 x seq_len # 返回的 是 attn_weigths 维度 与 encoder_outputs 保持一致 return",
"in list(jieba.cut(sen))] no_eos.append(0) return no_eos def as_minutes(s): pass def time_since(since, percent): pass #",
"NLTK 函数 en_word_counts = FreqDist(' '.join(en_sens).split(' ')) # zh_word_counts = FreqDist(list(jieba.cut(''.join(zh_sens)))) en_vocab =",
"is_cuda=False): super(DecoderRNN, self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers self.is_cuda",
"= 50 print_loss_total = 0 # 开始训练 for epoch in range(1, n_epochs +",
"wordandindex(zh_vocab) word2index_zh['EOS'] = 0 index2word_zh[0] = 'EOS' sen_vector = [[sen2index(pair[0], 'en'), sen2index(pair[1], 'zh')]",
"in_features) # output => (N, * , out_features) self.out = nn.Linear(hidden_size * 2,",
"= input_variable.cuda() encoder_hidden = encoder.init_hidden() encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) decoder_input = Variable(torch.LongTensor([[0]]))",
"= Variable(torch.LongTensor([[0]])) # [1, 1, 500] decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) # [1,",
"encoder_hidden = encoder.init_hidden() encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) decoder_input = Variable(torch.LongTensor([[0]])) decoder_context =",
"[word2index_en[word] for word in sen.split(' ')] else: no_eos = [word2index_zh[word] for word in",
"decoder_optimizer, criterion, False) print_loss_total += loss if epoch % print_every == 0: print_loss_avg",
"attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) # Normalize energies to weights in range 0 to",
"if lang == 'en': no_eos = [word2index_en[word] for word in sen.split(' ')] else:",
"time_since(since, percent): pass # 数据预处理 with open(path + 'cmn.txt') as f: lines =",
"open(path + 'cmn.txt') as f: lines = f.readlines() en_sens = [deal_en_sen(line.split('\\t')[0]) for line",
"encoder_output): energy = self.attn(encoder_output) energy = hidden.dot(energy) return energy class DecoderRNN(nn.Module): def __init__(self,",
"hidden_size self.n_layers = n_layers self.is_cuda = is_cuda # input (N, W) LongTensor N",
"attn_weigths 维度 与 encoder_outputs 保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden, encoder_output): energy =",
"def __init__(self, hidden_size, output_size, n_layers=1, is_cuda=False): super(DecoderRNN, self).__init__() self.hidden_size = hidden_size self.output_size =",
"= 'EOS' word2index_zh, index2word_zh = wordandindex(zh_vocab) word2index_zh['EOS'] = 0 index2word_zh[0] = 'EOS' sen_vector",
"# input => (N, *, in_features) # output => (N, * , out_features)",
"# print(encoder_outputs.transpose(0,1).size()) context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # print(\"decoder's context is {}\".format(context)) #print(\"{}\".format(self.out(torch.cat((rnn_output, context),",
"for i, word in enumerate(vocab)} def sen2index(sen, lang): global word2index_en global word2index_zh if",
"# h_n (num_layers * num_directions, batch, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size) def forward(self,",
"10](转置之前 [3, 1, 10]) => [1, 1, 10] # print(type(attn_weights)) # print(type(encoder_outputs.transpose(0, 1)))",
"from torch.autograd import Variable import numpy as np import pandas as pd import",
"def wordandindex(vocab): return {word: i + 1 for i, word in enumerate(vocab)}, {i",
"W, embedding_dim) self.embedded = nn.Embedding(input_size, hidden_size) # input (seq_len, batch, input_size) # h_0",
"Variable(torch.zeros(1, 1, decoder.hidden_size)) if is_cuda: decoder_input = decoder_input.cuda() decoder_context = decoder_context.cuda() decoder_hidden =",
"self.embedded(word_inputs).view(seq_len, 1, -1) output, hidden = self.gru(embedded, hidden) return output, hidden def init_hidden(self):",
"from nltk import FreqDist import re import jieba import math import time from",
"1 for i, word in enumerate(vocab)}, {i + 1: word for i, word",
"batch, hidden_size * num_directions) # h_n (num_layers * num_directions, batch, hidden_size) self.gru =",
"* num_directions) # h_n (num_layers * num_directions, batch, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size)",
"torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable import numpy",
"= Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) if self.is_cuda: hidden = hidden.cuda() return hidden # 为了简便",
"target_variable[0][i]) topv, topi = decoder_output.data.topk(1) max_similar_pos = topi[0][0] decoder_input = Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input)",
"encoder_hidden = encoder(input_variable, encoder_hidden) decoder_input = Variable(torch.LongTensor([[0]])) decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) if",
"word2index_zh, index2word_zh = wordandindex(zh_vocab) word2index_zh['EOS'] = 0 index2word_zh[0] = 'EOS' sen_vector = [[sen2index(pair[0],",
"decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) # ??? # print(target_variable[i].size()) loss += criterion(decoder_output, target_variable[0][i]) topv,",
"= train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, False) print_loss_total += loss if",
"MAX_LENGTH = 7 # USE_CUDA = False USE_CUDA = False encoder = EncoderRNN(len(en_vocab),",
"(en_sens, zh_sens)] en_max_len = max([len(x) for x in en_sens]) zh_max_len = max([len(x) for",
"# 翻译结果 decoded_words = [] # 这块还不是很理解 decoder_attentions = torch.zeros(max_length, max_length) for di",
"保持一致 return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden, encoder_output): energy = self.attn(encoder_output) energy = hidden.dot(energy)",
"in lines] pairs = [[en, zh] for en, zh in zip (en_sens, zh_sens)]",
"Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) if self.is_cuda: hidden = hidden.cuda() return hidden # 为了简便 这里实现的是",
"is_cuda # outout_size 为 中文 vocab 的 length self.embedded = nn.Embedding(output_size, hidden_size) self.gru",
"batch_s, fea] [1, 1, 500] encoder_hidden = encoder.init_hidden() # 假设 input 为 [1,",
"topv, topi = decoder_output.data.topk(1) ni = topi[0][0] # EOS_token if ni == 0:",
"sen2index(pair[1], 'zh')] for pair in filter_pairs] # 模型实现 # seq2seq with attention #",
"7 # USE_CUDA = False USE_CUDA = False encoder = EncoderRNN(len(en_vocab), hidden_size, n_layers,",
"= input_variable.size()[1] if is_cuda: input_variable = input_variable.cuda() encoder_hidden = encoder.init_hidden() encoder_outputs, encoder_hidden =",
"10] # print(type(attn_weights)) # print(type(encoder_outputs.transpose(0, 1))) # print(attn_weights.size()) # print(encoder_outputs.transpose(0,1).size()) context = attn_weights.bmm(encoder_outputs.transpose(0,",
"for pair in filter_pairs] # 模型实现 # seq2seq with attention # np.array([sen_vector[2][1]]).shape class",
"import jieba import math import time from collections import Counter import random path",
"no_eos def as_minutes(s): pass def time_since(since, percent): pass # 数据预处理 with open(path +",
"# 查看结果 def evaluate(sentence, max_length=MAX_LENGTH, is_cuda=False): input_sen2index = sen2index(sentence, 'en') input_variable = Variable(torch.LongTensor(input_sen2index).view(1,",
"# 工具函数 def deal_en_sen(raw): raw.strip() letters_only = re.sub(\"[^a-zA-Z]\", \" \", raw) words =",
"# input_size 实际上是 vocab 的size self.input_size = input_size self.hidden_size = hidden_size self.n_layers =",
"= optim.Adam(decoder.parameters(), lr=lr) criterion = nn.NLLLoss() # 训练函数 def train(input_variable, target_variable, encoder, decoder,",
"nn.Linear(hidden_size * 2, output_size) self.attn = Attn(hidden_size) def forward(self, word_input, last_context, last_hidden, encoder_outputs):",
"loss = 0 # added noto for each word # input_length = input_variable.size()[1]",
"return energy class DecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, n_layers=1, is_cuda=False): super(DecoderRNN, self).__init__() self.hidden_size",
"hidden def init_hidden(self): hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) if self.is_cuda: hidden = hidden.cuda()",
"topi[0][0] decoder_input = Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input) if USE_CUDA: decoder_input = decoder_input.cuda() if max_similar_pos",
"= re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw) return(letters_only) def wordandindex(vocab): return {word: i + 1 for",
"decoder # [1, 1] decoder_input = Variable(torch.LongTensor([[0]])) # [1, 1, 500] decoder_context =",
"loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss.data[0] / target_length # 训练细节定义 n_epochs = 500 print_every",
"开始训练 for epoch in range(1, n_epochs + 1): training_pair = random.choice(sen_vector) input_variable =",
"'en'), sen2index(pair[1], 'zh')] for pair in filter_pairs] # 模型实现 # seq2seq with attention",
"return {word: i + 1 for i, word in enumerate(vocab)}, {i + 1:",
"in filter_pairs] # 模型实现 # seq2seq with attention # np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module): def",
"forward(self, word_input, last_context, last_hidden, encoder_outputs): # embedding 的本来输出是 (n, w, embedding_dim) # [1,",
"= EncoderRNN(len(en_vocab), hidden_size, n_layers, False) decoder = DecoderRNN(hidden_size, len(zh_vocab), n_layers, False) if USE_CUDA:",
"word for i, word in enumerate(vocab)} def sen2index(sen, lang): global word2index_en global word2index_zh",
"# seq2seq with attention # np.array([sen_vector[2][1]]).shape class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1,",
"= 1e-3 encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr) decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr) criterion = nn.NLLLoss()",
"'en') input_variable = Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length = input_variable.size()[1] if is_cuda: input_variable = input_variable.cuda()",
"decoder_input.cuda() decoder_context = decoder_context.cuda() decoder_hidden = encoder_hidden # 翻译结果 decoded_words = [] #",
"in sen.split(' ')] else: no_eos = [word2index_zh[word] for word in list(jieba.cut(sen))] no_eos.append(0) return",
"range(seq_len): attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) # Normalize energies to weights in range 0",
"encoder_optimizer, decoder_optimizer, criterion, is_cuda=False): # 梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() loss = 0 # added",
"embedding 的本来输出是 (n, w, embedding_dim) # [1, 1, 10] embedded = self.embedded(word_input) #",
"import matplotlib.pyplot as plt from nltk import FreqDist import re import jieba import",
"raw.strip() letters_only = re.sub(\"[^\\u4e00-\\u9fa5]\", \"\", raw) return(letters_only) def wordandindex(vocab): return {word: i +",
"output (N, W, embedding_dim) self.embedded = nn.Embedding(input_size, hidden_size) # input (seq_len, batch, input_size)",
"decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) topv, topi = decoder_output.data.topk(1) ni =",
"i, word in enumerate(vocab)} def sen2index(sen, lang): global word2index_en global word2index_zh if lang",
"Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length = input_variable.size()[1] if is_cuda: input_variable = input_variable.cuda() encoder_hidden = encoder.init_hidden()",
"init_hidden(self): hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) if self.is_cuda: hidden = hidden.cuda() return hidden",
"class DecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, n_layers=1, is_cuda=False): super(DecoderRNN, self).__init__() self.hidden_size = hidden_size",
"hidden_size self.output_size = output_size self.n_layers = n_layers self.is_cuda = is_cuda # outout_size 为",
"= 0 index2word_zh[0] = 'EOS' sen_vector = [[sen2index(pair[0], 'en'), sen2index(pair[1], 'zh')] for pair",
"self.input_size = input_size self.hidden_size = hidden_size self.n_layers = n_layers self.is_cuda = is_cuda #",
"# print(decoder_input) if USE_CUDA: decoder_input = decoder_input.cuda() if max_similar_pos == 0: break loss.backward()",
"math import time from collections import Counter import random path = '../data/cmn-eng/' SOS_token",
"sen2index(sentence, 'en') input_variable = Variable(torch.LongTensor(input_sen2index).view(1, -1)) input_length = input_variable.size()[1] if is_cuda: input_variable =",
"zh in zip (en_sens, zh_sens)] en_max_len = max([len(x) for x in en_sens]) zh_max_len",
"num_directions, batch, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size) def forward(self, word_inputs, hidden): seq_len =",
"2, hidden_size) # input => (N, *, in_features) # output => (N, *",
", out_features) self.out = nn.Linear(hidden_size * 2, output_size) self.attn = Attn(hidden_size) def forward(self,",
"')) < MAX_LENGTH and len(list(jieba.cut(pair[1]))) < MAX_LENGTH] word2index_en, index2word_en = wordandindex(en_vocab) word2index_en['EOS'] =",
"def train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, is_cuda=False): # 梯度初始化 encoder_optimizer.zero_grad() decoder_optimizer.zero_grad()",
"input 为 [1, 4, 5, 7] [1, 4] # [4, 1, 500] [1,",
"# 训练函数 def train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, is_cuda=False): # 梯度初始化",
"decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) # [1, 1, 500] decoder_hidden = encoder_hidden if",
"added noto for each word # input_length = input_variable.size()[1] target_length = target_variable.size()[1] ##",
"for i in range(target_length): decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs)",
"= self.embedded(word_input) # print(\"decoder's embedded is {}\".format(embedded)) # [1, 1, 20] rnn_input =",
"decoder_attention = decoder(decoder_input, decoder_context, decoder_hidden, encoder_outputs) topv, topi = decoder_output.data.topk(1) ni = topi[0][0]",
"Variable(torch.LongTensor([training_pair[0]])) # int(input_variable.size()) target_variable = Variable(torch.LongTensor([training_pair[1]])) if USE_CUDA: input_variable = input_variable.cuda() target_variable =",
"target_variable.size()[1] ## encoder # [num_layers * direc, batch_s, fea] [1, 1, 500] encoder_hidden",
"nn.Embedding(input_size, hidden_size) # input (seq_len, batch, input_size) # h_0 (num_layers * num_directions, batch,",
"self.is_cuda = is_cuda # outout_size 为 中文 vocab 的 length self.embedded = nn.Embedding(output_size,",
"= decoder_output.data.topk(1) max_similar_pos = topi[0][0] decoder_input = Variable(torch.LongTensor([[max_similar_pos]])) # print(decoder_input) if USE_CUDA: decoder_input",
"== 0: break loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss.data[0] / target_length # 训练细节定义 n_epochs",
"lr=lr) criterion = nn.NLLLoss() # 训练函数 def train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer,",
"epoch in range(1, n_epochs + 1): training_pair = random.choice(sen_vector) input_variable = Variable(torch.LongTensor([training_pair[0]])) #",
"4] # [4, 1, 500] [1, 1, 500] encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden)",
"# [1, 1, 500] decoder_context = Variable(torch.zeros(1, 1, decoder.hidden_size)) # [1, 1, 500]",
"[4, 1, 500] [1, 1, 500] encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden) ## decoder",
"# [1, 1, 20] rnn_input = torch.cat((embedded,last_context), 2) # print(\"decoder's rnn_input is {}\".format(rnn_input))",
"的size self.input_size = input_size self.hidden_size = hidden_size self.n_layers = n_layers self.is_cuda = is_cuda",
"= attn_energies.cuda() for i in range(seq_len): attn_energies[i] = self.score(hidden.squeeze(0).squeeze(0), encoder_outputs[i].squeeze(0)) # Normalize energies",
"self.attn(rnn_output, encoder_outputs) # print(\"decoder's attn_weights is {}\".format(attn_weights)) # [1, 1, 3] bmm [1,",
"/ epoch print('epoch {}\\'s avg_loss is {}'.format(epoch, print_loss_avg)) # 查看结果 def evaluate(sentence, max_length=MAX_LENGTH,",
"nltk import FreqDist import re import jieba import math import time from collections",
"zh_sens)] en_max_len = max([len(x) for x in en_sens]) zh_max_len = max([len(x) for x"
] |
[
"= [] example[\"mention_to_predict\"] = str(mention_to_predict) example[\"predicted_clusters\"] = cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\") if example_num",
"= (span[0]-1, span[1]) return span def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return [char for sentence in",
"flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return [char for sentence in sentences for char in sentence] def",
"is_training=False) feed_dict = {i: t for i, t in zip(model.input_tensors, tensorized_example)} _, _,",
"= [] span_count = {} span2pos = {} for span in cluster: if",
"[span] com_name = set(span_count.keys()) for ex in except_name: com_name.discard(ex) max_name = \"\" max_count",
"\"\".join(fla_sentences[span[0]:span[1] + 1]) in [\"公司\", \"集团\"]: # 对缺失字符进行补充 span = check_span(fla_sentences, span) if",
"for ex in except_name: com_name.discard(ex) max_name = \"\" max_count = 0 for com",
"{} for cluster in example[\"predicted_clusters\"]: res_cluster = [] span_count = {} span2pos =",
"output_filename = sys.argv[3] # 输出地址 model = util.get_model(config) saver = tf.train.Saver() with tf.Session()",
"is None: com2cluster[max_name] = res_cluster else: print(res_cluster) com2cluster[max_name].extend(res_cluster) for key, value in except_cluster.items():",
"for v_cluster in com2cluster.values(): res_clusters.append(v_cluster) return res_clusters if __name__ == \"__main__\": \"\"\" 命令行示例",
"对不合法单词进行过滤 continue res_cluster.append(span) word = \"\".join(fla_sentences[span[0]:span[1] + 1]) span_count[word] = span_count.get(word, 0) +",
"example[\"predicted_clusters\"]: res_cluster = [] span_count = {} span2pos = {} for span in",
"print_function import sys import json import tensorflow as tf import util import json",
"max_name = com print(\"max_name:{}\".format(max_name)) for com in com_name: # 公司名称 if com[:2] ==",
"错误预测的span将会筛除 res_cluster.remove(n) if com2cluster.get(max_name, None) is None: com2cluster[max_name] = res_cluster else: print(res_cluster) com2cluster[max_name].extend(res_cluster)",
"= sys.argv[2] # 输入数据地址 # Predictions will be written to this file in",
"\"\"\" fla_sentences = flatten_sentence(example[\"sentences\"]) res_clusters = [] com2cluster = {} except_cluster = {}",
"model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) example[\"top_spans\"] = list(zip((int(i) for i in top_span_starts), (int(i) for i",
"__name__ == \"__main__\": \"\"\" 命令行示例 python predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\" config =",
"\"\"\" 对模型预测结果进行算法修正 :param example: 一条json数据 :return: 纠正后的predicted_cluster \"\"\" fla_sentences = flatten_sentence(example[\"sentences\"]) res_clusters =",
"span) if \"#\" in \"\".join(fla_sentences[span[0]:span[1] + 1]): # 对不合法单词进行过滤 continue res_cluster.append(span) word =",
"for span in cluster: if \"\".join(fla_sentences[span[0]:span[1] + 1]) in [\"公司\", \"集团\"]: # 对缺失字符进行补充",
"\"#\" in \"\".join(fla_sentences[span[0]:span[1] + 1]): # 对不合法单词进行过滤 continue res_cluster.append(span) word = \"\".join(fla_sentences[span[0]:span[1] +",
"[\"公司\", \"本公司\", \"该公司\", \"贵公司\", \"贵司\", \"本行\", \"该行\", \"本银行\", \"该集团\", \"本集团\", \"集团\", \"它\", \"他们\",",
"输入数据地址 # Predictions will be written to this file in .jsonlines format. output_filename",
"format. input_filename = sys.argv[2] # 输入数据地址 # Predictions will be written to this",
"None) is None: print(\"该span将被彻底清除:{}\".format(key)) continue else: print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value) # res_clusters.append(res_cluster) for v_cluster",
"input_filename = sys.argv[2] # 输入数据地址 # Predictions will be written to this file",
"com print(\"max_name:{}\".format(max_name)) for com in com_name: # 公司名称 if com[:2] == max_name[:2]: #",
"else: print(res_cluster) com2cluster[max_name].extend(res_cluster) for key, value in except_cluster.items(): # 这步是十分有用的 if com2cluster.get(key, None)",
"[\"该\", \"本\", \"贵\"]: # 对span进行补全 span = (span[0]-1, span[1]) return span def flatten_sentence(sentences):",
"= model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict = model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) example[\"top_spans\"] = list(zip((int(i) for",
"com2cluster[max_name] = res_cluster else: print(res_cluster) com2cluster[max_name].extend(res_cluster) for key, value in except_cluster.items(): # 这步是十分有用的",
"tf import util import json except_name = [\"公司\", \"本公司\", \"该公司\", \"贵公司\", \"贵司\", \"本行\",",
"util import json except_name = [\"公司\", \"本公司\", \"该公司\", \"贵公司\", \"贵司\", \"本行\", \"该行\", \"本银行\",",
"\"本集团\", \"集团\", \"它\", \"他们\", \"他们\", \"我们\", \"该股\", \"其\", \"自身\"] def check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\"",
"= span_count[com] max_name = com print(\"max_name:{}\".format(max_name)) for com in com_name: # 公司名称 if",
"fla_sentences = flatten_sentence(example[\"sentences\"]) res_clusters = [] com2cluster = {} except_cluster = {} for",
"com2cluster[key].extend(value) # res_clusters.append(res_cluster) for v_cluster in com2cluster.values(): res_clusters.append(v_cluster) return res_clusters if __name__ ==",
"= span_count.get(word, 0) + 1 if span2pos.get(word, None) is not None: span2pos[word].append(span) else:",
"com2cluster[max_name].extend(res_cluster) for key, value in except_cluster.items(): # 这步是十分有用的 if com2cluster.get(key, None) is None:",
"= \"\".join(fla_sentences[span[0]:span[1] + 1]) span_count[word] = span_count.get(word, 0) + 1 if span2pos.get(word, None)",
"span2pos[word].append(span) else: span2pos[word] = [span] com_name = set(span_count.keys()) for ex in except_name: com_name.discard(ex)",
"in [\"公司\", \"集团\"]: # 对缺失字符进行补充 span = check_span(fla_sentences, span) if \"#\" in \"\".join(fla_sentences[span[0]:span[1]",
"# 输入数据地址 # Predictions will be written to this file in .jsonlines format.",
"key, value in dict0.items()]) return a[0] def cluster_rule(example): \"\"\" 对模型预测结果进行算法修正 :param example: 一条json数据",
"for cluster in example[\"predicted_clusters\"]: res_cluster = [] span_count = {} span2pos = {}",
"1]) span_count[word] = span_count.get(word, 0) + 1 if span2pos.get(word, None) is not None:",
"# span2pos[com] except_cluster[com] = span2pos[com] # 该公司名 for n in span2pos[com]: # 错误预测的span将会筛除",
"None) is not None: span2pos[word].append(span) else: span2pos[word] = [span] com_name = set(span_count.keys()) for",
"res_clusters if __name__ == \"__main__\": \"\"\" 命令行示例 python predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\"",
"in dict0.items()]) return a[0] def cluster_rule(example): \"\"\" 对模型预测结果进行算法修正 :param example: 一条json数据 :return: 纠正后的predicted_cluster",
"for com in com_name: # 公司名称 if com[:2] == max_name[:2]: # 头部两个字相同则认为两公司相同 continue",
"print(\"max_name:{}\".format(max_name)) for com in com_name: # 公司名称 if com[:2] == max_name[:2]: # 头部两个字相同则认为两公司相同",
"in sentences for char in sentence] def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a = max([(value, key)",
"res_clusters.append(v_cluster) return res_clusters if __name__ == \"__main__\": \"\"\" 命令行示例 python predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines",
"\"\".join(fla_sentences[span[0]:span[1] + 1]): # 对不合法单词进行过滤 continue res_cluster.append(span) word = \"\".join(fla_sentences[span[0]:span[1] + 1]) span_count[word]",
"[] com2cluster = {} except_cluster = {} for cluster in example[\"predicted_clusters\"]: res_cluster =",
"and com in max_name: # 具有包含关系的两公司,则认为相同 continue elif len(com) > len(max_name) and max_name",
"None: span2pos[word].append(span) else: span2pos[word] = [span] com_name = set(span_count.keys()) for ex in except_name:",
"list(zip((int(i) for i in top_span_starts), (int(i) for i in top_span_ends))) example['head_scores'] = []",
"in top_span_starts), (int(i) for i in top_span_ends))) example['head_scores'] = [] example[\"mention_to_predict\"] = str(mention_to_predict)",
"\"该行\", \"本银行\", \"该集团\", \"本集团\", \"集团\", \"它\", \"他们\", \"他们\", \"我们\", \"该股\", \"其\", \"自身\"] def",
"span_count.get(word, 0) + 1 if span2pos.get(word, None) is not None: span2pos[word].append(span) else: span2pos[word]",
"if __name__ == \"__main__\": \"\"\" 命令行示例 python predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\" config",
"= com elif span_count[com] == max_count and len(com) > len(max_name): max_count = span_count[com]",
"\"集团\", \"它\", \"他们\", \"他们\", \"我们\", \"该股\", \"其\", \"自身\"] def check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\" if",
"头部两个字相同则认为两公司相同 continue elif len(com) < len(max_name) and com in max_name: # 具有包含关系的两公司,则认为相同 continue",
"absolute_import from __future__ import division from __future__ import print_function import sys import json",
"= {} except_cluster = {} for cluster in example[\"predicted_clusters\"]: res_cluster = [] span_count",
"1 if span2pos.get(word, None) is not None: span2pos[word].append(span) else: span2pos[word] = [span] com_name",
"com in max_name: # 具有包含关系的两公司,则认为相同 continue elif len(com) > len(max_name) and max_name in",
"return [char for sentence in sentences for char in sentence] def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\"",
"这步是十分有用的 if com2cluster.get(key, None) is None: print(\"该span将被彻底清除:{}\".format(key)) continue else: print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value) #",
"res_cluster.append(span) word = \"\".join(fla_sentences[span[0]:span[1] + 1]) span_count[word] = span_count.get(word, 0) + 1 if",
"span_count[word] = span_count.get(word, 0) + 1 if span2pos.get(word, None) is not None: span2pos[word].append(span)",
"util.initialize_from_env() log_dir = config[\"log_dir\"] # Input file in .jsonlines format. input_filename = sys.argv[2]",
"a[0] def cluster_rule(example): \"\"\" 对模型预测结果进行算法修正 :param example: 一条json数据 :return: 纠正后的predicted_cluster \"\"\" fla_sentences =",
"tensorized_example = model.tensorize_example(example, is_training=False) feed_dict = {i: t for i, t in zip(model.input_tensors,",
"json except_name = [\"公司\", \"本公司\", \"该公司\", \"贵公司\", \"贵司\", \"本行\", \"该行\", \"本银行\", \"该集团\", \"本集团\",",
"span2pos.get(word, None) is not None: span2pos[word].append(span) else: span2pos[word] = [span] com_name = set(span_count.keys())",
"com2cluster.values(): res_clusters.append(v_cluster) return res_clusters if __name__ == \"__main__\": \"\"\" 命令行示例 python predict.py bert_base",
"print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value) # res_clusters.append(res_cluster) for v_cluster in com2cluster.values(): res_clusters.append(v_cluster) return res_clusters if",
"for n in span2pos[com]: # 错误预测的span将会筛除 res_cluster.remove(n) if com2cluster.get(max_name, None) is None: com2cluster[max_name]",
"_, _, _, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents = model.get_predicted_antecedents(top_antecedents,",
"except_name = [\"公司\", \"本公司\", \"该公司\", \"贵公司\", \"贵司\", \"本行\", \"该行\", \"本银行\", \"该集团\", \"本集团\", \"集团\",",
"span[1]) return span def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return [char for sentence in sentences for",
"com2cluster.get(max_name, None) is None: com2cluster[max_name] = res_cluster else: print(res_cluster) com2cluster[max_name].extend(res_cluster) for key, value",
"[] span_count = {} span2pos = {} for span in cluster: if \"\".join(fla_sentences[span[0]:span[1]",
"# 错误预测的span将会筛除 res_cluster.remove(n) if com2cluster.get(max_name, None) is None: com2cluster[max_name] = res_cluster else: print(res_cluster)",
"file in .jsonlines format. output_filename = sys.argv[3] # 输出地址 model = util.get_model(config) saver",
"- 1]) in [\"该\", \"本\", \"贵\"]: # 对span进行补全 span = (span[0]-1, span[1]) return",
"com2cluster.get(key, None) is None: print(\"该span将被彻底清除:{}\".format(key)) continue else: print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value) # res_clusters.append(res_cluster) for",
"else: print(com) # span2pos[com] except_cluster[com] = span2pos[com] # 该公司名 for n in span2pos[com]:",
"result_of_20.txt \"\"\" config = util.initialize_from_env() log_dir = config[\"log_dir\"] # Input file in .jsonlines",
"example: 一条json数据 :return: 纠正后的predicted_cluster \"\"\" fla_sentences = flatten_sentence(example[\"sentences\"]) res_clusters = [] com2cluster =",
"print(\"该span将被彻底清除:{}\".format(key)) continue else: print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value) # res_clusters.append(res_cluster) for v_cluster in com2cluster.values(): res_clusters.append(v_cluster)",
"获取cluster当中的频率最大的单词 if span_count[com] > max_count: max_count = span_count[com] max_name = com elif span_count[com]",
"if span2pos.get(word, None) is not None: span2pos[word].append(span) else: span2pos[word] = [span] com_name =",
":param example: 一条json数据 :return: 纠正后的predicted_cluster \"\"\" fla_sentences = flatten_sentence(example[\"sentences\"]) res_clusters = [] com2cluster",
"\"本银行\", \"该集团\", \"本集团\", \"集团\", \"它\", \"他们\", \"他们\", \"我们\", \"该股\", \"其\", \"自身\"] def check_span(fla_sentences,",
"sentence in sentences for char in sentence] def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a = max([(value,",
"对span进行补全 span = (span[0]-1, span[1]) return span def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return [char for",
"具有包含关系的两公司,则认为相同 continue elif len(com) > len(max_name) and max_name in com: continue else: print(com)",
"res_cluster else: print(res_cluster) com2cluster[max_name].extend(res_cluster) for key, value in except_cluster.items(): # 这步是十分有用的 if com2cluster.get(key,",
"value in dict0.items()]) return a[0] def cluster_rule(example): \"\"\" 对模型预测结果进行算法修正 :param example: 一条json数据 :return:",
"file in .jsonlines format. input_filename = sys.argv[2] # 输入数据地址 # Predictions will be",
"> len(max_name): max_count = span_count[com] max_name = com print(\"max_name:{}\".format(max_name)) for com in com_name:",
"= tf.train.Saver() with tf.Session() as session: model.restore(session) with open(output_filename, \"w\") as output_file: with",
"\"他们\", \"他们\", \"我们\", \"该股\", \"其\", \"自身\"] def check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0] -",
"import tensorflow as tf import util import json except_name = [\"公司\", \"本公司\", \"该公司\",",
"\"自身\"] def check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0] - 1]) in [\"该\", \"本\", \"贵\"]:",
"be written to this file in .jsonlines format. output_filename = sys.argv[3] # 输出地址",
".jsonlines format. input_filename = sys.argv[2] # 输入数据地址 # Predictions will be written to",
"top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict",
"+ 1]) span_count[word] = span_count.get(word, 0) + 1 if span2pos.get(word, None) is not",
"as session: model.restore(session) with open(output_filename, \"w\") as output_file: with open(input_filename) as input_file: for",
"com: continue else: print(com) # span2pos[com] except_cluster[com] = span2pos[com] # 该公司名 for n",
"span_count[com] == max_count and len(com) > len(max_name): max_count = span_count[com] max_name = com",
"ex in except_name: com_name.discard(ex) max_name = \"\" max_count = 0 for com in",
"_, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"],",
"Input file in .jsonlines format. input_filename = sys.argv[2] # 输入数据地址 # Predictions will",
"cluster: if \"\".join(fla_sentences[span[0]:span[1] + 1]) in [\"公司\", \"集团\"]: # 对缺失字符进行补充 span = check_span(fla_sentences,",
"max_name in com: continue else: print(com) # span2pos[com] except_cluster[com] = span2pos[com] # 该公司名",
"for key, value in dict0.items()]) return a[0] def cluster_rule(example): \"\"\" 对模型预测结果进行算法修正 :param example:",
"= {i: t for i, t in zip(model.input_tensors, tensorized_example)} _, _, _, top_span_starts,",
"example[\"mention_to_predict\"] = str(mention_to_predict) example[\"predicted_clusters\"] = cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\") if example_num % 100",
"span2pos[com] except_cluster[com] = span2pos[com] # 该公司名 for n in span2pos[com]: # 错误预测的span将会筛除 res_cluster.remove(n)",
"except_cluster[com] = span2pos[com] # 该公司名 for n in span2pos[com]: # 错误预测的span将会筛除 res_cluster.remove(n) if",
"span2pos = {} for span in cluster: if \"\".join(fla_sentences[span[0]:span[1] + 1]) in [\"公司\",",
"open(output_filename, \"w\") as output_file: with open(input_filename) as input_file: for example_num, line in enumerate(input_file.readlines()):",
"span2pos[word] = [span] com_name = set(span_count.keys()) for ex in except_name: com_name.discard(ex) max_name =",
"res_clusters.append(res_cluster) for v_cluster in com2cluster.values(): res_clusters.append(v_cluster) return res_clusters if __name__ == \"__main__\": \"\"\"",
"span_count = {} span2pos = {} for span in cluster: if \"\".join(fla_sentences[span[0]:span[1] +",
"[\"公司\", \"集团\"]: # 对缺失字符进行补充 span = check_span(fla_sentences, span) if \"#\" in \"\".join(fla_sentences[span[0]:span[1] +",
"def cluster_rule(example): \"\"\" 对模型预测结果进行算法修正 :param example: 一条json数据 :return: 纠正后的predicted_cluster \"\"\" fla_sentences = flatten_sentence(example[\"sentences\"])",
"= session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict = model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents)",
"import print_function import sys import json import tensorflow as tf import util import",
"predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\" config = util.initialize_from_env() log_dir = config[\"log_dir\"] # Input",
"max_count = span_count[com] max_name = com print(\"max_name:{}\".format(max_name)) for com in com_name: # 公司名称",
"session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict = model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) example[\"top_spans\"]",
"print(res_cluster) com2cluster[max_name].extend(res_cluster) for key, value in except_cluster.items(): # 这步是十分有用的 if com2cluster.get(key, None) is",
"util.get_model(config) saver = tf.train.Saver() with tf.Session() as session: model.restore(session) with open(output_filename, \"w\") as",
"\"\".join(fla_sentences[span[0] - 1]) in [\"该\", \"本\", \"贵\"]: # 对span进行补全 span = (span[0]-1, span[1])",
"span = (span[0]-1, span[1]) return span def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return [char for sentence",
"continue elif len(com) < len(max_name) and com in max_name: # 具有包含关系的两公司,则认为相同 continue elif",
"com[:2] == max_name[:2]: # 头部两个字相同则认为两公司相同 continue elif len(com) < len(max_name) and com in",
"sys.argv[2] # 输入数据地址 # Predictions will be written to this file in .jsonlines",
"(int(i) for i in top_span_ends))) example['head_scores'] = [] example[\"mention_to_predict\"] = str(mention_to_predict) example[\"predicted_clusters\"] =",
"elif len(com) < len(max_name) and com in max_name: # 具有包含关系的两公司,则认为相同 continue elif len(com)",
"sys.argv[3] # 输出地址 model = util.get_model(config) saver = tf.train.Saver() with tf.Session() as session:",
"= config[\"log_dir\"] # Input file in .jsonlines format. input_filename = sys.argv[2] # 输入数据地址",
"in sentence] def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a = max([(value, key) for key, value in",
"= com print(\"max_name:{}\".format(max_name)) for com in com_name: # 公司名称 if com[:2] == max_name[:2]:",
"tensorflow as tf import util import json except_name = [\"公司\", \"本公司\", \"该公司\", \"贵公司\",",
"= sys.argv[3] # 输出地址 model = util.get_model(config) saver = tf.train.Saver() with tf.Session() as",
"as input_file: for example_num, line in enumerate(input_file.readlines()): example = json.loads(line) tensorized_example = model.tensorize_example(example,",
"top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict = model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) example[\"top_spans\"] = list(zip((int(i) for i in",
"key, value in except_cluster.items(): # 这步是十分有用的 if com2cluster.get(key, None) is None: print(\"该span将被彻底清除:{}\".format(key)) continue",
"# 头部两个字相同则认为两公司相同 continue elif len(com) < len(max_name) and com in max_name: # 具有包含关系的两公司,则认为相同",
"1]) in [\"公司\", \"集团\"]: # 对缺失字符进行补充 span = check_span(fla_sentences, span) if \"#\" in",
"example[\"top_spans\"] = list(zip((int(i) for i in top_span_starts), (int(i) for i in top_span_ends))) example['head_scores']",
"= res_cluster else: print(res_cluster) com2cluster[max_name].extend(res_cluster) for key, value in except_cluster.items(): # 这步是十分有用的 if",
"\"\".join(fla_sentences[span[0]:span[1] + 1]) span_count[word] = span_count.get(word, 0) + 1 if span2pos.get(word, None) is",
"except_name: com_name.discard(ex) max_name = \"\" max_count = 0 for com in com_name: #",
"with tf.Session() as session: model.restore(session) with open(output_filename, \"w\") as output_file: with open(input_filename) as",
"in span2pos[com]: # 错误预测的span将会筛除 res_cluster.remove(n) if com2cluster.get(max_name, None) is None: com2cluster[max_name] = res_cluster",
"saver = tf.train.Saver() with tf.Session() as session: model.restore(session) with open(output_filename, \"w\") as output_file:",
"config = util.initialize_from_env() log_dir = config[\"log_dir\"] # Input file in .jsonlines format. input_filename",
"[] example[\"mention_to_predict\"] = str(mention_to_predict) example[\"predicted_clusters\"] = cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\") if example_num %",
"in com_name: # 公司名称 if com[:2] == max_name[:2]: # 头部两个字相同则认为两公司相同 continue elif len(com)",
"import sys import json import tensorflow as tf import util import json except_name",
"\"贵公司\", \"贵司\", \"本行\", \"该行\", \"本银行\", \"该集团\", \"本集团\", \"集团\", \"它\", \"他们\", \"他们\", \"我们\", \"该股\",",
"return a[0] def cluster_rule(example): \"\"\" 对模型预测结果进行算法修正 :param example: 一条json数据 :return: 纠正后的predicted_cluster \"\"\" fla_sentences",
"if \"#\" in \"\".join(fla_sentences[span[0]:span[1] + 1]): # 对不合法单词进行过滤 continue res_cluster.append(span) word = \"\".join(fla_sentences[span[0]:span[1]",
"= [span] com_name = set(span_count.keys()) for ex in except_name: com_name.discard(ex) max_name = \"\"",
"com_name = set(span_count.keys()) for ex in except_name: com_name.discard(ex) max_name = \"\" max_count =",
"def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return [char for sentence in sentences for char in sentence]",
"i in top_span_ends))) example['head_scores'] = [] example[\"mention_to_predict\"] = str(mention_to_predict) example[\"predicted_clusters\"] = cluster_rule(example) output_file.write(str(json.dumps(example,",
"from __future__ import print_function import sys import json import tensorflow as tf import",
"def check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0] - 1]) in [\"该\", \"本\", \"贵\"]: #",
"0 for com in com_name: # 获取cluster当中的频率最大的单词 if span_count[com] > max_count: max_count =",
"feed_dict = {i: t for i, t in zip(model.input_tensors, tensorized_example)} _, _, _,",
"\"\"\" config = util.initialize_from_env() log_dir = config[\"log_dir\"] # Input file in .jsonlines format.",
"len(com) < len(max_name) and com in max_name: # 具有包含关系的两公司,则认为相同 continue elif len(com) >",
"com_name.discard(ex) max_name = \"\" max_count = 0 for com in com_name: # 获取cluster当中的频率最大的单词",
"\"\"\"将多维列表展开\"\"\" return [char for sentence in sentences for char in sentence] def max_all_count(dict0):",
"__future__ import absolute_import from __future__ import division from __future__ import print_function import sys",
"cluster_rule(example): \"\"\" 对模型预测结果进行算法修正 :param example: 一条json数据 :return: 纠正后的predicted_cluster \"\"\" fla_sentences = flatten_sentence(example[\"sentences\"]) res_clusters",
"\"__main__\": \"\"\" 命令行示例 python predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\" config = util.initialize_from_env() log_dir",
"format. output_filename = sys.argv[3] # 输出地址 model = util.get_model(config) saver = tf.train.Saver() with",
"example['head_scores'] = [] example[\"mention_to_predict\"] = str(mention_to_predict) example[\"predicted_clusters\"] = cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\") if",
"for i in top_span_ends))) example['head_scores'] = [] example[\"mention_to_predict\"] = str(mention_to_predict) example[\"predicted_clusters\"] = cluster_rule(example)",
"python predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\" config = util.initialize_from_env() log_dir = config[\"log_dir\"] #",
"for key, value in except_cluster.items(): # 这步是十分有用的 if com2cluster.get(key, None) is None: print(\"该span将被彻底清除:{}\".format(key))",
"example = json.loads(line) tensorized_example = model.tensorize_example(example, is_training=False) feed_dict = {i: t for i,",
"\"该公司\", \"贵公司\", \"贵司\", \"本行\", \"该行\", \"本银行\", \"该集团\", \"本集团\", \"集团\", \"它\", \"他们\", \"他们\", \"我们\",",
"对模型预测结果进行算法修正 :param example: 一条json数据 :return: 纠正后的predicted_cluster \"\"\" fla_sentences = flatten_sentence(example[\"sentences\"]) res_clusters = []",
"in enumerate(input_file.readlines()): example = json.loads(line) tensorized_example = model.tensorize_example(example, is_training=False) feed_dict = {i: t",
"in top_span_ends))) example['head_scores'] = [] example[\"mention_to_predict\"] = str(mention_to_predict) example[\"predicted_clusters\"] = cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False)))",
"res_cluster = [] span_count = {} span2pos = {} for span in cluster:",
"as output_file: with open(input_filename) as input_file: for example_num, line in enumerate(input_file.readlines()): example =",
"= model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) example[\"top_spans\"] = list(zip((int(i) for i in top_span_starts), (int(i) for",
"__future__ import division from __future__ import print_function import sys import json import tensorflow",
"n in span2pos[com]: # 错误预测的span将会筛除 res_cluster.remove(n) if com2cluster.get(max_name, None) is None: com2cluster[max_name] =",
"top_span_ends, predicted_antecedents) example[\"top_spans\"] = list(zip((int(i) for i in top_span_starts), (int(i) for i in",
"\"贵司\", \"本行\", \"该行\", \"本银行\", \"该集团\", \"本集团\", \"集团\", \"它\", \"他们\", \"他们\", \"我们\", \"该股\", \"其\",",
"in example[\"predicted_clusters\"]: res_cluster = [] span_count = {} span2pos = {} for span",
"continue else: print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value) # res_clusters.append(res_cluster) for v_cluster in com2cluster.values(): res_clusters.append(v_cluster) return",
"example_num, line in enumerate(input_file.readlines()): example = json.loads(line) tensorized_example = model.tensorize_example(example, is_training=False) feed_dict =",
"\"我们\", \"该股\", \"其\", \"自身\"] def check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0] - 1]) in",
"in com_name: # 获取cluster当中的频率最大的单词 if span_count[com] > max_count: max_count = span_count[com] max_name =",
"命令行示例 python predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\" config = util.initialize_from_env() log_dir = config[\"log_dir\"]",
"len(max_name) and max_name in com: continue else: print(com) # span2pos[com] except_cluster[com] = span2pos[com]",
"\"\" max_count = 0 for com in com_name: # 获取cluster当中的频率最大的单词 if span_count[com] >",
"not None: span2pos[word].append(span) else: span2pos[word] = [span] com_name = set(span_count.keys()) for ex in",
"to this file in .jsonlines format. output_filename = sys.argv[3] # 输出地址 model =",
"predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict = model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) example[\"top_spans\"] = list(zip((int(i)",
"cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\") if example_num % 100 == 0: print(\"Decoded {} examples.\".format(example_num",
"com_name: # 公司名称 if com[:2] == max_name[:2]: # 头部两个字相同则认为两公司相同 continue elif len(com) <",
":return: 纠正后的predicted_cluster \"\"\" fla_sentences = flatten_sentence(example[\"sentences\"]) res_clusters = [] com2cluster = {} except_cluster",
"== max_count and len(com) > len(max_name): max_count = span_count[com] max_name = com print(\"max_name:{}\".format(max_name))",
"= cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\") if example_num % 100 == 0: print(\"Decoded {}",
"_, _, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores)",
"\"\"\" 命令行示例 python predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\" config = util.initialize_from_env() log_dir =",
"+ 1 if span2pos.get(word, None) is not None: span2pos[word].append(span) else: span2pos[word] = [span]",
"in cluster: if \"\".join(fla_sentences[span[0]:span[1] + 1]) in [\"公司\", \"集团\"]: # 对缺失字符进行补充 span =",
"= max([(value, key) for key, value in dict0.items()]) return a[0] def cluster_rule(example): \"\"\"",
"\"\"\"获取字典当中的count最大值\"\"\" a = max([(value, key) for key, value in dict0.items()]) return a[0] def",
"return res_clusters if __name__ == \"__main__\": \"\"\" 命令行示例 python predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt",
"# 公司名称 if com[:2] == max_name[:2]: # 头部两个字相同则认为两公司相同 continue elif len(com) < len(max_name)",
"as tf import util import json except_name = [\"公司\", \"本公司\", \"该公司\", \"贵公司\", \"贵司\",",
"span in cluster: if \"\".join(fla_sentences[span[0]:span[1] + 1]) in [\"公司\", \"集团\"]: # 对缺失字符进行补充 span",
"max_count and len(com) > len(max_name): max_count = span_count[com] max_name = com print(\"max_name:{}\".format(max_name)) for",
"max_count = 0 for com in com_name: # 获取cluster当中的频率最大的单词 if span_count[com] > max_count:",
"\"集团\"]: # 对缺失字符进行补充 span = check_span(fla_sentences, span) if \"#\" in \"\".join(fla_sentences[span[0]:span[1] + 1]):",
"i, t in zip(model.input_tensors, tensorized_example)} _, _, _, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores =",
"len(max_name): max_count = span_count[com] max_name = com print(\"max_name:{}\".format(max_name)) for com in com_name: #",
"= model.tensorize_example(example, is_training=False) feed_dict = {i: t for i, t in zip(model.input_tensors, tensorized_example)}",
"sentences for char in sentence] def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a = max([(value, key) for",
"{} except_cluster = {} for cluster in example[\"predicted_clusters\"]: res_cluster = [] span_count =",
"this file in .jsonlines format. output_filename = sys.argv[3] # 输出地址 model = util.get_model(config)",
"for com in com_name: # 获取cluster当中的频率最大的单词 if span_count[com] > max_count: max_count = span_count[com]",
"if \"\".join(fla_sentences[span[0] - 1]) in [\"该\", \"本\", \"贵\"]: # 对span进行补全 span = (span[0]-1,",
"max_name[:2]: # 头部两个字相同则认为两公司相同 continue elif len(com) < len(max_name) and com in max_name: #",
"output_file: with open(input_filename) as input_file: for example_num, line in enumerate(input_file.readlines()): example = json.loads(line)",
"= \"\" max_count = 0 for com in com_name: # 获取cluster当中的频率最大的单词 if span_count[com]",
"in .jsonlines format. input_filename = sys.argv[2] # 输入数据地址 # Predictions will be written",
"import json import tensorflow as tf import util import json except_name = [\"公司\",",
"span_count[com] max_name = com elif span_count[com] == max_count and len(com) > len(max_name): max_count",
"span2pos[com]: # 错误预测的span将会筛除 res_cluster.remove(n) if com2cluster.get(max_name, None) is None: com2cluster[max_name] = res_cluster else:",
"a = max([(value, key) for key, value in dict0.items()]) return a[0] def cluster_rule(example):",
"except_cluster.items(): # 这步是十分有用的 if com2cluster.get(key, None) is None: print(\"该span将被彻底清除:{}\".format(key)) continue else: print(\"{}重新融入别的cluster当中\".format(key), value)",
"= util.initialize_from_env() log_dir = config[\"log_dir\"] # Input file in .jsonlines format. input_filename =",
"if com2cluster.get(key, None) is None: print(\"该span将被彻底清除:{}\".format(key)) continue else: print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value) # res_clusters.append(res_cluster)",
"written to this file in .jsonlines format. output_filename = sys.argv[3] # 输出地址 model",
"= span_count[com] max_name = com elif span_count[com] == max_count and len(com) > len(max_name):",
"zip(model.input_tensors, tensorized_example)} _, _, _, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents",
"in [\"该\", \"本\", \"贵\"]: # 对span进行补全 span = (span[0]-1, span[1]) return span def",
"= check_span(fla_sentences, span) if \"#\" in \"\".join(fla_sentences[span[0]:span[1] + 1]): # 对不合法单词进行过滤 continue res_cluster.append(span)",
"\"他们\", \"我们\", \"该股\", \"其\", \"自身\"] def check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0] - 1])",
"enumerate(input_file.readlines()): example = json.loads(line) tensorized_example = model.tensorize_example(example, is_training=False) feed_dict = {i: t for",
"= [] com2cluster = {} except_cluster = {} for cluster in example[\"predicted_clusters\"]: res_cluster",
"== \"__main__\": \"\"\" 命令行示例 python predict.py bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\" config = util.initialize_from_env()",
"t in zip(model.input_tensors, tensorized_example)} _, _, _, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores = session.run(model.predictions,",
"< len(max_name) and com in max_name: # 具有包含关系的两公司,则认为相同 continue elif len(com) > len(max_name)",
"in zip(model.input_tensors, tensorized_example)} _, _, _, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict)",
"sentence] def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a = max([(value, key) for key, value in dict0.items()])",
"import util import json except_name = [\"公司\", \"本公司\", \"该公司\", \"贵公司\", \"贵司\", \"本行\", \"该行\",",
"len(com) > len(max_name) and max_name in com: continue else: print(com) # span2pos[com] except_cluster[com]",
"json.loads(line) tensorized_example = model.tensorize_example(example, is_training=False) feed_dict = {i: t for i, t in",
"# 该公司名 for n in span2pos[com]: # 错误预测的span将会筛除 res_cluster.remove(n) if com2cluster.get(max_name, None) is",
".jsonlines format. output_filename = sys.argv[3] # 输出地址 model = util.get_model(config) saver = tf.train.Saver()",
"len(com) > len(max_name): max_count = span_count[com] max_name = com print(\"max_name:{}\".format(max_name)) for com in",
"com in com_name: # 公司名称 if com[:2] == max_name[:2]: # 头部两个字相同则认为两公司相同 continue elif",
"ensure_ascii=False))) output_file.write(\"\\n\") if example_num % 100 == 0: print(\"Decoded {} examples.\".format(example_num + 1))",
"from __future__ import division from __future__ import print_function import sys import json import",
"for sentence in sentences for char in sentence] def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a =",
"= set(span_count.keys()) for ex in except_name: com_name.discard(ex) max_name = \"\" max_count = 0",
"\"该股\", \"其\", \"自身\"] def check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0] - 1]) in [\"该\",",
"continue elif len(com) > len(max_name) and max_name in com: continue else: print(com) #",
"top_span_ends, top_antecedents, top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict =",
"set(span_count.keys()) for ex in except_name: com_name.discard(ex) max_name = \"\" max_count = 0 for",
"top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict = model.get_predicted_clusters(top_span_starts, top_span_ends,",
"span_count[com] > max_count: max_count = span_count[com] max_name = com elif span_count[com] == max_count",
"= span2pos[com] # 该公司名 for n in span2pos[com]: # 错误预测的span将会筛除 res_cluster.remove(n) if com2cluster.get(max_name,",
"1]): # 对不合法单词进行过滤 continue res_cluster.append(span) word = \"\".join(fla_sentences[span[0]:span[1] + 1]) span_count[word] = span_count.get(word,",
"# res_clusters.append(res_cluster) for v_cluster in com2cluster.values(): res_clusters.append(v_cluster) return res_clusters if __name__ == \"__main__\":",
"= json.loads(line) tensorized_example = model.tensorize_example(example, is_training=False) feed_dict = {i: t for i, t",
"\"本行\", \"该行\", \"本银行\", \"该集团\", \"本集团\", \"集团\", \"它\", \"他们\", \"他们\", \"我们\", \"该股\", \"其\", \"自身\"]",
"is not None: span2pos[word].append(span) else: span2pos[word] = [span] com_name = set(span_count.keys()) for ex",
"v_cluster in com2cluster.values(): res_clusters.append(v_cluster) return res_clusters if __name__ == \"__main__\": \"\"\" 命令行示例 python",
"= util.get_model(config) saver = tf.train.Saver() with tf.Session() as session: model.restore(session) with open(output_filename, \"w\")",
"None: com2cluster[max_name] = res_cluster else: print(res_cluster) com2cluster[max_name].extend(res_cluster) for key, value in except_cluster.items(): #",
"> len(max_name) and max_name in com: continue else: print(com) # span2pos[com] except_cluster[com] =",
"一条json数据 :return: 纠正后的predicted_cluster \"\"\" fla_sentences = flatten_sentence(example[\"sentences\"]) res_clusters = [] com2cluster = {}",
"log_dir = config[\"log_dir\"] # Input file in .jsonlines format. input_filename = sys.argv[2] #",
"word = \"\".join(fla_sentences[span[0]:span[1] + 1]) span_count[word] = span_count.get(word, 0) + 1 if span2pos.get(word,",
"import absolute_import from __future__ import division from __future__ import print_function import sys import",
"= {} for span in cluster: if \"\".join(fla_sentences[span[0]:span[1] + 1]) in [\"公司\", \"集团\"]:",
"max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a = max([(value, key) for key, value in dict0.items()]) return a[0]",
"\"贵\"]: # 对span进行补全 span = (span[0]-1, span[1]) return span def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return",
"is None: print(\"该span将被彻底清除:{}\".format(key)) continue else: print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value) # res_clusters.append(res_cluster) for v_cluster in",
"check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0] - 1]) in [\"该\", \"本\", \"贵\"]: # 对span进行补全",
"tf.train.Saver() with tf.Session() as session: model.restore(session) with open(output_filename, \"w\") as output_file: with open(input_filename)",
"output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\") if example_num % 100 == 0: print(\"Decoded {} examples.\".format(example_num +",
"json import tensorflow as tf import util import json except_name = [\"公司\", \"本公司\",",
"\"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0] - 1]) in [\"该\", \"本\", \"贵\"]: # 对span进行补全 span =",
"cluster in example[\"predicted_clusters\"]: res_cluster = [] span_count = {} span2pos = {} for",
"{} for span in cluster: if \"\".join(fla_sentences[span[0]:span[1] + 1]) in [\"公司\", \"集团\"]: #",
"# 具有包含关系的两公司,则认为相同 continue elif len(com) > len(max_name) and max_name in com: continue else:",
"com2cluster = {} except_cluster = {} for cluster in example[\"predicted_clusters\"]: res_cluster = []",
"in except_name: com_name.discard(ex) max_name = \"\" max_count = 0 for com in com_name:",
"# 这步是十分有用的 if com2cluster.get(key, None) is None: print(\"该span将被彻底清除:{}\".format(key)) continue else: print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value)",
"com in com_name: # 获取cluster当中的频率最大的单词 if span_count[com] > max_count: max_count = span_count[com] max_name",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function import",
"max_name = com elif span_count[com] == max_count and len(com) > len(max_name): max_count =",
"__future__ import print_function import sys import json import tensorflow as tf import util",
"= list(zip((int(i) for i in top_span_starts), (int(i) for i in top_span_ends))) example['head_scores'] =",
"for i, t in zip(model.input_tensors, tensorized_example)} _, _, _, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores",
"= {} for cluster in example[\"predicted_clusters\"]: res_cluster = [] span_count = {} span2pos",
"= str(mention_to_predict) example[\"predicted_clusters\"] = cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\") if example_num % 100 ==",
"in .jsonlines format. output_filename = sys.argv[3] # 输出地址 model = util.get_model(config) saver =",
"model.tensorize_example(example, is_training=False) feed_dict = {i: t for i, t in zip(model.input_tensors, tensorized_example)} _,",
"max_count = span_count[com] max_name = com elif span_count[com] == max_count and len(com) >",
"char in sentence] def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a = max([(value, key) for key, value",
"import json except_name = [\"公司\", \"本公司\", \"该公司\", \"贵公司\", \"贵司\", \"本行\", \"该行\", \"本银行\", \"该集团\",",
"res_clusters = [] com2cluster = {} except_cluster = {} for cluster in example[\"predicted_clusters\"]:",
"# Input file in .jsonlines format. input_filename = sys.argv[2] # 输入数据地址 # Predictions",
"model = util.get_model(config) saver = tf.train.Saver() with tf.Session() as session: model.restore(session) with open(output_filename,",
"open(input_filename) as input_file: for example_num, line in enumerate(input_file.readlines()): example = json.loads(line) tensorized_example =",
"输出地址 model = util.get_model(config) saver = tf.train.Saver() with tf.Session() as session: model.restore(session) with",
"# 对缺失字符进行补充 span = check_span(fla_sentences, span) if \"#\" in \"\".join(fla_sentences[span[0]:span[1] + 1]): #",
"top_antecedents, top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict = model.get_predicted_clusters(top_span_starts,",
"if span_count[com] > max_count: max_count = span_count[com] max_name = com elif span_count[com] ==",
"for char in sentence] def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a = max([(value, key) for key,",
"None: print(\"该span将被彻底清除:{}\".format(key)) continue else: print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value) # res_clusters.append(res_cluster) for v_cluster in com2cluster.values():",
"division from __future__ import print_function import sys import json import tensorflow as tf",
"res_cluster.remove(n) if com2cluster.get(max_name, None) is None: com2cluster[max_name] = res_cluster else: print(res_cluster) com2cluster[max_name].extend(res_cluster) for",
"span = check_span(fla_sentences, span) if \"#\" in \"\".join(fla_sentences[span[0]:span[1] + 1]): # 对不合法单词进行过滤 continue",
"对缺失字符进行补充 span = check_span(fla_sentences, span) if \"#\" in \"\".join(fla_sentences[span[0]:span[1] + 1]): # 对不合法单词进行过滤",
"in com: continue else: print(com) # span2pos[com] except_cluster[com] = span2pos[com] # 该公司名 for",
"sys import json import tensorflow as tf import util import json except_name =",
"will be written to this file in .jsonlines format. output_filename = sys.argv[3] #",
"top_span_ends))) example['head_scores'] = [] example[\"mention_to_predict\"] = str(mention_to_predict) example[\"predicted_clusters\"] = cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\")",
"value in except_cluster.items(): # 这步是十分有用的 if com2cluster.get(key, None) is None: print(\"该span将被彻底清除:{}\".format(key)) continue else:",
"max([(value, key) for key, value in dict0.items()]) return a[0] def cluster_rule(example): \"\"\" 对模型预测结果进行算法修正",
"in com2cluster.values(): res_clusters.append(v_cluster) return res_clusters if __name__ == \"__main__\": \"\"\" 命令行示例 python predict.py",
"predicted_antecedents) example[\"top_spans\"] = list(zip((int(i) for i in top_span_starts), (int(i) for i in top_span_ends)))",
"= [\"公司\", \"本公司\", \"该公司\", \"贵公司\", \"贵司\", \"本行\", \"该行\", \"本银行\", \"该集团\", \"本集团\", \"集团\", \"它\",",
"except_cluster = {} for cluster in example[\"predicted_clusters\"]: res_cluster = [] span_count = {}",
"max_name: # 具有包含关系的两公司,则认为相同 continue elif len(com) > len(max_name) and max_name in com: continue",
"session: model.restore(session) with open(output_filename, \"w\") as output_file: with open(input_filename) as input_file: for example_num,",
"# 对不合法单词进行过滤 continue res_cluster.append(span) word = \"\".join(fla_sentences[span[0]:span[1] + 1]) span_count[word] = span_count.get(word, 0)",
"model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict = model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) example[\"top_spans\"] = list(zip((int(i) for i",
"for example_num, line in enumerate(input_file.readlines()): example = json.loads(line) tensorized_example = model.tensorize_example(example, is_training=False) feed_dict",
"check_span(fla_sentences, span) if \"#\" in \"\".join(fla_sentences[span[0]:span[1] + 1]): # 对不合法单词进行过滤 continue res_cluster.append(span) word",
"and len(com) > len(max_name): max_count = span_count[com] max_name = com print(\"max_name:{}\".format(max_name)) for com",
"max_count: max_count = span_count[com] max_name = com elif span_count[com] == max_count and len(com)",
"with open(input_filename) as input_file: for example_num, line in enumerate(input_file.readlines()): example = json.loads(line) tensorized_example",
"纠正后的predicted_cluster \"\"\" fla_sentences = flatten_sentence(example[\"sentences\"]) res_clusters = [] com2cluster = {} except_cluster =",
"input_file: for example_num, line in enumerate(input_file.readlines()): example = json.loads(line) tensorized_example = model.tensorize_example(example, is_training=False)",
"feed_dict=feed_dict) predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores) example[\"predicted_clusters\"], mention_to_predict = model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) example[\"top_spans\"] =",
"str(mention_to_predict) example[\"predicted_clusters\"] = cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\") if example_num % 100 == 0:",
"return span def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return [char for sentence in sentences for char",
"value) com2cluster[key].extend(value) # res_clusters.append(res_cluster) for v_cluster in com2cluster.values(): res_clusters.append(v_cluster) return res_clusters if __name__",
"该公司名 for n in span2pos[com]: # 错误预测的span将会筛除 res_cluster.remove(n) if com2cluster.get(max_name, None) is None:",
"+ 1]) in [\"公司\", \"集团\"]: # 对缺失字符进行补充 span = check_span(fla_sentences, span) if \"#\"",
"span def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return [char for sentence in sentences for char in",
"= flatten_sentence(example[\"sentences\"]) res_clusters = [] com2cluster = {} except_cluster = {} for cluster",
"if com2cluster.get(max_name, None) is None: com2cluster[max_name] = res_cluster else: print(res_cluster) com2cluster[max_name].extend(res_cluster) for key,",
"if com[:2] == max_name[:2]: # 头部两个字相同则认为两公司相同 continue elif len(com) < len(max_name) and com",
"in except_cluster.items(): # 这步是十分有用的 if com2cluster.get(key, None) is None: print(\"该span将被彻底清除:{}\".format(key)) continue else: print(\"{}重新融入别的cluster当中\".format(key),",
"len(max_name) and com in max_name: # 具有包含关系的两公司,则认为相同 continue elif len(com) > len(max_name) and",
"example[\"predicted_clusters\"] = cluster_rule(example) output_file.write(str(json.dumps(example, ensure_ascii=False))) output_file.write(\"\\n\") if example_num % 100 == 0: print(\"Decoded",
"elif len(com) > len(max_name) and max_name in com: continue else: print(com) # span2pos[com]",
"com_name: # 获取cluster当中的频率最大的单词 if span_count[com] > max_count: max_count = span_count[com] max_name = com",
"bert_base conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\" config = util.initialize_from_env() log_dir = config[\"log_dir\"] # Input file",
"top_span_starts), (int(i) for i in top_span_ends))) example['head_scores'] = [] example[\"mention_to_predict\"] = str(mention_to_predict) example[\"predicted_clusters\"]",
"line in enumerate(input_file.readlines()): example = json.loads(line) tensorized_example = model.tensorize_example(example, is_training=False) feed_dict = {i:",
"\"该集团\", \"本集团\", \"集团\", \"它\", \"他们\", \"他们\", \"我们\", \"该股\", \"其\", \"自身\"] def check_span(fla_sentences, span):",
"{} span2pos = {} for span in cluster: if \"\".join(fla_sentences[span[0]:span[1] + 1]) in",
"tensorized_example)} _, _, _, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict) predicted_antecedents =",
"= {} span2pos = {} for span in cluster: if \"\".join(fla_sentences[span[0]:span[1] + 1])",
"continue res_cluster.append(span) word = \"\".join(fla_sentences[span[0]:span[1] + 1]) span_count[word] = span_count.get(word, 0) + 1",
"i in top_span_starts), (int(i) for i in top_span_ends))) example['head_scores'] = [] example[\"mention_to_predict\"] =",
"== max_name[:2]: # 头部两个字相同则认为两公司相同 continue elif len(com) < len(max_name) and com in max_name:",
"# Predictions will be written to this file in .jsonlines format. output_filename =",
"elif span_count[com] == max_count and len(com) > len(max_name): max_count = span_count[com] max_name =",
"公司名称 if com[:2] == max_name[:2]: # 头部两个字相同则认为两公司相同 continue elif len(com) < len(max_name) and",
"print(com) # span2pos[com] except_cluster[com] = span2pos[com] # 该公司名 for n in span2pos[com]: #",
"+ 1]): # 对不合法单词进行过滤 continue res_cluster.append(span) word = \"\".join(fla_sentences[span[0]:span[1] + 1]) span_count[word] =",
"def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a = max([(value, key) for key, value in dict0.items()]) return",
"in \"\".join(fla_sentences[span[0]:span[1] + 1]): # 对不合法单词进行过滤 continue res_cluster.append(span) word = \"\".join(fla_sentences[span[0]:span[1] + 1])",
"\"本\", \"贵\"]: # 对span进行补全 span = (span[0]-1, span[1]) return span def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\"",
"model.restore(session) with open(output_filename, \"w\") as output_file: with open(input_filename) as input_file: for example_num, line",
"t for i, t in zip(model.input_tensors, tensorized_example)} _, _, _, top_span_starts, top_span_ends, top_antecedents,",
"mention_to_predict = model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) example[\"top_spans\"] = list(zip((int(i) for i in top_span_starts), (int(i)",
"in max_name: # 具有包含关系的两公司,则认为相同 continue elif len(com) > len(max_name) and max_name in com:",
"\"其\", \"自身\"] def check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0] - 1]) in [\"该\", \"本\",",
"\"本公司\", \"该公司\", \"贵公司\", \"贵司\", \"本行\", \"该行\", \"本银行\", \"该集团\", \"本集团\", \"集团\", \"它\", \"他们\", \"他们\",",
"else: print(\"{}重新融入别的cluster当中\".format(key), value) com2cluster[key].extend(value) # res_clusters.append(res_cluster) for v_cluster in com2cluster.values(): res_clusters.append(v_cluster) return res_clusters",
"0) + 1 if span2pos.get(word, None) is not None: span2pos[word].append(span) else: span2pos[word] =",
"(span[0]-1, span[1]) return span def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return [char for sentence in sentences",
"\"它\", \"他们\", \"他们\", \"我们\", \"该股\", \"其\", \"自身\"] def check_span(fla_sentences, span): \"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0]",
"max_name = \"\" max_count = 0 for com in com_name: # 获取cluster当中的频率最大的单词 if",
"com elif span_count[com] == max_count and len(com) > len(max_name): max_count = span_count[com] max_name",
"1]) in [\"该\", \"本\", \"贵\"]: # 对span进行补全 span = (span[0]-1, span[1]) return span",
"import division from __future__ import print_function import sys import json import tensorflow as",
"flatten_sentence(example[\"sentences\"]) res_clusters = [] com2cluster = {} except_cluster = {} for cluster in",
"\"w\") as output_file: with open(input_filename) as input_file: for example_num, line in enumerate(input_file.readlines()): example",
"example[\"predicted_clusters\"], mention_to_predict = model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) example[\"top_spans\"] = list(zip((int(i) for i in top_span_starts),",
"for i in top_span_starts), (int(i) for i in top_span_ends))) example['head_scores'] = [] example[\"mention_to_predict\"]",
"# 对span进行补全 span = (span[0]-1, span[1]) return span def flatten_sentence(sentences): \"\"\"将多维列表展开\"\"\" return [char",
"[char for sentence in sentences for char in sentence] def max_all_count(dict0): \"\"\"获取字典当中的count最大值\"\"\" a",
"conll-2012/tagging_pure/tagging_dev_pos.chinese.128.jsonlines result_of_20.txt \"\"\" config = util.initialize_from_env() log_dir = config[\"log_dir\"] # Input file in",
"> max_count: max_count = span_count[com] max_name = com elif span_count[com] == max_count and",
"tf.Session() as session: model.restore(session) with open(output_filename, \"w\") as output_file: with open(input_filename) as input_file:",
"{i: t for i, t in zip(model.input_tensors, tensorized_example)} _, _, _, top_span_starts, top_span_ends,",
"span): \"\"\"检查span对应词语是否符合要求\"\"\" if \"\".join(fla_sentences[span[0] - 1]) in [\"该\", \"本\", \"贵\"]: # 对span进行补全 span",
"# 输出地址 model = util.get_model(config) saver = tf.train.Saver() with tf.Session() as session: model.restore(session)",
"span2pos[com] # 该公司名 for n in span2pos[com]: # 错误预测的span将会筛除 res_cluster.remove(n) if com2cluster.get(max_name, None)",
"if \"\".join(fla_sentences[span[0]:span[1] + 1]) in [\"公司\", \"集团\"]: # 对缺失字符进行补充 span = check_span(fla_sentences, span)",
"None) is None: com2cluster[max_name] = res_cluster else: print(res_cluster) com2cluster[max_name].extend(res_cluster) for key, value in",
"with open(output_filename, \"w\") as output_file: with open(input_filename) as input_file: for example_num, line in",
"else: span2pos[word] = [span] com_name = set(span_count.keys()) for ex in except_name: com_name.discard(ex) max_name",
"# 获取cluster当中的频率最大的单词 if span_count[com] > max_count: max_count = span_count[com] max_name = com elif",
"config[\"log_dir\"] # Input file in .jsonlines format. input_filename = sys.argv[2] # 输入数据地址 #",
"key) for key, value in dict0.items()]) return a[0] def cluster_rule(example): \"\"\" 对模型预测结果进行算法修正 :param",
"span_count[com] max_name = com print(\"max_name:{}\".format(max_name)) for com in com_name: # 公司名称 if com[:2]",
"continue else: print(com) # span2pos[com] except_cluster[com] = span2pos[com] # 该公司名 for n in",
"Predictions will be written to this file in .jsonlines format. output_filename = sys.argv[3]",
"= 0 for com in com_name: # 获取cluster当中的频率最大的单词 if span_count[com] > max_count: max_count",
"dict0.items()]) return a[0] def cluster_rule(example): \"\"\" 对模型预测结果进行算法修正 :param example: 一条json数据 :return: 纠正后的predicted_cluster \"\"\"",
"and max_name in com: continue else: print(com) # span2pos[com] except_cluster[com] = span2pos[com] #"
] |
[
"<gh_stars>1-10 from .future import Future from .lockwithabort import LockWithAbort, AcquireLockFailed from .threadwithreturnvalue import",
"from .future import Future from .lockwithabort import LockWithAbort, AcquireLockFailed from .threadwithreturnvalue import ThreadWithReturnValue"
] |
[
"extension files will be ignored during the copy operation :return: str, destination directory",
"directory target_directory :param source_directory: str, folder with full path :param target_directory: str, path",
"def get_files_and_folders(directory): \"\"\" Get files and folders found in the given directory :param",
"\"\"\" if path is None: path = os.path.curdir if sys.platform == 'darwin': subprocess.check_call(['open',",
"find (.py, .data, etc) :param root_directory: str, directory path :param full_path: bool, Whether",
"in the given directory :param root_directory: str, directory path :param extension: str, optional",
"create_folder(base_name, dir_name) def get_folder_size(directory, round_value=2, skip_names=None): \"\"\" Returns the size of the given",
"full_path = name if not name: full_path = directory if name and directory:",
"= None if osplatform.is_linux(): cmd = ['rsync', directory, directory_destination, '-azr'] elif osplatform.is_windows(): cmd",
"make_unique=False): \"\"\" Renames given with a new name :param directory: str, full path",
":return: int \"\"\" from tpDcc.libs.python import fileio, path size = 0 if path.is_dir(file_path):",
"def get_temp_folder(): \"\"\" Get the path to the temp folder :return: str, path",
"the new directory :param directory: str, path to the new directory :param make_unique:",
"if not path.is_dir(directory): create_folder(base_name, dir_name) def get_folder_size(directory, round_value=2, skip_names=None): \"\"\" Returns the size",
"with full path :param target_directory: str, path where path1 should be move into",
"continue size += fileio.get_file_size(path.join_path(root, name), round_value) return size def get_size(file_path, round_value=2): \"\"\" Return",
"file_list = os.listdir(source_directory) for i in file_list: src = os.path.join(source_directory, i) dest =",
"path.clean_path(tempfile.gettempdir()) def get_current_working_directory(): \"\"\" Returns current working directory :return: str, path to the",
"found.append(filename_and_extension) else: found.append(os.path.join(root_directory, filename_and_extension)) return found def get_files_date_sorted(root_directory, extension=None, filter_text=''): \"\"\" Returns files",
"folder_name) if not path.is_dir(full_path): return None try: shutil.rmtree(full_path, onerror=delete_read_only_error) except Exception as exc:",
"def delete_read_only_error(action, name, exc): \"\"\" Helper to delete read only files \"\"\" osplatform.get_permission(name)",
"root folder :param root_folder: str, folder we ant to search folders on :param",
"path1 should be move into :param only_contents: bool, Whether to move the folder",
"should be move into :param only_contents: bool, Whether to move the folder or",
"key=_get_mtime)) def open_folder(path=None): \"\"\" Opens a folder in the explorer in a independent",
"For now pattern only works in recursive searches. Fix it to work on",
"child folders or not :return: list<str> \"\"\" from tpDcc.libs.python import path found_folders =",
"in the given folder :param root_folder: str, folder we want to search files",
"recursive=False, filter_text=''): \"\"\" Returns file in given directory with given extensions :param extension:",
"full_path = folder_name if directory: full_path = path.join_path(directory, folder_name) if not path.is_dir(full_path): return",
"to find (.py, .data, etc) :param root_directory: str, directory path :param full_path: bool,",
"permission mode :param place_holder: bool, Whether to create place holder text file or",
"path to the user folder :return: str, path to the user folder \"\"\"",
"size to :return: str \"\"\" from tpDcc.libs.python import python, path, fileio skip_names =",
"out: logger.error(err) else: shutil.copytree(directory, directory_destination) else: shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination def move_folder(source_directory,",
"\"\"\" Get the path to the temp folder :return: str, path to the",
"get_files_date_sorted(folder_path, filter_text=filter_text) if not files: return None return path.join_path(folder_path, files[-1]) def walk_level(root_directory, level=None):",
":param extension: str, optional extension to find :param filter_text: str, optional text filtering",
"or not :return: list<str> \"\"\" from tpDcc.libs.python import path found_folders = list() if",
"{}'.format(source_directory, target_directory, exc)) return False return True def copy_directory_contents(path1, path2, *args, **kwargs): \"\"\"",
"!= '': folders.append(folder) else: if path != '': folders.append(path) break folders.reverse() return folders",
"str, folder path to open \"\"\" if path is None: path = os.path.curdir",
"for root, dirs, files in os.walk(directory): root_name = path.get_basename(root) if root_name in skip_names:",
"folder :return: str, path to the temp folder \"\"\" from tpDcc.libs.python import path",
"return files def get_files_with_extension(extension, root_directory, full_path=False, recursive=False, filter_text=''): \"\"\" Returns file in given",
"list() base_directory = base_directory or directory folders = get_folders(directory) for folder in folders:",
"or False if the folder creation failed \"\"\" from tpDcc.libs.python import path, osplatform",
"in the directory \"\"\" def _get_mtime(fld): return os.stat(os.path.join(root_folder, fld)).st_mtime return list(sorted(os.listdir(root_folder), key=_get_mtime)) def",
"the folder pointed by source_directory under the directory target_directory :param source_directory: str, folder",
"tpDcc.libs.python import path return path.clean_path(tempfile.gettempdir()) def get_current_working_directory(): \"\"\" Returns current working directory :return:",
"\"\"\" Opens a folder in the explorer in a independent platform way If",
"i) if os.path.exists(dest): if os.path.isdir(dest): move_folder(src, dest) continue else: os.remove(dest) shutil.move(src, target_directory) else:",
"path and with the given name :param name: str, name of the new",
"= get_files_date_sorted(folder_path, filter_text=filter_text) if not files: return None return path.join_path(folder_path, files[-1]) def walk_level(root_directory,",
"= get_folder_size(file_path, round_value) if path.is_file(file_path): size = fileio.get_file_size(file_path, round_value) return size def get_sub_folders(root_folder,",
"if err.errno != errno.EEXIST: raise def get_latest_file_at_folder(folder_path, filter_text=''): \"\"\" Returns the latest path",
"== 'linux2': subprocess.Popen(['xdg-open', path]) elif sys.platform in ['windows', 'win32', 'win64']: if path.endswith('/'): path",
"to the directory we want to rename :param name: str, new name of",
"'\\\\'), '/S', '/Z', '/MIR'] if cmd: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out,",
"list(str), list of files date sorted in the directory \"\"\" from tpDcc.libs.python import",
"num_sep = root_directory.count(os.path.sep) for root, dirs, files in os.walk(root_directory): yield root, dirs, files",
"found.append(file_name) else: found.append(os.path.join(root_directory, file_name)) else: try: objs = os.listdir(root_directory) except Exception: return found",
"path.is_dir(directory=directory): return if not ignore_patterns: cmd = None if osplatform.is_linux(): cmd = ['rsync',",
"size += fileio.get_file_size(path.join_path(root, name), round_value) return size def get_size(file_path, round_value=2): \"\"\" Return the",
"== 'darwin': subprocess.check_call(['open', '--', path]) elif sys.platform == 'linux2': subprocess.Popen(['xdg-open', path]) elif sys.platform",
":param permissions:int, folder permission mode :param place_holder: bool, Whether to create place holder",
"want to ignore when copying folder elements If ['txt', 'py'] is given all",
"name of the new directory :param directory: str, path to the new directory",
"in file_list: src = os.path.join(source_directory, i) dest = os.path.join(target_directory, i) if os.path.exists(dest): if",
"level=None): root_directory = root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory) if level is None: for root, dirs,",
"return path.join_path(folder_path, files[-1]) def walk_level(root_directory, level=None): root_directory = root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory) if level",
"Returns the size of the given folder :param directory: str :param round_value: int,",
"we want to ignore when copying folder elements If ['txt', 'py'] is given",
"{1}'.format(directory, rename_path) logger.info(message) os.rename(directory, rename_path) except Exception: time.sleep(0.1) try: os.rename(directory, rename_path) except Exception:",
"files = get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text) return list(sorted(files, key=_get_mtime)) def open_folder(path=None): \"\"\" Opens a",
"to a folder :param folder_path: :param filter_text: :return: str \"\"\" from tpDcc.libs.python import",
"'--', path]) elif sys.platform == 'linux2': subprocess.Popen(['xdg-open', path]) elif sys.platform in ['windows', 'win32',",
"['rsync', directory, directory_destination, '-azr'] elif osplatform.is_windows(): cmd = [ 'robocopy', directory.replace('/', '\\\\'), directory_destination.replace('/',",
"will be returned :return: list<str> \"\"\" from tpDcc.libs.python import path if not path.is_dir(root_folder):",
"dir_path, dir_names, file_names in os.walk(root_folder): for file_name in fnmatch.filter(file_names, pattern): if full_path: found.append(path.join_path(dir_path,",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = proc.communicate() if out: logger.error(err) else: shutil.copytree(directory, directory_destination)",
"dir_name) if not path.is_dir(directory): create_folder(base_name, dir_name) def get_folder_size(directory, round_value=2, skip_names=None): \"\"\" Returns the",
"folder_path: str, folder path to check or created :param permissions:int, folder permission mode",
"proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = proc.communicate() if out: logger.error(err)",
"= False if directory is None: full_path = name if not name: full_path",
"def get_files(root_folder, full_path=False, recursive=False, pattern=\"*\"): \"\"\" Returns files found in the given folder",
"new name of the folder we want to rename :param make_unique: bool, Whether",
"!= errno.EEXIST: raise def get_latest_file_at_folder(folder_path, filter_text=''): \"\"\" Returns the latest path added to",
"if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f) if sort: result.sort() return result def get_folders(root_folder, recursive=False, full_path=False):",
"return full_path def clean_folder(directory): \"\"\" Removes everything in the given directory :param directory:",
"as err: if err.errno != errno.EEXIST: raise def get_latest_file_at_folder(folder_path, filter_text=''): \"\"\" Returns the",
"delete_folder(folder_name, directory=None): \"\"\" Deletes the folder by name in the given directory :param",
"if not path.is_dir(directory=directory): return if not ignore_patterns: cmd = None if osplatform.is_linux(): cmd",
"path \"{}\" | {}'.format(full_path, exc)) return full_path def clean_folder(directory): \"\"\" Removes everything in",
"path1: str :param path2: str :param args: :param kwargs: :return: \"\"\" try: copy_tree(path1,",
":param root_folder: str, folder we ant to search folders on :param recursive: bool,",
"or created :param permissions:int, folder permission mode :param place_holder: bool, Whether to create",
"def get_sub_folders(root_folder, sort=True): \"\"\" Return a list with all the sub folders names",
"root folder child folders or not :return: list<str> \"\"\" from tpDcc.libs.python import path",
"is given all py and text extension files will be ignored during the",
"round size to :return: int \"\"\" from tpDcc.libs.python import fileio, path size =",
"during the copy operation :return: str, destination directory \"\"\" from tpDcc.libs.python import path,",
"to search files on :param full_path: bool, if true, full path to the",
"path, folder = os.path.split(path) if folder != '': folders.append(folder) else: if path !=",
"found in the given directory :param directory: str, folder we want to get",
"filter_text: :return: str \"\"\" from tpDcc.libs.python import path files = get_files_date_sorted(folder_path, filter_text=filter_text) if",
"path, osplatform if not path.is_dir(directory=directory): return if not ignore_patterns: cmd = None if",
"of path \"{}\" | {}'.format(full_path, exc)) return full_path def clean_folder(directory): \"\"\" Removes everything",
"import path, version if not path.exists(directory): return found_folders = list() base_directory = base_directory",
"from tpDcc.libs.python import path if not path.is_dir(root_folder): return [] # TODO: For now",
"sub_folders return found_folders def get_files(root_folder, full_path=False, recursive=False, pattern=\"*\"): \"\"\" Returns files found in",
"and folders found in the given directory :param directory: str, folder we want",
"folder creation failed \"\"\" from tpDcc.libs.python import path, osplatform full_path = False if",
"to get files and folders from :return: list<str> \"\"\" try: files = os.listdir(directory)",
"= next(os.walk(root_folder))[1] except Exception: pass else: try: for root, dirs, files in os.walk(root_folder):",
"not path.is_dir(root_folder): return [] # TODO: For now pattern only works in recursive",
"if we want sort alphabetically the returned folders or False otherwise :return: list<str>,",
"to :return: int \"\"\" from tpDcc.libs.python import fileio, path size = 0 if",
"under the directory target_directory :param source_directory: str, folder with full path :param target_directory:",
"we want to get files and folders from :return: list<str> \"\"\" try: files",
"folder.startswith('.'): continue folder_path = path.join_path(directory, folder) folder_name = path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name) if recursive:",
"in the directory \"\"\" from tpDcc.libs.python import fileio def _get_mtime(fld): return os.stat(os.path.join(root_directory, fld)).st_mtime",
"for filename_and_extension in objs: filename, found_extension = os.path.splitext(filename_and_extension) if filter_text and filename_and_extension.find(filter_text) ==",
"path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return path.clean_path(os.path.expanduser('~')) def get_temp_folder(): \"\"\" Get the path to the temp",
"version.updated_old: continue if folder.startswith('.'): continue folder_path = path.join_path(directory, folder) folder_name = path.clean_path(os.path.relpath(folder_path, base_directory))",
"return found def get_files_and_folders(directory): \"\"\" Get files and folders found in the given",
"folder path to open \"\"\" if path is None: path = os.path.curdir if",
"else: shutil.copytree(directory, directory_destination) else: shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination def move_folder(source_directory, target_directory, only_contents=False):",
"= get_folders(directory) for folder in folders: if folder == 'version': version = version.VersionFile(directory)",
"root_folder) folder_name = path.clean_path(folder_name) found_folders.append(folder_name) except Exception: return found_folders return found_folders def get_folders_without_dot_prefix(directory,",
"search in all root folder child folders or not :return: list<str> \"\"\" from",
"directory into a new directory :param directory: str, directory to copy with full",
"import path, fileio, folder base_name = path.get_basename(directory=directory) dir_name = path.get_dirname(directory=directory) if path.is_dir(directory): try:",
"get_files_with_extension(extension, root_directory, full_path=False, recursive=False, filter_text=''): \"\"\" Returns file in given directory with given",
"assert os.path.isdir(root_directory) if level is None: for root, dirs, files in os.walk(root_directory): yield",
"directory_destination def move_folder(source_directory, target_directory, only_contents=False): \"\"\" Moves the folder pointed by source_directory under",
":return: bool, Whether the move operation was successfully \"\"\" try: if only_contents or",
"be returned :return: list<str> \"\"\" from tpDcc.libs.python import path if not path.is_dir(root_folder): return",
":param directory: str \"\"\" from tpDcc.libs.python import path, fileio, folder base_name = path.get_basename(directory=directory)",
"to make it unique if the folder is not unique :return: variant, str",
"be ignored during the copy operation :return: str, destination directory \"\"\" from tpDcc.libs.python",
"given root directory :param root_folder: str, directory path :return: list(str): list of folder",
"coding: utf-8 -*- \"\"\" Utility methods related to folders \"\"\" from __future__ import",
"*args, **kwargs): \"\"\" Copies all the contents of the given path1 to the",
"given folder :param root_folder: str, folder we want to search files on :param",
"path :param target_directory: str, path where path1 should be move into :param only_contents:",
"or only its contents :return: bool, Whether the move operation was successfully \"\"\"",
"text filtering :return: list(str), list of files date sorted in the directory \"\"\"",
"if not full_path: found.append(filename_and_extension) else: found.append(os.path.join(root_directory, filename_and_extension)) return found def get_files_date_sorted(root_directory, extension=None, filter_text=''):",
"except Exception: logger.warning('Failed to move contents of {0} to {1}'.format(path1, path2)) return False",
"given directory :param root_directory: str, directory path :param extension: str, optional extension to",
"logger.warning('Could not remove children of path \"{}\" | {}'.format(full_path, exc)) return full_path def",
"True: path, folder = os.path.split(path) if folder != '': folders.append(folder) else: if path",
"tempfile import traceback import subprocess from distutils.dir_util import copy_tree logger = logging.getLogger('tpDcc-libs-python') def",
"if filter_text and filename_and_extension.find(filter_text) == -1: continue if found_extension == extension: if not",
"except Exception: files = list() for f in files: fileio.delete_file(f, directory) delete_folder(base_name, dir_name)",
"\"\"\" Gets a list of sub folders in the given path :param path:",
"'rename: {0} >> {1}'.format(directory, rename_path) logger.info(message) os.rename(directory, rename_path) except Exception: time.sleep(0.1) try: os.rename(directory,",
"filter_text=filter_text) else: files = get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text) return list(sorted(files, key=_get_mtime)) def open_folder(path=None): \"\"\"",
"full_path = path.join_path(directory, folder_name) if not path.is_dir(full_path): return None try: shutil.rmtree(full_path, onerror=delete_read_only_error) except",
"False return True def copy_directory_contents(path1, path2, *args, **kwargs): \"\"\" Copies all the contents",
"'placeholder') if not os.path.exists(place_path): with open(place_path, 'wt') as fh: fh.write('Automatically generated place holder",
"str \"\"\" from tpDcc.libs.python import python, path, fileio skip_names = python.force_list(skip_names) size =",
"destination directory :param ignore_patterns: list<str>, extensions we want to ignore when copying folder",
"**kwargs) except Exception: logger.warning('Failed to move contents of {0} to {1}'.format(path1, path2)) return",
"= list() base_directory = base_directory or directory folders = get_folders(directory) for folder in",
"make_unique: bool, Whether to pad the name with a number to make it",
"full_path: found.append(filename_and_extension) else: found.append(os.path.join(root_directory, filename_and_extension)) return found def get_files_date_sorted(root_directory, extension=None, filter_text=''): \"\"\" Returns",
"folder name to make it unique :return: str, path of the renamed folder",
"Fix it to work on both found = list() if recursive: for dir_path,",
"dir_path, dir_names, file_names in os.walk(root_directory): for file_name in file_names: filename, found_extension = os.path.splitext(file_name)",
"if the folder is not unique :return: variant, str || bool, folder name",
"directory \"\"\" return os.getcwd() def get_folders_from_path(path): \"\"\" Gets a list of sub folders",
":param directory_destination: str, destination directory :param ignore_patterns: list<str>, extensions we want to ignore",
"list() return files def get_files_with_extension(extension, root_directory, full_path=False, recursive=False, filter_text=''): \"\"\" Returns file in",
"= os.path.splitext(file_name) if found_extension == '{}'.format(extension): if not full_path: found.append(file_name) else: found.append(os.path.join(root_directory, file_name))",
"str, folder with full path :param target_directory: str, path where path1 should be",
"found_folders.append(folder_name) if recursive: sub_folders = get_folders_without_dot_prefix( folder_path, recursive=recursive, base_directory=base_directory) found_folders += sub_folders return",
"for f in file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f) if sort: result.sort() return result",
"delete :param directory: str, the directory path where the folder is stored :return:",
"directory path :param full_path: bool, Whether to return the file path or just",
"return result def get_folders(root_folder, recursive=False, full_path=False): \"\"\" Get folders found in the root",
"dir_names, file_names in os.walk(root_folder): for file_name in fnmatch.filter(file_names, pattern): if full_path: found.append(path.join_path(dir_path, file_name))",
"for file_name in fnmatch.filter(file_names, pattern): if full_path: found.append(path.join_path(dir_path, file_name)) else: found.append(file_name) else: files",
"full_path=False): \"\"\" Get folders found in the root folder :param root_folder: str, folder",
"fileio.get_file_size(path.join_path(root, name), round_value) return size def get_size(file_path, round_value=2): \"\"\" Return the size of",
"except Exception: return found for filename_and_extension in objs: filename, found_extension = os.path.splitext(filename_and_extension) if",
"to rename :param make_unique: bool, Whether to add a number to the folder",
"return False return rename_path def copy_folder(directory, directory_destination, ignore_patterns=[]): \"\"\" Copy the given directory",
"result def get_folders(root_folder, recursive=False, full_path=False): \"\"\" Get folders found in the root folder",
"kwargs: :return: \"\"\" try: copy_tree(path1, path2, *args, **kwargs) except Exception: logger.warning('Failed to move",
":param folder_path: str, folder path to check or created :param permissions:int, folder permission",
"# TODO: For now pattern only works in recursive searches. Fix it to",
"way If not path is passed the current directory will be opened :param",
"path, fileio, folder base_name = path.get_basename(directory=directory) dir_name = path.get_dirname(directory=directory) if path.is_dir(directory): try: files",
"name in files: if name in skip_names: continue size += fileio.get_file_size(path.join_path(root, name), round_value)",
"= path.unique_path_name(directory=rename_path) if path.exists(rename_path): return False try: osplatform.get_permission(directory) message = 'rename: {0} >>",
"\"\"\" Returns files date sorted found in the given directory :param root_directory: str,",
":param path: str :return: list<str> \"\"\" folders = list() while True: path, folder",
"*args, **kwargs) except Exception: logger.warning('Failed to move contents of {0} to {1}'.format(path1, path2))",
"not path.exists(directory): return found_folders = list() base_directory = base_directory or directory folders =",
"path.get_dirname(directory=directory) rename_path = path.join_path(parent_path, name) if make_unique: rename_path = path.unique_path_name(directory=rename_path) if path.exists(rename_path): return",
"bool, Whether to pad the name with a number to make it unique",
"{0} does not exists!'.format(root_folder)) file_names = os.listdir(root_folder) result = list() for f in",
"import name, path, osplatform def delete_read_only_error(action, name, exc): \"\"\" Helper to delete read",
"bool, Whether to create place holder text file or not :raise OSError: raise",
"extension: str, optional extension to find :param filter_text: str, optional text filtering :return:",
":param directory: str, directory to copy with full path :param directory_destination: str, destination",
"the sub folders names on a directory :param root_folder: str, folder we want",
"folders on :param recursive: bool, Whether to search in all root folder child",
"folder \"\"\" from tpDcc.libs.python import path if absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return path.clean_path(os.path.expanduser('~'))",
"to open \"\"\" if path is None: path = os.path.curdir if sys.platform ==",
"file_names: filename, found_extension = os.path.splitext(file_name) if found_extension == '{}'.format(extension): if not full_path: found.append(file_name)",
"if full_path: found.append(path.join_path(dir_path, file_name)) else: found.append(file_name) else: files = os.listdir(root_folder) for f in",
"folder_path, recursive=recursive, base_directory=base_directory) found_folders += sub_folders return found_folders def get_files(root_folder, full_path=False, recursive=False, pattern=\"*\"):",
"if name in skip_names: continue size += fileio.get_file_size(path.join_path(root, name), round_value) return size def",
"target_directory :param source_directory: str, folder with full path :param target_directory: str, path where",
"import python, path, fileio skip_names = python.force_list(skip_names) size = 0 for root, dirs,",
"else: try: for root, dirs, files in os.walk(root_folder): for d in dirs: if",
"return False return True def delete_folder(folder_name, directory=None): \"\"\" Deletes the folder by name",
"except Exception as exc: logger.warning('Could not remove children of path \"{}\" | {}'.format(full_path,",
"only files \"\"\" osplatform.get_permission(name) action(name) folder_name = name.clean_file_string(folder_name) full_path = folder_name if directory:",
"filename, found_extension = os.path.splitext(filename_and_extension) if filter_text and filename_and_extension.find(filter_text) == -1: continue if found_extension",
"= os.path.join(target_directory, i) if os.path.exists(dest): if os.path.isdir(dest): move_folder(src, dest) continue else: os.remove(dest) shutil.move(src,",
"it unique if the folder is not unique :return: variant, str || bool,",
"\"\"\" try: copy_tree(path1, path2, *args, **kwargs) except Exception: logger.warning('Failed to move contents of",
"str, optional text filtering :return: list(str), list of files date sorted in the",
"to {}: {}'.format(source_directory, target_directory, exc)) return False return True def copy_directory_contents(path1, path2, *args,",
"= name if not name: full_path = directory if name and directory: full_path",
"the creation of the folder fails \"\"\" if not os.path.exists(folder_path): try: logger.debug('Creating folder",
"folder by name in the given directory :param folder_name: str, name of the",
"try: logger.debug('Creating folder {} [{}]'.format(folder_path, permissions)) os.makedirs(folder_path, permissions) if place_holder: place_path = os.path.join(folder_path,",
"source_directory: str, folder with full path :param target_directory: str, path where path1 should",
"of the given path1 to the folder path2. If path2 directory does not",
"sub_folders = get_folders_without_dot_prefix( folder_path, recursive=recursive, base_directory=base_directory) found_folders += sub_folders return found_folders def get_files(root_folder,",
"not extension.startswith('.'): extension = '.{}'.format(extension) if recursive: for dir_path, dir_names, file_names in os.walk(root_directory):",
"shutil.move(source_directory, target_directory) except Exception as exc: logger.warning('Failed to move {} to {}: {}'.format(source_directory,",
"f in file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f) if sort: result.sort() return result def",
"subprocess from distutils.dir_util import copy_tree logger = logging.getLogger('tpDcc-libs-python') def create_folder(name, directory=None, make_unique=False): \"\"\"",
"exists. If not, folder is created. :param folder_path: str, folder path to check",
"path.is_file(file_path): size = fileio.get_file_size(file_path, round_value) return size def get_sub_folders(root_folder, sort=True): \"\"\" Return a",
"full_path: found.append(path.join_path(dir_path, file_name)) else: found.append(file_name) else: files = os.listdir(root_folder) for f in files:",
"def get_folders_without_dot_prefix(directory, recursive=False, base_directory=None): from tpDcc.libs.python import path, version if not path.exists(directory): return",
"def get_folders_from_path(path): \"\"\" Gets a list of sub folders in the given path",
"str, directory path :param extension: str, optional extension to find :param filter_text: str,",
"def delete_folder(folder_name, directory=None): \"\"\" Deletes the folder by name in the given directory",
"directory or file path :param file_path: str :param round_value: int, value to round",
"path to the new directory :param make_unique: bool, Whether to pad the name",
"logger.error(err) else: shutil.copytree(directory, directory_destination) else: shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination def move_folder(source_directory, target_directory,",
":param sort: bool, True if we want sort alphabetically the returned folders or",
"clean_folder(directory): \"\"\" Removes everything in the given directory :param directory: str \"\"\" from",
":return: str \"\"\" from tpDcc.libs.python import python, path, fileio skip_names = python.force_list(skip_names) size",
"filter_text=''): \"\"\" Returns the latest path added to a folder :param folder_path: :param",
"Exception: pass def get_user_folder(absolute=True): \"\"\" Get path to the user folder :return: str,",
"unique :return: variant, str || bool, folder name with path or False if",
"path: str, folder path to open \"\"\" if path is None: path =",
"str :return: list<str> \"\"\" folders = list() while True: path, folder = os.path.split(path)",
"= folder_name if directory: full_path = path.join_path(directory, folder_name) if not path.is_dir(full_path): return None",
"\"\"\" Return the size of the given directory or file path :param file_path:",
"path, osplatform full_path = False if directory is None: full_path = name if",
"it will be created :param path1: str :param path2: str :param args: :param",
"recursive=False, full_path=False): \"\"\" Get folders found in the root folder :param root_folder: str,",
"file_name in file_names: filename, found_extension = os.path.splitext(file_name) if found_extension == '{}'.format(extension): if not",
"return full_path try: os.makedirs(full_path) except Exception: return False osplatform.get_permission(full_path) return full_path def rename_folder(directory,",
"filter_text=''): \"\"\" Returns file in given directory with given extensions :param extension: str,",
"'': folders.append(path) break folders.reverse() return folders def get_folders_date_sorted(root_folder): \"\"\" Returns folder dates sorted",
"get_folder_size(directory, round_value=2, skip_names=None): \"\"\" Returns the size of the given folder :param directory:",
"path1 to the folder path2. If path2 directory does not exists, it will",
"and text extension files will be ignored during the copy operation :return: str,",
"created. :param folder_path: str, folder path to check or created :param permissions:int, folder",
"get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text) return list(sorted(files, key=_get_mtime)) def open_folder(path=None): \"\"\" Opens a folder in",
"files date sorted in the directory \"\"\" from tpDcc.libs.python import fileio def _get_mtime(fld):",
"path to the user folder \"\"\" from tpDcc.libs.python import path if absolute: return",
"we want sort alphabetically the returned folders or False otherwise :return: list<str>, sub",
"not name: full_path = directory if name and directory: full_path = path.join_path(directory, name)",
":param filter_text: str, optional text filtering :return: list(str), list of files date sorted",
"found.append(path.join_path(dir_path, file_name)) else: found.append(file_name) else: files = os.listdir(root_folder) for f in files: file_path",
"name) if make_unique: full_path = path.unique_path_name(directory=full_path) if not full_path: return False if path.is_dir(full_path):",
"str, folder path to check or created :param permissions:int, folder permission mode :param",
"otherwise file names will be returned :return: list<str> \"\"\" from tpDcc.libs.python import path",
"full_path: found.append(file_path) else: found.append(f) return found def get_files_and_folders(directory): \"\"\" Get files and folders",
"f in files: fileio.delete_file(f, directory) delete_folder(base_name, dir_name) if not path.is_dir(directory): create_folder(base_name, dir_name) def",
"shutil.rmtree(full_path, onerror=delete_read_only_error) except Exception as exc: logger.warning('Could not remove children of path \"{}\"",
"Copy the given directory into a new directory :param directory: str, directory to",
"import path if absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return path.clean_path(os.path.expanduser('~')) def get_temp_folder(): \"\"\" Get",
"directory with given extensions :param extension: str, extension to find (.py, .data, etc)",
"the current working directory \"\"\" return os.getcwd() def get_folders_from_path(path): \"\"\" Gets a list",
"(.py, .data, etc) :param root_directory: str, directory path :param full_path: bool, Whether to",
"root directory :param root_folder: str, directory path :return: list(str): list of folder date",
"= path.get_dirname(directory=directory) if path.is_dir(directory): try: files = folder.get_files(directory) except Exception: files = list()",
"the given folder :param root_folder: str, folder we want to search files on",
"on both found = list() if recursive: for dir_path, dir_names, file_names in os.walk(root_folder):",
"only its contents :return: bool, Whether the move operation was successfully \"\"\" try:",
"not extension: files = fileio.get_files(root_directory, filter_text=filter_text) else: files = get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text) return",
"folder = os.path.split(path) if folder != '': folders.append(folder) else: if path != '':",
"directory_destination) else: shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination def move_folder(source_directory, target_directory, only_contents=False): \"\"\" Moves",
"python, path, fileio skip_names = python.force_list(skip_names) size = 0 for root, dirs, files",
"extensions :param extension: str, extension to find (.py, .data, etc) :param root_directory: str,",
"name with a number to make it unique if the folder is not",
"path found_folders = list() if not recursive: try: found_folders = next(os.walk(root_folder))[1] except Exception:",
"on :param recursive: bool, Whether to search in all root folder child folders",
"continue if folder.startswith('.'): continue folder_path = path.join_path(directory, folder) folder_name = path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name)",
"path is passed the current directory will be opened :param path: str, folder",
"str || bool, folder name with path or False if the folder creation",
"open_folder(path=None): \"\"\" Opens a folder in the explorer in a independent platform way",
"dirs, files in os.walk(root_directory): yield root, dirs, files else: num_sep = root_directory.count(os.path.sep) for",
"'{}'.format(extension): if not full_path: found.append(file_name) else: found.append(os.path.join(root_directory, file_name)) else: try: objs = os.listdir(root_directory)",
"yield root, dirs, files else: num_sep = root_directory.count(os.path.sep) for root, dirs, files in",
"walk_level(root_directory, level=None): root_directory = root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory) if level is None: for root,",
"Returns files date sorted found in the given directory :param root_directory: str, directory",
"= folder.get_files(directory) except Exception: files = list() for f in files: fileio.delete_file(f, directory)",
"import path, osplatform full_path = False if directory is None: full_path = name",
"try: found_folders = next(os.walk(root_folder))[1] except Exception: pass else: try: for root, dirs, files",
"= os.path.curdir if sys.platform == 'darwin': subprocess.check_call(['open', '--', path]) elif sys.platform == 'linux2':",
"found = list() if not extension.startswith('.'): extension = '.{}'.format(extension) if recursive: for dir_path,",
"files def get_files_with_extension(extension, root_directory, full_path=False, recursive=False, filter_text=''): \"\"\" Returns file in given directory",
"found_extension == extension: if not full_path: found.append(filename_and_extension) else: found.append(os.path.join(root_directory, filename_and_extension)) return found def",
"elements If ['txt', 'py'] is given all py and text extension files will",
"with path \"\"\" from tpDcc.libs.python import name, path, osplatform def delete_read_only_error(action, name, exc):",
":return: list<str> \"\"\" folders = list() while True: path, folder = os.path.split(path) if",
"= path.replace('/', '\\\\') try: subprocess.check_call(['explorer', new_path], shell=False) except Exception: pass def get_user_folder(absolute=True): \"\"\"",
"not :raise OSError: raise OSError if the creation of the folder fails \"\"\"",
"size = 0 for root, dirs, files in os.walk(directory): root_name = path.get_basename(root) if",
"found def get_files_date_sorted(root_directory, extension=None, filter_text=''): \"\"\" Returns files date sorted found in the",
"return found_folders return found_folders def get_folders_without_dot_prefix(directory, recursive=False, base_directory=None): from tpDcc.libs.python import path, version",
"else: if path != '': folders.append(path) break folders.reverse() return folders def get_folders_date_sorted(root_folder): \"\"\"",
"If not path is passed the current directory will be opened :param path:",
"full_path = path.unique_path_name(directory=full_path) if not full_path: return False if path.is_dir(full_path): return full_path try:",
"for f in files: fileio.delete_file(f, directory) delete_folder(base_name, dir_name) if not path.is_dir(directory): create_folder(base_name, dir_name)",
"path = os.path.curdir if sys.platform == 'darwin': subprocess.check_call(['open', '--', path]) elif sys.platform ==",
"osplatform base_name = path.get_basename(directory=directory) if base_name == name: return parent_path = path.get_dirname(directory=directory) rename_path",
"to ignore when copying folder elements If ['txt', 'py'] is given all py",
"found.append(file_name) else: files = os.listdir(root_folder) for f in files: file_path = path.join_path(root_folder, f)",
"found in the given directory :param root_directory: str, directory path :param extension: str,",
"all py and text extension files will be ignored during the copy operation",
"logger.info(message) os.rename(directory, rename_path) except Exception: time.sleep(0.1) try: os.rename(directory, rename_path) except Exception: logger.error('{}'.format(traceback.format_exc())) return",
"path.exists(directory): return found_folders = list() base_directory = base_directory or directory folders = get_folders(directory)",
"optional extension to find :param filter_text: str, optional text filtering :return: list(str), list",
"latest path added to a folder :param folder_path: :param filter_text: :return: str \"\"\"",
"file_path: str :param round_value: int, value to round size to :return: int \"\"\"",
"key=_get_mtime)) def ensure_folder_exists(folder_path, permissions=0o755, place_holder=False): \"\"\" Checks that folder given folder exists. If",
"None: path = os.path.curdir if sys.platform == 'darwin': subprocess.check_call(['open', '--', path]) elif sys.platform",
"-*- coding: utf-8 -*- \"\"\" Utility methods related to folders \"\"\" from __future__",
"'/MIR'] if cmd: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = proc.communicate()",
"skip_names: continue size += fileio.get_file_size(path.join_path(root, name), round_value) return size def get_size(file_path, round_value=2): \"\"\"",
"return folders def get_folders_date_sorted(root_folder): \"\"\" Returns folder dates sorted found in the given",
"folders names \"\"\" if not os.path.exists(root_folder): raise RuntimeError('Folder {0} does not exists!'.format(root_folder)) file_names",
"to pad the name with a number to make it unique if the",
"in objs: filename, found_extension = os.path.splitext(filename_and_extension) if filter_text and filename_and_extension.find(filter_text) == -1: continue",
"the returned folders or False otherwise :return: list<str>, sub folders names \"\"\" if",
"just the file names :param recursive: bool :param filter_text: str :return: list(str) \"\"\"",
"into :param only_contents: bool, Whether to move the folder or only its contents",
"get_folders_without_dot_prefix(directory, recursive=False, base_directory=None): from tpDcc.libs.python import path, version if not path.exists(directory): return found_folders",
"a independent platform way If not path is passed the current directory will",
"folder_name = path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name) if recursive: sub_folders = get_folders_without_dot_prefix( folder_path, recursive=recursive, base_directory=base_directory)",
"folder.get_files(directory) except Exception: files = list() for f in files: fileio.delete_file(f, directory) delete_folder(base_name,",
"path2, *args, **kwargs): \"\"\" Copies all the contents of the given path1 to",
"folders = get_folders(directory) for folder in folders: if folder == 'version': version =",
"to work on both found = list() if recursive: for dir_path, dir_names, file_names",
"files[-1]) def walk_level(root_directory, level=None): root_directory = root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory) if level is None:",
"shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination def move_folder(source_directory, target_directory, only_contents=False): \"\"\" Moves the folder",
"base_name = path.get_basename(directory=directory) dir_name = path.get_dirname(directory=directory) if path.is_dir(directory): try: files = folder.get_files(directory) except",
"folder is created. :param folder_path: str, folder path to check or created :param",
"size = fileio.get_file_size(file_path, round_value) return size def get_sub_folders(root_folder, sort=True): \"\"\" Return a list",
"if cmd: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = proc.communicate() if",
"given path1 to the folder path2. If path2 directory does not exists, it",
"names on a directory :param root_folder: str, folder we want to search sub",
":param path: str, folder path to open \"\"\" if path is None: path",
"If ['txt', 'py'] is given all py and text extension files will be",
"[] # TODO: For now pattern only works in recursive searches. Fix it",
"found.append(os.path.join(root_directory, file_name)) else: try: objs = os.listdir(root_directory) except Exception: return found for filename_and_extension",
"\"\"\" def _get_mtime(fld): return os.stat(os.path.join(root_folder, fld)).st_mtime return list(sorted(os.listdir(root_folder), key=_get_mtime)) def ensure_folder_exists(folder_path, permissions=0o755, place_holder=False):",
"__future__ import print_function, division, absolute_import import os import sys import time import errno",
"files = os.listdir(root_folder) for f in files: file_path = path.join_path(root_folder, f) if path.is_file(file_path=file_path):",
"folder_name = path.clean_path(folder_name) found_folders.append(folder_name) except Exception: return found_folders return found_folders def get_folders_without_dot_prefix(directory, recursive=False,",
"name :param name: str, name of the new directory :param directory: str, path",
"if osplatform.is_linux(): cmd = ['rsync', directory, directory_destination, '-azr'] elif osplatform.is_windows(): cmd = [",
"in files: fileio.delete_file(f, directory) delete_folder(base_name, dir_name) if not path.is_dir(directory): create_folder(base_name, dir_name) def get_folder_size(directory,",
"os.walk(root_directory): for file_name in file_names: filename, found_extension = os.path.splitext(file_name) if found_extension == '{}'.format(extension):",
"only_contents or os.path.isdir(target_directory): file_list = os.listdir(source_directory) for i in file_list: src = os.path.join(source_directory,",
"= fileio.get_files(root_directory, filter_text=filter_text) else: files = get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text) return list(sorted(files, key=_get_mtime)) def",
"unique :return: str, path of the renamed folder \"\"\" from tpDcc.libs.python import path,",
"!= '': folders.append(path) break folders.reverse() return folders def get_folders_date_sorted(root_folder): \"\"\" Returns folder dates",
"path, fileio skip_names = python.force_list(skip_names) size = 0 for root, dirs, files in",
"tpDcc.libs.python import path files = get_files_date_sorted(folder_path, filter_text=filter_text) if not files: return None return",
"root, dirs, files else: num_sep = root_directory.count(os.path.sep) for root, dirs, files in os.walk(root_directory):",
"the folder fails \"\"\" if not os.path.exists(folder_path): try: logger.debug('Creating folder {} [{}]'.format(folder_path, permissions))",
"'\\\\') try: subprocess.check_call(['explorer', new_path], shell=False) except Exception: pass def get_user_folder(absolute=True): \"\"\" Get path",
"we want to rename :param make_unique: bool, Whether to add a number to",
"break folders.reverse() return folders def get_folders_date_sorted(root_folder): \"\"\" Returns folder dates sorted found in",
"os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f) if sort: result.sort() return result def get_folders(root_folder, recursive=False, full_path=False): \"\"\"",
"path \"\"\" from tpDcc.libs.python import name, path, osplatform def delete_read_only_error(action, name, exc): \"\"\"",
"folder_name = os.path.relpath(folder_name, root_folder) folder_name = path.clean_path(folder_name) found_folders.append(folder_name) except Exception: return found_folders return",
"/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" Utility methods related to folders",
"ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination def move_folder(source_directory, target_directory, only_contents=False): \"\"\" Moves the folder pointed by",
"os.rename(directory, rename_path) except Exception: time.sleep(0.1) try: os.rename(directory, rename_path) except Exception: logger.error('{}'.format(traceback.format_exc())) return False",
"found_folders = next(os.walk(root_folder))[1] except Exception: pass else: try: for root, dirs, files in",
"folder we want to search sub folders for :param sort: bool, True if",
"file names :param recursive: bool :param filter_text: str :return: list(str) \"\"\" found =",
"= get_folders_without_dot_prefix( folder_path, recursive=recursive, base_directory=base_directory) found_folders += sub_folders return found_folders def get_files(root_folder, full_path=False,",
"os.path.join(target_directory, i) if os.path.exists(dest): if os.path.isdir(dest): move_folder(src, dest) continue else: os.remove(dest) shutil.move(src, target_directory)",
"recursive: for dir_path, dir_names, file_names in os.walk(root_directory): for file_name in file_names: filename, found_extension",
"if path.exists(rename_path): return False try: osplatform.get_permission(directory) message = 'rename: {0} >> {1}'.format(directory, rename_path)",
"extension to find (.py, .data, etc) :param root_directory: str, directory path :param full_path:",
"where path1 should be move into :param only_contents: bool, Whether to move the",
"cmd: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = proc.communicate() if out:",
"skip_names=None): \"\"\" Returns the size of the given folder :param directory: str :param",
"not os.path.exists(root_folder): raise RuntimeError('Folder {0} does not exists!'.format(root_folder)) file_names = os.listdir(root_folder) result =",
"path to the temp folder \"\"\" from tpDcc.libs.python import path return path.clean_path(tempfile.gettempdir()) def",
"subprocess.check_call(['open', '--', path]) elif sys.platform == 'linux2': subprocess.Popen(['xdg-open', path]) elif sys.platform in ['windows',",
"place_holder: bool, Whether to create place holder text file or not :raise OSError:",
"[{}]'.format(folder_path, permissions)) os.makedirs(folder_path, permissions) if place_holder: place_path = os.path.join(folder_path, 'placeholder') if not os.path.exists(place_path):",
"found = list() if recursive: for dir_path, dir_names, file_names in os.walk(root_folder): for file_name",
"and with the given name :param name: str, name of the new directory",
"return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return path.clean_path(os.path.expanduser('~')) def get_temp_folder(): \"\"\" Get the path to the",
"{}'.format(full_path, exc)) return full_path def clean_folder(directory): \"\"\" Removes everything in the given directory",
"try: subprocess.check_call(['explorer', new_path], shell=False) except Exception: pass def get_user_folder(absolute=True): \"\"\" Get path to",
"does not exists!'.format(root_folder)) file_names = os.listdir(root_folder) result = list() for f in file_names:",
"not os.path.exists(place_path): with open(place_path, 'wt') as fh: fh.write('Automatically generated place holder file') except",
"to find :param filter_text: str, optional text filtering :return: list(str), list of files",
"message = 'rename: {0} >> {1}'.format(directory, rename_path) logger.info(message) os.rename(directory, rename_path) except Exception: time.sleep(0.1)",
":param root_folder: str, folder we want to search sub folders for :param sort:",
"None: for root, dirs, files in os.walk(root_directory): yield root, dirs, files else: num_sep",
"to search sub folders for :param sort: bool, True if we want sort",
"path :param directory_destination: str, destination directory :param ignore_patterns: list<str>, extensions we want to",
"root_folder: str, folder we ant to search folders on :param recursive: bool, Whether",
"if not full_path: found.append(file_name) else: found.append(os.path.join(root_directory, file_name)) else: try: objs = os.listdir(root_directory) except",
"= os.path.relpath(folder_name, root_folder) folder_name = path.clean_path(folder_name) found_folders.append(folder_name) except Exception: return found_folders return found_folders",
"list() while True: path, folder = os.path.split(path) if folder != '': folders.append(folder) else:",
"the folder we want to rename :param make_unique: bool, Whether to add a",
"python.force_list(skip_names) size = 0 for root, dirs, files in os.walk(directory): root_name = path.get_basename(root)",
"full_path def rename_folder(directory, name, make_unique=False): \"\"\" Renames given with a new name :param",
"\"{}\" | {}'.format(full_path, exc)) return full_path def clean_folder(directory): \"\"\" Removes everything in the",
"the given directory :param directory: str \"\"\" from tpDcc.libs.python import path, fileio, folder",
"number to make it unique if the folder is not unique :return: variant,",
"path.unique_path_name(directory=rename_path) if path.exists(rename_path): return False try: osplatform.get_permission(directory) message = 'rename: {0} >> {1}'.format(directory,",
":param round_value: int, value to round size to :return: int \"\"\" from tpDcc.libs.python",
"found in the given root directory :param root_folder: str, directory path :return: list(str):",
"folder fails \"\"\" if not os.path.exists(folder_path): try: logger.debug('Creating folder {} [{}]'.format(folder_path, permissions)) os.makedirs(folder_path,",
":param directory: str, folder we want to get files and folders from :return:",
"list() for f in files: fileio.delete_file(f, directory) delete_folder(base_name, dir_name) if not path.is_dir(directory): create_folder(base_name,",
"sort: result.sort() return result def get_folders(root_folder, recursive=False, full_path=False): \"\"\" Get folders found in",
":param only_contents: bool, Whether to move the folder or only its contents :return:",
"\"\"\" from tpDcc.libs.python import path, osplatform if not path.is_dir(directory=directory): return if not ignore_patterns:",
"recursive=False, pattern=\"*\"): \"\"\" Returns files found in the given folder :param root_folder: str,",
"{} to {}: {}'.format(source_directory, target_directory, exc)) return False return True def copy_directory_contents(path1, path2,",
"value to round size to :return: int \"\"\" from tpDcc.libs.python import fileio, path",
"Whether to pad the name with a number to make it unique if",
"round_value) return size def get_sub_folders(root_folder, sort=True): \"\"\" Return a list with all the",
"def get_size(file_path, round_value=2): \"\"\" Return the size of the given directory or file",
"get_temp_folder(): \"\"\" Get the path to the temp folder :return: str, path to",
"or os.path.isdir(target_directory): file_list = os.listdir(source_directory) for i in file_list: src = os.path.join(source_directory, i)",
"files = os.listdir(directory) except Exception: files = list() return files def get_files_with_extension(extension, root_directory,",
"folder we want to get files and folders from :return: list<str> \"\"\" try:",
"temp folder :return: str, path to the temp folder \"\"\" from tpDcc.libs.python import",
":param args: :param kwargs: :return: \"\"\" try: copy_tree(path1, path2, *args, **kwargs) except Exception:",
"found in the root folder :param root_folder: str, folder we ant to search",
"files and folders from :return: list<str> \"\"\" try: files = os.listdir(directory) except Exception:",
"fld)).st_mtime return list(sorted(os.listdir(root_folder), key=_get_mtime)) def ensure_folder_exists(folder_path, permissions=0o755, place_holder=False): \"\"\" Checks that folder given",
"tpDcc.libs.python import path, osplatform if not path.is_dir(directory=directory): return if not ignore_patterns: cmd =",
"files = folder.get_files(directory) except Exception: files = list() for f in files: fileio.delete_file(f,",
"os.path.join(source_directory, i) dest = os.path.join(target_directory, i) if os.path.exists(dest): if os.path.isdir(dest): move_folder(src, dest) continue",
"make_unique: rename_path = path.unique_path_name(directory=rename_path) if path.exists(rename_path): return False try: osplatform.get_permission(directory) message = 'rename:",
"created :param path1: str :param path2: str :param args: :param kwargs: :return: \"\"\"",
"return list(sorted(os.listdir(root_folder), key=_get_mtime)) def ensure_folder_exists(folder_path, permissions=0o755, place_holder=False): \"\"\" Checks that folder given folder",
"\"\"\" from __future__ import print_function, division, absolute_import import os import sys import time",
"value to round size to :return: str \"\"\" from tpDcc.libs.python import python, path,",
"list() if recursive: for dir_path, dir_names, file_names in os.walk(root_folder): for file_name in fnmatch.filter(file_names,",
"dirs, files in os.walk(root_directory): yield root, dirs, files num_sep_this = root.count(os.path.sep) if num_sep",
"copy with full path :param directory_destination: str, destination directory :param ignore_patterns: list<str>, extensions",
"ignore_patterns: cmd = None if osplatform.is_linux(): cmd = ['rsync', directory, directory_destination, '-azr'] elif",
"bool, Whether to move the folder or only its contents :return: bool, Whether",
"name: full_path = directory if name and directory: full_path = path.join_path(directory, name) if",
"bool, Whether to add a number to the folder name to make it",
"not :return: list<str> \"\"\" from tpDcc.libs.python import path found_folders = list() if not",
"Whether to search in all root folder child folders or not :return: list<str>",
"directory=None, make_unique=False): \"\"\" Creates a new folder on the given path and with",
"ignore_patterns=[]): \"\"\" Copy the given directory into a new directory :param directory: str,",
"return found_folders def get_folders_without_dot_prefix(directory, recursive=False, base_directory=None): from tpDcc.libs.python import path, version if not",
"the directory target_directory :param source_directory: str, folder with full path :param target_directory: str,",
"source_directory under the directory target_directory :param source_directory: str, folder with full path :param",
"str, path to the temp folder \"\"\" from tpDcc.libs.python import path return path.clean_path(tempfile.gettempdir())",
"else: num_sep = root_directory.count(os.path.sep) for root, dirs, files in os.walk(root_directory): yield root, dirs,",
"str, destination directory \"\"\" from tpDcc.libs.python import path, osplatform if not path.is_dir(directory=directory): return",
"to rename :param name: str, new name of the folder we want to",
"str, path to the user folder \"\"\" from tpDcc.libs.python import path if absolute:",
"in the explorer in a independent platform way If not path is passed",
"file_names in os.walk(root_directory): for file_name in file_names: filename, found_extension = os.path.splitext(file_name) if found_extension",
"path.is_dir(root_folder): return [] # TODO: For now pattern only works in recursive searches.",
"= proc.communicate() if out: logger.error(err) else: shutil.copytree(directory, directory_destination) else: shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return",
"Whether to add a number to the folder name to make it unique",
"= list() return files def get_files_with_extension(extension, root_directory, full_path=False, recursive=False, filter_text=''): \"\"\" Returns file",
"permissions=0o755, place_holder=False): \"\"\" Checks that folder given folder exists. If not, folder is",
"the directory \"\"\" def _get_mtime(fld): return os.stat(os.path.join(root_folder, fld)).st_mtime return list(sorted(os.listdir(root_folder), key=_get_mtime)) def ensure_folder_exists(folder_path,",
"shell=False) except Exception: pass def get_user_folder(absolute=True): \"\"\" Get path to the user folder",
"variant, str || bool, folder name with path or False if the folder",
"False if directory is None: full_path = name if not name: full_path =",
"root, dirs, files in os.walk(root_directory): yield root, dirs, files num_sep_this = root.count(os.path.sep) if",
"explorer in a independent platform way If not path is passed the current",
"extension: files = fileio.get_files(root_directory, filter_text=filter_text) else: files = get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text) return list(sorted(files,",
"failed \"\"\" from tpDcc.libs.python import path, osplatform full_path = False if directory is",
"found_folders def get_folders_without_dot_prefix(directory, recursive=False, base_directory=None): from tpDcc.libs.python import path, version if not path.exists(directory):",
"create place holder text file or not :raise OSError: raise OSError if the",
"fileio.delete_file(f, directory) delete_folder(base_name, dir_name) if not path.is_dir(directory): create_folder(base_name, dir_name) def get_folder_size(directory, round_value=2, skip_names=None):",
"shutil import fnmatch import logging import tempfile import traceback import subprocess from distutils.dir_util",
"to return the file path or just the file names :param recursive: bool",
":param directory: str :param round_value: int, value to round size to :return: str",
"for :param sort: bool, True if we want sort alphabetically the returned folders",
"sys import time import errno import shutil import fnmatch import logging import tempfile",
":param directory: str, full path to the directory we want to rename :param",
"to add a number to the folder name to make it unique :return:",
"folder elements If ['txt', 'py'] is given all py and text extension files",
"\"\"\" Copies all the contents of the given path1 to the folder path2.",
"directory path where the folder is stored :return: str, folder that was deleted",
":param folder_name: str, name of the folder to delete :param directory: str, the",
"sub folders in the given path :param path: str :return: list<str> \"\"\" folders",
"want to search files on :param full_path: bool, if true, full path to",
"None try: shutil.rmtree(full_path, onerror=delete_read_only_error) except Exception as exc: logger.warning('Could not remove children of",
"#! /usr/bin/env python # -*- coding: utf-8 -*- \"\"\" Utility methods related to",
"else: found.append(os.path.join(root_directory, file_name)) else: try: objs = os.listdir(root_directory) except Exception: return found for",
"'\\\\'), directory_destination.replace('/', '\\\\'), '/S', '/Z', '/MIR'] if cmd: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,",
"place_holder=False): \"\"\" Checks that folder given folder exists. If not, folder is created.",
"path.is_dir(file_path): size = get_folder_size(file_path, round_value) if path.is_file(file_path): size = fileio.get_file_size(file_path, round_value) return size",
"\"\"\" from tpDcc.libs.python import fileio def _get_mtime(fld): return os.stat(os.path.join(root_directory, fld)).st_mtime if not extension:",
"given directory :param directory: str, folder we want to get files and folders",
"filtering :return: list(str), list of files date sorted in the directory \"\"\" from",
"not path.is_dir(directory): create_folder(base_name, dir_name) def get_folder_size(directory, round_value=2, skip_names=None): \"\"\" Returns the size of",
"a folder in the explorer in a independent platform way If not path",
"will be ignored during the copy operation :return: str, destination directory \"\"\" from",
"d) found_folders.append(folder_name) else: folder_name = path.join_path(root, d) folder_name = os.path.relpath(folder_name, root_folder) folder_name =",
"move {} to {}: {}'.format(source_directory, target_directory, exc)) return False return True def copy_directory_contents(path1,",
"path to the files will be returned otherwise file names will be returned",
"base_directory=None): from tpDcc.libs.python import path, version if not path.exists(directory): return found_folders = list()",
"files \"\"\" osplatform.get_permission(name) action(name) folder_name = name.clean_file_string(folder_name) full_path = folder_name if directory: full_path",
"print_function, division, absolute_import import os import sys import time import errno import shutil",
"not path.is_dir(full_path): return None try: shutil.rmtree(full_path, onerror=delete_read_only_error) except Exception as exc: logger.warning('Could not",
"date sorted found in the given directory :param root_directory: str, directory path :param",
"if root_name in skip_names: continue for name in files: if name in skip_names:",
"given with a new name :param directory: str, full path to the directory",
"directory :param folder_name: str, name of the folder to delete :param directory: str,",
"list of files date sorted in the directory \"\"\" from tpDcc.libs.python import fileio",
"folder path2. If path2 directory does not exists, it will be created :param",
"if not path.is_dir(full_path): return None try: shutil.rmtree(full_path, onerror=delete_read_only_error) except Exception as exc: logger.warning('Could",
"the path to the temp folder :return: str, path to the temp folder",
"if folder != '': folders.append(folder) else: if path != '': folders.append(path) break folders.reverse()",
"\"\"\" Returns the latest path added to a folder :param folder_path: :param filter_text:",
"found.append(file_path) else: found.append(f) return found def get_files_and_folders(directory): \"\"\" Get files and folders found",
"f in files: file_path = path.join_path(root_folder, f) if path.is_file(file_path=file_path): if full_path: found.append(file_path) else:",
"a new directory :param directory: str, directory to copy with full path :param",
"for root, dirs, files in os.walk(root_directory): yield root, dirs, files num_sep_this = root.count(os.path.sep)",
"copy_directory_contents(path1, path2, *args, **kwargs): \"\"\" Copies all the contents of the given path1",
"folders for :param sort: bool, True if we want sort alphabetically the returned",
"found for filename_and_extension in objs: filename, found_extension = os.path.splitext(filename_and_extension) if filter_text and filename_and_extension.find(filter_text)",
"root, dirs, files num_sep_this = root.count(os.path.sep) if num_sep + level <= num_sep_this: del",
"if make_unique: full_path = path.unique_path_name(directory=full_path) if not full_path: return False if path.is_dir(full_path): return",
"get_folder_size(file_path, round_value) if path.is_file(file_path): size = fileio.get_file_size(file_path, round_value) return size def get_sub_folders(root_folder, sort=True):",
"shutil.move(src, target_directory) else: shutil.move(source_directory, target_directory) except Exception as exc: logger.warning('Failed to move {}",
"if found_extension == extension: if not full_path: found.append(filename_and_extension) else: found.append(os.path.join(root_directory, filename_and_extension)) return found",
":param full_path: bool, Whether to return the file path or just the file",
"search files on :param full_path: bool, if true, full path to the files",
"the folder creation failed \"\"\" from tpDcc.libs.python import path, osplatform full_path = False",
"os.stat(os.path.join(root_folder, fld)).st_mtime return list(sorted(os.listdir(root_folder), key=_get_mtime)) def ensure_folder_exists(folder_path, permissions=0o755, place_holder=False): \"\"\" Checks that folder",
"recursive: bool, Whether to search in all root folder child folders or not",
"sorted in the directory \"\"\" def _get_mtime(fld): return os.stat(os.path.join(root_folder, fld)).st_mtime return list(sorted(os.listdir(root_folder), key=_get_mtime))",
"children of path \"{}\" | {}'.format(full_path, exc)) return full_path def clean_folder(directory): \"\"\" Removes",
"folders in the given path :param path: str :return: list<str> \"\"\" folders =",
"not recursive: try: found_folders = next(os.walk(root_folder))[1] except Exception: pass else: try: for root,",
"osplatform.is_linux(): cmd = ['rsync', directory, directory_destination, '-azr'] elif osplatform.is_windows(): cmd = [ 'robocopy',",
"root_directory = root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory) if level is None: for root, dirs, files",
"the given name :param name: str, name of the new directory :param directory:",
"os.walk(root_folder): for d in dirs: if full_path: folder_name = path.join_path(root, d) found_folders.append(folder_name) else:",
"path to open \"\"\" if path is None: path = os.path.curdir if sys.platform",
"path[:-1] new_path = path.replace('/', '\\\\') try: subprocess.check_call(['explorer', new_path], shell=False) except Exception: pass def",
"size = get_folder_size(file_path, round_value) if path.is_file(file_path): size = fileio.get_file_size(file_path, round_value) return size def",
"permissions)) os.makedirs(folder_path, permissions) if place_holder: place_path = os.path.join(folder_path, 'placeholder') if not os.path.exists(place_path): with",
"folder dates sorted found in the given root directory :param root_folder: str, directory",
"not, folder is created. :param folder_path: str, folder path to check or created",
"return True def delete_folder(folder_name, directory=None): \"\"\" Deletes the folder by name in the",
"str :param round_value: int, value to round size to :return: str \"\"\" from",
"str, name of the folder to delete :param directory: str, the directory path",
"given all py and text extension files will be ignored during the copy",
"is None: full_path = name if not name: full_path = directory if name",
"bool, Whether to search in all root folder child folders or not :return:",
"def create_folder(name, directory=None, make_unique=False): \"\"\" Creates a new folder on the given path",
"from tpDcc.libs.python import python, path, fileio skip_names = python.force_list(skip_names) size = 0 for",
"path != '': folders.append(path) break folders.reverse() return folders def get_folders_date_sorted(root_folder): \"\"\" Returns folder",
"version = version.VersionFile(directory) if version.updated_old: continue if folder.startswith('.'): continue folder_path = path.join_path(directory, folder)",
"path2: str :param args: :param kwargs: :return: \"\"\" try: copy_tree(path1, path2, *args, **kwargs)",
"\"\"\" Get path to the user folder :return: str, path to the user",
"the directory we want to rename :param name: str, new name of the",
"return False if path.is_dir(full_path): return full_path try: os.makedirs(full_path) except Exception: return False osplatform.get_permission(full_path)",
"skip_names: continue for name in files: if name in skip_names: continue size +=",
"= path.join_path(root, d) folder_name = os.path.relpath(folder_name, root_folder) folder_name = path.clean_path(folder_name) found_folders.append(folder_name) except Exception:",
"in files: if name in skip_names: continue size += fileio.get_file_size(path.join_path(root, name), round_value) return",
"bool, Whether to return the file path or just the file names :param",
":param name: str, name of the new directory :param directory: str, path to",
"os.listdir(directory) except Exception: files = list() return files def get_files_with_extension(extension, root_directory, full_path=False, recursive=False,",
"base_directory or directory folders = get_folders(directory) for folder in folders: if folder ==",
"'robocopy', directory.replace('/', '\\\\'), directory_destination.replace('/', '\\\\'), '/S', '/Z', '/MIR'] if cmd: proc = subprocess.Popen(cmd,",
"from tpDcc.libs.python import fileio, path size = 0 if path.is_dir(file_path): size = get_folder_size(file_path,",
"\"\"\" if not os.path.exists(folder_path): try: logger.debug('Creating folder {} [{}]'.format(folder_path, permissions)) os.makedirs(folder_path, permissions) if",
"sorted found in the given directory :param root_directory: str, directory path :param extension:",
"import shutil import fnmatch import logging import tempfile import traceback import subprocess from",
"os.listdir(source_directory) for i in file_list: src = os.path.join(source_directory, i) dest = os.path.join(target_directory, i)",
"want to search sub folders for :param sort: bool, True if we want",
"the renamed folder \"\"\" from tpDcc.libs.python import path, osplatform base_name = path.get_basename(directory=directory) if",
"logger.warning('Failed to move {} to {}: {}'.format(source_directory, target_directory, exc)) return False return True",
"from tpDcc.libs.python import path, version if not path.exists(directory): return found_folders = list() base_directory",
"\"\"\" try: if only_contents or os.path.isdir(target_directory): file_list = os.listdir(source_directory) for i in file_list:",
"try: shutil.rmtree(full_path, onerror=delete_read_only_error) except Exception as exc: logger.warning('Could not remove children of path",
"str, name of the new directory :param directory: str, path to the new",
"round_value=2, skip_names=None): \"\"\" Returns the size of the given folder :param directory: str",
"if not path.is_dir(root_folder): return [] # TODO: For now pattern only works in",
"os.walk(root_directory): yield root, dirs, files num_sep_this = root.count(os.path.sep) if num_sep + level <=",
"the given directory :param directory: str, folder we want to get files and",
"dates sorted found in the given root directory :param root_folder: str, directory path",
"folders from :return: list<str> \"\"\" try: files = os.listdir(directory) except Exception: files =",
"if path.is_dir(directory): try: files = folder.get_files(directory) except Exception: files = list() for f",
"subprocess.check_call(['explorer', new_path], shell=False) except Exception: pass def get_user_folder(absolute=True): \"\"\" Get path to the",
"Checks that folder given folder exists. If not, folder is created. :param folder_path:",
"copying folder elements If ['txt', 'py'] is given all py and text extension",
"name: str, new name of the folder we want to rename :param make_unique:",
"fails \"\"\" if not os.path.exists(folder_path): try: logger.debug('Creating folder {} [{}]'.format(folder_path, permissions)) os.makedirs(folder_path, permissions)",
"return os.stat(os.path.join(root_directory, fld)).st_mtime if not extension: files = fileio.get_files(root_directory, filter_text=filter_text) else: files =",
"in the given directory :param folder_name: str, name of the folder to delete",
"not os.path.exists(folder_path): try: logger.debug('Creating folder {} [{}]'.format(folder_path, permissions)) os.makedirs(folder_path, permissions) if place_holder: place_path",
"osplatform.get_permission(full_path) return full_path def rename_folder(directory, name, make_unique=False): \"\"\" Renames given with a new",
"is None: for root, dirs, files in os.walk(root_directory): yield root, dirs, files else:",
"as exc: logger.warning('Failed to move {} to {}: {}'.format(source_directory, target_directory, exc)) return False",
":param target_directory: str, path where path1 should be move into :param only_contents: bool,",
"[ 'robocopy', directory.replace('/', '\\\\'), directory_destination.replace('/', '\\\\'), '/S', '/Z', '/MIR'] if cmd: proc =",
"path.is_dir(full_path): return full_path try: os.makedirs(full_path) except Exception: return False osplatform.get_permission(full_path) return full_path def",
"if not name: full_path = directory if name and directory: full_path = path.join_path(directory,",
"stderr=subprocess.PIPE, shell=True) out, err = proc.communicate() if out: logger.error(err) else: shutil.copytree(directory, directory_destination) else:",
"extension: if not full_path: found.append(filename_and_extension) else: found.append(os.path.join(root_directory, filename_and_extension)) return found def get_files_date_sorted(root_directory, extension=None,",
"Exception as exc: logger.warning('Could not remove children of path \"{}\" | {}'.format(full_path, exc))",
"name with path or False if the folder creation failed \"\"\" from tpDcc.libs.python",
"onerror=delete_read_only_error) except Exception as exc: logger.warning('Could not remove children of path \"{}\" |",
"round_value=2): \"\"\" Return the size of the given directory or file path :param",
":param make_unique: bool, Whether to pad the name with a number to make",
"continue else: os.remove(dest) shutil.move(src, target_directory) else: shutil.move(source_directory, target_directory) except Exception as exc: logger.warning('Failed",
"current directory will be opened :param path: str, folder path to open \"\"\"",
"\"\"\" found = list() if not extension.startswith('.'): extension = '.{}'.format(extension) if recursive: for",
"search sub folders for :param sort: bool, True if we want sort alphabetically",
"the given path and with the given name :param name: str, name of",
"pointed by source_directory under the directory target_directory :param source_directory: str, folder with full",
"import subprocess from distutils.dir_util import copy_tree logger = logging.getLogger('tpDcc-libs-python') def create_folder(name, directory=None, make_unique=False):",
"folder that was deleted with path \"\"\" from tpDcc.libs.python import name, path, osplatform",
"folder == 'version': version = version.VersionFile(directory) if version.updated_old: continue if folder.startswith('.'): continue folder_path",
"as exc: logger.warning('Could not remove children of path \"{}\" | {}'.format(full_path, exc)) return",
"size of the given folder :param directory: str :param round_value: int, value to",
"**kwargs): \"\"\" Copies all the contents of the given path1 to the folder",
"in dirs: if full_path: folder_name = path.join_path(root, d) found_folders.append(folder_name) else: folder_name = path.join_path(root,",
"or not :raise OSError: raise OSError if the creation of the folder fails",
"exc)) return False return True def copy_directory_contents(path1, path2, *args, **kwargs): \"\"\" Copies all",
"folder_name if directory: full_path = path.join_path(directory, folder_name) if not path.is_dir(full_path): return None try:",
"return directory_destination def move_folder(source_directory, target_directory, only_contents=False): \"\"\" Moves the folder pointed by source_directory",
"unique if the folder is not unique :return: variant, str || bool, folder",
"name, make_unique=False): \"\"\" Renames given with a new name :param directory: str, full",
"from tpDcc.libs.python import path, osplatform if not path.is_dir(directory=directory): return if not ignore_patterns: cmd",
"try: for root, dirs, files in os.walk(root_folder): for d in dirs: if full_path:",
"with given extensions :param extension: str, extension to find (.py, .data, etc) :param",
"errno import shutil import fnmatch import logging import tempfile import traceback import subprocess",
"root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory) if level is None: for root, dirs, files in os.walk(root_directory):",
"pattern only works in recursive searches. Fix it to work on both found",
"folder :param root_folder: str, folder we want to search files on :param full_path:",
"files date sorted found in the given directory :param root_directory: str, directory path",
"path of the renamed folder \"\"\" from tpDcc.libs.python import path, osplatform base_name =",
"path or just the file names :param recursive: bool :param filter_text: str :return:",
"name :param directory: str, full path to the directory we want to rename",
"in file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f) if sort: result.sort() return result def get_folders(root_folder,",
"given extensions :param extension: str, extension to find (.py, .data, etc) :param root_directory:",
"os.path.exists(place_path): with open(place_path, 'wt') as fh: fh.write('Automatically generated place holder file') except OSError",
"in files: file_path = path.join_path(root_folder, f) if path.is_file(file_path=file_path): if full_path: found.append(file_path) else: found.append(f)",
"extension.startswith('.'): extension = '.{}'.format(extension) if recursive: for dir_path, dir_names, file_names in os.walk(root_directory): for",
"base_directory = base_directory or directory folders = get_folders(directory) for folder in folders: if",
"folders.append(path) break folders.reverse() return folders def get_folders_date_sorted(root_folder): \"\"\" Returns folder dates sorted found",
"contents of {0} to {1}'.format(path1, path2)) return False return True def delete_folder(folder_name, directory=None):",
"= path.join_path(directory, folder_name) if not path.is_dir(full_path): return None try: shutil.rmtree(full_path, onerror=delete_read_only_error) except Exception",
"path if absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return path.clean_path(os.path.expanduser('~')) def get_temp_folder(): \"\"\" Get the",
"place holder file') except OSError as err: if err.errno != errno.EEXIST: raise def",
":return: list(str): list of folder date sorted in the directory \"\"\" def _get_mtime(fld):",
"== name: return parent_path = path.get_dirname(directory=directory) rename_path = path.join_path(parent_path, name) if make_unique: rename_path",
"= 0 if path.is_dir(file_path): size = get_folder_size(file_path, round_value) if path.is_file(file_path): size = fileio.get_file_size(file_path,",
"with path or False if the folder creation failed \"\"\" from tpDcc.libs.python import",
"os.makedirs(folder_path, permissions) if place_holder: place_path = os.path.join(folder_path, 'placeholder') if not os.path.exists(place_path): with open(place_path,",
"str, new name of the folder we want to rename :param make_unique: bool,",
"time import errno import shutil import fnmatch import logging import tempfile import traceback",
"in the given root directory :param root_folder: str, directory path :return: list(str): list",
"of {0} to {1}'.format(path1, path2)) return False return True def delete_folder(folder_name, directory=None): \"\"\"",
"int, value to round size to :return: int \"\"\" from tpDcc.libs.python import fileio,",
"name in the given directory :param folder_name: str, name of the folder to",
"files: file_path = path.join_path(root_folder, f) if path.is_file(file_path=file_path): if full_path: found.append(file_path) else: found.append(f) return",
"parent_path = path.get_dirname(directory=directory) rename_path = path.join_path(parent_path, name) if make_unique: rename_path = path.unique_path_name(directory=rename_path) if",
"os.path.relpath(folder_name, root_folder) folder_name = path.clean_path(folder_name) found_folders.append(folder_name) except Exception: return found_folders return found_folders def",
"directory folders = get_folders(directory) for folder in folders: if folder == 'version': version",
"else: shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination def move_folder(source_directory, target_directory, only_contents=False): \"\"\" Moves the",
"fld)).st_mtime if not extension: files = fileio.get_files(root_directory, filter_text=filter_text) else: files = get_files_with_extension(extension=extension, root_directory=root_directory,",
"filename_and_extension in objs: filename, found_extension = os.path.splitext(filename_and_extension) if filter_text and filename_and_extension.find(filter_text) == -1:",
"creation failed \"\"\" from tpDcc.libs.python import path, osplatform full_path = False if directory",
"False if the folder creation failed \"\"\" from tpDcc.libs.python import path, osplatform full_path",
"= path.join_path(root, d) found_folders.append(folder_name) else: folder_name = path.join_path(root, d) folder_name = os.path.relpath(folder_name, root_folder)",
"except Exception: files = list() return files def get_files_with_extension(extension, root_directory, full_path=False, recursive=False, filter_text=''):",
"raise RuntimeError('Folder {0} does not exists!'.format(root_folder)) file_names = os.listdir(root_folder) result = list() for",
"move contents of {0} to {1}'.format(path1, path2)) return False return True def delete_folder(folder_name,",
"import fileio, path size = 0 if path.is_dir(file_path): size = get_folder_size(file_path, round_value) if",
"os.path.isdir(dest): move_folder(src, dest) continue else: os.remove(dest) shutil.move(src, target_directory) else: shutil.move(source_directory, target_directory) except Exception",
"a folder :param folder_path: :param filter_text: :return: str \"\"\" from tpDcc.libs.python import path",
"tpDcc.libs.python import path, version if not path.exists(directory): return found_folders = list() base_directory =",
"want to rename :param name: str, new name of the folder we want",
"directory: str, full path to the directory we want to rename :param name:",
"that folder given folder exists. If not, folder is created. :param folder_path: str,",
"Get folders found in the root folder :param root_folder: str, folder we ant",
"result.append(f) if sort: result.sort() return result def get_folders(root_folder, recursive=False, full_path=False): \"\"\" Get folders",
"in skip_names: continue for name in files: if name in skip_names: continue size",
"path]) elif sys.platform == 'linux2': subprocess.Popen(['xdg-open', path]) elif sys.platform in ['windows', 'win32', 'win64']:",
"name and directory: full_path = path.join_path(directory, name) if make_unique: full_path = path.unique_path_name(directory=full_path) if",
"osplatform.get_permission(directory) message = 'rename: {0} >> {1}'.format(directory, rename_path) logger.info(message) os.rename(directory, rename_path) except Exception:",
"str, directory path :param full_path: bool, Whether to return the file path or",
"int \"\"\" from tpDcc.libs.python import fileio, path size = 0 if path.is_dir(file_path): size",
"passed the current directory will be opened :param path: str, folder path to",
"_get_mtime(fld): return os.stat(os.path.join(root_directory, fld)).st_mtime if not extension: files = fileio.get_files(root_directory, filter_text=filter_text) else: files",
"= name.clean_file_string(folder_name) full_path = folder_name if directory: full_path = path.join_path(directory, folder_name) if not",
"path where the folder is stored :return: str, folder that was deleted with",
"Creates a new folder on the given path and with the given name",
"add a number to the folder name to make it unique :return: str,",
"os.getcwd() def get_folders_from_path(path): \"\"\" Gets a list of sub folders in the given",
"a number to the folder name to make it unique :return: str, path",
"if out: logger.error(err) else: shutil.copytree(directory, directory_destination) else: shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination def",
"if true, full path to the files will be returned otherwise file names",
"directory :param root_folder: str, folder we want to search sub folders for :param",
"returned otherwise file names will be returned :return: list<str> \"\"\" from tpDcc.libs.python import",
"logger = logging.getLogger('tpDcc-libs-python') def create_folder(name, directory=None, make_unique=False): \"\"\" Creates a new folder on",
"the temp folder \"\"\" from tpDcc.libs.python import path return path.clean_path(tempfile.gettempdir()) def get_current_working_directory(): \"\"\"",
"directory.replace('/', '\\\\'), directory_destination.replace('/', '\\\\'), '/S', '/Z', '/MIR'] if cmd: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,",
"str, path to the current working directory \"\"\" return os.getcwd() def get_folders_from_path(path): \"\"\"",
"full path :param target_directory: str, path where path1 should be move into :param",
"folders def get_folders_date_sorted(root_folder): \"\"\" Returns folder dates sorted found in the given root",
"list(sorted(files, key=_get_mtime)) def open_folder(path=None): \"\"\" Opens a folder in the explorer in a",
"remove children of path \"{}\" | {}'.format(full_path, exc)) return full_path def clean_folder(directory): \"\"\"",
"work on both found = list() if recursive: for dir_path, dir_names, file_names in",
"mode :param place_holder: bool, Whether to create place holder text file or not",
"the given path1 to the folder path2. If path2 directory does not exists,",
"dirs, files else: num_sep = root_directory.count(os.path.sep) for root, dirs, files in os.walk(root_directory): yield",
"try: copy_tree(path1, path2, *args, **kwargs) except Exception: logger.warning('Failed to move contents of {0}",
"root_name in skip_names: continue for name in files: if name in skip_names: continue",
"from tpDcc.libs.python import path if absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return path.clean_path(os.path.expanduser('~')) def get_temp_folder():",
"given directory :param folder_name: str, name of the folder to delete :param directory:",
"return size def get_sub_folders(root_folder, sort=True): \"\"\" Return a list with all the sub",
"root, dirs, files in os.walk(root_folder): for d in dirs: if full_path: folder_name =",
"of the folder to delete :param directory: str, the directory path where the",
"folders or False otherwise :return: list<str>, sub folders names \"\"\" if not os.path.exists(root_folder):",
"fh: fh.write('Automatically generated place holder file') except OSError as err: if err.errno !=",
"for dir_path, dir_names, file_names in os.walk(root_directory): for file_name in file_names: filename, found_extension =",
"fileio skip_names = python.force_list(skip_names) size = 0 for root, dirs, files in os.walk(directory):",
"path, osplatform base_name = path.get_basename(directory=directory) if base_name == name: return parent_path = path.get_dirname(directory=directory)",
"root_directory: str, directory path :param extension: str, optional extension to find :param filter_text:",
"read only files \"\"\" osplatform.get_permission(name) action(name) folder_name = name.clean_file_string(folder_name) full_path = folder_name if",
"the file path or just the file names :param recursive: bool :param filter_text:",
"files will be returned otherwise file names will be returned :return: list<str> \"\"\"",
"path :param extension: str, optional extension to find :param filter_text: str, optional text",
"we want to search files on :param full_path: bool, if true, full path",
":param folder_path: :param filter_text: :return: str \"\"\" from tpDcc.libs.python import path files =",
"folder to delete :param directory: str, the directory path where the folder is",
"found_folders.append(folder_name) else: folder_name = path.join_path(root, d) folder_name = os.path.relpath(folder_name, root_folder) folder_name = path.clean_path(folder_name)",
"distutils.dir_util import copy_tree logger = logging.getLogger('tpDcc-libs-python') def create_folder(name, directory=None, make_unique=False): \"\"\" Creates a",
"files: if name in skip_names: continue size += fileio.get_file_size(path.join_path(root, name), round_value) return size",
"Returns folder dates sorted found in the given root directory :param root_folder: str,",
"true, full path to the files will be returned otherwise file names will",
"is None: path = os.path.curdir if sys.platform == 'darwin': subprocess.check_call(['open', '--', path]) elif",
"folders.reverse() return folders def get_folders_date_sorted(root_folder): \"\"\" Returns folder dates sorted found in the",
":param file_path: str :param round_value: int, value to round size to :return: int",
"return list(sorted(files, key=_get_mtime)) def open_folder(path=None): \"\"\" Opens a folder in the explorer in",
"not exists, it will be created :param path1: str :param path2: str :param",
"if only_contents or os.path.isdir(target_directory): file_list = os.listdir(source_directory) for i in file_list: src =",
"list() if not recursive: try: found_folders = next(os.walk(root_folder))[1] except Exception: pass else: try:",
"fileio.get_file_size(file_path, round_value) return size def get_sub_folders(root_folder, sort=True): \"\"\" Return a list with all",
"folder :return: str, path to the user folder \"\"\" from tpDcc.libs.python import path",
"copy_folder(directory, directory_destination, ignore_patterns=[]): \"\"\" Copy the given directory into a new directory :param",
"make it unique if the folder is not unique :return: variant, str ||",
"= [ 'robocopy', directory.replace('/', '\\\\'), directory_destination.replace('/', '\\\\'), '/S', '/Z', '/MIR'] if cmd: proc",
"Returns file in given directory with given extensions :param extension: str, extension to",
"was successfully \"\"\" try: if only_contents or os.path.isdir(target_directory): file_list = os.listdir(source_directory) for i",
"related to folders \"\"\" from __future__ import print_function, division, absolute_import import os import",
"list<str>, extensions we want to ignore when copying folder elements If ['txt', 'py']",
"if name and directory: full_path = path.join_path(directory, name) if make_unique: full_path = path.unique_path_name(directory=full_path)",
"or directory folders = get_folders(directory) for folder in folders: if folder == 'version':",
"path, version if not path.exists(directory): return found_folders = list() base_directory = base_directory or",
"round size to :return: str \"\"\" from tpDcc.libs.python import python, path, fileio skip_names",
"to round size to :return: str \"\"\" from tpDcc.libs.python import python, path, fileio",
"extension: str, extension to find (.py, .data, etc) :param root_directory: str, directory path",
"path to the directory we want to rename :param name: str, new name",
"want to rename :param make_unique: bool, Whether to add a number to the",
"to the current working directory \"\"\" return os.getcwd() def get_folders_from_path(path): \"\"\" Gets a",
"subprocess.Popen(['xdg-open', path]) elif sys.platform in ['windows', 'win32', 'win64']: if path.endswith('/'): path = path[:-1]",
"except Exception: logger.error('{}'.format(traceback.format_exc())) return False return rename_path def copy_folder(directory, directory_destination, ignore_patterns=[]): \"\"\" Copy",
"returned folders or False otherwise :return: list<str>, sub folders names \"\"\" if not",
"str :return: list(str) \"\"\" found = list() if not extension.startswith('.'): extension = '.{}'.format(extension)",
"folder on the given path and with the given name :param name: str,",
"otherwise :return: list<str>, sub folders names \"\"\" if not os.path.exists(root_folder): raise RuntimeError('Folder {0}",
"else: shutil.move(source_directory, target_directory) except Exception as exc: logger.warning('Failed to move {} to {}:",
"does not exists, it will be created :param path1: str :param path2: str",
"directory_destination, '-azr'] elif osplatform.is_windows(): cmd = [ 'robocopy', directory.replace('/', '\\\\'), directory_destination.replace('/', '\\\\'), '/S',",
":param extension: str, extension to find (.py, .data, etc) :param root_directory: str, directory",
"= list() for f in files: fileio.delete_file(f, directory) delete_folder(base_name, dir_name) if not path.is_dir(directory):",
"\"\"\" from tpDcc.libs.python import fileio, path size = 0 if path.is_dir(file_path): size =",
"the name with a number to make it unique if the folder is",
"path :param path: str :return: list<str> \"\"\" folders = list() while True: path,",
"to copy with full path :param directory_destination: str, destination directory :param ignore_patterns: list<str>,",
"int, value to round size to :return: str \"\"\" from tpDcc.libs.python import python,",
"= '.{}'.format(extension) if recursive: for dir_path, dir_names, file_names in os.walk(root_directory): for file_name in",
"= os.path.splitext(filename_and_extension) if filter_text and filename_and_extension.find(filter_text) == -1: continue if found_extension == extension:",
"import time import errno import shutil import fnmatch import logging import tempfile import",
"Returns current working directory :return: str, path to the current working directory \"\"\"",
"make_unique: full_path = path.unique_path_name(directory=full_path) if not full_path: return False if path.is_dir(full_path): return full_path",
"if path.is_dir(full_path): return full_path try: os.makedirs(full_path) except Exception: return False osplatform.get_permission(full_path) return full_path",
"file_name in fnmatch.filter(file_names, pattern): if full_path: found.append(path.join_path(dir_path, file_name)) else: found.append(file_name) else: files =",
"import traceback import subprocess from distutils.dir_util import copy_tree logger = logging.getLogger('tpDcc-libs-python') def create_folder(name,",
"the size of the given directory or file path :param file_path: str :param",
"os.path.exists(root_folder): raise RuntimeError('Folder {0} does not exists!'.format(root_folder)) file_names = os.listdir(root_folder) result = list()",
"root_directory=root_directory, filter_text=filter_text) return list(sorted(files, key=_get_mtime)) def open_folder(path=None): \"\"\" Opens a folder in the",
"objs: filename, found_extension = os.path.splitext(filename_and_extension) if filter_text and filename_and_extension.find(filter_text) == -1: continue if",
"path files = get_files_date_sorted(folder_path, filter_text=filter_text) if not files: return None return path.join_path(folder_path, files[-1])",
"Get path to the user folder :return: str, path to the user folder",
"file in given directory with given extensions :param extension: str, extension to find",
"a number to make it unique if the folder is not unique :return:",
"fileio def _get_mtime(fld): return os.stat(os.path.join(root_directory, fld)).st_mtime if not extension: files = fileio.get_files(root_directory, filter_text=filter_text)",
"full_path = directory if name and directory: full_path = path.join_path(directory, name) if make_unique:",
"os.path.exists(folder_path): try: logger.debug('Creating folder {} [{}]'.format(folder_path, permissions)) os.makedirs(folder_path, permissions) if place_holder: place_path =",
"= list() if recursive: for dir_path, dir_names, file_names in os.walk(root_folder): for file_name in",
"path.is_dir(full_path): return None try: shutil.rmtree(full_path, onerror=delete_read_only_error) except Exception as exc: logger.warning('Could not remove",
"files else: num_sep = root_directory.count(os.path.sep) for root, dirs, files in os.walk(root_directory): yield root,",
"fileio.get_files(root_directory, filter_text=filter_text) else: files = get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text) return list(sorted(files, key=_get_mtime)) def open_folder(path=None):",
"return found_folders def get_files(root_folder, full_path=False, recursive=False, pattern=\"*\"): \"\"\" Returns files found in the",
"find :param filter_text: str, optional text filtering :return: list(str), list of files date",
"base_name == name: return parent_path = path.get_dirname(directory=directory) rename_path = path.join_path(parent_path, name) if make_unique:",
"sub folders names \"\"\" if not os.path.exists(root_folder): raise RuntimeError('Folder {0} does not exists!'.format(root_folder))",
"= fileio.get_file_size(file_path, round_value) return size def get_sub_folders(root_folder, sort=True): \"\"\" Return a list with",
"tpDcc.libs.python import fileio, path size = 0 if path.is_dir(file_path): size = get_folder_size(file_path, round_value)",
"size = 0 if path.is_dir(file_path): size = get_folder_size(file_path, round_value) if path.is_file(file_path): size =",
"a directory :param root_folder: str, folder we want to search sub folders for",
"directory to copy with full path :param directory_destination: str, destination directory :param ignore_patterns:",
"directory does not exists, it will be created :param path1: str :param path2:",
"name.clean_file_string(folder_name) full_path = folder_name if directory: full_path = path.join_path(directory, folder_name) if not path.is_dir(full_path):",
"logging import tempfile import traceback import subprocess from distutils.dir_util import copy_tree logger =",
"|| bool, folder name with path or False if the folder creation failed",
"os.makedirs(full_path) except Exception: return False osplatform.get_permission(full_path) return full_path def rename_folder(directory, name, make_unique=False): \"\"\"",
"str, folder we want to search files on :param full_path: bool, if true,",
"path.join_path(folder_path, files[-1]) def walk_level(root_directory, level=None): root_directory = root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory) if level is",
"Whether to create place holder text file or not :raise OSError: raise OSError",
"files in os.walk(root_directory): yield root, dirs, files else: num_sep = root_directory.count(os.path.sep) for root,",
"directory \"\"\" from tpDcc.libs.python import fileio def _get_mtime(fld): return os.stat(os.path.join(root_directory, fld)).st_mtime if not",
"as fh: fh.write('Automatically generated place holder file') except OSError as err: if err.errno",
"shutil.copytree(directory, directory_destination) else: shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination def move_folder(source_directory, target_directory, only_contents=False): \"\"\"",
"full_path: folder_name = path.join_path(root, d) found_folders.append(folder_name) else: folder_name = path.join_path(root, d) folder_name =",
"str :param args: :param kwargs: :return: \"\"\" try: copy_tree(path1, path2, *args, **kwargs) except",
"Exception: logger.warning('Failed to move contents of {0} to {1}'.format(path1, path2)) return False return",
"= os.listdir(root_folder) result = list() for f in file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f)",
"rename_path) logger.info(message) os.rename(directory, rename_path) except Exception: time.sleep(0.1) try: os.rename(directory, rename_path) except Exception: logger.error('{}'.format(traceback.format_exc()))",
"folder pointed by source_directory under the directory target_directory :param source_directory: str, folder with",
"path if not path.is_dir(root_folder): return [] # TODO: For now pattern only works",
"working directory :return: str, path to the current working directory \"\"\" return os.getcwd()",
"of the folder fails \"\"\" if not os.path.exists(folder_path): try: logger.debug('Creating folder {} [{}]'.format(folder_path,",
"text file or not :raise OSError: raise OSError if the creation of the",
":return: list<str>, sub folders names \"\"\" if not os.path.exists(root_folder): raise RuntimeError('Folder {0} does",
"d in dirs: if full_path: folder_name = path.join_path(root, d) found_folders.append(folder_name) else: folder_name =",
"pass else: try: for root, dirs, files in os.walk(root_folder): for d in dirs:",
"elif osplatform.is_windows(): cmd = [ 'robocopy', directory.replace('/', '\\\\'), directory_destination.replace('/', '\\\\'), '/S', '/Z', '/MIR']",
"get_current_working_directory(): \"\"\" Returns current working directory :return: str, path to the current working",
"filter_text: str, optional text filtering :return: list(str), list of files date sorted in",
"= path.get_basename(directory=directory) if base_name == name: return parent_path = path.get_dirname(directory=directory) rename_path = path.join_path(parent_path,",
"contents :return: bool, Whether the move operation was successfully \"\"\" try: if only_contents",
"file_list: src = os.path.join(source_directory, i) dest = os.path.join(target_directory, i) if os.path.exists(dest): if os.path.isdir(dest):",
"Deletes the folder by name in the given directory :param folder_name: str, name",
"round_value: int, value to round size to :return: str \"\"\" from tpDcc.libs.python import",
"folder given folder exists. If not, folder is created. :param folder_path: str, folder",
"path2. If path2 directory does not exists, it will be created :param path1:",
"copy operation :return: str, destination directory \"\"\" from tpDcc.libs.python import path, osplatform if",
"not unique :return: variant, str || bool, folder name with path or False",
"cmd = [ 'robocopy', directory.replace('/', '\\\\'), directory_destination.replace('/', '\\\\'), '/S', '/Z', '/MIR'] if cmd:",
"with a new name :param directory: str, full path to the directory we",
"True def delete_folder(folder_name, directory=None): \"\"\" Deletes the folder by name in the given",
"\"\"\" from tpDcc.libs.python import path if not path.is_dir(root_folder): return [] # TODO: For",
"\"\"\" Returns the size of the given folder :param directory: str :param round_value:",
"directory :return: str, path to the current working directory \"\"\" return os.getcwd() def",
"dirs: if full_path: folder_name = path.join_path(root, d) found_folders.append(folder_name) else: folder_name = path.join_path(root, d)",
"\"\"\" from tpDcc.libs.python import path return path.clean_path(tempfile.gettempdir()) def get_current_working_directory(): \"\"\" Returns current working",
"path.get_basename(directory=directory) dir_name = path.get_dirname(directory=directory) if path.is_dir(directory): try: files = folder.get_files(directory) except Exception: files",
":return: str, path to the temp folder \"\"\" from tpDcc.libs.python import path return",
"return rename_path def copy_folder(directory, directory_destination, ignore_patterns=[]): \"\"\" Copy the given directory into a",
"If path2 directory does not exists, it will be created :param path1: str",
"files = list() for f in files: fileio.delete_file(f, directory) delete_folder(base_name, dir_name) if not",
"successfully \"\"\" try: if only_contents or os.path.isdir(target_directory): file_list = os.listdir(source_directory) for i in",
"Exception: pass else: try: for root, dirs, files in os.walk(root_folder): for d in",
"'win64']: if path.endswith('/'): path = path[:-1] new_path = path.replace('/', '\\\\') try: subprocess.check_call(['explorer', new_path],",
"return [] # TODO: For now pattern only works in recursive searches. Fix",
"Exception: time.sleep(0.1) try: os.rename(directory, rename_path) except Exception: logger.error('{}'.format(traceback.format_exc())) return False return rename_path def",
"try: os.makedirs(full_path) except Exception: return False osplatform.get_permission(full_path) return full_path def rename_folder(directory, name, make_unique=False):",
"files in os.walk(directory): root_name = path.get_basename(root) if root_name in skip_names: continue for name",
"py and text extension files will be ignored during the copy operation :return:",
"while True: path, folder = os.path.split(path) if folder != '': folders.append(folder) else: if",
"its contents :return: bool, Whether the move operation was successfully \"\"\" try: if",
"'wt') as fh: fh.write('Automatically generated place holder file') except OSError as err: if",
"cmd = ['rsync', directory, directory_destination, '-azr'] elif osplatform.is_windows(): cmd = [ 'robocopy', directory.replace('/',",
"found_extension == '{}'.format(extension): if not full_path: found.append(file_name) else: found.append(os.path.join(root_directory, file_name)) else: try: objs",
"if folder == 'version': version = version.VersionFile(directory) if version.updated_old: continue if folder.startswith('.'): continue",
":param round_value: int, value to round size to :return: str \"\"\" from tpDcc.libs.python",
"we ant to search folders on :param recursive: bool, Whether to search in",
"= os.path.join(source_directory, i) dest = os.path.join(target_directory, i) if os.path.exists(dest): if os.path.isdir(dest): move_folder(src, dest)",
"return False osplatform.get_permission(full_path) return full_path def rename_folder(directory, name, make_unique=False): \"\"\" Renames given with",
"\"\"\" Returns files found in the given folder :param root_folder: str, folder we",
"os.path.exists(dest): if os.path.isdir(dest): move_folder(src, dest) continue else: os.remove(dest) shutil.move(src, target_directory) else: shutil.move(source_directory, target_directory)",
"to the folder name to make it unique :return: str, path of the",
"with full path :param directory_destination: str, destination directory :param ignore_patterns: list<str>, extensions we",
"file') except OSError as err: if err.errno != errno.EEXIST: raise def get_latest_file_at_folder(folder_path, filter_text=''):",
"\"\"\" osplatform.get_permission(name) action(name) folder_name = name.clean_file_string(folder_name) full_path = folder_name if directory: full_path =",
"except Exception: time.sleep(0.1) try: os.rename(directory, rename_path) except Exception: logger.error('{}'.format(traceback.format_exc())) return False return rename_path",
"the latest path added to a folder :param folder_path: :param filter_text: :return: str",
"path :param full_path: bool, Whether to return the file path or just the",
"def get_folders_date_sorted(root_folder): \"\"\" Returns folder dates sorted found in the given root directory",
"if not files: return None return path.join_path(folder_path, files[-1]) def walk_level(root_directory, level=None): root_directory =",
"added to a folder :param folder_path: :param filter_text: :return: str \"\"\" from tpDcc.libs.python",
"to delete read only files \"\"\" osplatform.get_permission(name) action(name) folder_name = name.clean_file_string(folder_name) full_path =",
"Copies all the contents of the given path1 to the folder path2. If",
"dirs, files in os.walk(directory): root_name = path.get_basename(root) if root_name in skip_names: continue for",
"found_folders def get_files(root_folder, full_path=False, recursive=False, pattern=\"*\"): \"\"\" Returns files found in the given",
"delete read only files \"\"\" osplatform.get_permission(name) action(name) folder_name = name.clean_file_string(folder_name) full_path = folder_name",
"import tempfile import traceback import subprocess from distutils.dir_util import copy_tree logger = logging.getLogger('tpDcc-libs-python')",
"folder :param directory: str :param round_value: int, value to round size to :return:",
"the user folder :return: str, path to the user folder \"\"\" from tpDcc.libs.python",
"directory_destination, ignore_patterns=[]): \"\"\" Copy the given directory into a new directory :param directory:",
"name) if make_unique: rename_path = path.unique_path_name(directory=rename_path) if path.exists(rename_path): return False try: osplatform.get_permission(directory) message",
"folder or only its contents :return: bool, Whether the move operation was successfully",
"rename_path = path.unique_path_name(directory=rename_path) if path.exists(rename_path): return False try: osplatform.get_permission(directory) message = 'rename: {0}",
"try: osplatform.get_permission(directory) message = 'rename: {0} >> {1}'.format(directory, rename_path) logger.info(message) os.rename(directory, rename_path) except",
"'.{}'.format(extension) if recursive: for dir_path, dir_names, file_names in os.walk(root_directory): for file_name in file_names:",
"\"\"\" try: files = os.listdir(directory) except Exception: files = list() return files def",
"of the given folder :param directory: str :param round_value: int, value to round",
"round_value) return size def get_size(file_path, round_value=2): \"\"\" Return the size of the given",
"the copy operation :return: str, destination directory \"\"\" from tpDcc.libs.python import path, osplatform",
"a new folder on the given path and with the given name :param",
"root_directory: str, directory path :param full_path: bool, Whether to return the file path",
"make_unique=False): \"\"\" Creates a new folder on the given path and with the",
"absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return path.clean_path(os.path.expanduser('~')) def get_temp_folder(): \"\"\" Get the path to",
"def _get_mtime(fld): return os.stat(os.path.join(root_folder, fld)).st_mtime return list(sorted(os.listdir(root_folder), key=_get_mtime)) def ensure_folder_exists(folder_path, permissions=0o755, place_holder=False): \"\"\"",
"directory path :param extension: str, optional extension to find :param filter_text: str, optional",
"tpDcc.libs.python import path, fileio, folder base_name = path.get_basename(directory=directory) dir_name = path.get_dirname(directory=directory) if path.is_dir(directory):",
"move_folder(src, dest) continue else: os.remove(dest) shutil.move(src, target_directory) else: shutil.move(source_directory, target_directory) except Exception as",
"return False try: osplatform.get_permission(directory) message = 'rename: {0} >> {1}'.format(directory, rename_path) logger.info(message) os.rename(directory,",
"the given directory into a new directory :param directory: str, directory to copy",
"path.replace('/', '\\\\') try: subprocess.check_call(['explorer', new_path], shell=False) except Exception: pass def get_user_folder(absolute=True): \"\"\" Get",
"folders or not :return: list<str> \"\"\" from tpDcc.libs.python import path found_folders = list()",
"new name :param directory: str, full path to the directory we want to",
"for root, dirs, files in os.walk(root_directory): yield root, dirs, files else: num_sep =",
"folder in folders: if folder == 'version': version = version.VersionFile(directory) if version.updated_old: continue",
"= base_directory or directory folders = get_folders(directory) for folder in folders: if folder",
"date sorted in the directory \"\"\" def _get_mtime(fld): return os.stat(os.path.join(root_folder, fld)).st_mtime return list(sorted(os.listdir(root_folder),",
"try: files = folder.get_files(directory) except Exception: files = list() for f in files:",
"get_user_folder(absolute=True): \"\"\" Get path to the user folder :return: str, path to the",
"base_name = path.get_basename(directory=directory) if base_name == name: return parent_path = path.get_dirname(directory=directory) rename_path =",
"files = list() return files def get_files_with_extension(extension, root_directory, full_path=False, recursive=False, filter_text=''): \"\"\" Returns",
"opened :param path: str, folder path to open \"\"\" if path is None:",
"Exception: return found_folders return found_folders def get_folders_without_dot_prefix(directory, recursive=False, base_directory=None): from tpDcc.libs.python import path,",
"path.get_basename(directory=directory) if base_name == name: return parent_path = path.get_dirname(directory=directory) rename_path = path.join_path(parent_path, name)",
"to round size to :return: int \"\"\" from tpDcc.libs.python import fileio, path size",
"copy_tree logger = logging.getLogger('tpDcc-libs-python') def create_folder(name, directory=None, make_unique=False): \"\"\" Creates a new folder",
"not full_path: return False if path.is_dir(full_path): return full_path try: os.makedirs(full_path) except Exception: return",
"logger.debug('Creating folder {} [{}]'.format(folder_path, permissions)) os.makedirs(folder_path, permissions) if place_holder: place_path = os.path.join(folder_path, 'placeholder')",
"directory: str :param round_value: int, value to round size to :return: str \"\"\"",
"round_value: int, value to round size to :return: int \"\"\" from tpDcc.libs.python import",
"list(str): list of folder date sorted in the directory \"\"\" def _get_mtime(fld): return",
"version.VersionFile(directory) if version.updated_old: continue if folder.startswith('.'): continue folder_path = path.join_path(directory, folder) folder_name =",
"rename_path def copy_folder(directory, directory_destination, ignore_patterns=[]): \"\"\" Copy the given directory into a new",
"\"\"\" from tpDcc.libs.python import path found_folders = list() if not recursive: try: found_folders",
"list with all the sub folders names on a directory :param root_folder: str,",
"= path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name) if recursive: sub_folders = get_folders_without_dot_prefix( folder_path, recursive=recursive, base_directory=base_directory) found_folders",
"given folder :param directory: str :param round_value: int, value to round size to",
":return: str, path to the user folder \"\"\" from tpDcc.libs.python import path if",
"import path, osplatform base_name = path.get_basename(directory=directory) if base_name == name: return parent_path =",
"folder we want to search files on :param full_path: bool, if true, full",
"sorted in the directory \"\"\" from tpDcc.libs.python import fileio def _get_mtime(fld): return os.stat(os.path.join(root_directory,",
"size def get_size(file_path, round_value=2): \"\"\" Return the size of the given directory or",
"target_directory: str, path where path1 should be move into :param only_contents: bool, Whether",
"rename :param make_unique: bool, Whether to add a number to the folder name",
"directory_destination: str, destination directory :param ignore_patterns: list<str>, extensions we want to ignore when",
"list(str) \"\"\" found = list() if not extension.startswith('.'): extension = '.{}'.format(extension) if recursive:",
"folder base_name = path.get_basename(directory=directory) dir_name = path.get_dirname(directory=directory) if path.is_dir(directory): try: files = folder.get_files(directory)",
"independent platform way If not path is passed the current directory will be",
"False osplatform.get_permission(full_path) return full_path def rename_folder(directory, name, make_unique=False): \"\"\" Renames given with a",
"extension = '.{}'.format(extension) if recursive: for dir_path, dir_names, file_names in os.walk(root_directory): for file_name",
"the given path :param path: str :return: list<str> \"\"\" folders = list() while",
"full_path: bool, Whether to return the file path or just the file names",
"directory if name and directory: full_path = path.join_path(directory, name) if make_unique: full_path =",
"= path[:-1] new_path = path.replace('/', '\\\\') try: subprocess.check_call(['explorer', new_path], shell=False) except Exception: pass",
"alphabetically the returned folders or False otherwise :return: list<str>, sub folders names \"\"\"",
"\"\"\" from tpDcc.libs.python import path, fileio, folder base_name = path.get_basename(directory=directory) dir_name = path.get_dirname(directory=directory)",
"if recursive: for dir_path, dir_names, file_names in os.walk(root_folder): for file_name in fnmatch.filter(file_names, pattern):",
"tpDcc.libs.python import path if absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return path.clean_path(os.path.expanduser('~')) def get_temp_folder(): \"\"\"",
"if folder.startswith('.'): continue folder_path = path.join_path(directory, folder) folder_name = path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name) if",
"directory :param directory: str, path to the new directory :param make_unique: bool, Whether",
"check or created :param permissions:int, folder permission mode :param place_holder: bool, Whether to",
"both found = list() if recursive: for dir_path, dir_names, file_names in os.walk(root_folder): for",
"tpDcc.libs.python import path found_folders = list() if not recursive: try: found_folders = next(os.walk(root_folder))[1]",
"folder in the explorer in a independent platform way If not path is",
"files and folders found in the given directory :param directory: str, folder we",
"was deleted with path \"\"\" from tpDcc.libs.python import name, path, osplatform def delete_read_only_error(action,",
"create_folder(name, directory=None, make_unique=False): \"\"\" Creates a new folder on the given path and",
"out, err = proc.communicate() if out: logger.error(err) else: shutil.copytree(directory, directory_destination) else: shutil.copytree(directory, directory_destination,",
"os.path.join(folder_path, 'placeholder') if not os.path.exists(place_path): with open(place_path, 'wt') as fh: fh.write('Automatically generated place",
"bool, folder name with path or False if the folder creation failed \"\"\"",
"python # -*- coding: utf-8 -*- \"\"\" Utility methods related to folders \"\"\"",
"Get the path to the temp folder :return: str, path to the temp",
"to the files will be returned otherwise file names will be returned :return:",
"import path files = get_files_date_sorted(folder_path, filter_text=filter_text) if not files: return None return path.join_path(folder_path,",
"the folder by name in the given directory :param folder_name: str, name of",
"the move operation was successfully \"\"\" try: if only_contents or os.path.isdir(target_directory): file_list =",
"f) if path.is_file(file_path=file_path): if full_path: found.append(file_path) else: found.append(f) return found def get_files_and_folders(directory): \"\"\"",
"if full_path: found.append(file_path) else: found.append(f) return found def get_files_and_folders(directory): \"\"\" Get files and",
"in fnmatch.filter(file_names, pattern): if full_path: found.append(path.join_path(dir_path, file_name)) else: found.append(file_name) else: files = os.listdir(root_folder)",
"sorted found in the given root directory :param root_folder: str, directory path :return:",
"path.clean_path(os.path.expanduser('~')) def get_temp_folder(): \"\"\" Get the path to the temp folder :return: str,",
"full_path = path.join_path(directory, name) if make_unique: full_path = path.unique_path_name(directory=full_path) if not full_path: return",
"to delete :param directory: str, the directory path where the folder is stored",
"return size def get_size(file_path, round_value=2): \"\"\" Return the size of the given directory",
"path to check or created :param permissions:int, folder permission mode :param place_holder: bool,",
"directory: str \"\"\" from tpDcc.libs.python import path, fileio, folder base_name = path.get_basename(directory=directory) dir_name",
"folder we ant to search folders on :param recursive: bool, Whether to search",
">> {1}'.format(directory, rename_path) logger.info(message) os.rename(directory, rename_path) except Exception: time.sleep(0.1) try: os.rename(directory, rename_path) except",
"= path.join_path(directory, folder) folder_name = path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name) if recursive: sub_folders = get_folders_without_dot_prefix(",
"the current directory will be opened :param path: str, folder path to open",
"if found_extension == '{}'.format(extension): if not full_path: found.append(file_name) else: found.append(os.path.join(root_directory, file_name)) else: try:",
"\"\"\" Checks that folder given folder exists. If not, folder is created. :param",
"if absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return path.clean_path(os.path.expanduser('~')) def get_temp_folder(): \"\"\" Get the path",
":return: str \"\"\" from tpDcc.libs.python import path files = get_files_date_sorted(folder_path, filter_text=filter_text) if not",
"path.clean_path(folder_name) found_folders.append(folder_name) except Exception: return found_folders return found_folders def get_folders_without_dot_prefix(directory, recursive=False, base_directory=None): from",
"recursive: for dir_path, dir_names, file_names in os.walk(root_folder): for file_name in fnmatch.filter(file_names, pattern): if",
"root, dirs, files in os.walk(root_directory): yield root, dirs, files else: num_sep = root_directory.count(os.path.sep)",
"if not ignore_patterns: cmd = None if osplatform.is_linux(): cmd = ['rsync', directory, directory_destination,",
"names \"\"\" if not os.path.exists(root_folder): raise RuntimeError('Folder {0} does not exists!'.format(root_folder)) file_names =",
"exc): \"\"\" Helper to delete read only files \"\"\" osplatform.get_permission(name) action(name) folder_name =",
"found_folders return found_folders def get_folders_without_dot_prefix(directory, recursive=False, base_directory=None): from tpDcc.libs.python import path, version if",
"yield root, dirs, files num_sep_this = root.count(os.path.sep) if num_sep + level <= num_sep_this:",
"filename, found_extension = os.path.splitext(file_name) if found_extension == '{}'.format(extension): if not full_path: found.append(file_name) else:",
"next(os.walk(root_folder))[1] except Exception: pass else: try: for root, dirs, files in os.walk(root_folder): for",
"in os.walk(root_directory): for file_name in file_names: filename, found_extension = os.path.splitext(file_name) if found_extension ==",
"current working directory \"\"\" return os.getcwd() def get_folders_from_path(path): \"\"\" Gets a list of",
"new_path], shell=False) except Exception: pass def get_user_folder(absolute=True): \"\"\" Get path to the user",
"Returns the latest path added to a folder :param folder_path: :param filter_text: :return:",
"open \"\"\" if path is None: path = os.path.curdir if sys.platform == 'darwin':",
"= os.path.split(path) if folder != '': folders.append(folder) else: if path != '': folders.append(path)",
"sort alphabetically the returned folders or False otherwise :return: list<str>, sub folders names",
"filter_text: str :return: list(str) \"\"\" found = list() if not extension.startswith('.'): extension =",
"= path.get_basename(directory=directory) dir_name = path.get_dirname(directory=directory) if path.is_dir(directory): try: files = folder.get_files(directory) except Exception:",
":return: list(str) \"\"\" found = list() if not extension.startswith('.'): extension = '.{}'.format(extension) if",
"def open_folder(path=None): \"\"\" Opens a folder in the explorer in a independent platform",
"path.is_file(file_path=file_path): if full_path: found.append(file_path) else: found.append(f) return found def get_files_and_folders(directory): \"\"\" Get files",
"recursive: try: found_folders = next(os.walk(root_folder))[1] except Exception: pass else: try: for root, dirs,",
"not remove children of path \"{}\" | {}'.format(full_path, exc)) return full_path def clean_folder(directory):",
"str, extension to find (.py, .data, etc) :param root_directory: str, directory path :param",
"place holder text file or not :raise OSError: raise OSError if the creation",
"fileio, path size = 0 if path.is_dir(file_path): size = get_folder_size(file_path, round_value) if path.is_file(file_path):",
"path.unique_path_name(directory=full_path) if not full_path: return False if path.is_dir(full_path): return full_path try: os.makedirs(full_path) except",
"found def get_files_and_folders(directory): \"\"\" Get files and folders found in the given directory",
"pattern): if full_path: found.append(path.join_path(dir_path, file_name)) else: found.append(file_name) else: files = os.listdir(root_folder) for f",
"on a directory :param root_folder: str, folder we want to search sub folders",
"operation was successfully \"\"\" try: if only_contents or os.path.isdir(target_directory): file_list = os.listdir(source_directory) for",
"full path :param directory_destination: str, destination directory :param ignore_patterns: list<str>, extensions we want",
"def get_folders(root_folder, recursive=False, full_path=False): \"\"\" Get folders found in the root folder :param",
"filename_and_extension.find(filter_text) == -1: continue if found_extension == extension: if not full_path: found.append(filename_and_extension) else:",
"path.join_path(root, d) found_folders.append(folder_name) else: folder_name = path.join_path(root, d) folder_name = os.path.relpath(folder_name, root_folder) folder_name",
"if make_unique: rename_path = path.unique_path_name(directory=rename_path) if path.exists(rename_path): return False try: osplatform.get_permission(directory) message =",
"directory :param directory: str \"\"\" from tpDcc.libs.python import path, fileio, folder base_name =",
"return None return path.join_path(folder_path, files[-1]) def walk_level(root_directory, level=None): root_directory = root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory)",
"\"\"\" from tpDcc.libs.python import path, osplatform base_name = path.get_basename(directory=directory) if base_name == name:",
"from distutils.dir_util import copy_tree logger = logging.getLogger('tpDcc-libs-python') def create_folder(name, directory=None, make_unique=False): \"\"\" Creates",
"found.append(os.path.join(root_directory, filename_and_extension)) return found def get_files_date_sorted(root_directory, extension=None, filter_text=''): \"\"\" Returns files date sorted",
"of the new directory :param directory: str, path to the new directory :param",
"elif sys.platform in ['windows', 'win32', 'win64']: if path.endswith('/'): path = path[:-1] new_path =",
"if level is None: for root, dirs, files in os.walk(root_directory): yield root, dirs,",
"in a independent platform way If not path is passed the current directory",
"get_folders_without_dot_prefix( folder_path, recursive=recursive, base_directory=base_directory) found_folders += sub_folders return found_folders def get_files(root_folder, full_path=False, recursive=False,",
"given name :param name: str, name of the new directory :param directory: str,",
"+= fileio.get_file_size(path.join_path(root, name), round_value) return size def get_size(file_path, round_value=2): \"\"\" Return the size",
"names will be returned :return: list<str> \"\"\" from tpDcc.libs.python import path if not",
"on the given path and with the given name :param name: str, name",
"raise def get_latest_file_at_folder(folder_path, filter_text=''): \"\"\" Returns the latest path added to a folder",
"to folders \"\"\" from __future__ import print_function, division, absolute_import import os import sys",
"if not os.path.exists(root_folder): raise RuntimeError('Folder {0} does not exists!'.format(root_folder)) file_names = os.listdir(root_folder) result",
"to create place holder text file or not :raise OSError: raise OSError if",
"else: found.append(file_name) else: files = os.listdir(root_folder) for f in files: file_path = path.join_path(root_folder,",
"else: found.append(os.path.join(root_directory, filename_and_extension)) return found def get_files_date_sorted(root_directory, extension=None, filter_text=''): \"\"\" Returns files date",
"recursive: bool :param filter_text: str :return: list(str) \"\"\" found = list() if not",
"ignored during the copy operation :return: str, destination directory \"\"\" from tpDcc.libs.python import",
"folder :param root_folder: str, folder we ant to search folders on :param recursive:",
"if not os.path.exists(place_path): with open(place_path, 'wt') as fh: fh.write('Automatically generated place holder file')",
"except Exception: return found_folders return found_folders def get_folders_without_dot_prefix(directory, recursive=False, base_directory=None): from tpDcc.libs.python import",
"user folder :return: str, path to the user folder \"\"\" from tpDcc.libs.python import",
"is stored :return: str, folder that was deleted with path \"\"\" from tpDcc.libs.python",
"full_path: bool, if true, full path to the files will be returned otherwise",
"try: files = os.listdir(directory) except Exception: files = list() return files def get_files_with_extension(extension,",
"folder_name = path.join_path(root, d) found_folders.append(folder_name) else: folder_name = path.join_path(root, d) folder_name = os.path.relpath(folder_name,",
"'': folders.append(folder) else: if path != '': folders.append(path) break folders.reverse() return folders def",
"str, full path to the directory we want to rename :param name: str,",
"path2)) return False return True def delete_folder(folder_name, directory=None): \"\"\" Deletes the folder by",
"name, path, osplatform def delete_read_only_error(action, name, exc): \"\"\" Helper to delete read only",
"given directory or file path :param file_path: str :param round_value: int, value to",
"TODO: For now pattern only works in recursive searches. Fix it to work",
"Returns files found in the given folder :param root_folder: str, folder we want",
"return path.clean_path(os.path.expanduser('~')) def get_temp_folder(): \"\"\" Get the path to the temp folder :return:",
"if not os.path.exists(folder_path): try: logger.debug('Creating folder {} [{}]'.format(folder_path, permissions)) os.makedirs(folder_path, permissions) if place_holder:",
"if the creation of the folder fails \"\"\" if not os.path.exists(folder_path): try: logger.debug('Creating",
"directory: str, folder we want to get files and folders from :return: list<str>",
"os.stat(os.path.join(root_directory, fld)).st_mtime if not extension: files = fileio.get_files(root_directory, filter_text=filter_text) else: files = get_files_with_extension(extension=extension,",
"= ['rsync', directory, directory_destination, '-azr'] elif osplatform.is_windows(): cmd = [ 'robocopy', directory.replace('/', '\\\\'),",
"from tpDcc.libs.python import fileio def _get_mtime(fld): return os.stat(os.path.join(root_directory, fld)).st_mtime if not extension: files",
"traceback import subprocess from distutils.dir_util import copy_tree logger = logging.getLogger('tpDcc-libs-python') def create_folder(name, directory=None,",
"file_path = path.join_path(root_folder, f) if path.is_file(file_path=file_path): if full_path: found.append(file_path) else: found.append(f) return found",
"level is None: for root, dirs, files in os.walk(root_directory): yield root, dirs, files",
"if path.is_file(file_path): size = fileio.get_file_size(file_path, round_value) return size def get_sub_folders(root_folder, sort=True): \"\"\" Return",
"action(name) folder_name = name.clean_file_string(folder_name) full_path = folder_name if directory: full_path = path.join_path(directory, folder_name)",
"= python.force_list(skip_names) size = 0 for root, dirs, files in os.walk(directory): root_name =",
"directory \"\"\" def _get_mtime(fld): return os.stat(os.path.join(root_folder, fld)).st_mtime return list(sorted(os.listdir(root_folder), key=_get_mtime)) def ensure_folder_exists(folder_path, permissions=0o755,",
"of the folder we want to rename :param make_unique: bool, Whether to add",
"dir_name) def get_folder_size(directory, round_value=2, skip_names=None): \"\"\" Returns the size of the given folder",
"root_folder: str, folder we want to search files on :param full_path: bool, if",
"filename_and_extension)) return found def get_files_date_sorted(root_directory, extension=None, filter_text=''): \"\"\" Returns files date sorted found",
"new directory :param make_unique: bool, Whether to pad the name with a number",
"given path :param path: str :return: list<str> \"\"\" folders = list() while True:",
"{1}'.format(path1, path2)) return False return True def delete_folder(folder_name, directory=None): \"\"\" Deletes the folder",
"for folder in folders: if folder == 'version': version = version.VersionFile(directory) if version.updated_old:",
"recursive searches. Fix it to work on both found = list() if recursive:",
"import os import sys import time import errno import shutil import fnmatch import",
"filter_text=filter_text) if not files: return None return path.join_path(folder_path, files[-1]) def walk_level(root_directory, level=None): root_directory",
"the explorer in a independent platform way If not path is passed the",
"exists, it will be created :param path1: str :param path2: str :param args:",
"None return path.join_path(folder_path, files[-1]) def walk_level(root_directory, level=None): root_directory = root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory) if",
"to move {} to {}: {}'.format(source_directory, target_directory, exc)) return False return True def",
"path.get_dirname(directory=directory) if path.is_dir(directory): try: files = folder.get_files(directory) except Exception: files = list() for",
"\"\"\" return os.getcwd() def get_folders_from_path(path): \"\"\" Gets a list of sub folders in",
"be created :param path1: str :param path2: str :param args: :param kwargs: :return:",
"new_path = path.replace('/', '\\\\') try: subprocess.check_call(['explorer', new_path], shell=False) except Exception: pass def get_user_folder(absolute=True):",
"False return True def delete_folder(folder_name, directory=None): \"\"\" Deletes the folder by name in",
"result.sort() return result def get_folders(root_folder, recursive=False, full_path=False): \"\"\" Get folders found in the",
"\"\"\" Moves the folder pointed by source_directory under the directory target_directory :param source_directory:",
"where the folder is stored :return: str, folder that was deleted with path",
"src = os.path.join(source_directory, i) dest = os.path.join(target_directory, i) if os.path.exists(dest): if os.path.isdir(dest): move_folder(src,",
"'linux2': subprocess.Popen(['xdg-open', path]) elif sys.platform in ['windows', 'win32', 'win64']: if path.endswith('/'): path =",
"files on :param full_path: bool, if true, full path to the files will",
"\"\"\" from tpDcc.libs.python import python, path, fileio skip_names = python.force_list(skip_names) size = 0",
"platform way If not path is passed the current directory will be opened",
"name to make it unique :return: str, path of the renamed folder \"\"\"",
"recursive: sub_folders = get_folders_without_dot_prefix( folder_path, recursive=recursive, base_directory=base_directory) found_folders += sub_folders return found_folders def",
"tpDcc.libs.python import name, path, osplatform def delete_read_only_error(action, name, exc): \"\"\" Helper to delete",
"from tpDcc.libs.python import path, fileio, folder base_name = path.get_basename(directory=directory) dir_name = path.get_dirname(directory=directory) if",
"If not, folder is created. :param folder_path: str, folder path to check or",
"name of the folder we want to rename :param make_unique: bool, Whether to",
"\"\"\" from tpDcc.libs.python import name, path, osplatform def delete_read_only_error(action, name, exc): \"\"\" Helper",
"file_name)) else: found.append(file_name) else: files = os.listdir(root_folder) for f in files: file_path =",
"target_directory) else: shutil.move(source_directory, target_directory) except Exception as exc: logger.warning('Failed to move {} to",
"if path.is_file(file_path=file_path): if full_path: found.append(file_path) else: found.append(f) return found def get_files_and_folders(directory): \"\"\" Get",
"name, exc): \"\"\" Helper to delete read only files \"\"\" osplatform.get_permission(name) action(name) folder_name",
"recursive=False, base_directory=None): from tpDcc.libs.python import path, version if not path.exists(directory): return found_folders =",
"Exception: return False osplatform.get_permission(full_path) return full_path def rename_folder(directory, name, make_unique=False): \"\"\" Renames given",
"= path.join_path(root_folder, f) if path.is_file(file_path=file_path): if full_path: found.append(file_path) else: found.append(f) return found def",
"on :param full_path: bool, if true, full path to the files will be",
"if not extension.startswith('.'): extension = '.{}'.format(extension) if recursive: for dir_path, dir_names, file_names in",
"folder we want to rename :param make_unique: bool, Whether to add a number",
"except Exception as exc: logger.warning('Failed to move {} to {}: {}'.format(source_directory, target_directory, exc))",
"dirs, files num_sep_this = root.count(os.path.sep) if num_sep + level <= num_sep_this: del dirs[:]",
"\"\"\" Utility methods related to folders \"\"\" from __future__ import print_function, division, absolute_import",
"not path.is_dir(directory=directory): return if not ignore_patterns: cmd = None if osplatform.is_linux(): cmd =",
"path is None: path = os.path.curdir if sys.platform == 'darwin': subprocess.check_call(['open', '--', path])",
"with the given name :param name: str, name of the new directory :param",
"path.join_path(root, d) folder_name = os.path.relpath(folder_name, root_folder) folder_name = path.clean_path(folder_name) found_folders.append(folder_name) except Exception: return",
"= path.join_path(directory, name) if make_unique: full_path = path.unique_path_name(directory=full_path) if not full_path: return False",
"skip_names = python.force_list(skip_names) size = 0 for root, dirs, files in os.walk(directory): root_name",
"renamed folder \"\"\" from tpDcc.libs.python import path, osplatform base_name = path.get_basename(directory=directory) if base_name",
"dir_name = path.get_dirname(directory=directory) if path.is_dir(directory): try: files = folder.get_files(directory) except Exception: files =",
"Renames given with a new name :param directory: str, full path to the",
"= os.listdir(root_folder) for f in files: file_path = path.join_path(root_folder, f) if path.is_file(file_path=file_path): if",
"works in recursive searches. Fix it to work on both found = list()",
"extensions we want to ignore when copying folder elements If ['txt', 'py'] is",
"\"\"\" Return a list with all the sub folders names on a directory",
"to the user folder :return: str, path to the user folder \"\"\" from",
"logger.warning('Failed to move contents of {0} to {1}'.format(path1, path2)) return False return True",
"if recursive: for dir_path, dir_names, file_names in os.walk(root_directory): for file_name in file_names: filename,",
"folders found in the given directory :param directory: str, folder we want to",
"== 'version': version = version.VersionFile(directory) if version.updated_old: continue if folder.startswith('.'): continue folder_path =",
"folders = list() while True: path, folder = os.path.split(path) if folder != '':",
"path.join_path(directory, name) if make_unique: full_path = path.unique_path_name(directory=full_path) if not full_path: return False if",
"fnmatch.filter(file_names, pattern): if full_path: found.append(path.join_path(dir_path, file_name)) else: found.append(file_name) else: files = os.listdir(root_folder) for",
"of sub folders in the given path :param path: str :return: list<str> \"\"\"",
"or just the file names :param recursive: bool :param filter_text: str :return: list(str)",
"def get_files_date_sorted(root_directory, extension=None, filter_text=''): \"\"\" Returns files date sorted found in the given",
"str, directory path :return: list(str): list of folder date sorted in the directory",
"now pattern only works in recursive searches. Fix it to work on both",
"= version.VersionFile(directory) if version.updated_old: continue if folder.startswith('.'): continue folder_path = path.join_path(directory, folder) folder_name",
"for dir_path, dir_names, file_names in os.walk(root_folder): for file_name in fnmatch.filter(file_names, pattern): if full_path:",
":param place_holder: bool, Whether to create place holder text file or not :raise",
"get files and folders from :return: list<str> \"\"\" try: files = os.listdir(directory) except",
"in os.walk(root_folder): for d in dirs: if full_path: folder_name = path.join_path(root, d) found_folders.append(folder_name)",
"fileio, folder base_name = path.get_basename(directory=directory) dir_name = path.get_dirname(directory=directory) if path.is_dir(directory): try: files =",
"str \"\"\" from tpDcc.libs.python import path, fileio, folder base_name = path.get_basename(directory=directory) dir_name =",
"searches. Fix it to work on both found = list() if recursive: for",
"file path or just the file names :param recursive: bool :param filter_text: str",
"time.sleep(0.1) try: os.rename(directory, rename_path) except Exception: logger.error('{}'.format(traceback.format_exc())) return False return rename_path def copy_folder(directory,",
"or file path :param file_path: str :param round_value: int, value to round size",
"== extension: if not full_path: found.append(filename_and_extension) else: found.append(os.path.join(root_directory, filename_and_extension)) return found def get_files_date_sorted(root_directory,",
"full_path def clean_folder(directory): \"\"\" Removes everything in the given directory :param directory: str",
"filter_text=''): \"\"\" Returns files date sorted found in the given directory :param root_directory:",
"else: files = os.listdir(root_folder) for f in files: file_path = path.join_path(root_folder, f) if",
"directory \"\"\" from tpDcc.libs.python import path, osplatform if not path.is_dir(directory=directory): return if not",
"logger.error('{}'.format(traceback.format_exc())) return False return rename_path def copy_folder(directory, directory_destination, ignore_patterns=[]): \"\"\" Copy the given",
"root_folder: str, directory path :return: list(str): list of folder date sorted in the",
"| {}'.format(full_path, exc)) return full_path def clean_folder(directory): \"\"\" Removes everything in the given",
"of files date sorted in the directory \"\"\" from tpDcc.libs.python import fileio def",
"str, path to the new directory :param make_unique: bool, Whether to pad the",
":return: list<str> \"\"\" try: files = os.listdir(directory) except Exception: files = list() return",
"the contents of the given path1 to the folder path2. If path2 directory",
"else: found.append(f) return found def get_files_and_folders(directory): \"\"\" Get files and folders found in",
"folder permission mode :param place_holder: bool, Whether to create place holder text file",
"except OSError as err: if err.errno != errno.EEXIST: raise def get_latest_file_at_folder(folder_path, filter_text=''): \"\"\"",
"the new directory :param make_unique: bool, Whether to pad the name with a",
"if sort: result.sort() return result def get_folders(root_folder, recursive=False, full_path=False): \"\"\" Get folders found",
"to search in all root folder child folders or not :return: list<str> \"\"\"",
"try: if only_contents or os.path.isdir(target_directory): file_list = os.listdir(source_directory) for i in file_list: src",
"rename :param name: str, new name of the folder we want to rename",
"= list() while True: path, folder = os.path.split(path) if folder != '': folders.append(folder)",
"{}: {}'.format(source_directory, target_directory, exc)) return False return True def copy_directory_contents(path1, path2, *args, **kwargs):",
"root_directory, full_path=False, recursive=False, filter_text=''): \"\"\" Returns file in given directory with given extensions",
"not full_path: found.append(filename_and_extension) else: found.append(os.path.join(root_directory, filename_and_extension)) return found def get_files_date_sorted(root_directory, extension=None, filter_text=''): \"\"\"",
"return found for filename_and_extension in objs: filename, found_extension = os.path.splitext(filename_and_extension) if filter_text and",
"Exception as exc: logger.warning('Failed to move {} to {}: {}'.format(source_directory, target_directory, exc)) return",
"name: return parent_path = path.get_dirname(directory=directory) rename_path = path.join_path(parent_path, name) if make_unique: rename_path =",
"os.path.split(path) if folder != '': folders.append(folder) else: if path != '': folders.append(path) break",
"osplatform full_path = False if directory is None: full_path = name if not",
":param source_directory: str, folder with full path :param target_directory: str, path where path1",
"from __future__ import print_function, division, absolute_import import os import sys import time import",
"holder file') except OSError as err: if err.errno != errno.EEXIST: raise def get_latest_file_at_folder(folder_path,",
"i in file_list: src = os.path.join(source_directory, i) dest = os.path.join(target_directory, i) if os.path.exists(dest):",
"list<str> \"\"\" from tpDcc.libs.python import path found_folders = list() if not recursive: try:",
"= root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory) if level is None: for root, dirs, files in",
"0 if path.is_dir(file_path): size = get_folder_size(file_path, round_value) if path.is_file(file_path): size = fileio.get_file_size(file_path, round_value)",
"None if osplatform.is_linux(): cmd = ['rsync', directory, directory_destination, '-azr'] elif osplatform.is_windows(): cmd =",
"except Exception: pass def get_user_folder(absolute=True): \"\"\" Get path to the user folder :return:",
"def get_files_with_extension(extension, root_directory, full_path=False, recursive=False, filter_text=''): \"\"\" Returns file in given directory with",
"if place_holder: place_path = os.path.join(folder_path, 'placeholder') if not os.path.exists(place_path): with open(place_path, 'wt') as",
"'/Z', '/MIR'] if cmd: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err =",
"to check or created :param permissions:int, folder permission mode :param place_holder: bool, Whether",
"args: :param kwargs: :return: \"\"\" try: copy_tree(path1, path2, *args, **kwargs) except Exception: logger.warning('Failed",
"deleted with path \"\"\" from tpDcc.libs.python import name, path, osplatform def delete_read_only_error(action, name,",
"to move contents of {0} to {1}'.format(path1, path2)) return False return True def",
"list(sorted(os.listdir(root_folder), key=_get_mtime)) def ensure_folder_exists(folder_path, permissions=0o755, place_holder=False): \"\"\" Checks that folder given folder exists.",
"creation of the folder fails \"\"\" if not os.path.exists(folder_path): try: logger.debug('Creating folder {}",
":return: str, folder that was deleted with path \"\"\" from tpDcc.libs.python import name,",
"new directory :param directory: str, directory to copy with full path :param directory_destination:",
"want sort alphabetically the returned folders or False otherwise :return: list<str>, sub folders",
"path :param file_path: str :param round_value: int, value to round size to :return:",
"size of the given directory or file path :param file_path: str :param round_value:",
"we want to search sub folders for :param sort: bool, True if we",
"errno.EEXIST: raise def get_latest_file_at_folder(folder_path, filter_text=''): \"\"\" Returns the latest path added to a",
"folders found in the root folder :param root_folder: str, folder we ant to",
"Exception: files = list() return files def get_files_with_extension(extension, root_directory, full_path=False, recursive=False, filter_text=''): \"\"\"",
"os.listdir(root_folder) for f in files: file_path = path.join_path(root_folder, f) if path.is_file(file_path=file_path): if full_path:",
"the directory \"\"\" from tpDcc.libs.python import fileio def _get_mtime(fld): return os.stat(os.path.join(root_directory, fld)).st_mtime if",
"try: os.rename(directory, rename_path) except Exception: logger.error('{}'.format(traceback.format_exc())) return False return rename_path def copy_folder(directory, directory_destination,",
"not ignore_patterns: cmd = None if osplatform.is_linux(): cmd = ['rsync', directory, directory_destination, '-azr']",
"when copying folder elements If ['txt', 'py'] is given all py and text",
"move the folder or only its contents :return: bool, Whether the move operation",
"Exception: logger.error('{}'.format(traceback.format_exc())) return False return rename_path def copy_folder(directory, directory_destination, ignore_patterns=[]): \"\"\" Copy the",
"\"\"\" Copy the given directory into a new directory :param directory: str, directory",
"to the user folder \"\"\" from tpDcc.libs.python import path if absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~')))",
"is created. :param folder_path: str, folder path to check or created :param permissions:int,",
"the file names :param recursive: bool :param filter_text: str :return: list(str) \"\"\" found",
"by name in the given directory :param folder_name: str, name of the folder",
"directory path :return: list(str): list of folder date sorted in the directory \"\"\"",
"os.path.splitext(file_name) if found_extension == '{}'.format(extension): if not full_path: found.append(file_name) else: found.append(os.path.join(root_directory, file_name)) else:",
"found_folders.append(folder_name) except Exception: return found_folders return found_folders def get_folders_without_dot_prefix(directory, recursive=False, base_directory=None): from tpDcc.libs.python",
"if the folder creation failed \"\"\" from tpDcc.libs.python import path, osplatform full_path =",
"to {1}'.format(path1, path2)) return False return True def delete_folder(folder_name, directory=None): \"\"\" Deletes the",
"OSError: raise OSError if the creation of the folder fails \"\"\" if not",
"directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination def move_folder(source_directory, target_directory, only_contents=False): \"\"\" Moves the folder pointed",
"\"\"\" Returns current working directory :return: str, path to the current working directory",
"sys.platform in ['windows', 'win32', 'win64']: if path.endswith('/'): path = path[:-1] new_path = path.replace('/',",
"rename_path) except Exception: logger.error('{}'.format(traceback.format_exc())) return False return rename_path def copy_folder(directory, directory_destination, ignore_patterns=[]): \"\"\"",
"str :param path2: str :param args: :param kwargs: :return: \"\"\" try: copy_tree(path1, path2,",
"\"\"\" from tpDcc.libs.python import path files = get_files_date_sorted(folder_path, filter_text=filter_text) if not files: return",
"def get_folder_size(directory, round_value=2, skip_names=None): \"\"\" Returns the size of the given folder :param",
"Whether to move the folder or only its contents :return: bool, Whether the",
"= 'rename: {0} >> {1}'.format(directory, rename_path) logger.info(message) os.rename(directory, rename_path) except Exception: time.sleep(0.1) try:",
"'/S', '/Z', '/MIR'] if cmd: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err",
"from tpDcc.libs.python import path files = get_files_date_sorted(folder_path, filter_text=filter_text) if not files: return None",
"fnmatch import logging import tempfile import traceback import subprocess from distutils.dir_util import copy_tree",
"'py'] is given all py and text extension files will be ignored during",
"get_size(file_path, round_value=2): \"\"\" Return the size of the given directory or file path",
"temp folder \"\"\" from tpDcc.libs.python import path return path.clean_path(tempfile.gettempdir()) def get_current_working_directory(): \"\"\" Returns",
"OSError if the creation of the folder fails \"\"\" if not os.path.exists(folder_path): try:",
"pad the name with a number to make it unique if the folder",
"files = get_files_date_sorted(folder_path, filter_text=filter_text) if not files: return None return path.join_path(folder_path, files[-1]) def",
":param root_directory: str, directory path :param full_path: bool, Whether to return the file",
"folder :param folder_path: :param filter_text: :return: str \"\"\" from tpDcc.libs.python import path files",
":param root_directory: str, directory path :param extension: str, optional extension to find :param",
"tpDcc.libs.python import path, osplatform full_path = False if directory is None: full_path =",
"\"\"\" from tpDcc.libs.python import path if absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return path.clean_path(os.path.expanduser('~')) def",
"in os.walk(directory): root_name = path.get_basename(root) if root_name in skip_names: continue for name in",
"from tpDcc.libs.python import path found_folders = list() if not recursive: try: found_folders =",
"utf-8 -*- \"\"\" Utility methods related to folders \"\"\" from __future__ import print_function,",
"will be returned otherwise file names will be returned :return: list<str> \"\"\" from",
"in file_names: filename, found_extension = os.path.splitext(file_name) if found_extension == '{}'.format(extension): if not full_path:",
"['windows', 'win32', 'win64']: if path.endswith('/'): path = path[:-1] new_path = path.replace('/', '\\\\') try:",
"make_unique: bool, Whether to add a number to the folder name to make",
"{} [{}]'.format(folder_path, permissions)) os.makedirs(folder_path, permissions) if place_holder: place_path = os.path.join(folder_path, 'placeholder') if not",
"name if not name: full_path = directory if name and directory: full_path =",
"directory: str, directory to copy with full path :param directory_destination: str, destination directory",
":return: list<str> \"\"\" from tpDcc.libs.python import path found_folders = list() if not recursive:",
"found in the given folder :param root_folder: str, folder we want to search",
"full path to the directory we want to rename :param name: str, new",
"\"\"\" Get files and folders found in the given directory :param directory: str,",
"by source_directory under the directory target_directory :param source_directory: str, folder with full path",
"to the folder path2. If path2 directory does not exists, it will be",
"generated place holder file') except OSError as err: if err.errno != errno.EEXIST: raise",
"get_files_and_folders(directory): \"\"\" Get files and folders found in the given directory :param directory:",
"try: objs = os.listdir(root_directory) except Exception: return found for filename_and_extension in objs: filename,",
"Whether to return the file path or just the file names :param recursive:",
"in the given directory :param directory: str \"\"\" from tpDcc.libs.python import path, fileio,",
"path to the current working directory \"\"\" return os.getcwd() def get_folders_from_path(path): \"\"\" Gets",
"sub folders for :param sort: bool, True if we want sort alphabetically the",
"0 for root, dirs, files in os.walk(directory): root_name = path.get_basename(root) if root_name in",
"path.endswith('/'): path = path[:-1] new_path = path.replace('/', '\\\\') try: subprocess.check_call(['explorer', new_path], shell=False) except",
"from tpDcc.libs.python import path return path.clean_path(tempfile.gettempdir()) def get_current_working_directory(): \"\"\" Returns current working directory",
"of the renamed folder \"\"\" from tpDcc.libs.python import path, osplatform base_name = path.get_basename(directory=directory)",
"folder_name: str, name of the folder to delete :param directory: str, the directory",
"import sys import time import errno import shutil import fnmatch import logging import",
"for root, dirs, files in os.walk(root_folder): for d in dirs: if full_path: folder_name",
"new folder on the given path and with the given name :param name:",
"folders \"\"\" from __future__ import print_function, division, absolute_import import os import sys import",
":return: str, path to the current working directory \"\"\" return os.getcwd() def get_folders_from_path(path):",
"list() for f in file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f) if sort: result.sort() return",
"a list of sub folders in the given path :param path: str :return:",
"in os.walk(root_directory): yield root, dirs, files num_sep_this = root.count(os.path.sep) if num_sep + level",
"name), round_value) return size def get_size(file_path, round_value=2): \"\"\" Return the size of the",
"tpDcc.libs.python import path, osplatform base_name = path.get_basename(directory=directory) if base_name == name: return parent_path",
"Exception: return found for filename_and_extension in objs: filename, found_extension = os.path.splitext(filename_and_extension) if filter_text",
"or False otherwise :return: list<str>, sub folders names \"\"\" if not os.path.exists(root_folder): raise",
"rename_path) except Exception: time.sleep(0.1) try: os.rename(directory, rename_path) except Exception: logger.error('{}'.format(traceback.format_exc())) return False return",
"target_directory) except Exception as exc: logger.warning('Failed to move {} to {}: {}'.format(source_directory, target_directory,",
"cmd = None if osplatform.is_linux(): cmd = ['rsync', directory, directory_destination, '-azr'] elif osplatform.is_windows():",
"will be created :param path1: str :param path2: str :param args: :param kwargs:",
"tpDcc.libs.python import fileio def _get_mtime(fld): return os.stat(os.path.join(root_directory, fld)).st_mtime if not extension: files =",
"os.walk(root_directory): yield root, dirs, files else: num_sep = root_directory.count(os.path.sep) for root, dirs, files",
"get_folders_date_sorted(root_folder): \"\"\" Returns folder dates sorted found in the given root directory :param",
"err = proc.communicate() if out: logger.error(err) else: shutil.copytree(directory, directory_destination) else: shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns))",
"return found def get_files_date_sorted(root_directory, extension=None, filter_text=''): \"\"\" Returns files date sorted found in",
"directory) delete_folder(base_name, dir_name) if not path.is_dir(directory): create_folder(base_name, dir_name) def get_folder_size(directory, round_value=2, skip_names=None): \"\"\"",
"optional text filtering :return: list(str), list of files date sorted in the directory",
"given directory into a new directory :param directory: str, directory to copy with",
"if directory: full_path = path.join_path(directory, folder_name) if not path.is_dir(full_path): return None try: shutil.rmtree(full_path,",
"import path, osplatform if not path.is_dir(directory=directory): return if not ignore_patterns: cmd = None",
"path.exists(rename_path): return False try: osplatform.get_permission(directory) message = 'rename: {0} >> {1}'.format(directory, rename_path) logger.info(message)",
"files: return None return path.join_path(folder_path, files[-1]) def walk_level(root_directory, level=None): root_directory = root_directory.rstrip(os.path.sep) assert",
"full_path=False, recursive=False, filter_text=''): \"\"\" Returns file in given directory with given extensions :param",
"\"\"\" Helper to delete read only files \"\"\" osplatform.get_permission(name) action(name) folder_name = name.clean_file_string(folder_name)",
"only works in recursive searches. Fix it to work on both found =",
"the given directory or file path :param file_path: str :param round_value: int, value",
"= path.join_path(parent_path, name) if make_unique: rename_path = path.unique_path_name(directory=rename_path) if path.exists(rename_path): return False try:",
"'darwin': subprocess.check_call(['open', '--', path]) elif sys.platform == 'linux2': subprocess.Popen(['xdg-open', path]) elif sys.platform in",
"search folders on :param recursive: bool, Whether to search in all root folder",
"RuntimeError('Folder {0} does not exists!'.format(root_folder)) file_names = os.listdir(root_folder) result = list() for f",
"given directory with given extensions :param extension: str, extension to find (.py, .data,",
"osplatform def delete_read_only_error(action, name, exc): \"\"\" Helper to delete read only files \"\"\"",
"the given directory :param root_directory: str, directory path :param extension: str, optional extension",
"if path.is_dir(file_path): size = get_folder_size(file_path, round_value) if path.is_file(file_path): size = fileio.get_file_size(file_path, round_value) return",
"if recursive: sub_folders = get_folders_without_dot_prefix( folder_path, recursive=recursive, base_directory=base_directory) found_folders += sub_folders return found_folders",
"\"\"\" if not os.path.exists(root_folder): raise RuntimeError('Folder {0} does not exists!'.format(root_folder)) file_names = os.listdir(root_folder)",
"everything in the given directory :param directory: str \"\"\" from tpDcc.libs.python import path,",
"list<str> \"\"\" folders = list() while True: path, folder = os.path.split(path) if folder",
"full path to the files will be returned otherwise file names will be",
"str, folder we want to search sub folders for :param sort: bool, True",
"folder_path: :param filter_text: :return: str \"\"\" from tpDcc.libs.python import path files = get_files_date_sorted(folder_path,",
"in os.walk(root_directory): yield root, dirs, files else: num_sep = root_directory.count(os.path.sep) for root, dirs,",
"folder exists. If not, folder is created. :param folder_path: str, folder path to",
"file or not :raise OSError: raise OSError if the creation of the folder",
"to :return: str \"\"\" from tpDcc.libs.python import python, path, fileio skip_names = python.force_list(skip_names)",
"\"\"\" Returns file in given directory with given extensions :param extension: str, extension",
"open(place_path, 'wt') as fh: fh.write('Automatically generated place holder file') except OSError as err:",
"want to get files and folders from :return: list<str> \"\"\" try: files =",
"folder_name = name.clean_file_string(folder_name) full_path = folder_name if directory: full_path = path.join_path(directory, folder_name) if",
"round_value) if path.is_file(file_path): size = fileio.get_file_size(file_path, round_value) return size def get_sub_folders(root_folder, sort=True): \"\"\"",
"str, folder we want to get files and folders from :return: list<str> \"\"\"",
"files will be ignored during the copy operation :return: str, destination directory \"\"\"",
"folder name with path or False if the folder creation failed \"\"\" from",
"folders: if folder == 'version': version = version.VersionFile(directory) if version.updated_old: continue if folder.startswith('.'):",
"folder {} [{}]'.format(folder_path, permissions)) os.makedirs(folder_path, permissions) if place_holder: place_path = os.path.join(folder_path, 'placeholder') if",
"continue folder_path = path.join_path(directory, folder) folder_name = path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name) if recursive: sub_folders",
"str, optional extension to find :param filter_text: str, optional text filtering :return: list(str),",
"directory: str, path to the new directory :param make_unique: bool, Whether to pad",
"with open(place_path, 'wt') as fh: fh.write('Automatically generated place holder file') except OSError as",
"root_name = path.get_basename(root) if root_name in skip_names: continue for name in files: if",
"if path != '': folders.append(path) break folders.reverse() return folders def get_folders_date_sorted(root_folder): \"\"\" Returns",
"from tpDcc.libs.python import name, path, osplatform def delete_read_only_error(action, name, exc): \"\"\" Helper to",
":param directory: str, path to the new directory :param make_unique: bool, Whether to",
"folder with full path :param target_directory: str, path where path1 should be move",
"Whether the move operation was successfully \"\"\" try: if only_contents or os.path.isdir(target_directory): file_list",
"= path.get_basename(root) if root_name in skip_names: continue for name in files: if name",
"folder) folder_name = path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name) if recursive: sub_folders = get_folders_without_dot_prefix( folder_path, recursive=recursive,",
"raise OSError if the creation of the folder fails \"\"\" if not os.path.exists(folder_path):",
"root, dirs, files in os.walk(directory): root_name = path.get_basename(root) if root_name in skip_names: continue",
"it to work on both found = list() if recursive: for dir_path, dir_names,",
"= directory if name and directory: full_path = path.join_path(directory, name) if make_unique: full_path",
"str, folder we ant to search folders on :param recursive: bool, Whether to",
"found_folders = list() base_directory = base_directory or directory folders = get_folders(directory) for folder",
"we want to rename :param name: str, new name of the folder we",
"base_directory)) found_folders.append(folder_name) if recursive: sub_folders = get_folders_without_dot_prefix( folder_path, recursive=recursive, base_directory=base_directory) found_folders += sub_folders",
"import logging import tempfile import traceback import subprocess from distutils.dir_util import copy_tree logger",
"directory is None: full_path = name if not name: full_path = directory if",
"objs = os.listdir(root_directory) except Exception: return found for filename_and_extension in objs: filename, found_extension",
":return: list(str), list of files date sorted in the directory \"\"\" from tpDcc.libs.python",
"directory :param make_unique: bool, Whether to pad the name with a number to",
"path.get_basename(root) if root_name in skip_names: continue for name in files: if name in",
"for d in dirs: if full_path: folder_name = path.join_path(root, d) found_folders.append(folder_name) else: folder_name",
"i) dest = os.path.join(target_directory, i) if os.path.exists(dest): if os.path.isdir(dest): move_folder(src, dest) continue else:",
"the given root directory :param root_folder: str, directory path :return: list(str): list of",
"path.join_path(directory, folder) folder_name = path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name) if recursive: sub_folders = get_folders_without_dot_prefix( folder_path,",
"proc.communicate() if out: logger.error(err) else: shutil.copytree(directory, directory_destination) else: shutil.copytree(directory, directory_destination, ignore=shutil.ignore_patterns(ignore_patterns)) return directory_destination",
"return True def copy_directory_contents(path1, path2, *args, **kwargs): \"\"\" Copies all the contents of",
"\"\"\" Deletes the folder by name in the given directory :param folder_name: str,",
"base_directory=base_directory) found_folders += sub_folders return found_folders def get_files(root_folder, full_path=False, recursive=False, pattern=\"*\"): \"\"\" Returns",
"return found_folders = list() base_directory = base_directory or directory folders = get_folders(directory) for",
"if path.endswith('/'): path = path[:-1] new_path = path.replace('/', '\\\\') try: subprocess.check_call(['explorer', new_path], shell=False)",
"returned :return: list<str> \"\"\" from tpDcc.libs.python import path if not path.is_dir(root_folder): return []",
"path where path1 should be move into :param only_contents: bool, Whether to move",
"str \"\"\" from tpDcc.libs.python import path files = get_files_date_sorted(folder_path, filter_text=filter_text) if not files:",
"bool, if true, full path to the files will be returned otherwise file",
"os.rename(directory, rename_path) except Exception: logger.error('{}'.format(traceback.format_exc())) return False return rename_path def copy_folder(directory, directory_destination, ignore_patterns=[]):",
"if sys.platform == 'darwin': subprocess.check_call(['open', '--', path]) elif sys.platform == 'linux2': subprocess.Popen(['xdg-open', path])",
":param directory: str, the directory path where the folder is stored :return: str,",
"# -*- coding: utf-8 -*- \"\"\" Utility methods related to folders \"\"\" from",
"exists!'.format(root_folder)) file_names = os.listdir(root_folder) result = list() for f in file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder),",
"result = list() for f in file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f) if sort:",
"from tpDcc.libs.python import path, osplatform full_path = False if directory is None: full_path",
"Get files and folders found in the given directory :param directory: str, folder",
"import fnmatch import logging import tempfile import traceback import subprocess from distutils.dir_util import",
"= list() if not recursive: try: found_folders = next(os.walk(root_folder))[1] except Exception: pass else:",
"folder_name = path.join_path(root, d) folder_name = os.path.relpath(folder_name, root_folder) folder_name = path.clean_path(folder_name) found_folders.append(folder_name) except",
"sub folders names on a directory :param root_folder: str, folder we want to",
"found_extension = os.path.splitext(file_name) if found_extension == '{}'.format(extension): if not full_path: found.append(file_name) else: found.append(os.path.join(root_directory,",
"import path found_folders = list() if not recursive: try: found_folders = next(os.walk(root_folder))[1] except",
"Gets a list of sub folders in the given path :param path: str",
"else: files = get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text) return list(sorted(files, key=_get_mtime)) def open_folder(path=None): \"\"\" Opens",
"directory, directory_destination, '-azr'] elif osplatform.is_windows(): cmd = [ 'robocopy', directory.replace('/', '\\\\'), directory_destination.replace('/', '\\\\'),",
"= os.listdir(directory) except Exception: files = list() return files def get_files_with_extension(extension, root_directory, full_path=False,",
"exc: logger.warning('Failed to move {} to {}: {}'.format(source_directory, target_directory, exc)) return False return",
"found_extension = os.path.splitext(filename_and_extension) if filter_text and filename_and_extension.find(filter_text) == -1: continue if found_extension ==",
"found_folders = list() if not recursive: try: found_folders = next(os.walk(root_folder))[1] except Exception: pass",
"import fileio def _get_mtime(fld): return os.stat(os.path.join(root_directory, fld)).st_mtime if not extension: files = fileio.get_files(root_directory,",
"\"\"\" from tpDcc.libs.python import path, osplatform full_path = False if directory is None:",
"def clean_folder(directory): \"\"\" Removes everything in the given directory :param directory: str \"\"\"",
"path.join_path(parent_path, name) if make_unique: rename_path = path.unique_path_name(directory=rename_path) if path.exists(rename_path): return False try: osplatform.get_permission(directory)",
"folder \"\"\" from tpDcc.libs.python import path return path.clean_path(tempfile.gettempdir()) def get_current_working_directory(): \"\"\" Returns current",
"sys.platform == 'darwin': subprocess.check_call(['open', '--', path]) elif sys.platform == 'linux2': subprocess.Popen(['xdg-open', path]) elif",
"path.join_path(directory, folder_name) if not path.is_dir(full_path): return None try: shutil.rmtree(full_path, onerror=delete_read_only_error) except Exception as",
"bool :param filter_text: str :return: list(str) \"\"\" found = list() if not extension.startswith('.'):",
"place_holder: place_path = os.path.join(folder_path, 'placeholder') if not os.path.exists(place_path): with open(place_path, 'wt') as fh:",
"given path and with the given name :param name: str, name of the",
"given directory :param directory: str \"\"\" from tpDcc.libs.python import path, fileio, folder base_name",
"Return a list with all the sub folders names on a directory :param",
"bool, Whether the move operation was successfully \"\"\" try: if only_contents or os.path.isdir(target_directory):",
"= 0 for root, dirs, files in os.walk(directory): root_name = path.get_basename(root) if root_name",
"full_path: found.append(file_name) else: found.append(os.path.join(root_directory, file_name)) else: try: objs = os.listdir(root_directory) except Exception: return",
"extension to find :param filter_text: str, optional text filtering :return: list(str), list of",
"else: os.remove(dest) shutil.move(src, target_directory) else: shutil.move(source_directory, target_directory) except Exception as exc: logger.warning('Failed to",
"methods related to folders \"\"\" from __future__ import print_function, division, absolute_import import os",
"err.errno != errno.EEXIST: raise def get_latest_file_at_folder(folder_path, filter_text=''): \"\"\" Returns the latest path added",
"path added to a folder :param folder_path: :param filter_text: :return: str \"\"\" from",
"str, path where path1 should be move into :param only_contents: bool, Whether to",
"if not path.exists(directory): return found_folders = list() base_directory = base_directory or directory folders",
"not path is passed the current directory will be opened :param path: str,",
"str :param round_value: int, value to round size to :return: int \"\"\" from",
"pass def get_user_folder(absolute=True): \"\"\" Get path to the user folder :return: str, path",
"get_folders_from_path(path): \"\"\" Gets a list of sub folders in the given path :param",
":param root_folder: str, folder we want to search files on :param full_path: bool,",
"file_names in os.walk(root_folder): for file_name in fnmatch.filter(file_names, pattern): if full_path: found.append(path.join_path(dir_path, file_name)) else:",
".data, etc) :param root_directory: str, directory path :param full_path: bool, Whether to return",
"_get_mtime(fld): return os.stat(os.path.join(root_folder, fld)).st_mtime return list(sorted(os.listdir(root_folder), key=_get_mtime)) def ensure_folder_exists(folder_path, permissions=0o755, place_holder=False): \"\"\" Checks",
"directory :param ignore_patterns: list<str>, extensions we want to ignore when copying folder elements",
"return if not ignore_patterns: cmd = None if osplatform.is_linux(): cmd = ['rsync', directory,",
"tpDcc.libs.python import path if not path.is_dir(root_folder): return [] # TODO: For now pattern",
"in the given path :param path: str :return: list<str> \"\"\" folders = list()",
"to search folders on :param recursive: bool, Whether to search in all root",
"file names will be returned :return: list<str> \"\"\" from tpDcc.libs.python import path if",
"root_folder: str, folder we want to search sub folders for :param sort: bool,",
"from tpDcc.libs.python import path, osplatform base_name = path.get_basename(directory=directory) if base_name == name: return",
"all the sub folders names on a directory :param root_folder: str, folder we",
"folders names on a directory :param root_folder: str, folder we want to search",
"file_names = os.listdir(root_folder) result = list() for f in file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)):",
"not exists!'.format(root_folder)) file_names = os.listdir(root_folder) result = list() for f in file_names: if",
"get_latest_file_at_folder(folder_path, filter_text=''): \"\"\" Returns the latest path added to a folder :param folder_path:",
"for f in files: file_path = path.join_path(root_folder, f) if path.is_file(file_path=file_path): if full_path: found.append(file_path)",
"os.listdir(root_folder) result = list() for f in file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f) if",
"== '{}'.format(extension): if not full_path: found.append(file_name) else: found.append(os.path.join(root_directory, file_name)) else: try: objs =",
"name: str, name of the new directory :param directory: str, path to the",
"\"\"\" Returns folder dates sorted found in the given root directory :param root_folder:",
"full_path try: os.makedirs(full_path) except Exception: return False osplatform.get_permission(full_path) return full_path def rename_folder(directory, name,",
":param name: str, new name of the folder we want to rename :param",
"to the temp folder :return: str, path to the temp folder \"\"\" from",
"Exception: files = list() for f in files: fileio.delete_file(f, directory) delete_folder(base_name, dir_name) if",
"folder path to check or created :param permissions:int, folder permission mode :param place_holder:",
"= root_directory.count(os.path.sep) for root, dirs, files in os.walk(root_directory): yield root, dirs, files num_sep_this",
"def walk_level(root_directory, level=None): root_directory = root_directory.rstrip(os.path.sep) assert os.path.isdir(root_directory) if level is None: for",
"Return the size of the given directory or file path :param file_path: str",
"-*- \"\"\" Utility methods related to folders \"\"\" from __future__ import print_function, division,",
"ant to search folders on :param recursive: bool, Whether to search in all",
"os.path.splitext(filename_and_extension) if filter_text and filename_and_extension.find(filter_text) == -1: continue if found_extension == extension: if",
"place_path = os.path.join(folder_path, 'placeholder') if not os.path.exists(place_path): with open(place_path, 'wt') as fh: fh.write('Automatically",
"sys.platform == 'linux2': subprocess.Popen(['xdg-open', path]) elif sys.platform in ['windows', 'win32', 'win64']: if path.endswith('/'):",
"path2, *args, **kwargs) except Exception: logger.warning('Failed to move contents of {0} to {1}'.format(path1,",
"with a number to make it unique if the folder is not unique",
"make it unique :return: str, path of the renamed folder \"\"\" from tpDcc.libs.python",
":raise OSError: raise OSError if the creation of the folder fails \"\"\" if",
"os.path.isdir(target_directory): file_list = os.listdir(source_directory) for i in file_list: src = os.path.join(source_directory, i) dest",
"not files: return None return path.join_path(folder_path, files[-1]) def walk_level(root_directory, level=None): root_directory = root_directory.rstrip(os.path.sep)",
"for name in files: if name in skip_names: continue size += fileio.get_file_size(path.join_path(root, name),",
"directory: full_path = path.join_path(directory, name) if make_unique: full_path = path.unique_path_name(directory=full_path) if not full_path:",
"= list() for f in file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f) if sort: result.sort()",
"with all the sub folders names on a directory :param root_folder: str, folder",
"the temp folder :return: str, path to the temp folder \"\"\" from tpDcc.libs.python",
"user folder \"\"\" from tpDcc.libs.python import path if absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else: return",
"in all root folder child folders or not :return: list<str> \"\"\" from tpDcc.libs.python",
"subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = proc.communicate() if out: logger.error(err) else: shutil.copytree(directory,",
"{0} to {1}'.format(path1, path2)) return False return True def delete_folder(folder_name, directory=None): \"\"\" Deletes",
"= list() if not extension.startswith('.'): extension = '.{}'.format(extension) if recursive: for dir_path, dir_names,",
"files = fileio.get_files(root_directory, filter_text=filter_text) else: files = get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text) return list(sorted(files, key=_get_mtime))",
"get_sub_folders(root_folder, sort=True): \"\"\" Return a list with all the sub folders names on",
"of folder date sorted in the directory \"\"\" def _get_mtime(fld): return os.stat(os.path.join(root_folder, fld)).st_mtime",
"path, osplatform def delete_read_only_error(action, name, exc): \"\"\" Helper to delete read only files",
"from :return: list<str> \"\"\" try: files = os.listdir(directory) except Exception: files = list()",
"directory :param root_folder: str, directory path :return: list(str): list of folder date sorted",
"def get_current_working_directory(): \"\"\" Returns current working directory :return: str, path to the current",
"the folder path2. If path2 directory does not exists, it will be created",
"import copy_tree logger = logging.getLogger('tpDcc-libs-python') def create_folder(name, directory=None, make_unique=False): \"\"\" Creates a new",
"return os.stat(os.path.join(root_folder, fld)).st_mtime return list(sorted(os.listdir(root_folder), key=_get_mtime)) def ensure_folder_exists(folder_path, permissions=0o755, place_holder=False): \"\"\" Checks that",
"that was deleted with path \"\"\" from tpDcc.libs.python import name, path, osplatform def",
"directory: full_path = path.join_path(directory, folder_name) if not path.is_dir(full_path): return None try: shutil.rmtree(full_path, onerror=delete_read_only_error)",
"directory :param directory: str, directory to copy with full path :param directory_destination: str,",
"\"\"\" Creates a new folder on the given path and with the given",
"version if not path.exists(directory): return found_folders = list() base_directory = base_directory or directory",
"logging.getLogger('tpDcc-libs-python') def create_folder(name, directory=None, make_unique=False): \"\"\" Creates a new folder on the given",
"files in os.walk(root_folder): for d in dirs: if full_path: folder_name = path.join_path(root, d)",
"return False return True def copy_directory_contents(path1, path2, *args, **kwargs): \"\"\" Copies all the",
"the size of the given folder :param directory: str :param round_value: int, value",
"in given directory with given extensions :param extension: str, extension to find (.py,",
"the given folder :param directory: str :param round_value: int, value to round size",
"full_path: return False if path.is_dir(full_path): return full_path try: os.makedirs(full_path) except Exception: return False",
"list<str> \"\"\" try: files = os.listdir(directory) except Exception: files = list() return files",
"path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name) if recursive: sub_folders = get_folders_without_dot_prefix( folder_path, recursive=recursive, base_directory=base_directory) found_folders +=",
":param root_folder: str, directory path :return: list(str): list of folder date sorted in",
"ignore_patterns: list<str>, extensions we want to ignore when copying folder elements If ['txt',",
"in the root folder :param root_folder: str, folder we ant to search folders",
"os.walk(root_folder): for file_name in fnmatch.filter(file_names, pattern): if full_path: found.append(path.join_path(dir_path, file_name)) else: found.append(file_name) else:",
"file_names: if os.path.isdir(os.path.join(os.path.abspath(root_folder), f)): result.append(f) if sort: result.sort() return result def get_folders(root_folder, recursive=False,",
":param kwargs: :return: \"\"\" try: copy_tree(path1, path2, *args, **kwargs) except Exception: logger.warning('Failed to",
"path :return: list(str): list of folder date sorted in the directory \"\"\" def",
"given folder exists. If not, folder is created. :param folder_path: str, folder path",
"filter_text and filename_and_extension.find(filter_text) == -1: continue if found_extension == extension: if not full_path:",
"is passed the current directory will be opened :param path: str, folder path",
"directory_destination.replace('/', '\\\\'), '/S', '/Z', '/MIR'] if cmd: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)",
":return: \"\"\" try: copy_tree(path1, path2, *args, **kwargs) except Exception: logger.warning('Failed to move contents",
"path return path.clean_path(tempfile.gettempdir()) def get_current_working_directory(): \"\"\" Returns current working directory :return: str, path",
"import path if not path.is_dir(root_folder): return [] # TODO: For now pattern only",
":param filter_text: :return: str \"\"\" from tpDcc.libs.python import path files = get_files_date_sorted(folder_path, filter_text=filter_text)",
"folder != '': folders.append(folder) else: if path != '': folders.append(path) break folders.reverse() return",
"all the contents of the given path1 to the folder path2. If path2",
"for i in file_list: src = os.path.join(source_directory, i) dest = os.path.join(target_directory, i) if",
"osplatform.is_windows(): cmd = [ 'robocopy', directory.replace('/', '\\\\'), directory_destination.replace('/', '\\\\'), '/S', '/Z', '/MIR'] if",
":param filter_text: str :return: list(str) \"\"\" found = list() if not extension.startswith('.'): extension",
"all root folder child folders or not :return: list<str> \"\"\" from tpDcc.libs.python import",
"if base_name == name: return parent_path = path.get_dirname(directory=directory) rename_path = path.join_path(parent_path, name) if",
"to move the folder or only its contents :return: bool, Whether the move",
"be move into :param only_contents: bool, Whether to move the folder or only",
"bool, True if we want sort alphabetically the returned folders or False otherwise",
"exc)) return full_path def clean_folder(directory): \"\"\" Removes everything in the given directory :param",
"size to :return: int \"\"\" from tpDcc.libs.python import fileio, path size = 0",
"directory :param directory: str, folder we want to get files and folders from",
"into a new directory :param directory: str, directory to copy with full path",
"def rename_folder(directory, name, make_unique=False): \"\"\" Renames given with a new name :param directory:",
"Utility methods related to folders \"\"\" from __future__ import print_function, division, absolute_import import",
"of the given directory or file path :param file_path: str :param round_value: int,",
"the directory path where the folder is stored :return: str, folder that was",
"text extension files will be ignored during the copy operation :return: str, destination",
":param path2: str :param args: :param kwargs: :return: \"\"\" try: copy_tree(path1, path2, *args,",
"def get_latest_file_at_folder(folder_path, filter_text=''): \"\"\" Returns the latest path added to a folder :param",
"path = path[:-1] new_path = path.replace('/', '\\\\') try: subprocess.check_call(['explorer', new_path], shell=False) except Exception:",
"= get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text) return list(sorted(files, key=_get_mtime)) def open_folder(path=None): \"\"\" Opens a folder",
"in the given directory :param directory: str, folder we want to get files",
"fh.write('Automatically generated place holder file') except OSError as err: if err.errno != errno.EEXIST:",
"is not unique :return: variant, str || bool, folder name with path or",
"+= sub_folders return found_folders def get_files(root_folder, full_path=False, recursive=False, pattern=\"*\"): \"\"\" Returns files found",
"else: return path.clean_path(os.path.expanduser('~')) def get_temp_folder(): \"\"\" Get the path to the temp folder",
"False return rename_path def copy_folder(directory, directory_destination, ignore_patterns=[]): \"\"\" Copy the given directory into",
"str, the directory path where the folder is stored :return: str, folder that",
"destination directory \"\"\" from tpDcc.libs.python import path, osplatform if not path.is_dir(directory=directory): return if",
"path.is_dir(directory): try: files = folder.get_files(directory) except Exception: files = list() for f in",
"str, destination directory :param ignore_patterns: list<str>, extensions we want to ignore when copying",
"to the temp folder \"\"\" from tpDcc.libs.python import path return path.clean_path(tempfile.gettempdir()) def get_current_working_directory():",
":return: variant, str || bool, folder name with path or False if the",
"directory=None): \"\"\" Deletes the folder by name in the given directory :param folder_name:",
"in folders: if folder == 'version': version = version.VersionFile(directory) if version.updated_old: continue if",
"delete_read_only_error(action, name, exc): \"\"\" Helper to delete read only files \"\"\" osplatform.get_permission(name) action(name)",
"current working directory :return: str, path to the current working directory \"\"\" return",
"if os.path.exists(dest): if os.path.isdir(dest): move_folder(src, dest) continue else: os.remove(dest) shutil.move(src, target_directory) else: shutil.move(source_directory,",
"dir_names, file_names in os.walk(root_directory): for file_name in file_names: filename, found_extension = os.path.splitext(file_name) if",
"'-azr'] elif osplatform.is_windows(): cmd = [ 'robocopy', directory.replace('/', '\\\\'), directory_destination.replace('/', '\\\\'), '/S', '/Z',",
"if not recursive: try: found_folders = next(os.walk(root_folder))[1] except Exception: pass else: try: for",
"files: fileio.delete_file(f, directory) delete_folder(base_name, dir_name) if not path.is_dir(directory): create_folder(base_name, dir_name) def get_folder_size(directory, round_value=2,",
"else: folder_name = path.join_path(root, d) folder_name = os.path.relpath(folder_name, root_folder) folder_name = path.clean_path(folder_name) found_folders.append(folder_name)",
"name of the folder to delete :param directory: str, the directory path where",
"be returned otherwise file names will be returned :return: list<str> \"\"\" from tpDcc.libs.python",
":param ignore_patterns: list<str>, extensions we want to ignore when copying folder elements If",
"list of folder date sorted in the directory \"\"\" def _get_mtime(fld): return os.stat(os.path.join(root_folder,",
"dirs, files in os.walk(root_folder): for d in dirs: if full_path: folder_name = path.join_path(root,",
"the folder to delete :param directory: str, the directory path where the folder",
"sort: bool, True if we want sort alphabetically the returned folders or False",
"os.path.isdir(root_directory) if level is None: for root, dirs, files in os.walk(root_directory): yield root,",
"and folders from :return: list<str> \"\"\" try: files = os.listdir(directory) except Exception: files",
"division, absolute_import import os import sys import time import errno import shutil import",
"\"\"\" Removes everything in the given directory :param directory: str \"\"\" from tpDcc.libs.python",
"= os.listdir(root_directory) except Exception: return found for filename_and_extension in objs: filename, found_extension =",
"recursive=recursive, base_directory=base_directory) found_folders += sub_folders return found_folders def get_files(root_folder, full_path=False, recursive=False, pattern=\"*\"): \"\"\"",
"path: str :return: list<str> \"\"\" folders = list() while True: path, folder =",
"the folder name to make it unique :return: str, path of the renamed",
"str, path of the renamed folder \"\"\" from tpDcc.libs.python import path, osplatform base_name",
"list() if not extension.startswith('.'): extension = '.{}'.format(extension) if recursive: for dir_path, dir_names, file_names",
"def copy_directory_contents(path1, path2, *args, **kwargs): \"\"\" Copies all the contents of the given",
"elif sys.platform == 'linux2': subprocess.Popen(['xdg-open', path]) elif sys.platform in ['windows', 'win32', 'win64']: if",
"to the new directory :param make_unique: bool, Whether to pad the name with",
"in recursive searches. Fix it to work on both found = list() if",
"permissions:int, folder permission mode :param place_holder: bool, Whether to create place holder text",
"will be opened :param path: str, folder path to open \"\"\" if path",
"files in os.walk(root_directory): yield root, dirs, files num_sep_this = root.count(os.path.sep) if num_sep +",
"osplatform if not path.is_dir(directory=directory): return if not ignore_patterns: cmd = None if osplatform.is_linux():",
"permissions) if place_holder: place_path = os.path.join(folder_path, 'placeholder') if not os.path.exists(place_path): with open(place_path, 'wt')",
"directory we want to rename :param name: str, new name of the folder",
"created :param permissions:int, folder permission mode :param place_holder: bool, Whether to create place",
"move operation was successfully \"\"\" try: if only_contents or os.path.isdir(target_directory): file_list = os.listdir(source_directory)",
"None: full_path = name if not name: full_path = directory if name and",
"a new name :param directory: str, full path to the directory we want",
"import path return path.clean_path(tempfile.gettempdir()) def get_current_working_directory(): \"\"\" Returns current working directory :return: str,",
"new directory :param directory: str, path to the new directory :param make_unique: bool,",
"rename_folder(directory, name, make_unique=False): \"\"\" Renames given with a new name :param directory: str,",
"copy_tree(path1, path2, *args, **kwargs) except Exception: logger.warning('Failed to move contents of {0} to",
"list of sub folders in the given path :param path: str :return: list<str>",
"the user folder \"\"\" from tpDcc.libs.python import path if absolute: return path.clean_path(os.path.abspath(os.path.expanduser('~'))) else:",
"if version.updated_old: continue if folder.startswith('.'): continue folder_path = path.join_path(directory, folder) folder_name = path.clean_path(os.path.relpath(folder_path,",
"path or False if the folder creation failed \"\"\" from tpDcc.libs.python import path,",
"if not full_path: return False if path.is_dir(full_path): return full_path try: os.makedirs(full_path) except Exception:",
"found.append(f) return found def get_files_and_folders(directory): \"\"\" Get files and folders found in the",
"True def copy_directory_contents(path1, path2, *args, **kwargs): \"\"\" Copies all the contents of the",
"False try: osplatform.get_permission(directory) message = 'rename: {0} >> {1}'.format(directory, rename_path) logger.info(message) os.rename(directory, rename_path)",
"filter_text=filter_text) return list(sorted(files, key=_get_mtime)) def open_folder(path=None): \"\"\" Opens a folder in the explorer",
"etc) :param root_directory: str, directory path :param full_path: bool, Whether to return the",
"os.path.curdir if sys.platform == 'darwin': subprocess.check_call(['open', '--', path]) elif sys.platform == 'linux2': subprocess.Popen(['xdg-open',",
"not full_path: found.append(file_name) else: found.append(os.path.join(root_directory, file_name)) else: try: objs = os.listdir(root_directory) except Exception:",
"folder is not unique :return: variant, str || bool, folder name with path",
"get_files(root_folder, full_path=False, recursive=False, pattern=\"*\"): \"\"\" Returns files found in the given folder :param",
"list<str> \"\"\" from tpDcc.libs.python import path if not path.is_dir(root_folder): return [] # TODO:",
"os.remove(dest) shutil.move(src, target_directory) else: shutil.move(source_directory, target_directory) except Exception as exc: logger.warning('Failed to move",
"absolute_import import os import sys import time import errno import shutil import fnmatch",
"number to the folder name to make it unique :return: str, path of",
"shell=True) out, err = proc.communicate() if out: logger.error(err) else: shutil.copytree(directory, directory_destination) else: shutil.copytree(directory,",
":param full_path: bool, if true, full path to the files will be returned",
"os.walk(directory): root_name = path.get_basename(root) if root_name in skip_names: continue for name in files:",
"d) folder_name = os.path.relpath(folder_name, root_folder) folder_name = path.clean_path(folder_name) found_folders.append(folder_name) except Exception: return found_folders",
"else: try: objs = os.listdir(root_directory) except Exception: return found for filename_and_extension in objs:",
"holder text file or not :raise OSError: raise OSError if the creation of",
"folder \"\"\" from tpDcc.libs.python import path, osplatform base_name = path.get_basename(directory=directory) if base_name ==",
"path.join_path(root_folder, f) if path.is_file(file_path=file_path): if full_path: found.append(file_path) else: found.append(f) return found def get_files_and_folders(directory):",
"Opens a folder in the explorer in a independent platform way If not",
"f)): result.append(f) if sort: result.sort() return result def get_folders(root_folder, recursive=False, full_path=False): \"\"\" Get",
"and directory: full_path = path.join_path(directory, name) if make_unique: full_path = path.unique_path_name(directory=full_path) if not",
"the folder is stored :return: str, folder that was deleted with path \"\"\"",
"except Exception: return False osplatform.get_permission(full_path) return full_path def rename_folder(directory, name, make_unique=False): \"\"\" Renames",
"\"\"\" Renames given with a new name :param directory: str, full path to",
"{0} >> {1}'.format(directory, rename_path) logger.info(message) os.rename(directory, rename_path) except Exception: time.sleep(0.1) try: os.rename(directory, rename_path)",
"directory: str, the directory path where the folder is stored :return: str, folder",
"the given directory :param folder_name: str, name of the folder to delete :param",
"'win32', 'win64']: if path.endswith('/'): path = path[:-1] new_path = path.replace('/', '\\\\') try: subprocess.check_call(['explorer',",
"path to the temp folder :return: str, path to the temp folder \"\"\"",
"True if we want sort alphabetically the returned folders or False otherwise :return:",
"file_name)) else: try: objs = os.listdir(root_directory) except Exception: return found for filename_and_extension in",
"path2 directory does not exists, it will be created :param path1: str :param",
"names :param recursive: bool :param filter_text: str :return: list(str) \"\"\" found = list()",
"the folder or only its contents :return: bool, Whether the move operation was",
"dest) continue else: os.remove(dest) shutil.move(src, target_directory) else: shutil.move(source_directory, target_directory) except Exception as exc:",
"if directory is None: full_path = name if not name: full_path = directory",
"def get_user_folder(absolute=True): \"\"\" Get path to the user folder :return: str, path to",
"except Exception: pass else: try: for root, dirs, files in os.walk(root_folder): for d",
"the root folder :param root_folder: str, folder we ant to search folders on",
"def ensure_folder_exists(folder_path, permissions=0o755, place_holder=False): \"\"\" Checks that folder given folder exists. If not,",
"files found in the given folder :param root_folder: str, folder we want to",
"= path.clean_path(folder_name) found_folders.append(folder_name) except Exception: return found_folders return found_folders def get_folders_without_dot_prefix(directory, recursive=False, base_directory=None):",
"['txt', 'py'] is given all py and text extension files will be ignored",
":param path1: str :param path2: str :param args: :param kwargs: :return: \"\"\" try:",
"full_path=False, recursive=False, pattern=\"*\"): \"\"\" Returns files found in the given folder :param root_folder:",
"root_directory.count(os.path.sep) for root, dirs, files in os.walk(root_directory): yield root, dirs, files num_sep_this =",
"extension=None, filter_text=''): \"\"\" Returns files date sorted found in the given directory :param",
"delete_folder(base_name, dir_name) if not path.is_dir(directory): create_folder(base_name, dir_name) def get_folder_size(directory, round_value=2, skip_names=None): \"\"\" Returns",
"folder child folders or not :return: list<str> \"\"\" from tpDcc.libs.python import path found_folders",
"Helper to delete read only files \"\"\" osplatform.get_permission(name) action(name) folder_name = name.clean_file_string(folder_name) full_path",
"continue if found_extension == extension: if not full_path: found.append(filename_and_extension) else: found.append(os.path.join(root_directory, filename_and_extension)) return",
"str, directory to copy with full path :param directory_destination: str, destination directory :param",
"return None try: shutil.rmtree(full_path, onerror=delete_read_only_error) except Exception as exc: logger.warning('Could not remove children",
"return the file path or just the file names :param recursive: bool :param",
"list<str>, sub folders names \"\"\" if not os.path.exists(root_folder): raise RuntimeError('Folder {0} does not",
"get_folders(directory) for folder in folders: if folder == 'version': version = version.VersionFile(directory) if",
"\"\"\" Get folders found in the root folder :param root_folder: str, folder we",
"'version': version = version.VersionFile(directory) if version.updated_old: continue if folder.startswith('.'): continue folder_path = path.join_path(directory,",
"if full_path: folder_name = path.join_path(root, d) found_folders.append(folder_name) else: folder_name = path.join_path(root, d) folder_name",
"pattern=\"*\"): \"\"\" Returns files found in the given folder :param root_folder: str, folder",
"sort=True): \"\"\" Return a list with all the sub folders names on a",
"exc: logger.warning('Could not remove children of path \"{}\" | {}'.format(full_path, exc)) return full_path",
"def _get_mtime(fld): return os.stat(os.path.join(root_directory, fld)).st_mtime if not extension: files = fileio.get_files(root_directory, filter_text=filter_text) else:",
"if path is None: path = os.path.curdir if sys.platform == 'darwin': subprocess.check_call(['open', '--',",
"= os.path.join(folder_path, 'placeholder') if not os.path.exists(place_path): with open(place_path, 'wt') as fh: fh.write('Automatically generated",
"to make it unique :return: str, path of the renamed folder \"\"\" from",
":return: str, path of the renamed folder \"\"\" from tpDcc.libs.python import path, osplatform",
"path.is_dir(directory): create_folder(base_name, dir_name) def get_folder_size(directory, round_value=2, skip_names=None): \"\"\" Returns the size of the",
"name in skip_names: continue size += fileio.get_file_size(path.join_path(root, name), round_value) return size def get_size(file_path,",
"== -1: continue if found_extension == extension: if not full_path: found.append(filename_and_extension) else: found.append(os.path.join(root_directory,",
"os.listdir(root_directory) except Exception: return found for filename_and_extension in objs: filename, found_extension = os.path.splitext(filename_and_extension)",
"path]) elif sys.platform in ['windows', 'win32', 'win64']: if path.endswith('/'): path = path[:-1] new_path",
"for file_name in file_names: filename, found_extension = os.path.splitext(file_name) if found_extension == '{}'.format(extension): if",
"err: if err.errno != errno.EEXIST: raise def get_latest_file_at_folder(folder_path, filter_text=''): \"\"\" Returns the latest",
"def copy_folder(directory, directory_destination, ignore_patterns=[]): \"\"\" Copy the given directory into a new directory",
":return: str, destination directory \"\"\" from tpDcc.libs.python import path, osplatform if not path.is_dir(directory=directory):",
"only_contents: bool, Whether to move the folder or only its contents :return: bool,",
"def move_folder(source_directory, target_directory, only_contents=False): \"\"\" Moves the folder pointed by source_directory under the",
"-1: continue if found_extension == extension: if not full_path: found.append(filename_and_extension) else: found.append(os.path.join(root_directory, filename_and_extension))",
":param make_unique: bool, Whether to add a number to the folder name to",
"False if path.is_dir(full_path): return full_path try: os.makedirs(full_path) except Exception: return False osplatform.get_permission(full_path) return",
":param recursive: bool :param filter_text: str :return: list(str) \"\"\" found = list() if",
"only_contents=False): \"\"\" Moves the folder pointed by source_directory under the directory target_directory :param",
"= subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = proc.communicate() if out: logger.error(err) else:",
"OSError as err: if err.errno != errno.EEXIST: raise def get_latest_file_at_folder(folder_path, filter_text=''): \"\"\" Returns",
"return full_path def rename_folder(directory, name, make_unique=False): \"\"\" Renames given with a new name",
"ensure_folder_exists(folder_path, permissions=0o755, place_holder=False): \"\"\" Checks that folder given folder exists. If not, folder",
":param recursive: bool, Whether to search in all root folder child folders or",
"in skip_names: continue size += fileio.get_file_size(path.join_path(root, name), round_value) return size def get_size(file_path, round_value=2):",
"full_path = False if directory is None: full_path = name if not name:",
"False otherwise :return: list<str>, sub folders names \"\"\" if not os.path.exists(root_folder): raise RuntimeError('Folder",
"size def get_sub_folders(root_folder, sort=True): \"\"\" Return a list with all the sub folders",
"folder is stored :return: str, folder that was deleted with path \"\"\" from",
"it unique :return: str, path of the renamed folder \"\"\" from tpDcc.libs.python import",
"be opened :param path: str, folder path to open \"\"\" if path is",
"import errno import shutil import fnmatch import logging import tempfile import traceback import",
"in os.walk(root_folder): for file_name in fnmatch.filter(file_names, pattern): if full_path: found.append(path.join_path(dir_path, file_name)) else: found.append(file_name)",
"contents of the given path1 to the folder path2. If path2 directory does",
"if not extension: files = fileio.get_files(root_directory, filter_text=filter_text) else: files = get_files_with_extension(extension=extension, root_directory=root_directory, filter_text=filter_text)",
"the folder is not unique :return: variant, str || bool, folder name with",
"= path.get_dirname(directory=directory) rename_path = path.join_path(parent_path, name) if make_unique: rename_path = path.unique_path_name(directory=rename_path) if path.exists(rename_path):",
"\"\"\" folders = list() while True: path, folder = os.path.split(path) if folder !=",
"os import sys import time import errno import shutil import fnmatch import logging",
"= path.unique_path_name(directory=full_path) if not full_path: return False if path.is_dir(full_path): return full_path try: os.makedirs(full_path)",
":return: list<str> \"\"\" from tpDcc.libs.python import path if not path.is_dir(root_folder): return [] #",
"directory :param root_directory: str, directory path :param extension: str, optional extension to find",
"file path :param file_path: str :param round_value: int, value to round size to",
"path size = 0 if path.is_dir(file_path): size = get_folder_size(file_path, round_value) if path.is_file(file_path): size",
"= logging.getLogger('tpDcc-libs-python') def create_folder(name, directory=None, make_unique=False): \"\"\" Creates a new folder on the",
"working directory \"\"\" return os.getcwd() def get_folders_from_path(path): \"\"\" Gets a list of sub",
"return path.clean_path(tempfile.gettempdir()) def get_current_working_directory(): \"\"\" Returns current working directory :return: str, path to",
"and filename_and_extension.find(filter_text) == -1: continue if found_extension == extension: if not full_path: found.append(filename_and_extension)",
"found_folders += sub_folders return found_folders def get_files(root_folder, full_path=False, recursive=False, pattern=\"*\"): \"\"\" Returns files",
"get_folders(root_folder, recursive=False, full_path=False): \"\"\" Get folders found in the root folder :param root_folder:",
"if os.path.isdir(dest): move_folder(src, dest) continue else: os.remove(dest) shutil.move(src, target_directory) else: shutil.move(source_directory, target_directory) except",
"date sorted in the directory \"\"\" from tpDcc.libs.python import fileio def _get_mtime(fld): return",
"directory will be opened :param path: str, folder path to open \"\"\" if",
"move into :param only_contents: bool, Whether to move the folder or only its",
"operation :return: str, destination directory \"\"\" from tpDcc.libs.python import path, osplatform if not",
"str, folder that was deleted with path \"\"\" from tpDcc.libs.python import name, path,",
"a list with all the sub folders names on a directory :param root_folder:",
"get_files_date_sorted(root_directory, extension=None, filter_text=''): \"\"\" Returns files date sorted found in the given directory",
"return parent_path = path.get_dirname(directory=directory) rename_path = path.join_path(parent_path, name) if make_unique: rename_path = path.unique_path_name(directory=rename_path)",
"folders.append(folder) else: if path != '': folders.append(path) break folders.reverse() return folders def get_folders_date_sorted(root_folder):",
"return os.getcwd() def get_folders_from_path(path): \"\"\" Gets a list of sub folders in the",
"dest = os.path.join(target_directory, i) if os.path.exists(dest): if os.path.isdir(dest): move_folder(src, dest) continue else: os.remove(dest)",
"= os.listdir(source_directory) for i in file_list: src = os.path.join(source_directory, i) dest = os.path.join(target_directory,",
"move_folder(source_directory, target_directory, only_contents=False): \"\"\" Moves the folder pointed by source_directory under the directory",
"Removes everything in the given directory :param directory: str \"\"\" from tpDcc.libs.python import",
"osplatform.get_permission(name) action(name) folder_name = name.clean_file_string(folder_name) full_path = folder_name if directory: full_path = path.join_path(directory,",
"ignore when copying folder elements If ['txt', 'py'] is given all py and",
"continue for name in files: if name in skip_names: continue size += fileio.get_file_size(path.join_path(root,",
"target_directory, exc)) return False return True def copy_directory_contents(path1, path2, *args, **kwargs): \"\"\" Copies",
"folder date sorted in the directory \"\"\" def _get_mtime(fld): return os.stat(os.path.join(root_folder, fld)).st_mtime return",
"stored :return: str, folder that was deleted with path \"\"\" from tpDcc.libs.python import",
"in ['windows', 'win32', 'win64']: if path.endswith('/'): path = path[:-1] new_path = path.replace('/', '\\\\')",
"the files will be returned otherwise file names will be returned :return: list<str>",
"Moves the folder pointed by source_directory under the directory target_directory :param source_directory: str,",
"rename_path = path.join_path(parent_path, name) if make_unique: rename_path = path.unique_path_name(directory=rename_path) if path.exists(rename_path): return False",
"import print_function, division, absolute_import import os import sys import time import errno import",
"folder_path = path.join_path(directory, folder) folder_name = path.clean_path(os.path.relpath(folder_path, base_directory)) found_folders.append(folder_name) if recursive: sub_folders =",
"tpDcc.libs.python import python, path, fileio skip_names = python.force_list(skip_names) size = 0 for root,",
"target_directory, only_contents=False): \"\"\" Moves the folder pointed by source_directory under the directory target_directory"
] |
[
"to file...') with open('additives.json', 'w') as file: json.dump(additives_info, file, indent=2) if __name__ ==",
"json file logger.info('Done') logger.info('Saving additives to file...') with open('additives.json', 'w') as file: json.dump(additives_info,",
"scrappers ready europa_scrapper = EuropaScrapper() eaditivos_scrapper = EAditivosScrapper() laveganisteria_scrapper = LaVeganisteriaScrapper() # Get",
"the json file logger.info('Done') logger.info('Saving additives to file...') with open('additives.json', 'w') as file:",
"# Get the information additives_info = europa_scrapper.get_additives(args.start, args.end) # returns an array of",
"element: element['number'], additives_info) # Get some dietary information from several sources dietary_info =",
"logger.info('Saving additives to file...') with open('additives.json', 'w') as file: json.dump(additives_info, file, indent=2) if",
"import EAditivosScrapper, EuropaScrapper, LaVeganisteriaScrapper from util import parse_args, select_dietary, setup_logger, update_dietary def main():",
"e_id = element['number'] if e_id in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) # Now save the json",
"select_dietary, setup_logger, update_dietary def main(): args = parse_args() logger = setup_logger(level=args.log_level) logger.info('Starting') #",
"# Get some dietary information from several sources dietary_info = eaditivos_scrapper.get_additives() dietary_info =",
"base with it dietary_info = select_dietary(dietary_info) for index, element in enumerate(additives_info): e_id =",
"enumerate(additives_info): e_id = element['number'] if e_id in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) # Now save the",
"# 'id': ..., # 'number': ..., # 'name': ..., # 'synonyms': ..., #",
"dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) # Now save the json file logger.info('Done') logger.info('Saving additives to file...')",
"= LaVeganisteriaScrapper() # Get the information additives_info = europa_scrapper.get_additives(args.start, args.end) # returns an",
"'number': ..., # 'name': ..., # 'synonyms': ..., # 'groups': ..., # 'dietary':",
"# Get the scrappers ready europa_scrapper = EuropaScrapper() eaditivos_scrapper = EAditivosScrapper() laveganisteria_scrapper =",
"parse_args, select_dietary, setup_logger, update_dietary def main(): args = parse_args() logger = setup_logger(level=args.log_level) logger.info('Starting')",
"... # 'vegan': ... # } # } # Consolidate the dietary info",
"# } # See which numbers we get numbers = map(lambda element: element['number'],",
"} # Consolidate the dietary info and update the original base with it",
"logger.info('Starting') # Get the scrappers ready europa_scrapper = EuropaScrapper() eaditivos_scrapper = EAditivosScrapper() laveganisteria_scrapper",
"select_dietary(dietary_info) for index, element in enumerate(additives_info): e_id = element['number'] if e_id in dietary_info.keys():",
"# 'groups': ..., # 'dietary': { # 'vegetarian': 'unknown', # 'vegan': 'unknown' #",
"'vegetarian': 'unknown', # 'vegan': 'unknown' # }, # 'authorisations': ... # } #",
"python3 import json from scrappers import EAditivosScrapper, EuropaScrapper, LaVeganisteriaScrapper from util import parse_args,",
"Get the scrappers ready europa_scrapper = EuropaScrapper() eaditivos_scrapper = EAditivosScrapper() laveganisteria_scrapper = LaVeganisteriaScrapper()",
"= parse_args() logger = setup_logger(level=args.log_level) logger.info('Starting') # Get the scrappers ready europa_scrapper =",
"several sources dietary_info = eaditivos_scrapper.get_additives() dietary_info = update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) # returns a dict",
"# number: { # 'vegetarian': ... # 'vegan': ... # } # }",
"the scrappers ready europa_scrapper = EuropaScrapper() eaditivos_scrapper = EAditivosScrapper() laveganisteria_scrapper = LaVeganisteriaScrapper() #",
"'vegetarian': ... # 'vegan': ... # } # } # Consolidate the dietary",
"= EuropaScrapper() eaditivos_scrapper = EAditivosScrapper() laveganisteria_scrapper = LaVeganisteriaScrapper() # Get the information additives_info",
"= europa_scrapper.get_additives(args.start, args.end) # returns an array of # { # 'id': ...,",
"main(): args = parse_args() logger = setup_logger(level=args.log_level) logger.info('Starting') # Get the scrappers ready",
"Get some dietary information from several sources dietary_info = eaditivos_scrapper.get_additives() dietary_info = update_dietary(dietary_info,",
"# 'vegan': ... # } # } # Consolidate the dietary info and",
"'vegan': ... # } # } # Consolidate the dietary info and update",
"..., # 'groups': ..., # 'dietary': { # 'vegetarian': 'unknown', # 'vegan': 'unknown'",
"of # { # number: { # 'vegetarian': ... # 'vegan': ... #",
"of # { # 'id': ..., # 'number': ..., # 'name': ..., #",
"# Consolidate the dietary info and update the original base with it dietary_info",
"# returns a dict of # { # number: { # 'vegetarian': ...",
"= map(lambda element: element['number'], additives_info) # Get some dietary information from several sources",
"additives_info = europa_scrapper.get_additives(args.start, args.end) # returns an array of # { # 'id':",
"{ # number: { # 'vegetarian': ... # 'vegan': ... # } #",
"we get numbers = map(lambda element: element['number'], additives_info) # Get some dietary information",
"a dict of # { # number: { # 'vegetarian': ... # 'vegan':",
"laveganisteria_scrapper.get_additives()) # returns a dict of # { # number: { # 'vegetarian':",
"..., # 'synonyms': ..., # 'groups': ..., # 'dietary': { # 'vegetarian': 'unknown',",
"file...') with open('additives.json', 'w') as file: json.dump(additives_info, file, indent=2) if __name__ == '__main__':",
"= EAditivosScrapper() laveganisteria_scrapper = LaVeganisteriaScrapper() # Get the information additives_info = europa_scrapper.get_additives(args.start, args.end)",
"# Now save the json file logger.info('Done') logger.info('Saving additives to file...') with open('additives.json',",
"from scrappers import EAditivosScrapper, EuropaScrapper, LaVeganisteriaScrapper from util import parse_args, select_dietary, setup_logger, update_dietary",
"the dietary info and update the original base with it dietary_info = select_dietary(dietary_info)",
"# } # Consolidate the dietary info and update the original base with",
"# 'vegetarian': ... # 'vegan': ... # } # } # Consolidate the",
"'groups': ..., # 'dietary': { # 'vegetarian': 'unknown', # 'vegan': 'unknown' # },",
"} # See which numbers we get numbers = map(lambda element: element['number'], additives_info)",
"EAditivosScrapper, EuropaScrapper, LaVeganisteriaScrapper from util import parse_args, select_dietary, setup_logger, update_dietary def main(): args",
"'name': ..., # 'synonyms': ..., # 'groups': ..., # 'dietary': { # 'vegetarian':",
"dietary info and update the original base with it dietary_info = select_dietary(dietary_info) for",
"EAditivosScrapper() laveganisteria_scrapper = LaVeganisteriaScrapper() # Get the information additives_info = europa_scrapper.get_additives(args.start, args.end) #",
"get numbers = map(lambda element: element['number'], additives_info) # Get some dietary information from",
"europa_scrapper.get_additives(args.start, args.end) # returns an array of # { # 'id': ..., #",
"element in enumerate(additives_info): e_id = element['number'] if e_id in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) # Now",
"parse_args() logger = setup_logger(level=args.log_level) logger.info('Starting') # Get the scrappers ready europa_scrapper = EuropaScrapper()",
"information from several sources dietary_info = eaditivos_scrapper.get_additives() dietary_info = update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) # returns",
"dietary_info = select_dietary(dietary_info) for index, element in enumerate(additives_info): e_id = element['number'] if e_id",
"index, element in enumerate(additives_info): e_id = element['number'] if e_id in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) #",
"util import parse_args, select_dietary, setup_logger, update_dietary def main(): args = parse_args() logger =",
"Get the information additives_info = europa_scrapper.get_additives(args.start, args.end) # returns an array of #",
"europa_scrapper = EuropaScrapper() eaditivos_scrapper = EAditivosScrapper() laveganisteria_scrapper = LaVeganisteriaScrapper() # Get the information",
"# 'dietary': { # 'vegetarian': 'unknown', # 'vegan': 'unknown' # }, # 'authorisations':",
"scrappers import EAditivosScrapper, EuropaScrapper, LaVeganisteriaScrapper from util import parse_args, select_dietary, setup_logger, update_dietary def",
"file logger.info('Done') logger.info('Saving additives to file...') with open('additives.json', 'w') as file: json.dump(additives_info, file,",
"dietary_info = update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) # returns a dict of # { # number:",
"in enumerate(additives_info): e_id = element['number'] if e_id in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) # Now save",
"number: { # 'vegetarian': ... # 'vegan': ... # } # } #",
"update_dietary def main(): args = parse_args() logger = setup_logger(level=args.log_level) logger.info('Starting') # Get the",
"args.end) # returns an array of # { # 'id': ..., # 'number':",
"update the original base with it dietary_info = select_dietary(dietary_info) for index, element in",
"..., # 'name': ..., # 'synonyms': ..., # 'groups': ..., # 'dietary': {",
"See which numbers we get numbers = map(lambda element: element['number'], additives_info) # Get",
"# { # 'id': ..., # 'number': ..., # 'name': ..., # 'synonyms':",
"additives_info) # Get some dietary information from several sources dietary_info = eaditivos_scrapper.get_additives() dietary_info",
"the original base with it dietary_info = select_dietary(dietary_info) for index, element in enumerate(additives_info):",
"eaditivos_scrapper.get_additives() dietary_info = update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) # returns a dict of # { #",
"ready europa_scrapper = EuropaScrapper() eaditivos_scrapper = EAditivosScrapper() laveganisteria_scrapper = LaVeganisteriaScrapper() # Get the",
"dict of # { # number: { # 'vegetarian': ... # 'vegan': ...",
"element['number'], additives_info) # Get some dietary information from several sources dietary_info = eaditivos_scrapper.get_additives()",
"additives_info[index]['dietary'].update(dietary_info[e_id]) # Now save the json file logger.info('Done') logger.info('Saving additives to file...') with",
"{ # 'id': ..., # 'number': ..., # 'name': ..., # 'synonyms': ...,",
"numbers we get numbers = map(lambda element: element['number'], additives_info) # Get some dietary",
"<filename>main.py #!/usr/bin/env python3 import json from scrappers import EAditivosScrapper, EuropaScrapper, LaVeganisteriaScrapper from util",
"json from scrappers import EAditivosScrapper, EuropaScrapper, LaVeganisteriaScrapper from util import parse_args, select_dietary, setup_logger,",
"update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) # returns a dict of # { # number: { #",
"EuropaScrapper() eaditivos_scrapper = EAditivosScrapper() laveganisteria_scrapper = LaVeganisteriaScrapper() # Get the information additives_info =",
"import json from scrappers import EAditivosScrapper, EuropaScrapper, LaVeganisteriaScrapper from util import parse_args, select_dietary,",
"dietary information from several sources dietary_info = eaditivos_scrapper.get_additives() dietary_info = update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) #",
"{ # 'vegetarian': 'unknown', # 'vegan': 'unknown' # }, # 'authorisations': ... #",
"if e_id in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) # Now save the json file logger.info('Done') logger.info('Saving",
"= eaditivos_scrapper.get_additives() dietary_info = update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) # returns a dict of # {",
"EuropaScrapper, LaVeganisteriaScrapper from util import parse_args, select_dietary, setup_logger, update_dietary def main(): args =",
"= setup_logger(level=args.log_level) logger.info('Starting') # Get the scrappers ready europa_scrapper = EuropaScrapper() eaditivos_scrapper =",
"= update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) # returns a dict of # { # number: {",
"= select_dietary(dietary_info) for index, element in enumerate(additives_info): e_id = element['number'] if e_id in",
"info and update the original base with it dietary_info = select_dietary(dietary_info) for index,",
"Consolidate the dietary info and update the original base with it dietary_info =",
"array of # { # 'id': ..., # 'number': ..., # 'name': ...,",
"from several sources dietary_info = eaditivos_scrapper.get_additives() dietary_info = update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) # returns a",
"'unknown', # 'vegan': 'unknown' # }, # 'authorisations': ... # } # See",
"# 'vegetarian': 'unknown', # 'vegan': 'unknown' # }, # 'authorisations': ... # }",
"with it dietary_info = select_dietary(dietary_info) for index, element in enumerate(additives_info): e_id = element['number']",
"numbers = map(lambda element: element['number'], additives_info) # Get some dietary information from several",
"dietary_info = eaditivos_scrapper.get_additives() dietary_info = update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) # returns a dict of #",
"e_id in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) # Now save the json file logger.info('Done') logger.info('Saving additives",
"with open('additives.json', 'w') as file: json.dump(additives_info, file, indent=2) if __name__ == '__main__': main()",
"import parse_args, select_dietary, setup_logger, update_dietary def main(): args = parse_args() logger = setup_logger(level=args.log_level)",
"# See which numbers we get numbers = map(lambda element: element['number'], additives_info) #",
"setup_logger(level=args.log_level) logger.info('Starting') # Get the scrappers ready europa_scrapper = EuropaScrapper() eaditivos_scrapper = EAditivosScrapper()",
"# 'vegan': 'unknown' # }, # 'authorisations': ... # } # See which",
"setup_logger, update_dietary def main(): args = parse_args() logger = setup_logger(level=args.log_level) logger.info('Starting') # Get",
"some dietary information from several sources dietary_info = eaditivos_scrapper.get_additives() dietary_info = update_dietary(dietary_info, laveganisteria_scrapper.get_additives())",
"and update the original base with it dietary_info = select_dietary(dietary_info) for index, element",
"..., # 'dietary': { # 'vegetarian': 'unknown', # 'vegan': 'unknown' # }, #",
"# { # number: { # 'vegetarian': ... # 'vegan': ... # }",
"'authorisations': ... # } # See which numbers we get numbers = map(lambda",
"for index, element in enumerate(additives_info): e_id = element['number'] if e_id in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id])",
"save the json file logger.info('Done') logger.info('Saving additives to file...') with open('additives.json', 'w') as",
"# } # } # Consolidate the dietary info and update the original",
"it dietary_info = select_dietary(dietary_info) for index, element in enumerate(additives_info): e_id = element['number'] if",
"logger.info('Done') logger.info('Saving additives to file...') with open('additives.json', 'w') as file: json.dump(additives_info, file, indent=2)",
"'id': ..., # 'number': ..., # 'name': ..., # 'synonyms': ..., # 'groups':",
"element['number'] if e_id in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) # Now save the json file logger.info('Done')",
"# 'name': ..., # 'synonyms': ..., # 'groups': ..., # 'dietary': { #",
"# 'number': ..., # 'name': ..., # 'synonyms': ..., # 'groups': ..., #",
"from util import parse_args, select_dietary, setup_logger, update_dietary def main(): args = parse_args() logger",
"information additives_info = europa_scrapper.get_additives(args.start, args.end) # returns an array of # { #",
"logger = setup_logger(level=args.log_level) logger.info('Starting') # Get the scrappers ready europa_scrapper = EuropaScrapper() eaditivos_scrapper",
"#!/usr/bin/env python3 import json from scrappers import EAditivosScrapper, EuropaScrapper, LaVeganisteriaScrapper from util import",
"'dietary': { # 'vegetarian': 'unknown', # 'vegan': 'unknown' # }, # 'authorisations': ...",
"= element['number'] if e_id in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) # Now save the json file",
"'vegan': 'unknown' # }, # 'authorisations': ... # } # See which numbers",
"} # } # Consolidate the dietary info and update the original base",
"Now save the json file logger.info('Done') logger.info('Saving additives to file...') with open('additives.json', 'w')",
"... # } # } # Consolidate the dietary info and update the",
"sources dietary_info = eaditivos_scrapper.get_additives() dietary_info = update_dietary(dietary_info, laveganisteria_scrapper.get_additives()) # returns a dict of",
"additives to file...') with open('additives.json', 'w') as file: json.dump(additives_info, file, indent=2) if __name__",
"returns a dict of # { # number: { # 'vegetarian': ... #",
"LaVeganisteriaScrapper from util import parse_args, select_dietary, setup_logger, update_dietary def main(): args = parse_args()",
"}, # 'authorisations': ... # } # See which numbers we get numbers",
"original base with it dietary_info = select_dietary(dietary_info) for index, element in enumerate(additives_info): e_id",
"returns an array of # { # 'id': ..., # 'number': ..., #",
"def main(): args = parse_args() logger = setup_logger(level=args.log_level) logger.info('Starting') # Get the scrappers",
"LaVeganisteriaScrapper() # Get the information additives_info = europa_scrapper.get_additives(args.start, args.end) # returns an array",
"# returns an array of # { # 'id': ..., # 'number': ...,",
"laveganisteria_scrapper = LaVeganisteriaScrapper() # Get the information additives_info = europa_scrapper.get_additives(args.start, args.end) # returns",
"... # } # See which numbers we get numbers = map(lambda element:",
"map(lambda element: element['number'], additives_info) # Get some dietary information from several sources dietary_info",
"eaditivos_scrapper = EAditivosScrapper() laveganisteria_scrapper = LaVeganisteriaScrapper() # Get the information additives_info = europa_scrapper.get_additives(args.start,",
"the information additives_info = europa_scrapper.get_additives(args.start, args.end) # returns an array of # {",
"..., # 'number': ..., # 'name': ..., # 'synonyms': ..., # 'groups': ...,",
"which numbers we get numbers = map(lambda element: element['number'], additives_info) # Get some",
"'unknown' # }, # 'authorisations': ... # } # See which numbers we",
"{ # 'vegetarian': ... # 'vegan': ... # } # } # Consolidate",
"# 'authorisations': ... # } # See which numbers we get numbers =",
"in dietary_info.keys(): additives_info[index]['dietary'].update(dietary_info[e_id]) # Now save the json file logger.info('Done') logger.info('Saving additives to",
"'synonyms': ..., # 'groups': ..., # 'dietary': { # 'vegetarian': 'unknown', # 'vegan':",
"# }, # 'authorisations': ... # } # See which numbers we get",
"args = parse_args() logger = setup_logger(level=args.log_level) logger.info('Starting') # Get the scrappers ready europa_scrapper",
"# 'synonyms': ..., # 'groups': ..., # 'dietary': { # 'vegetarian': 'unknown', #",
"an array of # { # 'id': ..., # 'number': ..., # 'name':"
] |
[
"= np.abs(weights[-1]) w_input = np.abs(weights[0]) for i in range(len(weights) - 2, 0, -1):",
"= create_mlp([feats.shape[1]] + arch + [1]).to(device) model, mlp_loss = train(model, data_loaders, device=device, **kwargs)",
"numpy as np import torch from torch.utils import data from multilayer_perceptron import *",
"def preprocess_weights(weights): w_later = np.abs(weights[-1]) w_input = np.abs(weights[0]) for i in range(len(weights) -",
"else: return interaction_ranking def prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned = [] current_superset_inters = [] for",
"> superset_inter): update_superset_inters.append(superset_inter) if subset_inter_skip: continue current_superset_inters = update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength)) return",
"not in interaction_strengths: interaction_strengths[interaction_tup] = 0 interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:, i])) interaction_strengths[interaction_tup]",
"< superset_inter: subset_inter_skip = True break elif not (set_inter > superset_inter): update_superset_inters.append(superset_inter) if",
"+ arch + [1]).to(device) model, mlp_loss = train(model, data_loaders, device=device, **kwargs) inters =",
"w_later, get_main_effects=False): interaction_strengths = {} for i in range(w_later.shape[1]): sorted_hweights = sorted( enumerate(w_input[i]),",
"continue interaction_tup = tuple(interaction_candidate) if interaction_tup not in interaction_strengths: interaction_strengths[interaction_tup] = 0 interaction_strength",
"make_one_indexed(interaction_ranking) else: return interaction_ranking def prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned = [] current_superset_inters = []",
"update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength)) return interaction_ranking_pruned def detect_interactions( Xd, Yd, arch=[256, 128, 64],",
"if i < j: strength = (np.minimum(w_input[:, i], w_input[:, j]) * w_later).sum() interaction_ranking.append(((i,",
"for i in range(p): for j in range(p): if i < j: strength",
"interaction_strengths[interaction_tup] += interaction_strength interaction_ranking = sorted( interaction_strengths.items(), key=operator.itemgetter(1), reverse=True ) return interaction_ranking def",
") interaction_candidate = [] candidate_weights = [] for j in range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0])",
"w_later): p = w_input.shape[1] interaction_ranking = [] for i in range(p): for j",
"w_later) else: interaction_ranking = interpret_interactions(w_input, w_later) interaction_ranking = prune_redundant_interactions(interaction_ranking) if one_indexed: return make_one_indexed(interaction_ranking)",
"is not None: set_seed(seed) data_loaders = convert_to_torch_loaders(Xd, Yd, batch_size) model = create_mlp([feats.shape[1]] +",
"import * from utils import * def preprocess_weights(weights): w_later = np.abs(weights[-1]) w_input =",
"return interaction_ranking def interpret_pairwise_interactions(w_input, w_later): p = w_input.shape[1] interaction_ranking = [] for i",
"w_later = np.abs(weights[-1]) w_input = np.abs(weights[0]) for i in range(len(weights) - 2, 0,",
"interaction_ranking: set_inter = set(inter) if len(interaction_ranking_pruned) >= max_interactions: break subset_inter_skip = False update_superset_inters",
"interaction_ranking = [] for i in range(p): for j in range(p): if i",
"set(inter) if len(interaction_ranking_pruned) >= max_interactions: break subset_inter_skip = False update_superset_inters = [] for",
"if subset_inter_skip: continue current_superset_inters = update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength)) return interaction_ranking_pruned def detect_interactions(",
"batch_size=100, device=torch.device(\"cpu\"), seed=None, **kwargs ): if seed is not None: set_seed(seed) data_loaders =",
"x[1], reverse=True ) interaction_candidate = [] candidate_weights = [] for j in range(w_input.shape[1]):",
"create_mlp([feats.shape[1]] + arch + [1]).to(device) model, mlp_loss = train(model, data_loaders, device=device, **kwargs) inters",
"model, mlp_loss = train(model, data_loaders, device=device, **kwargs) inters = get_interactions(get_weights(model)) return inters, mlp_loss",
"= interpret_pairwise_interactions(w_input, w_later) else: interaction_ranking = interpret_interactions(w_input, w_later) interaction_ranking = prune_redundant_interactions(interaction_ranking) if one_indexed:",
"64], batch_size=100, device=torch.device(\"cpu\"), seed=None, **kwargs ): if seed is not None: set_seed(seed) data_loaders",
"def make_one_indexed(interaction_ranking): return [(tuple(np.array(i) + 1), s) for i, s in interaction_ranking] def",
"import numpy as np import torch from torch.utils import data from multilayer_perceptron import",
"one_indexed: return make_one_indexed(interaction_ranking) else: return interaction_ranking def prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned = [] current_superset_inters",
"import torch from torch.utils import data from multilayer_perceptron import * from utils import",
"from multilayer_perceptron import * from utils import * def preprocess_weights(weights): w_later = np.abs(weights[-1])",
"get_main_effects=False): interaction_strengths = {} for i in range(w_later.shape[1]): sorted_hweights = sorted( enumerate(w_input[i]), key=lambda",
"candidate_weights.append(sorted_hweights[j][1]) if not get_main_effects and len(interaction_candidate) == 1: continue interaction_tup = tuple(interaction_candidate) if",
"[] for inter, strength in interaction_ranking: set_inter = set(inter) if len(interaction_ranking_pruned) >= max_interactions:",
"preprocess_weights(weights) if pairwise: interaction_ranking = interpret_pairwise_interactions(w_input, w_later) else: interaction_ranking = interpret_interactions(w_input, w_later) interaction_ranking",
"not None: set_seed(seed) data_loaders = convert_to_torch_loaders(Xd, Yd, batch_size) model = create_mlp([feats.shape[1]] + arch",
"j in range(p): if i < j: strength = (np.minimum(w_input[:, i], w_input[:, j])",
"= interpret_interactions(w_input, w_later) interaction_ranking = prune_redundant_interactions(interaction_ranking) if one_indexed: return make_one_indexed(interaction_ranking) else: return interaction_ranking",
"len(interaction_candidate) == 1: continue interaction_tup = tuple(interaction_candidate) if interaction_tup not in interaction_strengths: interaction_strengths[interaction_tup]",
"= tuple(interaction_candidate) if interaction_tup not in interaction_strengths: interaction_strengths[interaction_tup] = 0 interaction_strength = (min(candidate_weights))",
"np import torch from torch.utils import data from multilayer_perceptron import * from utils",
"if interaction_tup not in interaction_strengths: interaction_strengths[interaction_tup] = 0 interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:,",
"= [] for i in range(p): for j in range(p): if i <",
"interaction_ranking_pruned.append((inter, strength)) return interaction_ranking_pruned def detect_interactions( Xd, Yd, arch=[256, 128, 64], batch_size=100, device=torch.device(\"cpu\"),",
"x: x[1], reverse=True ) interaction_candidate = [] candidate_weights = [] for j in",
"max_interactions=100): interaction_ranking_pruned = [] current_superset_inters = [] for inter, strength in interaction_ranking: set_inter",
"interaction_ranking def get_interactions(weights, pairwise=False, one_indexed=False): w_input, w_later = preprocess_weights(weights) if pairwise: interaction_ranking =",
"one_indexed=False): w_input, w_later = preprocess_weights(weights) if pairwise: interaction_ranking = interpret_pairwise_interactions(w_input, w_later) else: interaction_ranking",
"import * def preprocess_weights(weights): w_later = np.abs(weights[-1]) w_input = np.abs(weights[0]) for i in",
"superset_inter): update_superset_inters.append(superset_inter) if subset_inter_skip: continue current_superset_inters = update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength)) return interaction_ranking_pruned",
"pairwise: interaction_ranking = interpret_pairwise_interactions(w_input, w_later) else: interaction_ranking = interpret_interactions(w_input, w_later) interaction_ranking = prune_redundant_interactions(interaction_ranking)",
"pairwise=False, one_indexed=False): w_input, w_later = preprocess_weights(weights) if pairwise: interaction_ranking = interpret_pairwise_interactions(w_input, w_later) else:",
"[1]).to(device) model, mlp_loss = train(model, data_loaders, device=device, **kwargs) inters = get_interactions(get_weights(model)) return inters,",
"in range(p): if i < j: strength = (np.minimum(w_input[:, i], w_input[:, j]) *",
"interaction_tup not in interaction_strengths: interaction_strengths[interaction_tup] = 0 interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:, i]))",
"for i, s in interaction_ranking] def interpret_interactions(w_input, w_later, get_main_effects=False): interaction_strengths = {} for",
"for j in range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if not get_main_effects and len(interaction_candidate) ==",
"np.matmul(w_later, np.abs(weights[i])) return w_input, w_later def make_one_indexed(interaction_ranking): return [(tuple(np.array(i) + 1), s) for",
"j]) * w_later).sum() interaction_ranking.append(((i, j), strength)) interaction_ranking.sort(key=lambda x: x[1], reverse=True) return interaction_ranking def",
"in range(p): for j in range(p): if i < j: strength = (np.minimum(w_input[:,",
"import data from multilayer_perceptron import * from utils import * def preprocess_weights(weights): w_later",
"j), strength)) interaction_ranking.sort(key=lambda x: x[1], reverse=True) return interaction_ranking def get_interactions(weights, pairwise=False, one_indexed=False): w_input,",
"= [] candidate_weights = [] for j in range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if",
"get_interactions(weights, pairwise=False, one_indexed=False): w_input, w_later = preprocess_weights(weights) if pairwise: interaction_ranking = interpret_pairwise_interactions(w_input, w_later)",
"128, 64], batch_size=100, device=torch.device(\"cpu\"), seed=None, **kwargs ): if seed is not None: set_seed(seed)",
"* (np.sum(w_later[:, i])) interaction_strengths[interaction_tup] += interaction_strength interaction_ranking = sorted( interaction_strengths.items(), key=operator.itemgetter(1), reverse=True )",
"for i in range(w_later.shape[1]): sorted_hweights = sorted( enumerate(w_input[i]), key=lambda x: x[1], reverse=True )",
"interaction_candidate = [] candidate_weights = [] for j in range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1])",
"[] current_superset_inters = [] for inter, strength in interaction_ranking: set_inter = set(inter) if",
"set_inter < superset_inter: subset_inter_skip = True break elif not (set_inter > superset_inter): update_superset_inters.append(superset_inter)",
"not get_main_effects and len(interaction_candidate) == 1: continue interaction_tup = tuple(interaction_candidate) if interaction_tup not",
"< j: strength = (np.minimum(w_input[:, i], w_input[:, j]) * w_later).sum() interaction_ranking.append(((i, j), strength))",
"x: x[1], reverse=True) return interaction_ranking def get_interactions(weights, pairwise=False, one_indexed=False): w_input, w_later = preprocess_weights(weights)",
"): if seed is not None: set_seed(seed) data_loaders = convert_to_torch_loaders(Xd, Yd, batch_size) model",
"if seed is not None: set_seed(seed) data_loaders = convert_to_torch_loaders(Xd, Yd, batch_size) model =",
"= np.abs(weights[0]) for i in range(len(weights) - 2, 0, -1): w_later = np.matmul(w_later,",
"Yd, arch=[256, 128, 64], batch_size=100, device=torch.device(\"cpu\"), seed=None, **kwargs ): if seed is not",
"interaction_strengths: interaction_strengths[interaction_tup] = 0 interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:, i])) interaction_strengths[interaction_tup] += interaction_strength",
"def detect_interactions( Xd, Yd, arch=[256, 128, 64], batch_size=100, device=torch.device(\"cpu\"), seed=None, **kwargs ): if",
"interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:, i])) interaction_strengths[interaction_tup] += interaction_strength interaction_ranking = sorted( interaction_strengths.items(),",
"return interaction_ranking def prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned = [] current_superset_inters = [] for inter,",
"if set_inter < superset_inter: subset_inter_skip = True break elif not (set_inter > superset_inter):",
"= update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength)) return interaction_ranking_pruned def detect_interactions( Xd, Yd, arch=[256, 128,",
"= [] for superset_inter in current_superset_inters: if set_inter < superset_inter: subset_inter_skip = True",
"return interaction_ranking_pruned def detect_interactions( Xd, Yd, arch=[256, 128, 64], batch_size=100, device=torch.device(\"cpu\"), seed=None, **kwargs",
"in interaction_strengths: interaction_strengths[interaction_tup] = 0 interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:, i])) interaction_strengths[interaction_tup] +=",
"return make_one_indexed(interaction_ranking) else: return interaction_ranking def prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned = [] current_superset_inters =",
"detect_interactions( Xd, Yd, arch=[256, 128, 64], batch_size=100, device=torch.device(\"cpu\"), seed=None, **kwargs ): if seed",
"(np.minimum(w_input[:, i], w_input[:, j]) * w_later).sum() interaction_ranking.append(((i, j), strength)) interaction_ranking.sort(key=lambda x: x[1], reverse=True)",
"= [] current_superset_inters = [] for inter, strength in interaction_ranking: set_inter = set(inter)",
"torch.utils import data from multilayer_perceptron import * from utils import * def preprocess_weights(weights):",
"x[1], reverse=True) return interaction_ranking def get_interactions(weights, pairwise=False, one_indexed=False): w_input, w_later = preprocess_weights(weights) if",
"sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if not get_main_effects and len(interaction_candidate) == 1: continue interaction_tup = tuple(interaction_candidate)",
"seed is not None: set_seed(seed) data_loaders = convert_to_torch_loaders(Xd, Yd, batch_size) model = create_mlp([feats.shape[1]]",
"import operator import numpy as np import torch from torch.utils import data from",
"w_later def make_one_indexed(interaction_ranking): return [(tuple(np.array(i) + 1), s) for i, s in interaction_ranking]",
"interpret_interactions(w_input, w_later, get_main_effects=False): interaction_strengths = {} for i in range(w_later.shape[1]): sorted_hweights = sorted(",
"sorted( interaction_strengths.items(), key=operator.itemgetter(1), reverse=True ) return interaction_ranking def interpret_pairwise_interactions(w_input, w_later): p = w_input.shape[1]",
"reverse=True ) return interaction_ranking def interpret_pairwise_interactions(w_input, w_later): p = w_input.shape[1] interaction_ranking = []",
"strength = (np.minimum(w_input[:, i], w_input[:, j]) * w_later).sum() interaction_ranking.append(((i, j), strength)) interaction_ranking.sort(key=lambda x:",
"def get_interactions(weights, pairwise=False, one_indexed=False): w_input, w_later = preprocess_weights(weights) if pairwise: interaction_ranking = interpret_pairwise_interactions(w_input,",
"= prune_redundant_interactions(interaction_ranking) if one_indexed: return make_one_indexed(interaction_ranking) else: return interaction_ranking def prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned",
"prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned = [] current_superset_inters = [] for inter, strength in interaction_ranking:",
"= convert_to_torch_loaders(Xd, Yd, batch_size) model = create_mlp([feats.shape[1]] + arch + [1]).to(device) model, mlp_loss",
"return w_input, w_later def make_one_indexed(interaction_ranking): return [(tuple(np.array(i) + 1), s) for i, s",
"Yd, batch_size) model = create_mlp([feats.shape[1]] + arch + [1]).to(device) model, mlp_loss = train(model,",
"interaction_ranking.append(((i, j), strength)) interaction_ranking.sort(key=lambda x: x[1], reverse=True) return interaction_ranking def get_interactions(weights, pairwise=False, one_indexed=False):",
"for inter, strength in interaction_ranking: set_inter = set(inter) if len(interaction_ranking_pruned) >= max_interactions: break",
"arch + [1]).to(device) model, mlp_loss = train(model, data_loaders, device=device, **kwargs) inters = get_interactions(get_weights(model))",
"interaction_ranking_pruned def detect_interactions( Xd, Yd, arch=[256, 128, 64], batch_size=100, device=torch.device(\"cpu\"), seed=None, **kwargs ):",
"w_later = np.matmul(w_later, np.abs(weights[i])) return w_input, w_later def make_one_indexed(interaction_ranking): return [(tuple(np.array(i) + 1),",
"sorted( enumerate(w_input[i]), key=lambda x: x[1], reverse=True ) interaction_candidate = [] candidate_weights = []",
"batch_size) model = create_mlp([feats.shape[1]] + arch + [1]).to(device) model, mlp_loss = train(model, data_loaders,",
"+= interaction_strength interaction_ranking = sorted( interaction_strengths.items(), key=operator.itemgetter(1), reverse=True ) return interaction_ranking def interpret_pairwise_interactions(w_input,",
"bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if not get_main_effects and len(interaction_candidate) == 1: continue interaction_tup =",
"as np import torch from torch.utils import data from multilayer_perceptron import * from",
"current_superset_inters = update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength)) return interaction_ranking_pruned def detect_interactions( Xd, Yd, arch=[256,",
"strength)) return interaction_ranking_pruned def detect_interactions( Xd, Yd, arch=[256, 128, 64], batch_size=100, device=torch.device(\"cpu\"), seed=None,",
"set_inter = set(inter) if len(interaction_ranking_pruned) >= max_interactions: break subset_inter_skip = False update_superset_inters =",
"def interpret_interactions(w_input, w_later, get_main_effects=False): interaction_strengths = {} for i in range(w_later.shape[1]): sorted_hweights =",
"w_input, w_later = preprocess_weights(weights) if pairwise: interaction_ranking = interpret_pairwise_interactions(w_input, w_later) else: interaction_ranking =",
"def interpret_pairwise_interactions(w_input, w_later): p = w_input.shape[1] interaction_ranking = [] for i in range(p):",
"def prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned = [] current_superset_inters = [] for inter, strength in",
"None: set_seed(seed) data_loaders = convert_to_torch_loaders(Xd, Yd, batch_size) model = create_mlp([feats.shape[1]] + arch +",
"interaction_strengths[interaction_tup] = 0 interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:, i])) interaction_strengths[interaction_tup] += interaction_strength interaction_ranking",
"False update_superset_inters = [] for superset_inter in current_superset_inters: if set_inter < superset_inter: subset_inter_skip",
"interaction_strength interaction_ranking = sorted( interaction_strengths.items(), key=operator.itemgetter(1), reverse=True ) return interaction_ranking def interpret_pairwise_interactions(w_input, w_later):",
"w_input = np.abs(weights[0]) for i in range(len(weights) - 2, 0, -1): w_later =",
"reverse=True ) interaction_candidate = [] candidate_weights = [] for j in range(w_input.shape[1]): bisect.insort(interaction_candidate,",
"torch from torch.utils import data from multilayer_perceptron import * from utils import *",
"if not get_main_effects and len(interaction_candidate) == 1: continue interaction_tup = tuple(interaction_candidate) if interaction_tup",
"True break elif not (set_inter > superset_inter): update_superset_inters.append(superset_inter) if subset_inter_skip: continue current_superset_inters =",
"**kwargs ): if seed is not None: set_seed(seed) data_loaders = convert_to_torch_loaders(Xd, Yd, batch_size)",
"= True break elif not (set_inter > superset_inter): update_superset_inters.append(superset_inter) if subset_inter_skip: continue current_superset_inters",
"[(tuple(np.array(i) + 1), s) for i, s in interaction_ranking] def interpret_interactions(w_input, w_later, get_main_effects=False):",
"0, -1): w_later = np.matmul(w_later, np.abs(weights[i])) return w_input, w_later def make_one_indexed(interaction_ranking): return [(tuple(np.array(i)",
"elif not (set_inter > superset_inter): update_superset_inters.append(superset_inter) if subset_inter_skip: continue current_superset_inters = update_superset_inters current_superset_inters.append(set_inter)",
"= {} for i in range(w_later.shape[1]): sorted_hweights = sorted( enumerate(w_input[i]), key=lambda x: x[1],",
"np.abs(weights[0]) for i in range(len(weights) - 2, 0, -1): w_later = np.matmul(w_later, np.abs(weights[i]))",
"range(p): for j in range(p): if i < j: strength = (np.minimum(w_input[:, i],",
"seed=None, **kwargs ): if seed is not None: set_seed(seed) data_loaders = convert_to_torch_loaders(Xd, Yd,",
"Xd, Yd, arch=[256, 128, 64], batch_size=100, device=torch.device(\"cpu\"), seed=None, **kwargs ): if seed is",
"from utils import * def preprocess_weights(weights): w_later = np.abs(weights[-1]) w_input = np.abs(weights[0]) for",
"interaction_ranking_pruned = [] current_superset_inters = [] for inter, strength in interaction_ranking: set_inter =",
"interaction_strengths = {} for i in range(w_later.shape[1]): sorted_hweights = sorted( enumerate(w_input[i]), key=lambda x:",
"interpret_interactions(w_input, w_later) interaction_ranking = prune_redundant_interactions(interaction_ranking) if one_indexed: return make_one_indexed(interaction_ranking) else: return interaction_ranking def",
"0 interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:, i])) interaction_strengths[interaction_tup] += interaction_strength interaction_ranking = sorted(",
"current_superset_inters = [] for inter, strength in interaction_ranking: set_inter = set(inter) if len(interaction_ranking_pruned)",
"update_superset_inters.append(superset_inter) if subset_inter_skip: continue current_superset_inters = update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength)) return interaction_ranking_pruned def",
"j in range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if not get_main_effects and len(interaction_candidate) == 1:",
"interaction_ranking = sorted( interaction_strengths.items(), key=operator.itemgetter(1), reverse=True ) return interaction_ranking def interpret_pairwise_interactions(w_input, w_later): p",
"w_input, w_later def make_one_indexed(interaction_ranking): return [(tuple(np.array(i) + 1), s) for i, s in",
"interaction_ranking] def interpret_interactions(w_input, w_later, get_main_effects=False): interaction_strengths = {} for i in range(w_later.shape[1]): sorted_hweights",
"in range(w_later.shape[1]): sorted_hweights = sorted( enumerate(w_input[i]), key=lambda x: x[1], reverse=True ) interaction_candidate =",
"range(len(weights) - 2, 0, -1): w_later = np.matmul(w_later, np.abs(weights[i])) return w_input, w_later def",
"[] for i in range(p): for j in range(p): if i < j:",
"if pairwise: interaction_ranking = interpret_pairwise_interactions(w_input, w_later) else: interaction_ranking = interpret_interactions(w_input, w_later) interaction_ranking =",
"superset_inter: subset_inter_skip = True break elif not (set_inter > superset_inter): update_superset_inters.append(superset_inter) if subset_inter_skip:",
"= np.matmul(w_later, np.abs(weights[i])) return w_input, w_later def make_one_indexed(interaction_ranking): return [(tuple(np.array(i) + 1), s)",
"data_loaders = convert_to_torch_loaders(Xd, Yd, batch_size) model = create_mlp([feats.shape[1]] + arch + [1]).to(device) model,",
"in range(len(weights) - 2, 0, -1): w_later = np.matmul(w_later, np.abs(weights[i])) return w_input, w_later",
"= sorted( enumerate(w_input[i]), key=lambda x: x[1], reverse=True ) interaction_candidate = [] candidate_weights =",
"if one_indexed: return make_one_indexed(interaction_ranking) else: return interaction_ranking def prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned = []",
"range(p): if i < j: strength = (np.minimum(w_input[:, i], w_input[:, j]) * w_later).sum()",
">= max_interactions: break subset_inter_skip = False update_superset_inters = [] for superset_inter in current_superset_inters:",
"make_one_indexed(interaction_ranking): return [(tuple(np.array(i) + 1), s) for i, s in interaction_ranking] def interpret_interactions(w_input,",
"s) for i, s in interaction_ranking] def interpret_interactions(w_input, w_later, get_main_effects=False): interaction_strengths = {}",
"range(w_later.shape[1]): sorted_hweights = sorted( enumerate(w_input[i]), key=lambda x: x[1], reverse=True ) interaction_candidate = []",
"w_input[:, j]) * w_later).sum() interaction_ranking.append(((i, j), strength)) interaction_ranking.sort(key=lambda x: x[1], reverse=True) return interaction_ranking",
"interaction_ranking = interpret_pairwise_interactions(w_input, w_later) else: interaction_ranking = interpret_interactions(w_input, w_later) interaction_ranking = prune_redundant_interactions(interaction_ranking) if",
"subset_inter_skip = False update_superset_inters = [] for superset_inter in current_superset_inters: if set_inter <",
"import bisect import operator import numpy as np import torch from torch.utils import",
"interaction_ranking def prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned = [] current_superset_inters = [] for inter, strength",
"device=torch.device(\"cpu\"), seed=None, **kwargs ): if seed is not None: set_seed(seed) data_loaders = convert_to_torch_loaders(Xd,",
"= preprocess_weights(weights) if pairwise: interaction_ranking = interpret_pairwise_interactions(w_input, w_later) else: interaction_ranking = interpret_interactions(w_input, w_later)",
"+ [1]).to(device) model, mlp_loss = train(model, data_loaders, device=device, **kwargs) inters = get_interactions(get_weights(model)) return",
"continue current_superset_inters = update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength)) return interaction_ranking_pruned def detect_interactions( Xd, Yd,",
"w_input.shape[1] interaction_ranking = [] for i in range(p): for j in range(p): if",
"if len(interaction_ranking_pruned) >= max_interactions: break subset_inter_skip = False update_superset_inters = [] for superset_inter",
"convert_to_torch_loaders(Xd, Yd, batch_size) model = create_mlp([feats.shape[1]] + arch + [1]).to(device) model, mlp_loss =",
"for j in range(p): if i < j: strength = (np.minimum(w_input[:, i], w_input[:,",
"candidate_weights = [] for j in range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if not get_main_effects",
"interaction_ranking.sort(key=lambda x: x[1], reverse=True) return interaction_ranking def get_interactions(weights, pairwise=False, one_indexed=False): w_input, w_later =",
"np.abs(weights[i])) return w_input, w_later def make_one_indexed(interaction_ranking): return [(tuple(np.array(i) + 1), s) for i,",
"return [(tuple(np.array(i) + 1), s) for i, s in interaction_ranking] def interpret_interactions(w_input, w_later,",
"i, s in interaction_ranking] def interpret_interactions(w_input, w_later, get_main_effects=False): interaction_strengths = {} for i",
"interaction_tup = tuple(interaction_candidate) if interaction_tup not in interaction_strengths: interaction_strengths[interaction_tup] = 0 interaction_strength =",
"multilayer_perceptron import * from utils import * def preprocess_weights(weights): w_later = np.abs(weights[-1]) w_input",
"utils import * def preprocess_weights(weights): w_later = np.abs(weights[-1]) w_input = np.abs(weights[0]) for i",
"inter, strength in interaction_ranking: set_inter = set(inter) if len(interaction_ranking_pruned) >= max_interactions: break subset_inter_skip",
"for superset_inter in current_superset_inters: if set_inter < superset_inter: subset_inter_skip = True break elif",
"+ 1), s) for i, s in interaction_ranking] def interpret_interactions(w_input, w_later, get_main_effects=False): interaction_strengths",
"in interaction_ranking: set_inter = set(inter) if len(interaction_ranking_pruned) >= max_interactions: break subset_inter_skip = False",
"i in range(p): for j in range(p): if i < j: strength =",
"i in range(len(weights) - 2, 0, -1): w_later = np.matmul(w_later, np.abs(weights[i])) return w_input,",
"reverse=True) return interaction_ranking def get_interactions(weights, pairwise=False, one_indexed=False): w_input, w_later = preprocess_weights(weights) if pairwise:",
"1: continue interaction_tup = tuple(interaction_candidate) if interaction_tup not in interaction_strengths: interaction_strengths[interaction_tup] = 0",
"in interaction_ranking] def interpret_interactions(w_input, w_later, get_main_effects=False): interaction_strengths = {} for i in range(w_later.shape[1]):",
"* w_later).sum() interaction_ranking.append(((i, j), strength)) interaction_ranking.sort(key=lambda x: x[1], reverse=True) return interaction_ranking def get_interactions(weights,",
"current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength)) return interaction_ranking_pruned def detect_interactions( Xd, Yd, arch=[256, 128, 64], batch_size=100,",
"i])) interaction_strengths[interaction_tup] += interaction_strength interaction_ranking = sorted( interaction_strengths.items(), key=operator.itemgetter(1), reverse=True ) return interaction_ranking",
"i < j: strength = (np.minimum(w_input[:, i], w_input[:, j]) * w_later).sum() interaction_ranking.append(((i, j),",
"bisect import operator import numpy as np import torch from torch.utils import data",
"break elif not (set_inter > superset_inter): update_superset_inters.append(superset_inter) if subset_inter_skip: continue current_superset_inters = update_superset_inters",
"preprocess_weights(weights): w_later = np.abs(weights[-1]) w_input = np.abs(weights[0]) for i in range(len(weights) - 2,",
"range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if not get_main_effects and len(interaction_candidate) == 1: continue interaction_tup",
"[] candidate_weights = [] for j in range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if not",
"- 2, 0, -1): w_later = np.matmul(w_later, np.abs(weights[i])) return w_input, w_later def make_one_indexed(interaction_ranking):",
"p = w_input.shape[1] interaction_ranking = [] for i in range(p): for j in",
"== 1: continue interaction_tup = tuple(interaction_candidate) if interaction_tup not in interaction_strengths: interaction_strengths[interaction_tup] =",
"(np.sum(w_later[:, i])) interaction_strengths[interaction_tup] += interaction_strength interaction_ranking = sorted( interaction_strengths.items(), key=operator.itemgetter(1), reverse=True ) return",
") return interaction_ranking def interpret_pairwise_interactions(w_input, w_later): p = w_input.shape[1] interaction_ranking = [] for",
"= w_input.shape[1] interaction_ranking = [] for i in range(p): for j in range(p):",
"current_superset_inters: if set_inter < superset_inter: subset_inter_skip = True break elif not (set_inter >",
"sorted_hweights = sorted( enumerate(w_input[i]), key=lambda x: x[1], reverse=True ) interaction_candidate = [] candidate_weights",
"w_later).sum() interaction_ranking.append(((i, j), strength)) interaction_ranking.sort(key=lambda x: x[1], reverse=True) return interaction_ranking def get_interactions(weights, pairwise=False,",
"prune_redundant_interactions(interaction_ranking) if one_indexed: return make_one_indexed(interaction_ranking) else: return interaction_ranking def prune_redundant_interactions(interaction_ranking, max_interactions=100): interaction_ranking_pruned =",
"for i in range(len(weights) - 2, 0, -1): w_later = np.matmul(w_later, np.abs(weights[i])) return",
"= sorted( interaction_strengths.items(), key=operator.itemgetter(1), reverse=True ) return interaction_ranking def interpret_pairwise_interactions(w_input, w_later): p =",
"enumerate(w_input[i]), key=lambda x: x[1], reverse=True ) interaction_candidate = [] candidate_weights = [] for",
"2, 0, -1): w_later = np.matmul(w_later, np.abs(weights[i])) return w_input, w_later def make_one_indexed(interaction_ranking): return",
"get_main_effects and len(interaction_candidate) == 1: continue interaction_tup = tuple(interaction_candidate) if interaction_tup not in",
"i], w_input[:, j]) * w_later).sum() interaction_ranking.append(((i, j), strength)) interaction_ranking.sort(key=lambda x: x[1], reverse=True) return",
"model = create_mlp([feats.shape[1]] + arch + [1]).to(device) model, mlp_loss = train(model, data_loaders, device=device,",
"(min(candidate_weights)) * (np.sum(w_later[:, i])) interaction_strengths[interaction_tup] += interaction_strength interaction_ranking = sorted( interaction_strengths.items(), key=operator.itemgetter(1), reverse=True",
"key=lambda x: x[1], reverse=True ) interaction_candidate = [] candidate_weights = [] for j",
"1), s) for i, s in interaction_ranking] def interpret_interactions(w_input, w_later, get_main_effects=False): interaction_strengths =",
"max_interactions: break subset_inter_skip = False update_superset_inters = [] for superset_inter in current_superset_inters: if",
"operator import numpy as np import torch from torch.utils import data from multilayer_perceptron",
"break subset_inter_skip = False update_superset_inters = [] for superset_inter in current_superset_inters: if set_inter",
"s in interaction_ranking] def interpret_interactions(w_input, w_later, get_main_effects=False): interaction_strengths = {} for i in",
"j: strength = (np.minimum(w_input[:, i], w_input[:, j]) * w_later).sum() interaction_ranking.append(((i, j), strength)) interaction_ranking.sort(key=lambda",
"= 0 interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:, i])) interaction_strengths[interaction_tup] += interaction_strength interaction_ranking =",
"from torch.utils import data from multilayer_perceptron import * from utils import * def",
"data from multilayer_perceptron import * from utils import * def preprocess_weights(weights): w_later =",
"interaction_strengths.items(), key=operator.itemgetter(1), reverse=True ) return interaction_ranking def interpret_pairwise_interactions(w_input, w_later): p = w_input.shape[1] interaction_ranking",
"interpret_pairwise_interactions(w_input, w_later) else: interaction_ranking = interpret_interactions(w_input, w_later) interaction_ranking = prune_redundant_interactions(interaction_ranking) if one_indexed: return",
"else: interaction_ranking = interpret_interactions(w_input, w_later) interaction_ranking = prune_redundant_interactions(interaction_ranking) if one_indexed: return make_one_indexed(interaction_ranking) else:",
"tuple(interaction_candidate) if interaction_tup not in interaction_strengths: interaction_strengths[interaction_tup] = 0 interaction_strength = (min(candidate_weights)) *",
"-1): w_later = np.matmul(w_later, np.abs(weights[i])) return w_input, w_later def make_one_indexed(interaction_ranking): return [(tuple(np.array(i) +",
"interaction_ranking = prune_redundant_interactions(interaction_ranking) if one_indexed: return make_one_indexed(interaction_ranking) else: return interaction_ranking def prune_redundant_interactions(interaction_ranking, max_interactions=100):",
"= set(inter) if len(interaction_ranking_pruned) >= max_interactions: break subset_inter_skip = False update_superset_inters = []",
"return interaction_ranking def get_interactions(weights, pairwise=False, one_indexed=False): w_input, w_later = preprocess_weights(weights) if pairwise: interaction_ranking",
"and len(interaction_candidate) == 1: continue interaction_tup = tuple(interaction_candidate) if interaction_tup not in interaction_strengths:",
"in current_superset_inters: if set_inter < superset_inter: subset_inter_skip = True break elif not (set_inter",
"subset_inter_skip: continue current_superset_inters = update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength)) return interaction_ranking_pruned def detect_interactions( Xd,",
"interpret_pairwise_interactions(w_input, w_later): p = w_input.shape[1] interaction_ranking = [] for i in range(p): for",
"[] for superset_inter in current_superset_inters: if set_inter < superset_inter: subset_inter_skip = True break",
"subset_inter_skip = True break elif not (set_inter > superset_inter): update_superset_inters.append(superset_inter) if subset_inter_skip: continue",
"w_later) interaction_ranking = prune_redundant_interactions(interaction_ranking) if one_indexed: return make_one_indexed(interaction_ranking) else: return interaction_ranking def prune_redundant_interactions(interaction_ranking,",
"arch=[256, 128, 64], batch_size=100, device=torch.device(\"cpu\"), seed=None, **kwargs ): if seed is not None:",
"update_superset_inters = [] for superset_inter in current_superset_inters: if set_inter < superset_inter: subset_inter_skip =",
"i in range(w_later.shape[1]): sorted_hweights = sorted( enumerate(w_input[i]), key=lambda x: x[1], reverse=True ) interaction_candidate",
"superset_inter in current_superset_inters: if set_inter < superset_inter: subset_inter_skip = True break elif not",
"strength in interaction_ranking: set_inter = set(inter) if len(interaction_ranking_pruned) >= max_interactions: break subset_inter_skip =",
"in range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if not get_main_effects and len(interaction_candidate) == 1: continue",
"= [] for j in range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if not get_main_effects and",
"{} for i in range(w_later.shape[1]): sorted_hweights = sorted( enumerate(w_input[i]), key=lambda x: x[1], reverse=True",
"strength)) interaction_ranking.sort(key=lambda x: x[1], reverse=True) return interaction_ranking def get_interactions(weights, pairwise=False, one_indexed=False): w_input, w_later",
"set_seed(seed) data_loaders = convert_to_torch_loaders(Xd, Yd, batch_size) model = create_mlp([feats.shape[1]] + arch + [1]).to(device)",
"* def preprocess_weights(weights): w_later = np.abs(weights[-1]) w_input = np.abs(weights[0]) for i in range(len(weights)",
"not (set_inter > superset_inter): update_superset_inters.append(superset_inter) if subset_inter_skip: continue current_superset_inters = update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter,",
"= [] for inter, strength in interaction_ranking: set_inter = set(inter) if len(interaction_ranking_pruned) >=",
"len(interaction_ranking_pruned) >= max_interactions: break subset_inter_skip = False update_superset_inters = [] for superset_inter in",
"[] for j in range(w_input.shape[1]): bisect.insort(interaction_candidate, sorted_hweights[j][0]) candidate_weights.append(sorted_hweights[j][1]) if not get_main_effects and len(interaction_candidate)",
"key=operator.itemgetter(1), reverse=True ) return interaction_ranking def interpret_pairwise_interactions(w_input, w_later): p = w_input.shape[1] interaction_ranking =",
"= (min(candidate_weights)) * (np.sum(w_later[:, i])) interaction_strengths[interaction_tup] += interaction_strength interaction_ranking = sorted( interaction_strengths.items(), key=operator.itemgetter(1),",
"= False update_superset_inters = [] for superset_inter in current_superset_inters: if set_inter < superset_inter:",
"= (np.minimum(w_input[:, i], w_input[:, j]) * w_later).sum() interaction_ranking.append(((i, j), strength)) interaction_ranking.sort(key=lambda x: x[1],",
"np.abs(weights[-1]) w_input = np.abs(weights[0]) for i in range(len(weights) - 2, 0, -1): w_later",
"interaction_ranking def interpret_pairwise_interactions(w_input, w_later): p = w_input.shape[1] interaction_ranking = [] for i in",
"(set_inter > superset_inter): update_superset_inters.append(superset_inter) if subset_inter_skip: continue current_superset_inters = update_superset_inters current_superset_inters.append(set_inter) interaction_ranking_pruned.append((inter, strength))",
"* from utils import * def preprocess_weights(weights): w_later = np.abs(weights[-1]) w_input = np.abs(weights[0])",
"interaction_ranking = interpret_interactions(w_input, w_later) interaction_ranking = prune_redundant_interactions(interaction_ranking) if one_indexed: return make_one_indexed(interaction_ranking) else: return",
"w_later = preprocess_weights(weights) if pairwise: interaction_ranking = interpret_pairwise_interactions(w_input, w_later) else: interaction_ranking = interpret_interactions(w_input,"
] |
[
"collector.add_result_handler(handler) start_time = datetime(2015, 12, 23, 8, 14, 12) duration = timedelta(seconds=10) end_time",
"collector.startTest(case) # Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTest(case) #",
"TestTextTestResult(ExcInfoFixture, unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler)",
"SMALL LETTER PHI}'.encode('utf-8') with self.failure_exc_info(msg) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration,",
"self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time",
"TestCompletionStatus.success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called)",
"17, 39) # When with mock.patch( 'haas.result.datetime', new=MockDateTime( [start_time, test_end_time, tear_down_end_time])): case.run(collector) #",
"mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self):",
"self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self): # Given collector = ResultCollector() case = _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time =",
"= datetime(2016, 4, 12, 8, 17, 32) test_end_time = datetime(2016, 4, 12, 8,",
"= ResultCollector() collector.add_result_handler(handler) case = _test_cases.TestCase('test_method') # When handler.reset_mock() collector.startTestRun() # Then handler.start_test_run.assert_called_once_with()",
"handler.reset_mock() collector.stopTestRun() # Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.startTest(case)",
"# When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called)",
"new=MockDateTime(end_time)): collector.addFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self):",
"collector.addUnexpectedSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self): # Given",
"handler.start_test.reset_mock() # Given with self.failure_exc_info() as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.failure, expected_duration,",
"case, TestCompletionStatus.skipped, expected_duration, message='reason') # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case, 'reason') # Then",
"msg = '\\N{GREEK SMALL LETTER PHI}'.encode('utf-8') with self.failure_exc_info(msg) as exc_info: expected_result = TestResult.from_test_case(",
"IResultHandlerPlugin from ..result import ( ResultCollector, TestResult, TestCompletionStatus, TestDuration ) from ..testing import",
"collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given msg = '\\N{GREEK SMALL LETTER PHI}'.encode('utf-8')",
"as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When with mock.patch(",
"Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.skipped, expected_duration, message='reason') #",
"When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given msg =",
"..plugins.i_result_handler_plugin import IResultHandlerPlugin from ..result import ( ResultCollector, TestResult, TestCompletionStatus, TestDuration ) from",
"handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin)",
"expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called)",
"handler.reset_mock() collector.startTestRun() # Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTestRun()",
"= datetime(2016, 4, 12, 8, 17, 39) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(",
"case = _test_cases.TestCase('test_method') # When handler.reset_mock() collector.startTestRun() # Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called)",
"3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import,",
"from ..result import ( ResultCollector, TestResult, TestCompletionStatus, TestDuration ) from ..testing import unittest",
"= TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case,",
"TestCompletionStatus.unexpected_success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called)",
"collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.skipped, expected_duration,",
"# Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.success, expected_duration) #",
"test_end_time = datetime(2016, 4, 12, 8, 17, 38) tear_down_end_time = datetime(2016, 4, 12,",
"38) tear_down_end_time = datetime(2016, 4, 12, 8, 17, 39) # When with mock.patch(",
"be modified and distributed under the terms # of the 3-clause BSD license.",
"TestDuration ) from ..testing import unittest from . import _test_cases, _test_case_data from .fixtures",
"self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler)",
"datetime, timedelta from ..plugins.i_result_handler_plugin import IResultHandlerPlugin from ..result import ( ResultCollector, TestResult, TestCompletionStatus,",
"# This software may be modified and distributed under the terms # of",
"as exc_info: # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When",
"may be modified and distributed under the terms # of the 3-clause BSD",
"= mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015, 12, 23, 8, 14,",
"expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result)",
"Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015, 12, 23,",
"# Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self): # Given handler",
"rights reserved. # # This software may be modified and distributed under the",
"new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.success,",
"collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.exc_info(RuntimeError) as exc_info: expected_result =",
"with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called)",
"self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector()",
"ResultCollector, TestResult, TestCompletionStatus, TestDuration ) from ..testing import unittest from . import _test_cases,",
"# When handler.reset_mock() collector.startTest(case) # Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) # When",
"4, 12, 8, 17, 39) # When with mock.patch( 'haas.result.datetime', new=MockDateTime( [start_time, test_end_time,",
"_test_cases.TestCase('test_method') # When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # When",
"the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals from datetime import",
"self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTestRun() # Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called)",
"= ResultCollector() case = _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time = datetime(2016, 4, 12, 8, 17, 32)",
"_test_case_data.TestWithTwoErrors('test_with_two_errors') start_time = datetime(2016, 4, 12, 8, 17, 32) test_end_time = datetime(2016, 4,",
"_test_cases.TestCase('test_method') # When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given",
"Given with self.failure_exc_info() as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.failure, expected_duration, exception=exc_info) #",
"= TestResult.from_test_case( case, TestCompletionStatus.success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case) # Then",
"handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self): # Given collector = ResultCollector()",
"import IResultHandlerPlugin from ..result import ( ResultCollector, TestResult, TestCompletionStatus, TestDuration ) from ..testing",
"self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.startTest(case) # Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called)",
"Copyright (c) 2013-2019 <NAME> # All rights reserved. # # This software may",
"case, TestCompletionStatus.unexpected_success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called)",
"# When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given msg",
"When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.failure_exc_info()",
"'reason') # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self): # Given",
"4, 12, 8, 17, 38) tear_down_end_time = datetime(2016, 4, 12, 8, 17, 39)",
"handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTestRun() # Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called)",
"expected_result = TestResult.from_test_case( case, TestCompletionStatus.expected_failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)):",
"as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.expected_failure, expected_duration, exception=exc_info) # When with mock.patch(",
"(c) 2013-2019 <NAME> # All rights reserved. # # This software may be",
"# Given msg = '\\N{GREEK SMALL LETTER PHI}'.encode('utf-8') with self.failure_exc_info(msg) as exc_info: expected_result",
"mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful())",
"# Given with self.failure_exc_info() as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.failure, expected_duration, exception=exc_info)",
"from ..testing import unittest from . import _test_cases, _test_case_data from .fixtures import ExcInfoFixture,",
"self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTestRun() # Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called)",
"Given msg = '\\N{GREEK SMALL LETTER PHI}'.encode('utf-8') with self.failure_exc_info(msg) as exc_info: expected_result =",
"new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self): #",
"self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTest(case) # Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called)",
"Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.unexpected_success, expected_duration) # When",
"__future__ import absolute_import, unicode_literals from datetime import datetime, timedelta from ..plugins.i_result_handler_plugin import IResultHandlerPlugin",
"self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def test_unicode_traceback(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector =",
"# Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self): # Given collector",
"datetime import datetime, timedelta from ..plugins.i_result_handler_plugin import IResultHandlerPlugin from ..result import ( ResultCollector,",
"def test_result_collector_calls_handlers_on_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time =",
"collector = ResultCollector() collector.add_result_handler(handler) case = _test_cases.TestCase('test_method') # When handler.reset_mock() collector.startTestRun() # Then",
"8, 17, 32) test_end_time = datetime(2016, 4, 12, 8, 17, 38) tear_down_end_time =",
"Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTest(case) # Then handler.stop_test.assert_called_once_with(case)",
"When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called)",
"handler.start_test.reset_mock() # Given with self.exc_info(RuntimeError) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.expected_failure, expected_duration,",
"expected_result = TestResult.from_test_case( case, TestCompletionStatus.skipped, expected_duration, message='reason') # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case,",
"Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self): # Given handler =",
".fixtures import ExcInfoFixture, MockDateTime from .compat import mock class TestTextTestResult(ExcInfoFixture, unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self):",
"= ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015, 12, 23, 8, 14, 12) duration =",
"self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self): # Given collector = ResultCollector() #",
"self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time",
"ResultCollector() # Then self.assertFalse(collector.shouldStop) # When collector.stop() # Then self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self): #",
"under the terms # of the 3-clause BSD license. See the LICENSE.txt file",
"expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called)",
"TestDuration(start_time, end_time) case = _test_cases.TestCase('test_method') # When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then",
"# When collector.stop() # Then self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self): # Given collector = ResultCollector()",
"= _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time = datetime(2016, 4, 12, 8, 17, 32) test_end_time = datetime(2016,",
"Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTestRun() # Then handler.stop_test_run.assert_called_once_with()",
"expected_result = TestResult.from_test_case( case, TestCompletionStatus.unexpected_success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) #",
"new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given msg = '\\N{GREEK SMALL LETTER",
"exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime',",
"collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.failure_exc_info() as exc_info: expected_result =",
"self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector =",
"def test_result_collector_calls_handlers_start_stop_methods(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) case =",
"8, 14, 12) duration = timedelta(seconds=10) end_time = start_time + duration expected_duration =",
"new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.failure_exc_info() as exc_info: expected_result",
"# When handler.reset_mock() collector.stopTest(case) # Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def test_unicode_traceback(self):",
"= mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) case = _test_cases.TestCase('test_method') # When handler.reset_mock() collector.startTestRun()",
"handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015, 12, 23, 8,",
"exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self): # Given",
"# Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.unexpected_success, expected_duration) #",
"When handler.reset_mock() collector.startTest(case) # Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock()",
"expected_result = TestResult.from_test_case( case, TestCompletionStatus.success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case) #",
"32) test_end_time = datetime(2016, 4, 12, 8, 17, 38) tear_down_end_time = datetime(2016, 4,",
"test_result_collector_calls_handlers_on_failure(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015,",
"Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.exc_info(RuntimeError) as exc_info: expected_result = TestResult.from_test_case( case,",
"self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector =",
"Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self): # Given collector =",
"self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # When with self.exc_info(RuntimeError) as exc_info: # Given expected_result = TestResult.from_test_case(",
"self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector()",
"= TestResult.from_test_case( case, TestCompletionStatus.skipped, expected_duration, message='reason') # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case, 'reason')",
"Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.unexpected_success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case)",
"4, 12, 8, 17, 32) test_end_time = datetime(2016, 4, 12, 8, 17, 38)",
"exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called)",
"expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result)",
"8, 17, 38) tear_down_end_time = datetime(2016, 4, 12, 8, 17, 39) # When",
"case = _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time = datetime(2016, 4, 12, 8, 17, 32) test_end_time =",
"handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def test_unicode_traceback(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector",
"tear_down_end_time = datetime(2016, 4, 12, 8, 17, 39) # When with mock.patch( 'haas.result.datetime',",
"details. from __future__ import absolute_import, unicode_literals from datetime import datetime, timedelta from ..plugins.i_result_handler_plugin",
"def test_result_collector_calls_handlers_on_skip(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time =",
"mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.exc_info(RuntimeError) as exc_info:",
"and distributed under the terms # of the 3-clause BSD license. See the",
"self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler)",
"handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin)",
"# Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.failure_exc_info() as exc_info: expected_result = TestResult.from_test_case(",
"self.assertFalse(collector.shouldStop) # When collector.stop() # Then self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self): # Given collector =",
"end_time = start_time + duration expected_duration = TestDuration(start_time, end_time) case = _test_cases.TestCase('test_method') #",
"# When with mock.patch( 'haas.result.datetime', new=MockDateTime( [start_time, test_end_time, tear_down_end_time])): case.run(collector) # Then self.assertEqual(len(collector.errors),",
"the terms # of the 3-clause BSD license. See the LICENSE.txt file for",
"coding: utf-8 -*- # Copyright (c) 2013-2019 <NAME> # All rights reserved. #",
"collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self): #",
"# When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called)",
"self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTestRun() # Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) #",
"from .compat import mock class TestTextTestResult(ExcInfoFixture, unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self): # Given handler =",
"unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) case",
"test_result_collector_calls_handlers_start_stop_methods(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) case = _test_cases.TestCase('test_method')",
"collector.addExpectedFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self): #",
"self.failure_exc_info() as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.failure, expected_duration, exception=exc_info) # When with",
"# When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # When with",
"datetime(2016, 4, 12, 8, 17, 38) tear_down_end_time = datetime(2016, 4, 12, 8, 17,",
"self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time",
"ResultCollector() collector.add_result_handler(handler) case = _test_cases.TestCase('test_method') # When handler.reset_mock() collector.startTestRun() # Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called)",
"PHI}'.encode('utf-8') with self.failure_exc_info(msg) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) #",
"# Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.unexpected_success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)):",
"handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin)",
"message='reason') # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case, 'reason') # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called)",
"collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.success, expected_duration)",
"with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def",
"collector.stopTest(case) # Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def test_unicode_traceback(self): # Given handler",
"2013-2019 <NAME> # All rights reserved. # # This software may be modified",
"mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case,",
"def test_result_collector_calls_handlers_on_failure(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time =",
"# Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self): # Given handler",
"'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def",
"self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector =",
"= TestResult.from_test_case( case, TestCompletionStatus.failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case,",
"handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) case = _test_cases.TestCase('test_method') # When handler.reset_mock()",
"test_result_collector_calls_handlers_on_expected_fail(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015,",
"with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.failure_exc_info() as",
"exc_info: # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When with",
"self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector",
"reserved. # # This software may be modified and distributed under the terms",
"( ResultCollector, TestResult, TestCompletionStatus, TestDuration ) from ..testing import unittest from . import",
"duration expected_duration = TestDuration(start_time, end_time) case = _test_cases.TestCase('test_method') # When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)):",
"exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self): # Given",
"handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTest(case) # Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called)",
"BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals",
"_test_cases.TestCase('test_method') # When handler.reset_mock() collector.startTestRun() # Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) #",
"TestResult.from_test_case( case, TestCompletionStatus.success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case) # Then handler.assert_called_once_with(expected_result)",
"collector.addFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self): #",
"collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015, 12, 23, 8, 14, 12) duration",
"import unittest from . import _test_cases, _test_case_data from .fixtures import ExcInfoFixture, MockDateTime from",
"# When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called)",
"self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTest(case) # Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called)",
"When handler.reset_mock() collector.stopTest(case) # Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def test_unicode_traceback(self): #",
"def test_multiple_errors_from_one_test(self): # Given collector = ResultCollector() case = _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time = datetime(2016,",
"= timedelta(seconds=10) end_time = start_time + duration expected_duration = TestDuration(start_time, end_time) case =",
"When handler.reset_mock() collector.stopTestRun() # Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock()",
"Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.skipped, expected_duration, message='reason') # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)):",
"self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time",
"datetime(2016, 4, 12, 8, 17, 39) # When with mock.patch( 'haas.result.datetime', new=MockDateTime( [start_time,",
"exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self): # Given",
"from ..plugins.i_result_handler_plugin import IResultHandlerPlugin from ..result import ( ResultCollector, TestResult, TestCompletionStatus, TestDuration )",
"handler.reset_mock() collector.startTest(case) # Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTest(case)",
"# Then self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self): # Given collector = ResultCollector() case = _test_case_data.TestWithTwoErrors('test_with_two_errors')",
"test_result_collector_calls_handlers_on_error(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015,",
"mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015, 12, 23, 8, 14, 12)",
"ExcInfoFixture, MockDateTime from .compat import mock class TestTextTestResult(ExcInfoFixture, unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self): # Given",
"# Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTestRun() # Then",
"collector.addSkip(case, 'reason') # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self): #",
"Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self): # Given handler =",
". import _test_cases, _test_case_data from .fixtures import ExcInfoFixture, MockDateTime from .compat import mock",
"datetime(2016, 4, 12, 8, 17, 32) test_end_time = datetime(2016, 4, 12, 8, 17,",
"expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)):",
"test_result_collector_calls_handlers_on_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015,",
"new=MockDateTime(end_time)): collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self):",
"with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.exc_info(RuntimeError) as",
"# Given collector = ResultCollector() # Then self.assertFalse(collector.shouldStop) # When collector.stop() # Then",
"TestCompletionStatus.expected_failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info) # Then",
"start_time = datetime(2015, 12, 23, 8, 14, 12) duration = timedelta(seconds=10) end_time =",
"TestCompletionStatus, TestDuration ) from ..testing import unittest from . import _test_cases, _test_case_data from",
"# Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTest(case) # Then",
"terms # of the 3-clause BSD license. See the LICENSE.txt file for details.",
"case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case, exc_info) #",
"8, 17, 39) # When with mock.patch( 'haas.result.datetime', new=MockDateTime( [start_time, test_end_time, tear_down_end_time])): case.run(collector)",
"handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.skipped, expected_duration, message='reason') # When with",
"12, 8, 17, 32) test_end_time = datetime(2016, 4, 12, 8, 17, 38) tear_down_end_time",
"# Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given msg = '\\N{GREEK SMALL LETTER PHI}'.encode('utf-8') with",
"new=MockDateTime(end_time)): collector.addSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self): #",
"self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector",
"self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTest(case) # Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def",
"new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # When with self.exc_info(RuntimeError) as exc_info: #",
"timedelta from ..plugins.i_result_handler_plugin import IResultHandlerPlugin from ..result import ( ResultCollector, TestResult, TestCompletionStatus, TestDuration",
"Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self): # Given handler =",
"handler.start_test.reset_mock() # When with self.exc_info(RuntimeError) as exc_info: # Given expected_result = TestResult.from_test_case( case,",
"exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.expected_failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime',",
"= TestDuration(start_time, end_time) case = _test_cases.TestCase('test_method') # When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) #",
"case, TestCompletionStatus.success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called)",
"class TestTextTestResult(ExcInfoFixture, unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector()",
"mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) case = _test_cases.TestCase('test_method') # When handler.reset_mock() collector.startTestRun() #",
"handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.success, expected_duration) # When with mock.patch('haas.result.datetime',",
"When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful())",
"self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.startTest(case) # Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called)",
"# Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self): # Given handler",
"new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self):",
"test_result_collector_should_stop(self): # Given collector = ResultCollector() # Then self.assertFalse(collector.shouldStop) # When collector.stop() #",
"self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTest(case) # Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called)",
"# -*- coding: utf-8 -*- # Copyright (c) 2013-2019 <NAME> # All rights",
"software may be modified and distributed under the terms # of the 3-clause",
"= _test_cases.TestCase('test_method') # When handler.reset_mock() collector.startTestRun() # Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called)",
"When collector.stop() # Then self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self): # Given collector = ResultCollector() case",
"# All rights reserved. # # This software may be modified and distributed",
"exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called)",
"handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin)",
"# Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def test_unicode_traceback(self): # Given handler =",
"case, TestCompletionStatus.expected_failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info) #",
"..result import ( ResultCollector, TestResult, TestCompletionStatus, TestDuration ) from ..testing import unittest from",
"new=MockDateTime(end_time)): collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self):",
"+ duration expected_duration = TestDuration(start_time, end_time) case = _test_cases.TestCase('test_method') # When with mock.patch('haas.result.datetime',",
"Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given msg = '\\N{GREEK SMALL LETTER PHI}'.encode('utf-8') with self.failure_exc_info(msg)",
"Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.failure_exc_info() as exc_info: expected_result = TestResult.from_test_case( case,",
"new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.exc_info(RuntimeError) as exc_info: expected_result",
"23, 8, 14, 12) duration = timedelta(seconds=10) end_time = start_time + duration expected_duration",
"absolute_import, unicode_literals from datetime import datetime, timedelta from ..plugins.i_result_handler_plugin import IResultHandlerPlugin from ..result",
"with self.exc_info(RuntimeError) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.expected_failure, expected_duration, exception=exc_info) # When",
"12, 8, 17, 38) tear_down_end_time = datetime(2016, 4, 12, 8, 17, 39) #",
"# Copyright (c) 2013-2019 <NAME> # All rights reserved. # # This software",
"# Given collector = ResultCollector() case = _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time = datetime(2016, 4, 12,",
"# Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015, 12,",
"from __future__ import absolute_import, unicode_literals from datetime import datetime, timedelta from ..plugins.i_result_handler_plugin import",
"test_multiple_errors_from_one_test(self): # Given collector = ResultCollector() case = _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time = datetime(2016, 4,",
"with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # When with self.exc_info(RuntimeError) as",
"When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called)",
"test_result_collector_calls_handlers_on_skip(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015,",
"for details. from __future__ import absolute_import, unicode_literals from datetime import datetime, timedelta from",
"modified and distributed under the terms # of the 3-clause BSD license. See",
"expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result)",
"self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector()",
"# Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # When with self.exc_info(RuntimeError) as exc_info: # Given expected_result",
"All rights reserved. # # This software may be modified and distributed under",
"# # This software may be modified and distributed under the terms #",
"timedelta(seconds=10) end_time = start_time + duration expected_duration = TestDuration(start_time, end_time) case = _test_cases.TestCase('test_method')",
"self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self): # Given collector = ResultCollector() # Then self.assertFalse(collector.shouldStop) # When",
"from . import _test_cases, _test_case_data from .fixtures import ExcInfoFixture, MockDateTime from .compat import",
"import datetime, timedelta from ..plugins.i_result_handler_plugin import IResultHandlerPlugin from ..result import ( ResultCollector, TestResult,",
"import ExcInfoFixture, MockDateTime from .compat import mock class TestTextTestResult(ExcInfoFixture, unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self): #",
"# Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)):",
"handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.startTest(case) # Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called)",
"the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import",
"def test_unicode_traceback(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time =",
"-*- # Copyright (c) 2013-2019 <NAME> # All rights reserved. # # This",
"# When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called)",
"When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case, 'reason') # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called)",
"# When handler.reset_mock() collector.stopTestRun() # Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When",
"self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector =",
"file for details. from __future__ import absolute_import, unicode_literals from datetime import datetime, timedelta",
"12, 8, 17, 39) # When with mock.patch( 'haas.result.datetime', new=MockDateTime( [start_time, test_end_time, tear_down_end_time])):",
"collector = ResultCollector() case = _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time = datetime(2016, 4, 12, 8, 17,",
"exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called)",
"LETTER PHI}'.encode('utf-8') with self.failure_exc_info(msg) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info)",
"handler.reset_mock() collector.stopTest(case) # Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def test_unicode_traceback(self): # Given",
"When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # When with self.exc_info(RuntimeError)",
"17, 38) tear_down_end_time = datetime(2016, 4, 12, 8, 17, 39) # When with",
"self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler)",
"mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful())",
"= datetime(2016, 4, 12, 8, 17, 38) tear_down_end_time = datetime(2016, 4, 12, 8,",
"Then self.assertFalse(collector.shouldStop) # When collector.stop() # Then self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self): # Given collector",
"self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self): # Given collector = ResultCollector() # Then self.assertFalse(collector.shouldStop)",
"self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler)",
"TestResult.from_test_case( case, TestCompletionStatus.unexpected_success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) # Then handler.assert_called_once_with(expected_result)",
"When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.exc_info(RuntimeError)",
"case = _test_cases.TestCase('test_method') # When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock()",
"self.assertFalse(handler.start_test.called) def test_unicode_traceback(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time",
"unittest from . import _test_cases, _test_case_data from .fixtures import ExcInfoFixture, MockDateTime from .compat",
"collector.stop() # Then self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self): # Given collector = ResultCollector() case =",
"When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful())",
"TestResult.from_test_case( case, TestCompletionStatus.failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case, exc_info)",
"Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.success, expected_duration) # When",
"self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector",
"with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case(",
"mock class TestTextTestResult(ExcInfoFixture, unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector =",
"= ResultCollector() # Then self.assertFalse(collector.shouldStop) # When collector.stop() # Then self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self):",
"See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals from datetime",
"= TestResult.from_test_case( case, TestCompletionStatus.expected_failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case,",
"# When with self.exc_info(RuntimeError) as exc_info: # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.error,",
"Then handler.stop_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def test_unicode_traceback(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin)",
"= TestResult.from_test_case( case, TestCompletionStatus.unexpected_success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) # Then",
"self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self): # Given collector = ResultCollector() # Then",
"mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self):",
"with self.exc_info(RuntimeError) as exc_info: # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info)",
"mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given msg = '\\N{GREEK SMALL",
"self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.startTest(case) # Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called)",
"datetime(2015, 12, 23, 8, 14, 12) duration = timedelta(seconds=10) end_time = start_time +",
"collector.addSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self): # Given",
"= '\\N{GREEK SMALL LETTER PHI}'.encode('utf-8') with self.failure_exc_info(msg) as exc_info: expected_result = TestResult.from_test_case( case,",
"with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addUnexpectedSuccess(case) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def",
"# When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result",
"collector.stopTestRun() # Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.startTest(case) #",
"When with mock.patch( 'haas.result.datetime', new=MockDateTime( [start_time, test_end_time, tear_down_end_time])): case.run(collector) # Then self.assertEqual(len(collector.errors), 2)",
"# Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When with mock.patch(",
"as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.failure, expected_duration, exception=exc_info) # When with mock.patch(",
"unicode_literals from datetime import datetime, timedelta from ..plugins.i_result_handler_plugin import IResultHandlerPlugin from ..result import",
"self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.skipped, expected_duration, message='reason') # When",
"TestCompletionStatus.skipped, expected_duration, message='reason') # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case, 'reason') # Then handler.assert_called_once_with(expected_result)",
"collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self): #",
"39) # When with mock.patch( 'haas.result.datetime', new=MockDateTime( [start_time, test_end_time, tear_down_end_time])): case.run(collector) # Then",
"self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def test_unicode_traceback(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler)",
"exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime',",
"Given with self.exc_info(RuntimeError) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.expected_failure, expected_duration, exception=exc_info) #",
"def test_result_collector_calls_handlers_on_error(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time =",
"mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.failure_exc_info() as exc_info:",
"self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler)",
"self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector",
"self.exc_info(RuntimeError) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.expected_failure, expected_duration, exception=exc_info) # When with",
"with self.failure_exc_info(msg) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When",
"# Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.skipped, expected_duration, message='reason')",
"self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector()",
"collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.unexpected_success, expected_duration)",
"handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin)",
"TestResult.from_test_case( case, TestCompletionStatus.skipped, expected_duration, message='reason') # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case, 'reason') #",
"self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector =",
"self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector =",
"collector.startTestRun() # Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTestRun() #",
"self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time",
"case, TestCompletionStatus.failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case, exc_info) #",
"self.failure_exc_info(msg) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When with",
"self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector()",
"self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.success, expected_duration) # When with",
"self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.unexpected_success, expected_duration) # When with",
"from .fixtures import ExcInfoFixture, MockDateTime from .compat import mock class TestTextTestResult(ExcInfoFixture, unittest.TestCase): def",
"handler.start_test.reset_mock() # Given msg = '\\N{GREEK SMALL LETTER PHI}'.encode('utf-8') with self.failure_exc_info(msg) as exc_info:",
"expected_result = TestResult.from_test_case( case, TestCompletionStatus.failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)):",
"new=MockDateTime(end_time)): collector.addSkip(case, 'reason') # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self):",
"with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called)",
"mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful())",
"-*- coding: utf-8 -*- # Copyright (c) 2013-2019 <NAME> # All rights reserved.",
") from ..testing import unittest from . import _test_cases, _test_case_data from .fixtures import",
"expected_duration = TestDuration(start_time, end_time) case = _test_cases.TestCase('test_method') # When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case)",
"self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given msg = '\\N{GREEK SMALL LETTER PHI}'.encode('utf-8') with self.failure_exc_info(msg) as",
"ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015, 12, 23, 8, 14, 12) duration = timedelta(seconds=10)",
"utf-8 -*- # Copyright (c) 2013-2019 <NAME> # All rights reserved. # #",
"= _test_cases.TestCase('test_method') # When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() #",
"12) duration = timedelta(seconds=10) end_time = start_time + duration expected_duration = TestDuration(start_time, end_time)",
"self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_should_stop(self): # Given collector = ResultCollector() # Then self.assertFalse(collector.shouldStop) #",
"with self.failure_exc_info() as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.failure, expected_duration, exception=exc_info) # When",
"mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # When with self.exc_info(RuntimeError) as exc_info:",
"distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt",
"# When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called)",
"= start_time + duration expected_duration = TestDuration(start_time, end_time) case = _test_cases.TestCase('test_method') # When",
"collector.add_result_handler(handler) case = _test_cases.TestCase('test_method') # When handler.reset_mock() collector.startTestRun() # Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called)",
"17, 32) test_end_time = datetime(2016, 4, 12, 8, 17, 38) tear_down_end_time = datetime(2016,",
"with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given msg = '\\N{GREEK",
"end_time) case = _test_cases.TestCase('test_method') # When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called)",
"new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.skipped,",
"12, 23, 8, 14, 12) duration = timedelta(seconds=10) end_time = start_time + duration",
"# Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) case = _test_cases.TestCase('test_method') #",
"ResultCollector() case = _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time = datetime(2016, 4, 12, 8, 17, 32) test_end_time",
"Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) case = _test_cases.TestCase('test_method') # When",
"Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime',",
"self.exc_info(RuntimeError) as exc_info: # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) #",
"duration = timedelta(seconds=10) end_time = start_time + duration expected_duration = TestDuration(start_time, end_time) case",
"# Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.exc_info(RuntimeError) as exc_info: expected_result = TestResult.from_test_case(",
"Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.success, expected_duration) # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSuccess(case)",
"self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.startTest(case) # Then handler.start_test.assert_called_once_with(case) self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.stop_test.called) #",
"When with self.exc_info(RuntimeError) as exc_info: # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration,",
"LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals from datetime import datetime,",
"license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals from",
"# Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.startTest(case) # Then",
"'\\N{GREEK SMALL LETTER PHI}'.encode('utf-8') with self.failure_exc_info(msg) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.error,",
"# Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self): # Given handler",
"exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self): # Given",
"TestResult.from_test_case( case, TestCompletionStatus.expected_failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info)",
"expected_duration, message='reason') # When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case, 'reason') # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called)",
"# Then self.assertFalse(collector.shouldStop) # When collector.stop() # Then self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self): # Given",
"Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # When with self.exc_info(RuntimeError) as exc_info: # Given expected_result =",
"self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.exc_info(RuntimeError) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.expected_failure,",
"14, 12) duration = timedelta(seconds=10) end_time = start_time + duration expected_duration = TestDuration(start_time,",
"When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result =",
"MockDateTime from .compat import mock class TestTextTestResult(ExcInfoFixture, unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self): # Given handler",
"Given collector = ResultCollector() # Then self.assertFalse(collector.shouldStop) # When collector.stop() # Then self.assertTrue(collector.shouldStop)",
"handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.unexpected_success, expected_duration) # When with mock.patch('haas.result.datetime',",
"import mock class TestTextTestResult(ExcInfoFixture, unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector",
"_test_case_data from .fixtures import ExcInfoFixture, MockDateTime from .compat import mock class TestTextTestResult(ExcInfoFixture, unittest.TestCase):",
"Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self): # Given handler =",
"# of the 3-clause BSD license. See the LICENSE.txt file for details. from",
"This software may be modified and distributed under the terms # of the",
"# When with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case, 'reason') # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called)",
"self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector()",
"import ( ResultCollector, TestResult, TestCompletionStatus, TestDuration ) from ..testing import unittest from .",
"with mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case, 'reason') # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful())",
"collector = ResultCollector() # Then self.assertFalse(collector.shouldStop) # When collector.stop() # Then self.assertTrue(collector.shouldStop) def",
"of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__",
"# Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.skipped, expected_duration, message='reason') # When with mock.patch('haas.result.datetime',",
"start_time + duration expected_duration = TestDuration(start_time, end_time) case = _test_cases.TestCase('test_method') # When with",
"self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_error(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler)",
"Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.startTest(case) # Then handler.start_test.assert_called_once_with(case)",
"self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) def test_unicode_traceback(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector()",
"= datetime(2015, 12, 23, 8, 14, 12) duration = timedelta(seconds=10) end_time = start_time",
"new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given expected_result = TestResult.from_test_case( case, TestCompletionStatus.unexpected_success,",
"Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self): # Given handler =",
"self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock() collector.stopTestRun() # Then handler.stop_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.start_test_run.called)",
"Then self.assertTrue(collector.shouldStop) def test_multiple_errors_from_one_test(self): # Given collector = ResultCollector() case = _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time",
"'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def",
"test_unicode_traceback(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015,",
"from datetime import datetime, timedelta from ..plugins.i_result_handler_plugin import IResultHandlerPlugin from ..result import (",
"TestResult, TestCompletionStatus, TestDuration ) from ..testing import unittest from . import _test_cases, _test_case_data",
"# Given with self.exc_info(RuntimeError) as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.expected_failure, expected_duration, exception=exc_info)",
"collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # When with self.exc_info(RuntimeError) as exc_info: # Given",
"self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with self.failure_exc_info() as exc_info: expected_result = TestResult.from_test_case( case, TestCompletionStatus.failure,",
"_test_cases, _test_case_data from .fixtures import ExcInfoFixture, MockDateTime from .compat import mock class TestTextTestResult(ExcInfoFixture,",
"When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called)",
"# Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self): # Given handler",
"TestCompletionStatus.error, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case, exc_info) # Then",
"import _test_cases, _test_case_data from .fixtures import ExcInfoFixture, MockDateTime from .compat import mock class",
"'haas.result.datetime', new=MockDateTime(end_time)): collector.addExpectedFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def",
"def test_result_collector_calls_handlers_on_unexpected_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time =",
"..testing import unittest from . import _test_cases, _test_case_data from .fixtures import ExcInfoFixture, MockDateTime",
"mock.patch('haas.result.datetime', new=MockDateTime(end_time)): collector.addSkip(case, 'reason') # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def",
"self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_failure(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector",
"start_time = datetime(2016, 4, 12, 8, 17, 32) test_end_time = datetime(2016, 4, 12,",
"self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time",
"test_result_collector_calls_handlers_on_unexpected_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time = datetime(2015,",
"# When handler.reset_mock() collector.startTestRun() # Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When",
"with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case, exc_info) # Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called)",
"def test_result_collector_should_stop(self): # Given collector = ResultCollector() # Then self.assertFalse(collector.shouldStop) # When collector.stop()",
"TestCompletionStatus.failure, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addFailure(case, exc_info) # Then",
"<NAME> # All rights reserved. # # This software may be modified and",
"def test_result_collector_calls_handlers_on_expected_fail(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector = ResultCollector() collector.add_result_handler(handler) start_time =",
".compat import mock class TestTextTestResult(ExcInfoFixture, unittest.TestCase): def test_result_collector_calls_handlers_start_stop_methods(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin)",
"TestResult.from_test_case( case, TestCompletionStatus.error, expected_duration, exception=exc_info) # When with mock.patch( 'haas.result.datetime', new=MockDateTime(end_time)): collector.addError(case, exc_info)",
"handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_unexpected_success(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin)",
"import absolute_import, unicode_literals from datetime import datetime, timedelta from ..plugins.i_result_handler_plugin import IResultHandlerPlugin from",
"# When with mock.patch('haas.result.datetime', new=MockDateTime(start_time)): collector.startTest(case) # Then self.assertTrue(handler.start_test.called) handler.start_test.reset_mock() # Given with",
"Given collector = ResultCollector() case = _test_case_data.TestWithTwoErrors('test_with_two_errors') start_time = datetime(2016, 4, 12, 8,",
"# Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertFalse(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_success(self): # Given handler",
"When handler.reset_mock() collector.startTestRun() # Then handler.start_test_run.assert_called_once_with() self.assertFalse(handler.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) # When handler.reset_mock()",
"self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_expected_fail(self): # Given handler = mock.Mock(spec=IResultHandlerPlugin) collector",
"Then handler.assert_called_once_with(expected_result) self.assertFalse(handler.start_test_run.called) self.assertFalse(handler.stop_test_run.called) self.assertFalse(handler.start_test.called) self.assertFalse(handler.stop_test.called) self.assertTrue(collector.wasSuccessful()) def test_result_collector_calls_handlers_on_skip(self): # Given handler ="
] |
[
"'shape': _all_shapes, 'Re': range(55, 106, 10), 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/velocity.txt', {",
"'halfcircle', 'triangle'] # Script to use. program = \"scripts/coef.py\" experiments = [ ExperimentGroup(\"scripts/results/theta.txt\",",
"[ ExperimentGroup(\"scripts/results/theta.txt\", { 'shape': _all_shapes, 'theta': range(0, 181, 30), 'time': [20], 'Re': [105],",
"'time': [30], 'r': [64], }), ExperimentGroup('scripts/results/size.txt', { 'shape': _all_shapes, 'size': np.arange(5, 24, 3)",
"100, 'time': [30], 'r': [64], }), ExperimentGroup('scripts/results/size.txt', { 'shape': _all_shapes, 'size': np.arange(5, 24,",
"range(0, 181, 30), 'time': [20], 'Re': [105], 'r': [64], }), ExperimentGroup('scripts/results/reynolds.txt', { 'shape':",
"'shape': _all_shapes, 'Uin': np.arange(4, 16, 2) / 100, 'time': [30], 'r': [64], }),",
"[64], }), ExperimentGroup('scripts/results/velocity.txt', { 'shape': _all_shapes, 'Uin': np.arange(4, 16, 2) / 100, 'time':",
"[64], }), ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape': ['circle'], 'Re': range(10, 1001, 100), 'time': [40], 'r':",
"2) / 100, 'time': [30], 'r': [64], }), ExperimentGroup('scripts/results/size.txt', { 'shape': _all_shapes, 'size':",
"}), ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape': ['circle'], 'Re': range(10, 1001, 100), 'time': [40], 'r': [64],",
"'shape': _all_shapes, 'theta': range(0, 181, 30), 'time': [20], 'Re': [105], 'r': [64], }),",
"16, 2) / 100, 'time': [30], 'r': [64], }), ExperimentGroup('scripts/results/size.txt', { 'shape': _all_shapes,",
"Script to use. program = \"scripts/coef.py\" experiments = [ ExperimentGroup(\"scripts/results/theta.txt\", { 'shape': _all_shapes,",
"[20], 'Re': [105], 'r': [64], }), ExperimentGroup('scripts/results/reynolds.txt', { 'shape': _all_shapes, 'Re': range(55, 106,",
"{ 'shape': _all_shapes, 'theta': range(0, 181, 30), 'time': [20], 'Re': [105], 'r': [64],",
"['rect', 'halfcircle', 'triangle'] # Script to use. program = \"scripts/coef.py\" experiments = [",
"[20], 'r': [64], }), ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape': ['circle'], 'Re': range(10, 1001, 100), 'time':",
"range(55, 106, 10), 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/velocity.txt', { 'shape': _all_shapes, 'Uin':",
"3) / 64, 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape': ['circle'], 'Re':",
"as np from pcs_aero.experiment import ExperimentGroup # Convenience _all_shapes = ['rect', 'halfcircle', 'triangle']",
"/ 100, 'time': [30], 'r': [64], }), ExperimentGroup('scripts/results/size.txt', { 'shape': _all_shapes, 'size': np.arange(5,",
"ExperimentGroup(\"scripts/results/theta.txt\", { 'shape': _all_shapes, 'theta': range(0, 181, 30), 'time': [20], 'Re': [105], 'r':",
"experiments = [ ExperimentGroup(\"scripts/results/theta.txt\", { 'shape': _all_shapes, 'theta': range(0, 181, 30), 'time': [20],",
"Convenience _all_shapes = ['rect', 'halfcircle', 'triangle'] # Script to use. program = \"scripts/coef.py\"",
"<gh_stars>0 import numpy as np from pcs_aero.experiment import ExperimentGroup # Convenience _all_shapes =",
"}), ExperimentGroup('scripts/results/reynolds.txt', { 'shape': _all_shapes, 'Re': range(55, 106, 10), 'time': [20], 'r': [64],",
"}), ExperimentGroup('scripts/results/velocity.txt', { 'shape': _all_shapes, 'Uin': np.arange(4, 16, 2) / 100, 'time': [30],",
"{ 'shape': _all_shapes, 'Re': range(55, 106, 10), 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/velocity.txt',",
"'triangle'] # Script to use. program = \"scripts/coef.py\" experiments = [ ExperimentGroup(\"scripts/results/theta.txt\", {",
"_all_shapes, 'size': np.arange(5, 24, 3) / 64, 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/circle_reynolds.txt',",
"'Re': [105], 'r': [64], }), ExperimentGroup('scripts/results/reynolds.txt', { 'shape': _all_shapes, 'Re': range(55, 106, 10),",
"30), 'time': [20], 'Re': [105], 'r': [64], }), ExperimentGroup('scripts/results/reynolds.txt', { 'shape': _all_shapes, 'Re':",
"'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape': ['circle'], 'Re': range(10, 1001, 100),",
"10), 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/velocity.txt', { 'shape': _all_shapes, 'Uin': np.arange(4, 16,",
"ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape': ['circle'], 'Re': range(10, 1001, 100), 'time': [40], 'r': [64], }),",
"# Convenience _all_shapes = ['rect', 'halfcircle', 'triangle'] # Script to use. program =",
"ExperimentGroup('scripts/results/size.txt', { 'shape': _all_shapes, 'size': np.arange(5, 24, 3) / 64, 'time': [20], 'r':",
"= ['rect', 'halfcircle', 'triangle'] # Script to use. program = \"scripts/coef.py\" experiments =",
"= \"scripts/coef.py\" experiments = [ ExperimentGroup(\"scripts/results/theta.txt\", { 'shape': _all_shapes, 'theta': range(0, 181, 30),",
"'size': np.arange(5, 24, 3) / 64, 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/circle_reynolds.txt', {",
"'theta': range(0, 181, 30), 'time': [20], 'Re': [105], 'r': [64], }), ExperimentGroup('scripts/results/reynolds.txt', {",
"_all_shapes = ['rect', 'halfcircle', 'triangle'] # Script to use. program = \"scripts/coef.py\" experiments",
"from pcs_aero.experiment import ExperimentGroup # Convenience _all_shapes = ['rect', 'halfcircle', 'triangle'] # Script",
"'shape': _all_shapes, 'size': np.arange(5, 24, 3) / 64, 'time': [20], 'r': [64], }),",
"64, 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape': ['circle'], 'Re': range(10, 1001,",
"\"scripts/coef.py\" experiments = [ ExperimentGroup(\"scripts/results/theta.txt\", { 'shape': _all_shapes, 'theta': range(0, 181, 30), 'time':",
"[20], 'r': [64], }), ExperimentGroup('scripts/results/velocity.txt', { 'shape': _all_shapes, 'Uin': np.arange(4, 16, 2) /",
"{ 'shape': ['circle'], 'Re': range(10, 1001, 100), 'time': [40], 'r': [64], }), ]",
"'time': [20], 'Re': [105], 'r': [64], }), ExperimentGroup('scripts/results/reynolds.txt', { 'shape': _all_shapes, 'Re': range(55,",
"}), ExperimentGroup('scripts/results/size.txt', { 'shape': _all_shapes, 'size': np.arange(5, 24, 3) / 64, 'time': [20],",
"= [ ExperimentGroup(\"scripts/results/theta.txt\", { 'shape': _all_shapes, 'theta': range(0, 181, 30), 'time': [20], 'Re':",
"import ExperimentGroup # Convenience _all_shapes = ['rect', 'halfcircle', 'triangle'] # Script to use.",
"[105], 'r': [64], }), ExperimentGroup('scripts/results/reynolds.txt', { 'shape': _all_shapes, 'Re': range(55, 106, 10), 'time':",
"'r': [64], }), ExperimentGroup('scripts/results/reynolds.txt', { 'shape': _all_shapes, 'Re': range(55, 106, 10), 'time': [20],",
"np from pcs_aero.experiment import ExperimentGroup # Convenience _all_shapes = ['rect', 'halfcircle', 'triangle'] #",
"_all_shapes, 'Re': range(55, 106, 10), 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/velocity.txt', { 'shape':",
"106, 10), 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/velocity.txt', { 'shape': _all_shapes, 'Uin': np.arange(4,",
"np.arange(4, 16, 2) / 100, 'time': [30], 'r': [64], }), ExperimentGroup('scripts/results/size.txt', { 'shape':",
"'Uin': np.arange(4, 16, 2) / 100, 'time': [30], 'r': [64], }), ExperimentGroup('scripts/results/size.txt', {",
"'Re': range(55, 106, 10), 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/velocity.txt', { 'shape': _all_shapes,",
"ExperimentGroup # Convenience _all_shapes = ['rect', 'halfcircle', 'triangle'] # Script to use. program",
"ExperimentGroup('scripts/results/velocity.txt', { 'shape': _all_shapes, 'Uin': np.arange(4, 16, 2) / 100, 'time': [30], 'r':",
"[64], }), ExperimentGroup('scripts/results/size.txt', { 'shape': _all_shapes, 'size': np.arange(5, 24, 3) / 64, 'time':",
"'r': [64], }), ExperimentGroup('scripts/results/velocity.txt', { 'shape': _all_shapes, 'Uin': np.arange(4, 16, 2) / 100,",
"_all_shapes, 'theta': range(0, 181, 30), 'time': [20], 'Re': [105], 'r': [64], }), ExperimentGroup('scripts/results/reynolds.txt',",
"[64], }), ExperimentGroup('scripts/results/reynolds.txt', { 'shape': _all_shapes, 'Re': range(55, 106, 10), 'time': [20], 'r':",
"# Script to use. program = \"scripts/coef.py\" experiments = [ ExperimentGroup(\"scripts/results/theta.txt\", { 'shape':",
"/ 64, 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape': ['circle'], 'Re': range(10,",
"'r': [64], }), ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape': ['circle'], 'Re': range(10, 1001, 100), 'time': [40],",
"'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/velocity.txt', { 'shape': _all_shapes, 'Uin': np.arange(4, 16, 2)",
"pcs_aero.experiment import ExperimentGroup # Convenience _all_shapes = ['rect', 'halfcircle', 'triangle'] # Script to",
"program = \"scripts/coef.py\" experiments = [ ExperimentGroup(\"scripts/results/theta.txt\", { 'shape': _all_shapes, 'theta': range(0, 181,",
"[30], 'r': [64], }), ExperimentGroup('scripts/results/size.txt', { 'shape': _all_shapes, 'size': np.arange(5, 24, 3) /",
"ExperimentGroup('scripts/results/reynolds.txt', { 'shape': _all_shapes, 'Re': range(55, 106, 10), 'time': [20], 'r': [64], }),",
"use. program = \"scripts/coef.py\" experiments = [ ExperimentGroup(\"scripts/results/theta.txt\", { 'shape': _all_shapes, 'theta': range(0,",
"{ 'shape': _all_shapes, 'size': np.arange(5, 24, 3) / 64, 'time': [20], 'r': [64],",
"'r': [64], }), ExperimentGroup('scripts/results/size.txt', { 'shape': _all_shapes, 'size': np.arange(5, 24, 3) / 64,",
"{ 'shape': _all_shapes, 'Uin': np.arange(4, 16, 2) / 100, 'time': [30], 'r': [64],",
"_all_shapes, 'Uin': np.arange(4, 16, 2) / 100, 'time': [30], 'r': [64], }), ExperimentGroup('scripts/results/size.txt',",
"np.arange(5, 24, 3) / 64, 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape':",
"to use. program = \"scripts/coef.py\" experiments = [ ExperimentGroup(\"scripts/results/theta.txt\", { 'shape': _all_shapes, 'theta':",
"numpy as np from pcs_aero.experiment import ExperimentGroup # Convenience _all_shapes = ['rect', 'halfcircle',",
"import numpy as np from pcs_aero.experiment import ExperimentGroup # Convenience _all_shapes = ['rect',",
"181, 30), 'time': [20], 'Re': [105], 'r': [64], }), ExperimentGroup('scripts/results/reynolds.txt', { 'shape': _all_shapes,",
"24, 3) / 64, 'time': [20], 'r': [64], }), ExperimentGroup('scripts/results/circle_reynolds.txt', { 'shape': ['circle'],"
] |
[
"# tuition = models.FloatField(default=None, null=True, blank=True) # us_deadline = models.DateTimeField(default=None, null=True, blank=True) #",
"for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to medicine",
"blank=True) acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) #",
"# tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True) int_deadline =",
"search_fields = ('university__name',) ordering = ('university__rank',) class LawGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment",
"= models.TextField(default=None, null=True, blank=True) grad_school_link = models.TextField(default=None, null=True, blank=True, max_length=500) undergrad_link = models.TextField(default=None,",
"us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # tuition",
"null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate = models.FloatField(default=None, null=True, blank=True) tuition",
"null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) male = models.FloatField(default=None, null=True, blank=True) female",
"models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) min_toefl_score =",
"int_rolling = models.BooleanField(default=False) employed = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True)",
"employed = models.FloatField(default=None, null=True, blank=True) bar_passage_rate = models.FloatField(default=None, null=True, blank=True) median_grant = models.IntegerField(default=None,",
"null=True, blank=True) gmat = models.IntegerField(default=None, null=True, blank=True) gre = models.OneToOneField(GRE, on_delete=models.CASCADE) # avg_salary",
"total_int_students = models.IntegerField(default=None, null=True, blank=True) address = models.TextField(default=None, null=True, blank=True) website = models.TextField(default=None,",
"from django.contrib import admin grad_streams_list = [ 'Engineering', 'Law', 'Medicine', 'Business', ] grad_streams",
"room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to medicine mcat",
"models.TextField(default=None, null=True, blank=True, max_length=500) med_link = models.TextField(default=None, null=True, blank=True, max_length=500) law_link = models.TextField(default=None,",
"female = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None,",
"blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd",
"# acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) #",
"int_application_fee = models.IntegerField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) us_deadline =",
"mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) min_ielts_score = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None,",
"# avg_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class BusinessGradAdmin(admin.ModelAdmin): search_fields",
"null=True, blank=True) bar_passage_rate = models.FloatField(default=None, null=True, blank=True) median_grant = models.IntegerField(default=None, null=True, blank=True) lsat_score",
"= models.TextField(default=None, null=True, blank=True) # fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None,",
"# female = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) #",
"= models.IntegerField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee =",
"max_length=500) business_link = models.TextField(default=None, null=True, blank=True, max_length=500) med_link = models.TextField(default=None, null=True, blank=True, max_length=500)",
"ordering = ('university__rank',) class EngineeringGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) # enrollment = models.IntegerField(default=None,",
"on_delete=models.CASCADE) def __str__(self): return self.university.name class MedicineGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',)",
"teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) # research_assistantships = models.IntegerField(default=None, null=True, blank=True) # #",
"blank=True, max_length=500) slug = models.SlugField(default=None, null=True, blank=True, max_length=500) logo = models.TextField(default=None, null=True, blank=True,",
"models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True,",
"= models.FloatField(default=None, null=True, blank=True) median_grant = models.IntegerField(default=None, null=True, blank=True) lsat_score = models.IntegerField(default=None, null=True,",
"= models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True,",
"blank=True) rolling = models.BooleanField(default=False) int_rolling = models.BooleanField(default=False) employed = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name",
"blank=True) international = models.FloatField(default=None, null=True, blank=True) us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee",
"null=True, blank=True) # def __str__(self): return self.university.name class EngineeringGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering",
"= models.FloatField(default=None, null=True, blank=True) # female = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_masters =",
"int_deadline = models.DateTimeField(default=None, null=True, blank=True) # rolling = models.BooleanField(default=False) # gpa = models.FloatField(default=None,",
"male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate_masters = models.FloatField(default=None,",
"= models.TextField(default=None, null=True, blank=True, max_length=500) med_link = models.TextField(default=None, null=True, blank=True, max_length=500) law_link =",
"models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True)",
"= models.FloatField(default=None, null=True, blank=True) bar_passage_rate = models.FloatField(default=None, null=True, blank=True) median_grant = models.IntegerField(default=None, null=True,",
"blank=True, max_length=500) med_link = models.TextField(default=None, null=True, blank=True, max_length=500) law_link = models.TextField(default=None, null=True, blank=True,",
"blank=True) biologic_biochemical = models.IntegerField(default=None, null=True, blank=True) psycho_social_biological = models.IntegerField(default=None, null=True, blank=True) def __str__(self):",
"null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) research_assistantships = models.IntegerField(default=None, null=True, blank=True) #",
"class BusinessGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class EngineeringGrad(models.Model): university = models.OneToOneField(University,",
"int_application_fee = models.IntegerField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd",
"= models.IntegerField(default=None, null=True, blank=True) def __str__(self): return str(self.new_total) class University(models.Model): name = models.TextField(default=None)",
"models.BooleanField(default=False) # gpa = models.FloatField(default=None, null=True, blank=True) # min_toefl_score = models.IntegerField(default=None, null=True, blank=True)",
"models.OneToOneField(University, on_delete=models.CASCADE) # enrollment = models.IntegerField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True,",
"null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True,",
"= models.IntegerField(default=None, null=True, blank=True) # unique to business employed = models.FloatField(default=None, null=True, blank=True)",
"blank=True) new_total = models.IntegerField(default=None, null=True, blank=True) chemical_physical = models.IntegerField(default=None, null=True, blank=True) critical_analysis =",
"search_fields = ('name',) ordering = ('rank',) class BusinessGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment",
"blank=True) us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) #",
"fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) # research_assistantships =",
"models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True)",
"= models.IntegerField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd =",
"min_toefl_score = models.IntegerField(default=None, null=True, blank=True) mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) min_ielts_score = models.FloatField(default=None,",
"= models.IntegerField(default=None, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) total_students = models.IntegerField(default=None, null=True, blank=True)",
"blank=True) gpa = models.FloatField(default=None, null=True, blank=True) # # look for room and board",
"null=True, blank=True) # us_deadline = models.DateTimeField(default=None, null=True, blank=True) # int_deadline = models.DateTimeField(default=None, null=True,",
"# acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) female",
"def __str__(self): return self.university.name class BusinessGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class",
"acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee",
"= models.FloatField(default=None, null=True, blank=True) min_toefl_score = models.IntegerField(default=None, null=True, blank=True) mean_toefl_score = models.IntegerField(default=None, null=True,",
"university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True,",
"blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) # look",
"BusinessGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class EngineeringGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE)",
"on_delete=models.CASCADE) # avg_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class BusinessGradAdmin(admin.ModelAdmin):",
"models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None,",
"null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True)",
"male = models.FloatField(default=None, null=True, blank=True) # female = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_masters",
"= models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) us_application_fee = models.IntegerField(default=None, null=True,",
"= models.IntegerField(default=None, null=True, blank=True) new_total = models.IntegerField(default=None, null=True, blank=True) chemical_physical = models.IntegerField(default=None, null=True,",
"acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # tuition",
"models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) fellowships = models.IntegerField(default=None, null=True, blank=True)",
"engg_link = models.TextField(default=None, null=True, blank=True, max_length=500) slug = models.SlugField(default=None, null=True, blank=True, max_length=500) logo",
"return self.university.name class EngineeringGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class MedicineGrad(models.Model): university",
"blank=True) def __str__(self): return str(self.new_total) class University(models.Model): name = models.TextField(default=None) info_link = models.TextField(default=None,",
"look for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to",
"logo = models.TextField(default=None, null=True, blank=True, max_length=500) def __str__(self): return self.name class UniversityAdmin(admin.ModelAdmin): search_fields",
"= ('name',) ordering = ('rank',) class BusinessGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment =",
"= models.IntegerField(default=None, null=True, blank=True) lsat_score = models.IntegerField(default=None, null=True, blank=True) median_public_salary = models.IntegerField(default=None, null=True,",
"class MCAT(models.Model): old_total = models.IntegerField(default=None, null=True, blank=True) new_total = models.IntegerField(default=None, null=True, blank=True) chemical_physical",
"models.FloatField(default=None, null=True, blank=True) acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True,",
"null=True, blank=True) grad_school_link = models.TextField(default=None, null=True, blank=True, max_length=500) undergrad_link = models.TextField(default=None, null=True, blank=True,",
"= ('university__name',) ordering = ('university__rank',) class EngineeringGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) # enrollment",
"and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to business employed =",
"__str__(self): return str(self.verbal) class MCAT(models.Model): old_total = models.IntegerField(default=None, null=True, blank=True) new_total = models.IntegerField(default=None,",
"blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) total_students = models.IntegerField(default=None, null=True, blank=True) total_int_students = models.IntegerField(default=None,",
"models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) us_application_fee",
"def __str__(self): return self.name class UniversityAdmin(admin.ModelAdmin): search_fields = ('name',) ordering = ('rank',) class",
"null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True,",
"null=True, blank=True) # min_toefl_score = models.IntegerField(default=None, null=True, blank=True) # mean_toefl_score = models.IntegerField(default=None, null=True,",
"= ( ('Engineering', 'Engineering'), ('Law', 'Law'), ('Medicine', 'Medicine'), ('Business', 'Business'), ) class GRE(models.Model):",
"blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling =",
"= ('university__rank',) class LawGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True)",
"models.TextField(default=None, null=True, blank=True) uni_type = models.TextField(default=None, null=True, blank=True) grad_school_link = models.TextField(default=None, null=True, blank=True,",
"board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to medicine mcat = models.OneToOneField(MCAT,",
"min_ielts_score = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None,",
"rolling = models.BooleanField(default=False) int_rolling = models.BooleanField(default=False) employed = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name =",
"models.TextField(default=None, null=True, blank=True, max_length=500) business_link = models.TextField(default=None, null=True, blank=True, max_length=500) med_link = models.TextField(default=None,",
"fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) # look for",
"blank=True) bar_passage_rate = models.FloatField(default=None, null=True, blank=True) median_grant = models.IntegerField(default=None, null=True, blank=True) lsat_score =",
"null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True,",
"blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) # fin_aid_director_phone = models.TextField(default=None, null=True, blank=True)",
"null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) # fin_aid_director_phone = models.TextField(default=None, null=True,",
"business employed = models.FloatField(default=None, null=True, blank=True) employed_3_months = models.FloatField(default=None, null=True, blank=True) avg_work_ex_months =",
"# min_toefl_score = models.IntegerField(default=None, null=True, blank=True) # mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) #",
"null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True)",
"to engineering gre = models.OneToOneField(GRE, on_delete=models.CASCADE, null=True, blank=True) # def __str__(self): return self.university.name",
"models.IntegerField(default=None, null=True, blank=True) # min_ielts_score = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None,",
"male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate = models.FloatField(default=None,",
"null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True,",
"# int_application_fee = models.IntegerField(default=None, null=True, blank=True) # international = models.FloatField(default=None, null=True, blank=True) #",
"blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True)",
"__str__(self): return self.university.name class MedicineGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class LawGrad(models.Model):",
"blank=True) # int_deadline = models.DateTimeField(default=None, null=True, blank=True) # rolling = models.BooleanField(default=False) # gpa",
"blank=True) # look for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) #",
"median_grant = models.IntegerField(default=None, null=True, blank=True) lsat_score = models.IntegerField(default=None, null=True, blank=True) median_public_salary = models.IntegerField(default=None,",
"female = models.FloatField(default=None, null=True, blank=True) acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd =",
"research_assistantships = models.IntegerField(default=None, null=True, blank=True) # look for room and board living_expenses =",
"models.FloatField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None,",
"blank=True) # us_deadline = models.DateTimeField(default=None, null=True, blank=True) # int_deadline = models.DateTimeField(default=None, null=True, blank=True)",
"= models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) min_toefl_score",
"models.TextField(default=None, null=True, blank=True, max_length=500) undergrad_link = models.TextField(default=None, null=True, blank=True, max_length=500) business_link = models.TextField(default=None,",
"import models from account.models import Country from django.contrib import admin grad_streams_list = [",
"models.IntegerField(default=None, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) total_students = models.IntegerField(default=None, null=True, blank=True) total_int_students",
"= models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) research_assistantships = models.IntegerField(default=None, null=True,",
"teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) research_assistantships = models.IntegerField(default=None, null=True, blank=True) # look for",
"look for median lsat employed = models.FloatField(default=None, null=True, blank=True) bar_passage_rate = models.FloatField(default=None, null=True,",
"null=True, blank=True, max_length=500) law_link = models.TextField(default=None, null=True, blank=True, max_length=500) engg_link = models.TextField(default=None, null=True,",
"= models.IntegerField(default=None, null=True, blank=True) critical_analysis = models.IntegerField(default=None, null=True, blank=True) biologic_biochemical = models.IntegerField(default=None, null=True,",
"models.TextField(default=None, null=True) rank = models.IntegerField(default=None, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) total_students =",
"blank=True) # # unique to engineering gre = models.OneToOneField(GRE, on_delete=models.CASCADE, null=True, blank=True) #",
"null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True,",
"employed = models.FloatField(default=None, null=True, blank=True) employed_3_months = models.FloatField(default=None, null=True, blank=True) avg_work_ex_months = models.IntegerField(default=None,",
"null=True, blank=True) median_public_salary = models.IntegerField(default=None, null=True, blank=True) median_private_salary = models.IntegerField(default=None, null=True, blank=True) def",
"models.IntegerField(default=None, null=True, blank=True) awa = models.FloatField(default=None, null=True, blank=True) def __str__(self): return str(self.verbal) class",
"] grad_streams = ( ('Engineering', 'Engineering'), ('Law', 'Law'), ('Medicine', 'Medicine'), ('Business', 'Business'), )",
"country = models.ForeignKey(Country, on_delete=models.CASCADE) total_students = models.IntegerField(default=None, null=True, blank=True) total_int_students = models.IntegerField(default=None, null=True,",
"models.IntegerField(default=None, null=True, blank=True) total_int_students = models.IntegerField(default=None, null=True, blank=True) address = models.TextField(default=None, null=True, blank=True)",
"models.TextField(default=None, null=True, blank=True) # fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True,",
"null=True, blank=True) acceptance_rate = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True) us_deadline",
"blank=True, max_length=500) schools = models.TextField(default=None, null=True, blank=True) uni_type = models.TextField(default=None, null=True, blank=True) grad_school_link",
"null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling",
"models.IntegerField(default=None, null=True, blank=True) gre = models.OneToOneField(GRE, on_delete=models.CASCADE) # avg_salary = models.IntegerField(default=None, null=True, blank=True)",
"models.OneToOneField(MCAT, on_delete=models.CASCADE) def __str__(self): return self.university.name class MedicineGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering =",
"models.FloatField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None,",
"= models.IntegerField(default=None, null=True, blank=True) gre = models.OneToOneField(GRE, on_delete=models.CASCADE) # avg_salary = models.IntegerField(default=None, null=True,",
"blank=True) median_private_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class LawGradAdmin(admin.ModelAdmin): search_fields",
"# fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) # research_assistantships",
"models.IntegerField(default=None, null=True, blank=True) psycho_social_biological = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return str(self.new_total) class",
"gpa = models.FloatField(default=None, null=True, blank=True) min_toefl_score = models.IntegerField(default=None, null=True, blank=True) mean_toefl_score = models.IntegerField(default=None,",
"# us_deadline = models.DateTimeField(default=None, null=True, blank=True) # int_deadline = models.DateTimeField(default=None, null=True, blank=True) #",
"= models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # acceptance_rate_masters =",
"fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) fellowships = models.IntegerField(default=None,",
"blank=True) # male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) tuition",
"blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True)",
"info_link = models.TextField(default=None, null=True) rank = models.IntegerField(default=None, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE)",
"('Engineering', 'Engineering'), ('Law', 'Law'), ('Medicine', 'Medicine'), ('Business', 'Business'), ) class GRE(models.Model): verbal =",
"null=True, blank=True) total_int_students = models.IntegerField(default=None, null=True, blank=True) address = models.TextField(default=None, null=True, blank=True) website",
"null=True, blank=True) acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True)",
"blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) # research_assistantships = models.IntegerField(default=None, null=True, blank=True) #",
"schools = models.TextField(default=None, null=True, blank=True) uni_type = models.TextField(default=None, null=True, blank=True) grad_school_link = models.TextField(default=None,",
"living_expenses = models.IntegerField(default=None, null=True, blank=True) # # unique to engineering gre = models.OneToOneField(GRE,",
"blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) # look for room and board living_expenses",
"MedicineGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None,",
"null=True, blank=True) rolling = models.BooleanField(default=False) int_rolling = models.BooleanField(default=False) employed = models.FloatField(default=None, null=True, blank=True)",
"null=True, blank=True) median_grant = models.IntegerField(default=None, null=True, blank=True) lsat_score = models.IntegerField(default=None, null=True, blank=True) median_public_salary",
"('university__rank',) class EngineeringGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) # enrollment = models.IntegerField(default=None, null=True, blank=True)",
"models.IntegerField(default=None, null=True, blank=True) # research_assistantships = models.IntegerField(default=None, null=True, blank=True) # # look for",
"admin grad_streams_list = [ 'Engineering', 'Law', 'Medicine', 'Business', ] grad_streams = ( ('Engineering',",
"null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) gpa = models.FloatField(default=None, null=True, blank=True) #",
"= models.FloatField(default=None, null=True, blank=True) acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None,",
"medicine mcat = models.OneToOneField(MCAT, on_delete=models.CASCADE) def __str__(self): return self.university.name class MedicineGradAdmin(admin.ModelAdmin): search_fields =",
"= models.DateTimeField(default=None, null=True, blank=True) # int_deadline = models.DateTimeField(default=None, null=True, blank=True) # rolling =",
"__str__(self): return str(self.new_total) class University(models.Model): name = models.TextField(default=None) info_link = models.TextField(default=None, null=True) rank",
"models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None,",
"fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) # fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships =",
"new_total = models.IntegerField(default=None, null=True, blank=True) chemical_physical = models.IntegerField(default=None, null=True, blank=True) critical_analysis = models.IntegerField(default=None,",
"blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None,",
"null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True) us_deadline",
"'Medicine'), ('Business', 'Business'), ) class GRE(models.Model): verbal = models.IntegerField(default=None, null=True, blank=True) quant =",
"blank=True) # min_ielts_score = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True)",
"blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) fellowships =",
"blank=True, max_length=500) def __str__(self): return self.name class UniversityAdmin(admin.ModelAdmin): search_fields = ('name',) ordering =",
"null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) total_students = models.IntegerField(default=None, null=True, blank=True) total_int_students =",
"models from account.models import Country from django.contrib import admin grad_streams_list = [ 'Engineering',",
"university = models.OneToOneField(University, on_delete=models.CASCADE) # enrollment = models.IntegerField(default=None, null=True, blank=True) # us_application_fee =",
"null=True, blank=True, max_length=500) med_link = models.TextField(default=None, null=True, blank=True, max_length=500) law_link = models.TextField(default=None, null=True,",
"max_length=500) engg_link = models.TextField(default=None, null=True, blank=True, max_length=500) slug = models.SlugField(default=None, null=True, blank=True, max_length=500)",
"models.IntegerField(default=None, null=True, blank=True) median_private_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class",
"account.models import Country from django.contrib import admin grad_streams_list = [ 'Engineering', 'Law', 'Medicine',",
"return str(self.new_total) class University(models.Model): name = models.TextField(default=None) info_link = models.TextField(default=None, null=True) rank =",
"null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) #",
"# unique to engineering gre = models.OneToOneField(GRE, on_delete=models.CASCADE, null=True, blank=True) # def __str__(self):",
"= models.BooleanField(default=False) # gpa = models.FloatField(default=None, null=True, blank=True) # min_toefl_score = models.IntegerField(default=None, null=True,",
"null=True, blank=True) biologic_biochemical = models.IntegerField(default=None, null=True, blank=True) psycho_social_biological = models.IntegerField(default=None, null=True, blank=True) def",
"lsat_score = models.IntegerField(default=None, null=True, blank=True) median_public_salary = models.IntegerField(default=None, null=True, blank=True) median_private_salary = models.IntegerField(default=None,",
"= models.IntegerField(default=None, null=True, blank=True) median_public_salary = models.IntegerField(default=None, null=True, blank=True) median_private_salary = models.IntegerField(default=None, null=True,",
"# unique to business employed = models.FloatField(default=None, null=True, blank=True) employed_3_months = models.FloatField(default=None, null=True,",
"enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) male = models.FloatField(default=None,",
"# # look for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) #",
"models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) us_application_fee = models.IntegerField(default=None, null=True, blank=True)",
"= models.IntegerField(default=None, null=True, blank=True) # unique to law # look for median lsat",
"median_public_salary = models.IntegerField(default=None, null=True, blank=True) median_private_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return",
"models.DateTimeField(default=None, null=True, blank=True) # rolling = models.BooleanField(default=False) # gpa = models.FloatField(default=None, null=True, blank=True)",
"models.IntegerField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None,",
"null=True, blank=True) def __str__(self): return self.university.name class LawGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering =",
"models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) int_rolling = models.BooleanField(default=False) employed = models.FloatField(default=None, null=True,",
"models.FloatField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) # us_deadline = models.DateTimeField(default=None,",
"blank=True) median_public_salary = models.IntegerField(default=None, null=True, blank=True) median_private_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self):",
"blank=True) min_toefl_score = models.IntegerField(default=None, null=True, blank=True) mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) min_ielts_score =",
"grad_streams_list = [ 'Engineering', 'Law', 'Medicine', 'Business', ] grad_streams = ( ('Engineering', 'Engineering'),",
"= models.FloatField(default=None, null=True, blank=True) def __str__(self): return str(self.verbal) class MCAT(models.Model): old_total = models.IntegerField(default=None,",
"blank=True) research_assistantships = models.IntegerField(default=None, null=True, blank=True) # look for room and board living_expenses",
"models.FloatField(default=None, null=True, blank=True) def __str__(self): return str(self.verbal) class MCAT(models.Model): old_total = models.IntegerField(default=None, null=True,",
"# research_assistantships = models.IntegerField(default=None, null=True, blank=True) # # look for room and board",
"models.TextField(default=None, null=True, blank=True, max_length=500) schools = models.TextField(default=None, null=True, blank=True) uni_type = models.TextField(default=None, null=True,",
"models.IntegerField(default=None, null=True, blank=True) median_public_salary = models.IntegerField(default=None, null=True, blank=True) median_private_salary = models.IntegerField(default=None, null=True, blank=True)",
"models.IntegerField(default=None, null=True, blank=True) new_total = models.IntegerField(default=None, null=True, blank=True) chemical_physical = models.IntegerField(default=None, null=True, blank=True)",
"blank=True) # unique to business employed = models.FloatField(default=None, null=True, blank=True) employed_3_months = models.FloatField(default=None,",
"max_length=500) logo = models.TextField(default=None, null=True, blank=True, max_length=500) def __str__(self): return self.name class UniversityAdmin(admin.ModelAdmin):",
"rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) min_toefl_score = models.IntegerField(default=None, null=True, blank=True)",
"models.IntegerField(default=None, null=True, blank=True) gmat = models.IntegerField(default=None, null=True, blank=True) gre = models.OneToOneField(GRE, on_delete=models.CASCADE) #",
"= [ 'Engineering', 'Law', 'Medicine', 'Business', ] grad_streams = ( ('Engineering', 'Engineering'), ('Law',",
"null=True, blank=True) male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate_masters",
"__str__(self): return self.university.name class BusinessGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class EngineeringGrad(models.Model):",
"null=True, blank=True) mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) min_ielts_score = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name",
"room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # # unique to engineering",
"female = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd",
"fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None,",
"null=True, blank=True, max_length=500) undergrad_link = models.TextField(default=None, null=True, blank=True, max_length=500) business_link = models.TextField(default=None, null=True,",
"uni_type = models.TextField(default=None, null=True, blank=True) grad_school_link = models.TextField(default=None, null=True, blank=True, max_length=500) undergrad_link =",
"on_delete=models.CASCADE) # enrollment = models.IntegerField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True)",
"= models.IntegerField(default=None, null=True, blank=True) address = models.TextField(default=None, null=True, blank=True) website = models.TextField(default=None, null=True,",
"blank=True) female = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True) us_deadline =",
"us_deadline = models.DateTimeField(default=None, null=True, blank=True) # int_deadline = models.DateTimeField(default=None, null=True, blank=True) # rolling",
"models.IntegerField(default=None, null=True, blank=True) biologic_biochemical = models.IntegerField(default=None, null=True, blank=True) psycho_social_biological = models.IntegerField(default=None, null=True, blank=True)",
"# male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) tuition =",
"models.FloatField(default=None, null=True, blank=True) # us_deadline = models.DateTimeField(default=None, null=True, blank=True) # int_deadline = models.DateTimeField(default=None,",
"blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships =",
"to medicine mcat = models.OneToOneField(MCAT, on_delete=models.CASCADE) def __str__(self): return self.university.name class MedicineGradAdmin(admin.ModelAdmin): search_fields",
"django.db import models from account.models import Country from django.contrib import admin grad_streams_list =",
"= models.IntegerField(default=None, null=True, blank=True) mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) min_ielts_score = models.FloatField(default=None, null=True,",
"avg_work_ex_months = models.IntegerField(default=None, null=True, blank=True) gmat = models.IntegerField(default=None, null=True, blank=True) gre = models.OneToOneField(GRE,",
"max_length=500) undergrad_link = models.TextField(default=None, null=True, blank=True, max_length=500) business_link = models.TextField(default=None, null=True, blank=True, max_length=500)",
"'Engineering'), ('Law', 'Law'), ('Medicine', 'Medicine'), ('Business', 'Business'), ) class GRE(models.Model): verbal = models.IntegerField(default=None,",
"grad_school_link = models.TextField(default=None, null=True, blank=True, max_length=500) undergrad_link = models.TextField(default=None, null=True, blank=True, max_length=500) business_link",
"null=True, blank=True, max_length=500) def __str__(self): return self.name class UniversityAdmin(admin.ModelAdmin): search_fields = ('name',) ordering",
"= models.FloatField(default=None, null=True, blank=True) male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True,",
"('university__name',) ordering = ('university__rank',) class MedicineGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None,",
"bar_passage_rate = models.FloatField(default=None, null=True, blank=True) median_grant = models.IntegerField(default=None, null=True, blank=True) lsat_score = models.IntegerField(default=None,",
"class MedicineGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international =",
"min_ielts_score = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) # fin_aid_director_phone",
"models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) # research_assistantships = models.IntegerField(default=None, null=True,",
"male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None,",
"acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) female =",
"gre = models.OneToOneField(GRE, on_delete=models.CASCADE, null=True, blank=True) # def __str__(self): return self.university.name class EngineeringGradAdmin(admin.ModelAdmin):",
"blank=True) tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True) int_deadline =",
"blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate = models.FloatField(default=None, null=True, blank=True) tuition =",
"avg_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class BusinessGradAdmin(admin.ModelAdmin): search_fields =",
"= models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True,",
"# acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True) #",
"address = models.TextField(default=None, null=True, blank=True) website = models.TextField(default=None, null=True, blank=True, max_length=500) schools =",
"= models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # tuition =",
"acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # us_application_fee",
"= models.IntegerField(default=None, null=True, blank=True) min_ielts_score = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True,",
"blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True)",
"self.university.name class MedicineGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class LawGrad(models.Model): university =",
"blank=True) # male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate",
"blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True)",
"models.FloatField(default=None, null=True, blank=True) avg_work_ex_months = models.IntegerField(default=None, null=True, blank=True) gmat = models.IntegerField(default=None, null=True, blank=True)",
"blank=True) # unique to law # look for median lsat employed = models.FloatField(default=None,",
"to business employed = models.FloatField(default=None, null=True, blank=True) employed_3_months = models.FloatField(default=None, null=True, blank=True) avg_work_ex_months",
"null=True, blank=True) min_toefl_score = models.IntegerField(default=None, null=True, blank=True) mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) min_ielts_score",
"null=True, blank=True) def __str__(self): return str(self.new_total) class University(models.Model): name = models.TextField(default=None) info_link =",
"null=True, blank=True) quant = models.IntegerField(default=None, null=True, blank=True) awa = models.FloatField(default=None, null=True, blank=True) def",
"models.SlugField(default=None, null=True, blank=True, max_length=500) logo = models.TextField(default=None, null=True, blank=True, max_length=500) def __str__(self): return",
"= models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None,",
"models.IntegerField(default=None, null=True, blank=True) quant = models.IntegerField(default=None, null=True, blank=True) awa = models.FloatField(default=None, null=True, blank=True)",
"= models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate = models.FloatField(default=None, null=True,",
"('Business', 'Business'), ) class GRE(models.Model): verbal = models.IntegerField(default=None, null=True, blank=True) quant = models.IntegerField(default=None,",
"# gpa = models.FloatField(default=None, null=True, blank=True) # min_toefl_score = models.IntegerField(default=None, null=True, blank=True) #",
"blank=True) gre = models.OneToOneField(GRE, on_delete=models.CASCADE) # avg_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self):",
"blank=True) critical_analysis = models.IntegerField(default=None, null=True, blank=True) biologic_biochemical = models.IntegerField(default=None, null=True, blank=True) psycho_social_biological =",
"= models.FloatField(default=None, null=True, blank=True) employed_3_months = models.FloatField(default=None, null=True, blank=True) avg_work_ex_months = models.IntegerField(default=None, null=True,",
"blank=True) # fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) #",
"= models.TextField(default=None, null=True, blank=True, max_length=500) law_link = models.TextField(default=None, null=True, blank=True, max_length=500) engg_link =",
"[ 'Engineering', 'Law', 'Medicine', 'Business', ] grad_streams = ( ('Engineering', 'Engineering'), ('Law', 'Law'),",
"min_toefl_score = models.IntegerField(default=None, null=True, blank=True) # mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) # min_ielts_score",
"name = models.TextField(default=None) info_link = models.TextField(default=None, null=True) rank = models.IntegerField(default=None, null=True, blank=True) country",
"board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to business employed = models.FloatField(default=None,",
"look for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # # unique",
"models.OneToOneField(GRE, on_delete=models.CASCADE) # avg_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class",
"models.FloatField(default=None, null=True, blank=True) median_grant = models.IntegerField(default=None, null=True, blank=True) lsat_score = models.IntegerField(default=None, null=True, blank=True)",
"blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) gpa =",
"models.IntegerField(default=None, null=True, blank=True) def __str__(self): return str(self.new_total) class University(models.Model): name = models.TextField(default=None) info_link",
"blank=True) total_int_students = models.IntegerField(default=None, null=True, blank=True) address = models.TextField(default=None, null=True, blank=True) website =",
"= models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate_masters = models.FloatField(default=None, null=True,",
"blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True) int_deadline",
"null=True, blank=True) chemical_physical = models.IntegerField(default=None, null=True, blank=True) critical_analysis = models.IntegerField(default=None, null=True, blank=True) biologic_biochemical",
"'Medicine', 'Business', ] grad_streams = ( ('Engineering', 'Engineering'), ('Law', 'Law'), ('Medicine', 'Medicine'), ('Business',",
"models.IntegerField(default=None, null=True, blank=True) # # unique to engineering gre = models.OneToOneField(GRE, on_delete=models.CASCADE, null=True,",
"null=True, blank=True) us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True)",
"= models.IntegerField(default=None, null=True, blank=True) gmat = models.IntegerField(default=None, null=True, blank=True) gre = models.OneToOneField(GRE, on_delete=models.CASCADE)",
"null=True, blank=True) # unique to medicine mcat = models.OneToOneField(MCAT, on_delete=models.CASCADE) def __str__(self): return",
"# unique to law # look for median lsat employed = models.FloatField(default=None, null=True,",
"null=True, blank=True) lsat_score = models.IntegerField(default=None, null=True, blank=True) median_public_salary = models.IntegerField(default=None, null=True, blank=True) median_private_salary",
"int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) int_rolling = models.BooleanField(default=False) employed =",
"def __str__(self): return str(self.verbal) class MCAT(models.Model): old_total = models.IntegerField(default=None, null=True, blank=True) new_total =",
"board living_expenses = models.IntegerField(default=None, null=True, blank=True) # # unique to engineering gre =",
"models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate = models.FloatField(default=None, null=True, blank=True)",
"= models.TextField(default=None, null=True, blank=True, max_length=500) slug = models.SlugField(default=None, null=True, blank=True, max_length=500) logo =",
"models.TextField(default=None, null=True, blank=True, max_length=500) slug = models.SlugField(default=None, null=True, blank=True, max_length=500) logo = models.TextField(default=None,",
"class MedicineGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class LawGrad(models.Model): university = models.OneToOneField(University,",
"('Medicine', 'Medicine'), ('Business', 'Business'), ) class GRE(models.Model): verbal = models.IntegerField(default=None, null=True, blank=True) quant",
"business_link = models.TextField(default=None, null=True, blank=True, max_length=500) med_link = models.TextField(default=None, null=True, blank=True, max_length=500) law_link",
"= models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # male =",
"models.FloatField(default=None, null=True, blank=True) # look for room and board living_expenses = models.IntegerField(default=None, null=True,",
"us_deadline = models.DateTimeField(default=None, null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False)",
"= models.IntegerField(default=None, null=True, blank=True) total_int_students = models.IntegerField(default=None, null=True, blank=True) address = models.TextField(default=None, null=True,",
"models.IntegerField(default=None, null=True, blank=True) # international = models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None,",
"blank=True) # male = models.FloatField(default=None, null=True, blank=True) # female = models.FloatField(default=None, null=True, blank=True)",
"fin_aid_director_name = models.TextField(default=None, null=True, blank=True) # fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) # fellowships",
"null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) fellowships",
"lsat employed = models.FloatField(default=None, null=True, blank=True) bar_passage_rate = models.FloatField(default=None, null=True, blank=True) median_grant =",
"from account.models import Country from django.contrib import admin grad_streams_list = [ 'Engineering', 'Law',",
"blank=True) uni_type = models.TextField(default=None, null=True, blank=True) grad_school_link = models.TextField(default=None, null=True, blank=True, max_length=500) undergrad_link",
"= models.IntegerField(default=None, null=True, blank=True) chemical_physical = models.IntegerField(default=None, null=True, blank=True) critical_analysis = models.IntegerField(default=None, null=True,",
"models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) male",
"blank=True) acceptance_rate = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True) us_deadline =",
"models.IntegerField(default=None, null=True, blank=True) chemical_physical = models.IntegerField(default=None, null=True, blank=True) critical_analysis = models.IntegerField(default=None, null=True, blank=True)",
"models.DateTimeField(default=None, null=True, blank=True) # int_deadline = models.DateTimeField(default=None, null=True, blank=True) # rolling = models.BooleanField(default=False)",
"room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to law #",
"return self.university.name class BusinessGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class EngineeringGrad(models.Model): university",
"employed = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None,",
"law # look for median lsat employed = models.FloatField(default=None, null=True, blank=True) bar_passage_rate =",
"models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) research_assistantships = models.IntegerField(default=None, null=True, blank=True)",
"blank=True) awa = models.FloatField(default=None, null=True, blank=True) def __str__(self): return str(self.verbal) class MCAT(models.Model): old_total",
"= models.IntegerField(default=None, null=True, blank=True) # research_assistantships = models.IntegerField(default=None, null=True, blank=True) # # look",
"acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # male",
"# def __str__(self): return self.university.name class EngineeringGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',)",
"median_private_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class LawGradAdmin(admin.ModelAdmin): search_fields =",
"living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to business employed = models.FloatField(default=None, null=True,",
"models.FloatField(default=None, null=True, blank=True) gpa = models.FloatField(default=None, null=True, blank=True) # # look for room",
"models.IntegerField(default=None, null=True, blank=True) # unique to law # look for median lsat employed",
") class GRE(models.Model): verbal = models.IntegerField(default=None, null=True, blank=True) quant = models.IntegerField(default=None, null=True, blank=True)",
"BusinessGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None,",
"= models.TextField(default=None, null=True, blank=True, max_length=500) business_link = models.TextField(default=None, null=True, blank=True, max_length=500) med_link =",
"slug = models.SlugField(default=None, null=True, blank=True, max_length=500) logo = models.TextField(default=None, null=True, blank=True, max_length=500) def",
"null=True, blank=True) new_total = models.IntegerField(default=None, null=True, blank=True) chemical_physical = models.IntegerField(default=None, null=True, blank=True) critical_analysis",
"for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # # unique to",
"gre = models.OneToOneField(GRE, on_delete=models.CASCADE) # avg_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return",
"null=True, blank=True) def __str__(self): return str(self.verbal) class MCAT(models.Model): old_total = models.IntegerField(default=None, null=True, blank=True)",
"# enrollment = models.IntegerField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True) #",
"models.IntegerField(default=None, null=True, blank=True) mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) min_ielts_score = models.FloatField(default=None, null=True, blank=True)",
"models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) min_toefl_score = models.IntegerField(default=None, null=True, blank=True) mean_toefl_score =",
"null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) #",
"= models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True)",
"max_length=500) def __str__(self): return self.name class UniversityAdmin(admin.ModelAdmin): search_fields = ('name',) ordering = ('rank',)",
"from django.db import models from account.models import Country from django.contrib import admin grad_streams_list",
"null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) gpa",
"fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None,",
"models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) gpa = models.FloatField(default=None, null=True, blank=True)",
"null=True, blank=True) median_private_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class LawGradAdmin(admin.ModelAdmin):",
"blank=True) grad_school_link = models.TextField(default=None, null=True, blank=True, max_length=500) undergrad_link = models.TextField(default=None, null=True, blank=True, max_length=500)",
"# min_ielts_score = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) #",
"models.IntegerField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None,",
"psycho_social_biological = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return str(self.new_total) class University(models.Model): name =",
"= models.IntegerField(default=None, null=True, blank=True) # min_ielts_score = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name =",
"and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # # unique to engineering gre",
"= models.IntegerField(default=None, null=True, blank=True) # unique to medicine mcat = models.OneToOneField(MCAT, on_delete=models.CASCADE) def",
"blank=True) chemical_physical = models.IntegerField(default=None, null=True, blank=True) critical_analysis = models.IntegerField(default=None, null=True, blank=True) biologic_biochemical =",
"null=True, blank=True) def __str__(self): return self.university.name class BusinessGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering =",
"blank=True, max_length=500) business_link = models.TextField(default=None, null=True, blank=True, max_length=500) med_link = models.TextField(default=None, null=True, blank=True,",
"self.university.name class BusinessGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class EngineeringGrad(models.Model): university =",
"= models.TextField(default=None, null=True) rank = models.IntegerField(default=None, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) total_students",
"null=True, blank=True) # min_ielts_score = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True,",
"us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # international",
"= models.TextField(default=None) info_link = models.TextField(default=None, null=True) rank = models.IntegerField(default=None, null=True, blank=True) country =",
"null=True, blank=True) # fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) # fellowships = models.IntegerField(default=None, null=True,",
"LawGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None,",
"blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True,",
"= models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None,",
"models.TextField(default=None, null=True, blank=True) # fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) # fellowships = models.IntegerField(default=None,",
"null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships",
"models.IntegerField(default=None, null=True, blank=True) # # look for room and board living_expenses = models.IntegerField(default=None,",
"null=True, blank=True, max_length=500) logo = models.TextField(default=None, null=True, blank=True, max_length=500) def __str__(self): return self.name",
"blank=True) gmat = models.IntegerField(default=None, null=True, blank=True) gre = models.OneToOneField(GRE, on_delete=models.CASCADE) # avg_salary =",
"models.FloatField(default=None, null=True, blank=True) min_toefl_score = models.IntegerField(default=None, null=True, blank=True) mean_toefl_score = models.IntegerField(default=None, null=True, blank=True)",
"UniversityAdmin(admin.ModelAdmin): search_fields = ('name',) ordering = ('rank',) class BusinessGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE)",
"blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True)",
"null=True, blank=True) critical_analysis = models.IntegerField(default=None, null=True, blank=True) biologic_biochemical = models.IntegerField(default=None, null=True, blank=True) psycho_social_biological",
"blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid",
"('Law', 'Law'), ('Medicine', 'Medicine'), ('Business', 'Business'), ) class GRE(models.Model): verbal = models.IntegerField(default=None, null=True,",
"class EngineeringGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class MedicineGrad(models.Model): university = models.OneToOneField(University,",
"# look for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique",
"null=True, blank=True) # rolling = models.BooleanField(default=False) # gpa = models.FloatField(default=None, null=True, blank=True) #",
"= models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True,",
"models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) # look for room and",
"research_assistantships = models.IntegerField(default=None, null=True, blank=True) # # look for room and board living_expenses",
"models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None,",
"return self.university.name class MedicineGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class LawGrad(models.Model): university",
"models.OneToOneField(GRE, on_delete=models.CASCADE, null=True, blank=True) # def __str__(self): return self.university.name class EngineeringGradAdmin(admin.ModelAdmin): search_fields =",
"rolling = models.BooleanField(default=False) # gpa = models.FloatField(default=None, null=True, blank=True) # min_toefl_score = models.IntegerField(default=None,",
"blank=True) # # look for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True)",
"models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True)",
"import admin grad_streams_list = [ 'Engineering', 'Law', 'Medicine', 'Business', ] grad_streams = (",
"rank = models.IntegerField(default=None, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) total_students = models.IntegerField(default=None, null=True,",
"blank=True) def __str__(self): return self.university.name class LawGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',)",
"= models.FloatField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd =",
"models.FloatField(default=None, null=True, blank=True) # min_toefl_score = models.IntegerField(default=None, null=True, blank=True) # mean_toefl_score = models.IntegerField(default=None,",
"blank=True) international = models.FloatField(default=None, null=True, blank=True) male = models.FloatField(default=None, null=True, blank=True) female =",
"models.IntegerField(default=None, null=True, blank=True) research_assistantships = models.IntegerField(default=None, null=True, blank=True) # look for room and",
"null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True,",
"null=True, blank=True) research_assistantships = models.IntegerField(default=None, null=True, blank=True) # look for room and board",
"('university__name',) ordering = ('university__rank',) class EngineeringGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) # enrollment =",
"class EngineeringGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) # enrollment = models.IntegerField(default=None, null=True, blank=True) #",
"= models.IntegerField(default=None, null=True, blank=True) # mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) # min_ielts_score =",
"for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to law",
"ordering = ('university__rank',) class MedicineGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True,",
"models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True)",
"null=True, blank=True) fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) research_assistantships",
"# int_application_fee = models.IntegerField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) female",
"fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) gpa = models.FloatField(default=None,",
"old_total = models.IntegerField(default=None, null=True, blank=True) new_total = models.IntegerField(default=None, null=True, blank=True) chemical_physical = models.IntegerField(default=None,",
"('rank',) class BusinessGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international",
"blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True)",
"# look for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # #",
"null=True, blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) min_toefl_score = models.IntegerField(default=None,",
"models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class BusinessGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering",
"null=True, blank=True) # fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True)",
"enrollment = models.IntegerField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee",
"'Business', ] grad_streams = ( ('Engineering', 'Engineering'), ('Law', 'Law'), ('Medicine', 'Medicine'), ('Business', 'Business'),",
"= models.TextField(default=None, null=True, blank=True) website = models.TextField(default=None, null=True, blank=True, max_length=500) schools = models.TextField(default=None,",
"models.BooleanField(default=False) employed = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone =",
"# male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate =",
"blank=True) quant = models.IntegerField(default=None, null=True, blank=True) awa = models.FloatField(default=None, null=True, blank=True) def __str__(self):",
"for median lsat employed = models.FloatField(default=None, null=True, blank=True) bar_passage_rate = models.FloatField(default=None, null=True, blank=True)",
"= models.SlugField(default=None, null=True, blank=True, max_length=500) logo = models.TextField(default=None, null=True, blank=True, max_length=500) def __str__(self):",
"models.FloatField(default=None, null=True, blank=True) bar_passage_rate = models.FloatField(default=None, null=True, blank=True) median_grant = models.IntegerField(default=None, null=True, blank=True)",
"models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # male = models.FloatField(default=None,",
"students_receiving_aid = models.FloatField(default=None, null=True, blank=True) # look for room and board living_expenses =",
"undergrad_link = models.TextField(default=None, null=True, blank=True, max_length=500) business_link = models.TextField(default=None, null=True, blank=True, max_length=500) med_link",
"unique to business employed = models.FloatField(default=None, null=True, blank=True) employed_3_months = models.FloatField(default=None, null=True, blank=True)",
"class University(models.Model): name = models.TextField(default=None) info_link = models.TextField(default=None, null=True) rank = models.IntegerField(default=None, null=True,",
"international = models.FloatField(default=None, null=True, blank=True) male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None,",
"blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) research_assistantships = models.IntegerField(default=None, null=True, blank=True) # look",
"gmat = models.IntegerField(default=None, null=True, blank=True) gre = models.OneToOneField(GRE, on_delete=models.CASCADE) # avg_salary = models.IntegerField(default=None,",
"fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) research_assistantships = models.IntegerField(default=None,",
"enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) us_application_fee = models.IntegerField(default=None,",
"# acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) #",
"= models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class BusinessGradAdmin(admin.ModelAdmin): search_fields = ('university__name',)",
"models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone",
"= models.FloatField(default=None, null=True, blank=True) # min_toefl_score = models.IntegerField(default=None, null=True, blank=True) # mean_toefl_score =",
"on_delete=models.CASCADE, null=True, blank=True) # def __str__(self): return self.university.name class EngineeringGradAdmin(admin.ModelAdmin): search_fields = ('university__name',)",
"('name',) ordering = ('rank',) class BusinessGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None,",
"unique to medicine mcat = models.OneToOneField(MCAT, on_delete=models.CASCADE) def __str__(self): return self.university.name class MedicineGradAdmin(admin.ModelAdmin):",
"and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to law # look",
"EngineeringGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) # enrollment = models.IntegerField(default=None, null=True, blank=True) # us_application_fee",
"blank=True) avg_work_ex_months = models.IntegerField(default=None, null=True, blank=True) gmat = models.IntegerField(default=None, null=True, blank=True) gre =",
"models.IntegerField(default=None, null=True, blank=True) # look for room and board living_expenses = models.IntegerField(default=None, null=True,",
"def __str__(self): return self.university.name class EngineeringGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class",
"mcat = models.OneToOneField(MCAT, on_delete=models.CASCADE) def __str__(self): return self.university.name class MedicineGradAdmin(admin.ModelAdmin): search_fields = ('university__name',)",
"__str__(self): return self.university.name class EngineeringGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class MedicineGrad(models.Model):",
"= models.IntegerField(default=None, null=True, blank=True) awa = models.FloatField(default=None, null=True, blank=True) def __str__(self): return str(self.verbal)",
"null=True, blank=True, max_length=500) business_link = models.TextField(default=None, null=True, blank=True, max_length=500) med_link = models.TextField(default=None, null=True,",
"EngineeringGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class MedicineGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE)",
"django.contrib import admin grad_streams_list = [ 'Engineering', 'Law', 'Medicine', 'Business', ] grad_streams =",
"= models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) # female =",
"= models.OneToOneField(GRE, on_delete=models.CASCADE, null=True, blank=True) # def __str__(self): return self.university.name class EngineeringGradAdmin(admin.ModelAdmin): search_fields",
"engineering gre = models.OneToOneField(GRE, on_delete=models.CASCADE, null=True, blank=True) # def __str__(self): return self.university.name class",
"blank=True) # def __str__(self): return self.university.name class EngineeringGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering =",
"total_students = models.IntegerField(default=None, null=True, blank=True) total_int_students = models.IntegerField(default=None, null=True, blank=True) address = models.TextField(default=None,",
"null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True,",
"= models.FloatField(default=None, null=True, blank=True) avg_work_ex_months = models.IntegerField(default=None, null=True, blank=True) gmat = models.IntegerField(default=None, null=True,",
"null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) int_rolling = models.BooleanField(default=False)",
"= models.DateTimeField(default=None, null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) gpa",
"models.IntegerField(default=None, null=True, blank=True) # mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) # min_ielts_score = models.FloatField(default=None,",
"= models.FloatField(default=None, null=True, blank=True) acceptance_rate = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True,",
"employed_3_months = models.FloatField(default=None, null=True, blank=True) avg_work_ex_months = models.IntegerField(default=None, null=True, blank=True) gmat = models.IntegerField(default=None,",
"models.DateTimeField(default=None, null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) int_rolling =",
"# fin_aid_director_name = models.TextField(default=None, null=True, blank=True) # fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) #",
"med_link = models.TextField(default=None, null=True, blank=True, max_length=500) law_link = models.TextField(default=None, null=True, blank=True, max_length=500) engg_link",
"room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to business employed",
"null=True, blank=True, max_length=500) schools = models.TextField(default=None, null=True, blank=True) uni_type = models.TextField(default=None, null=True, blank=True)",
"models.FloatField(default=None, null=True, blank=True) us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True,",
"max_length=500) schools = models.TextField(default=None, null=True, blank=True) uni_type = models.TextField(default=None, null=True, blank=True) grad_school_link =",
"models.TextField(default=None, null=True, blank=True, max_length=500) engg_link = models.TextField(default=None, null=True, blank=True, max_length=500) slug = models.SlugField(default=None,",
"= models.TextField(default=None, null=True, blank=True) uni_type = models.TextField(default=None, null=True, blank=True) grad_school_link = models.TextField(default=None, null=True,",
"board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to law # look for",
"class GRE(models.Model): verbal = models.IntegerField(default=None, null=True, blank=True) quant = models.IntegerField(default=None, null=True, blank=True) awa",
"models.TextField(default=None, null=True, blank=True) website = models.TextField(default=None, null=True, blank=True, max_length=500) schools = models.TextField(default=None, null=True,",
"= ('university__name',) ordering = ('university__rank',) class LawGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment =",
"max_length=500) law_link = models.TextField(default=None, null=True, blank=True, max_length=500) engg_link = models.TextField(default=None, null=True, blank=True, max_length=500)",
"models.TextField(default=None, null=True, blank=True, max_length=500) law_link = models.TextField(default=None, null=True, blank=True, max_length=500) engg_link = models.TextField(default=None,",
"= models.IntegerField(default=None, null=True, blank=True) biologic_biochemical = models.IntegerField(default=None, null=True, blank=True) psycho_social_biological = models.IntegerField(default=None, null=True,",
"blank=True) employed_3_months = models.FloatField(default=None, null=True, blank=True) avg_work_ex_months = models.IntegerField(default=None, null=True, blank=True) gmat =",
"null=True, blank=True) # female = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True,",
"gpa = models.FloatField(default=None, null=True, blank=True) # # look for room and board living_expenses",
"GRE(models.Model): verbal = models.IntegerField(default=None, null=True, blank=True) quant = models.IntegerField(default=None, null=True, blank=True) awa =",
"= models.IntegerField(default=None, null=True, blank=True) research_assistantships = models.IntegerField(default=None, null=True, blank=True) # look for room",
"int_application_fee = models.IntegerField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) female =",
"'Law'), ('Medicine', 'Medicine'), ('Business', 'Business'), ) class GRE(models.Model): verbal = models.IntegerField(default=None, null=True, blank=True)",
"null=True, blank=True) # unique to law # look for median lsat employed =",
"# look for median lsat employed = models.FloatField(default=None, null=True, blank=True) bar_passage_rate = models.FloatField(default=None,",
"models.FloatField(default=None, null=True, blank=True) employed_3_months = models.FloatField(default=None, null=True, blank=True) avg_work_ex_months = models.IntegerField(default=None, null=True, blank=True)",
"# male = models.FloatField(default=None, null=True, blank=True) # female = models.FloatField(default=None, null=True, blank=True) #",
"models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name",
"gpa = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone =",
"null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # international = models.FloatField(default=None, null=True,",
"blank=True) # research_assistantships = models.IntegerField(default=None, null=True, blank=True) # # look for room and",
"null=True, blank=True) psycho_social_biological = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return str(self.new_total) class University(models.Model):",
"def __str__(self): return self.university.name class MedicineGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class",
"max_length=500) med_link = models.TextField(default=None, null=True, blank=True, max_length=500) law_link = models.TextField(default=None, null=True, blank=True, max_length=500)",
"quant = models.IntegerField(default=None, null=True, blank=True) awa = models.FloatField(default=None, null=True, blank=True) def __str__(self): return",
"= models.IntegerField(default=None, null=True, blank=True) psycho_social_biological = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return str(self.new_total)",
"null=True, blank=True) employed_3_months = models.FloatField(default=None, null=True, blank=True) avg_work_ex_months = models.IntegerField(default=None, null=True, blank=True) gmat",
"models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class LawGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering",
"# int_deadline = models.DateTimeField(default=None, null=True, blank=True) # rolling = models.BooleanField(default=False) # gpa =",
"awa = models.FloatField(default=None, null=True, blank=True) def __str__(self): return str(self.verbal) class MCAT(models.Model): old_total =",
"null=True, blank=True, max_length=500) slug = models.SlugField(default=None, null=True, blank=True, max_length=500) logo = models.TextField(default=None, null=True,",
"models.IntegerField(default=None, null=True, blank=True) # unique to business employed = models.FloatField(default=None, null=True, blank=True) employed_3_months",
"blank=True) # fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) # fellowships = models.IntegerField(default=None, null=True, blank=True)",
"null=True, blank=True) # mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) # min_ielts_score = models.FloatField(default=None, null=True,",
"blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) int_rolling = models.BooleanField(default=False) employed",
"blank=True, max_length=500) undergrad_link = models.TextField(default=None, null=True, blank=True, max_length=500) business_link = models.TextField(default=None, null=True, blank=True,",
"= models.OneToOneField(GRE, on_delete=models.CASCADE) # avg_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name",
"# mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) # min_ielts_score = models.FloatField(default=None, null=True, blank=True) #",
"blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) # us_deadline = models.DateTimeField(default=None, null=True, blank=True)",
"models.BooleanField(default=False) int_rolling = models.BooleanField(default=False) employed = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True,",
"models.ForeignKey(Country, on_delete=models.CASCADE) total_students = models.IntegerField(default=None, null=True, blank=True) total_int_students = models.IntegerField(default=None, null=True, blank=True) address",
"= models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) # look for room",
"University(models.Model): name = models.TextField(default=None) info_link = models.TextField(default=None, null=True) rank = models.IntegerField(default=None, null=True, blank=True)",
"__str__(self): return self.name class UniversityAdmin(admin.ModelAdmin): search_fields = ('name',) ordering = ('rank',) class BusinessGrad(models.Model):",
"null=True, blank=True) min_ielts_score = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone",
"= models.IntegerField(default=None, null=True, blank=True) # international = models.FloatField(default=None, null=True, blank=True) # male =",
"= models.TextField(default=None, null=True, blank=True) # fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) # fellowships =",
"models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True)",
"acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) # us_deadline",
"null=True, blank=True) address = models.TextField(default=None, null=True, blank=True) website = models.TextField(default=None, null=True, blank=True, max_length=500)",
"null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) us_application_fee = models.IntegerField(default=None, null=True, blank=True) #",
"= models.FloatField(default=None, null=True, blank=True) # # look for room and board living_expenses =",
"= models.TextField(default=None, null=True, blank=True, max_length=500) def __str__(self): return self.name class UniversityAdmin(admin.ModelAdmin): search_fields =",
"ordering = ('rank',) class BusinessGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True,",
"= models.IntegerField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None,",
"gpa = models.FloatField(default=None, null=True, blank=True) # min_toefl_score = models.IntegerField(default=None, null=True, blank=True) # mean_toefl_score",
"self.university.name class EngineeringGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class MedicineGrad(models.Model): university =",
"blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) min_toefl_score = models.IntegerField(default=None, null=True,",
"tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True) int_deadline = models.DateTimeField(default=None,",
"website = models.TextField(default=None, null=True, blank=True, max_length=500) schools = models.TextField(default=None, null=True, blank=True) uni_type =",
"null=True, blank=True) # look for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True)",
"# fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) # fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships",
"= models.OneToOneField(MCAT, on_delete=models.CASCADE) def __str__(self): return self.university.name class MedicineGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering",
"models.FloatField(default=None, null=True, blank=True) # # look for room and board living_expenses = models.IntegerField(default=None,",
"max_length=500) slug = models.SlugField(default=None, null=True, blank=True, max_length=500) logo = models.TextField(default=None, null=True, blank=True, max_length=500)",
"null=True, blank=True, max_length=500) engg_link = models.TextField(default=None, null=True, blank=True, max_length=500) slug = models.SlugField(default=None, null=True,",
"self.name class UniversityAdmin(admin.ModelAdmin): search_fields = ('name',) ordering = ('rank',) class BusinessGrad(models.Model): university =",
"null=True, blank=True) # unique to business employed = models.FloatField(default=None, null=True, blank=True) employed_3_months =",
"models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) # female = models.FloatField(default=None,",
"# int_application_fee = models.IntegerField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True) #",
"# int_application_fee = models.IntegerField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) us_deadline",
"null=True, blank=True) awa = models.FloatField(default=None, null=True, blank=True) def __str__(self): return str(self.verbal) class MCAT(models.Model):",
"null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) # us_deadline = models.DateTimeField(default=None, null=True,",
"ordering = ('university__rank',) class LawGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True,",
"= models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True,",
"unique to engineering gre = models.OneToOneField(GRE, on_delete=models.CASCADE, null=True, blank=True) # def __str__(self): return",
"blank=True) # unique to medicine mcat = models.OneToOneField(MCAT, on_delete=models.CASCADE) def __str__(self): return self.university.name",
"int_application_fee = models.IntegerField(default=None, null=True, blank=True) # international = models.FloatField(default=None, null=True, blank=True) # male",
"= models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) int_rolling = models.BooleanField(default=False) employed = models.FloatField(default=None,",
"rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True,",
"models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) male = models.FloatField(default=None, null=True, blank=True)",
"blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # international = models.FloatField(default=None, null=True, blank=True)",
"= models.FloatField(default=None, null=True, blank=True) # look for room and board living_expenses = models.IntegerField(default=None,",
"null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True) int_deadline",
"('university__name',) ordering = ('university__rank',) class LawGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None,",
"null=True, blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name =",
"median lsat employed = models.FloatField(default=None, null=True, blank=True) bar_passage_rate = models.FloatField(default=None, null=True, blank=True) median_grant",
"= models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name class LawGradAdmin(admin.ModelAdmin): search_fields = ('university__name',)",
"blank=True) def __str__(self): return str(self.verbal) class MCAT(models.Model): old_total = models.IntegerField(default=None, null=True, blank=True) new_total",
"= models.IntegerField(default=None, null=True, blank=True) median_private_salary = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return self.university.name",
"models.IntegerField(default=None, null=True, blank=True) address = models.TextField(default=None, null=True, blank=True) website = models.TextField(default=None, null=True, blank=True,",
"= ('university__rank',) class EngineeringGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) # enrollment = models.IntegerField(default=None, null=True,",
"= models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # tuition =",
"= models.BooleanField(default=False) employed = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone",
"blank=True) median_grant = models.IntegerField(default=None, null=True, blank=True) lsat_score = models.IntegerField(default=None, null=True, blank=True) median_public_salary =",
"= models.DateTimeField(default=None, null=True, blank=True) # rolling = models.BooleanField(default=False) # gpa = models.FloatField(default=None, null=True,",
"= models.TextField(default=None, null=True, blank=True, max_length=500) undergrad_link = models.TextField(default=None, null=True, blank=True, max_length=500) business_link =",
"= models.FloatField(default=None, null=True, blank=True) us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None,",
"= models.TextField(default=None, null=True, blank=True, max_length=500) schools = models.TextField(default=None, null=True, blank=True) uni_type = models.TextField(default=None,",
"# rolling = models.BooleanField(default=False) # gpa = models.FloatField(default=None, null=True, blank=True) # min_toefl_score =",
"= ('rank',) class BusinessGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True)",
"import Country from django.contrib import admin grad_streams_list = [ 'Engineering', 'Law', 'Medicine', 'Business',",
"null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None,",
"= models.FloatField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) # us_deadline =",
"Country from django.contrib import admin grad_streams_list = [ 'Engineering', 'Law', 'Medicine', 'Business', ]",
"blank=True, max_length=500) engg_link = models.TextField(default=None, null=True, blank=True, max_length=500) slug = models.SlugField(default=None, null=True, blank=True,",
"( ('Engineering', 'Engineering'), ('Law', 'Law'), ('Medicine', 'Medicine'), ('Business', 'Business'), ) class GRE(models.Model): verbal",
"MCAT(models.Model): old_total = models.IntegerField(default=None, null=True, blank=True) new_total = models.IntegerField(default=None, null=True, blank=True) chemical_physical =",
"blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True)",
"('university__rank',) class LawGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international",
"'Business'), ) class GRE(models.Model): verbal = models.IntegerField(default=None, null=True, blank=True) quant = models.IntegerField(default=None, null=True,",
"= models.TextField(default=None, null=True, blank=True) fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True,",
"blank=True) address = models.TextField(default=None, null=True, blank=True) website = models.TextField(default=None, null=True, blank=True, max_length=500) schools",
"return self.name class UniversityAdmin(admin.ModelAdmin): search_fields = ('name',) ordering = ('rank',) class BusinessGrad(models.Model): university",
"models.TextField(default=None, null=True, blank=True) fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True)",
"models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # international = models.FloatField(default=None,",
"blank=True) # female = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None, null=True, blank=True)",
"null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True, blank=True)",
"null=True) rank = models.IntegerField(default=None, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) total_students = models.IntegerField(default=None,",
"null=True, blank=True) # # unique to engineering gre = models.OneToOneField(GRE, on_delete=models.CASCADE, null=True, blank=True)",
"models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) # fin_aid_director_phone = models.TextField(default=None,",
"tuition = models.FloatField(default=None, null=True, blank=True) # us_deadline = models.DateTimeField(default=None, null=True, blank=True) # int_deadline",
"critical_analysis = models.IntegerField(default=None, null=True, blank=True) biologic_biochemical = models.IntegerField(default=None, null=True, blank=True) psycho_social_biological = models.IntegerField(default=None,",
"models.TextField(default=None) info_link = models.TextField(default=None, null=True) rank = models.IntegerField(default=None, null=True, blank=True) country = models.ForeignKey(Country,",
"models.IntegerField(default=None, null=True, blank=True) # unique to medicine mcat = models.OneToOneField(MCAT, on_delete=models.CASCADE) def __str__(self):",
"= models.TextField(default=None, null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) gpa = models.FloatField(default=None, null=True,",
"= models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) min_toefl_score = models.IntegerField(default=None, null=True, blank=True) mean_toefl_score",
"= models.IntegerField(default=None, null=True, blank=True) quant = models.IntegerField(default=None, null=True, blank=True) awa = models.FloatField(default=None, null=True,",
"= models.ForeignKey(Country, on_delete=models.CASCADE) total_students = models.IntegerField(default=None, null=True, blank=True) total_int_students = models.IntegerField(default=None, null=True, blank=True)",
"= models.FloatField(default=None, null=True, blank=True) # us_deadline = models.DateTimeField(default=None, null=True, blank=True) # int_deadline =",
"= models.OneToOneField(University, on_delete=models.CASCADE) # enrollment = models.IntegerField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None,",
"models.IntegerField(default=None, null=True, blank=True) lsat_score = models.IntegerField(default=None, null=True, blank=True) median_public_salary = models.IntegerField(default=None, null=True, blank=True)",
"blank=True) website = models.TextField(default=None, null=True, blank=True, max_length=500) schools = models.TextField(default=None, null=True, blank=True) uni_type",
"null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid",
"blank=True) def __str__(self): return self.university.name class BusinessGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',)",
"for room and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to business",
"living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to law # look for median",
"unique to law # look for median lsat employed = models.FloatField(default=None, null=True, blank=True)",
"'Engineering', 'Law', 'Medicine', 'Business', ] grad_streams = ( ('Engineering', 'Engineering'), ('Law', 'Law'), ('Medicine',",
"blank=True) # international = models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True)",
"grad_streams = ( ('Engineering', 'Engineering'), ('Law', 'Law'), ('Medicine', 'Medicine'), ('Business', 'Business'), ) class",
"blank=True) male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True) acceptance_rate_masters =",
"models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None,",
"= models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) # research_assistantships = models.IntegerField(default=None,",
"= models.TextField(default=None, null=True, blank=True, max_length=500) engg_link = models.TextField(default=None, null=True, blank=True, max_length=500) slug =",
"return str(self.verbal) class MCAT(models.Model): old_total = models.IntegerField(default=None, null=True, blank=True) new_total = models.IntegerField(default=None, null=True,",
"= models.FloatField(default=None, null=True, blank=True) gpa = models.FloatField(default=None, null=True, blank=True) # # look for",
"models.IntegerField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True,",
"= models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) male = models.FloatField(default=None, null=True,",
"and board living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to medicine mcat =",
"models.IntegerField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True,",
"str(self.new_total) class University(models.Model): name = models.TextField(default=None) info_link = models.TextField(default=None, null=True) rank = models.IntegerField(default=None,",
"str(self.verbal) class MCAT(models.Model): old_total = models.IntegerField(default=None, null=True, blank=True) new_total = models.IntegerField(default=None, null=True, blank=True)",
"blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True, blank=True)",
"= ('university__rank',) class MedicineGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True)",
"('university__rank',) class MedicineGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international",
"on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) us_application_fee =",
"blank=True) # mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) # min_ielts_score = models.FloatField(default=None, null=True, blank=True)",
"null=True, blank=True) # research_assistantships = models.IntegerField(default=None, null=True, blank=True) # # look for room",
"= models.DateTimeField(default=None, null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) int_rolling",
"# international = models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) #",
"blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid =",
"blank=True, max_length=500) law_link = models.TextField(default=None, null=True, blank=True, max_length=500) engg_link = models.TextField(default=None, null=True, blank=True,",
"blank=True) fellowships = models.IntegerField(default=None, null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) research_assistantships =",
"null=True, blank=True) uni_type = models.TextField(default=None, null=True, blank=True) grad_school_link = models.TextField(default=None, null=True, blank=True, max_length=500)",
"= models.IntegerField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None,",
"acceptance_rate = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None,",
"null=True, blank=True) avg_work_ex_months = models.IntegerField(default=None, null=True, blank=True) gmat = models.IntegerField(default=None, null=True, blank=True) gre",
"null=True, blank=True) # # look for room and board living_expenses = models.IntegerField(default=None, null=True,",
"search_fields = ('university__name',) ordering = ('university__rank',) class MedicineGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment",
"null=True, blank=True) gre = models.OneToOneField(GRE, on_delete=models.CASCADE) # avg_salary = models.IntegerField(default=None, null=True, blank=True) def",
"= models.IntegerField(default=None, null=True, blank=True) # look for room and board living_expenses = models.IntegerField(default=None,",
"models.TextField(default=None, null=True, blank=True, max_length=500) def __str__(self): return self.name class UniversityAdmin(admin.ModelAdmin): search_fields = ('name',)",
"= models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name = models.TextField(default=None, null=True, blank=True) # fin_aid_director_phone =",
"us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # male",
"female = models.FloatField(default=None, null=True, blank=True) acceptance_rate = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None,",
"us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # acceptance_rate_masters",
"= models.FloatField(default=None, null=True, blank=True) # us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee =",
"class LawGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international =",
"models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None,",
"class BusinessGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international =",
"null=True, blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) # look for room and board",
"# unique to medicine mcat = models.OneToOneField(MCAT, on_delete=models.CASCADE) def __str__(self): return self.university.name class",
"models.IntegerField(default=None, null=True, blank=True) min_ielts_score = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True)",
"on_delete=models.CASCADE) total_students = models.IntegerField(default=None, null=True, blank=True) total_int_students = models.IntegerField(default=None, null=True, blank=True) address =",
"# us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) #",
"= models.IntegerField(default=None, null=True, blank=True) # # look for room and board living_expenses =",
"models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True,",
"= models.FloatField(default=None, null=True, blank=True) # acceptance_rate_phd = models.FloatField(default=None, null=True, blank=True) # us_application_fee =",
"int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True)",
"models.FloatField(default=None, null=True, blank=True) male = models.FloatField(default=None, null=True, blank=True) female = models.FloatField(default=None, null=True, blank=True)",
"null=True, blank=True) # int_deadline = models.DateTimeField(default=None, null=True, blank=True) # rolling = models.BooleanField(default=False) #",
"biologic_biochemical = models.IntegerField(default=None, null=True, blank=True) psycho_social_biological = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return",
"null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # tuition = models.FloatField(default=None, null=True,",
"= models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # male =",
"to law # look for median lsat employed = models.FloatField(default=None, null=True, blank=True) bar_passage_rate",
"blank=True) psycho_social_biological = models.IntegerField(default=None, null=True, blank=True) def __str__(self): return str(self.new_total) class University(models.Model): name",
"null=True, blank=True) teaching_assistantships = models.IntegerField(default=None, null=True, blank=True) # research_assistantships = models.IntegerField(default=None, null=True, blank=True)",
"MedicineGradAdmin(admin.ModelAdmin): search_fields = ('university__name',) ordering = ('university__rank',) class LawGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE)",
"models.FloatField(default=None, null=True, blank=True) acceptance_rate = models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True)",
"# fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) students_receiving_aid =",
"blank=True) min_ielts_score = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone =",
"living_expenses = models.IntegerField(default=None, null=True, blank=True) # unique to medicine mcat = models.OneToOneField(MCAT, on_delete=models.CASCADE)",
"= models.BooleanField(default=False) int_rolling = models.BooleanField(default=False) employed = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None,",
"= models.FloatField(default=None, null=True, blank=True) tuition = models.FloatField(default=None, null=True, blank=True) us_deadline = models.DateTimeField(default=None, null=True,",
"law_link = models.TextField(default=None, null=True, blank=True, max_length=500) engg_link = models.TextField(default=None, null=True, blank=True, max_length=500) slug",
"verbal = models.IntegerField(default=None, null=True, blank=True) quant = models.IntegerField(default=None, null=True, blank=True) awa = models.FloatField(default=None,",
"= models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True) fellowships = models.IntegerField(default=None, null=True,",
"= models.IntegerField(default=None, null=True, blank=True) # int_application_fee = models.IntegerField(default=None, null=True, blank=True) # international =",
"blank=True) # rolling = models.BooleanField(default=False) # gpa = models.FloatField(default=None, null=True, blank=True) # min_toefl_score",
"models.IntegerField(default=None, null=True, blank=True) critical_analysis = models.IntegerField(default=None, null=True, blank=True) biologic_biochemical = models.IntegerField(default=None, null=True, blank=True)",
"models.FloatField(default=None, null=True, blank=True) # female = models.FloatField(default=None, null=True, blank=True) # acceptance_rate_masters = models.FloatField(default=None,",
"blank=True) students_receiving_aid = models.FloatField(default=None, null=True, blank=True) gpa = models.FloatField(default=None, null=True, blank=True) # #",
"blank=True) # min_toefl_score = models.IntegerField(default=None, null=True, blank=True) # mean_toefl_score = models.IntegerField(default=None, null=True, blank=True)",
"models.FloatField(default=None, null=True, blank=True) fin_aid_director_name = models.TextField(default=None, null=True, blank=True) fin_aid_director_phone = models.TextField(default=None, null=True, blank=True)",
"'Law', 'Medicine', 'Business', ] grad_streams = ( ('Engineering', 'Engineering'), ('Law', 'Law'), ('Medicine', 'Medicine'),",
"= models.OneToOneField(University, on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True)",
"null=True, blank=True) gpa = models.FloatField(default=None, null=True, blank=True) # # look for room and",
"mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) # min_ielts_score = models.FloatField(default=None, null=True, blank=True) # fin_aid_director_name",
"chemical_physical = models.IntegerField(default=None, null=True, blank=True) critical_analysis = models.IntegerField(default=None, null=True, blank=True) biologic_biochemical = models.IntegerField(default=None,",
"class UniversityAdmin(admin.ModelAdmin): search_fields = ('name',) ordering = ('rank',) class BusinessGrad(models.Model): university = models.OneToOneField(University,",
"blank=True, max_length=500) logo = models.TextField(default=None, null=True, blank=True, max_length=500) def __str__(self): return self.name class",
"on_delete=models.CASCADE) enrollment = models.IntegerField(default=None, null=True, blank=True) international = models.FloatField(default=None, null=True, blank=True) male =",
"blank=True) mean_toefl_score = models.IntegerField(default=None, null=True, blank=True) min_ielts_score = models.FloatField(default=None, null=True, blank=True) fin_aid_director_name =",
"international = models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) # female",
"= models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) gpa = models.FloatField(default=None, null=True, blank=True) #",
"search_fields = ('university__name',) ordering = ('university__rank',) class EngineeringGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) #",
"= ('university__name',) ordering = ('university__rank',) class MedicineGrad(models.Model): university = models.OneToOneField(University, on_delete=models.CASCADE) enrollment =",
"models.DateTimeField(default=None, null=True, blank=True) int_deadline = models.DateTimeField(default=None, null=True, blank=True) rolling = models.BooleanField(default=False) gpa =",
"null=True, blank=True) # male = models.FloatField(default=None, null=True, blank=True) # female = models.FloatField(default=None, null=True,",
"models.TextField(default=None, null=True, blank=True) grad_school_link = models.TextField(default=None, null=True, blank=True, max_length=500) undergrad_link = models.TextField(default=None, null=True,",
"def __str__(self): return str(self.new_total) class University(models.Model): name = models.TextField(default=None) info_link = models.TextField(default=None, null=True)",
"= models.IntegerField(default=None, null=True, blank=True) # # unique to engineering gre = models.OneToOneField(GRE, on_delete=models.CASCADE,",
"students_receiving_aid = models.FloatField(default=None, null=True, blank=True) gpa = models.FloatField(default=None, null=True, blank=True) # # look",
"international = models.FloatField(default=None, null=True, blank=True) us_application_fee = models.IntegerField(default=None, null=True, blank=True) # int_application_fee =",
"# # unique to engineering gre = models.OneToOneField(GRE, on_delete=models.CASCADE, null=True, blank=True) # def",
"blank=True) lsat_score = models.IntegerField(default=None, null=True, blank=True) median_public_salary = models.IntegerField(default=None, null=True, blank=True) median_private_salary =",
"null=True, blank=True) # international = models.FloatField(default=None, null=True, blank=True) # male = models.FloatField(default=None, null=True,",
"null=True, blank=True) website = models.TextField(default=None, null=True, blank=True, max_length=500) schools = models.TextField(default=None, null=True, blank=True)"
] |
[
"def detect_disk(): count = 0 disks = [] while disks == []: disks",
"0 disks = [] while disks == []: disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if",
"10: return False, \"a\", \"b\", \"c\" count += 1 else: for disk in",
"count += 1 else: for disk in disks: disk_size = int(disk.size) gig =",
"+= 1 else: for disk in disks: disk_size = int(disk.size) gig = 1024",
"print(\" Flashing...\", end=\"\") booster.seek(addr2) for piece in read_in_chunks(f): booster.write(piece) print (\"Completed\") return True",
"= wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if disks == []: time.sleep(2) print (\"Please connect \") if",
"if disks == []: time.sleep(2) print (\"Please connect \") if count == 10:",
"__author__ = \"Oz\" __copyright__ = \"Disk Reader WMI\" def read_in_chunks(fileobj, chunksize=65536): \"\"\" Lazy",
"= int(addr2, 16) print(\" Flashing...\", end=\"\") booster.seek(addr2) for piece in read_in_chunks(f): booster.write(piece) print",
"[] while disks == []: disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if disks == []:",
"== 10: return False, \"a\", \"b\", \"c\" count += 1 else: for disk",
"= [] while disks == []: disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if disks ==",
"= open(image, \"rb\") booster = open(d, \"r+b\") addr2 = addr.strip(\"L\") addr2 = int(addr2,",
"disk_size, sector_size def reading(): pass def writing(d, image, addr): f = open(image, \"rb\")",
"print (\"Please connect \") if count == 10: return False, \"a\", \"b\", \"c\"",
"WMI\" def read_in_chunks(fileobj, chunksize=65536): \"\"\" Lazy function to read a file piece by",
"piece. Default chunk size: 64kB. \"\"\" while True: data = fileobj.read(chunksize) if not",
"return False, \"a\", \"b\", \"c\" count += 1 else: for disk in disks:",
"yield data def detect_disk(): count = 0 disks = [] while disks ==",
"print_function import sys import time import wmi __author__ = \"Oz\" __copyright__ = \"Disk",
"image, addr): f = open(image, \"rb\") booster = open(d, \"r+b\") addr2 = addr.strip(\"L\")",
"to read a file piece by piece. Default chunk size: 64kB. \"\"\" while",
"from __future__ import print_function import sys import time import wmi __author__ = \"Oz\"",
"time.sleep(2) print (\"Please connect \") if count == 10: return False, \"a\", \"b\",",
"= 1024 * 1024 uid = disk.serialnumber sector_size = disk.BytesPerSector return True, disk.name,",
"disk.serialnumber sector_size = disk.BytesPerSector return True, disk.name, disk_size, sector_size def reading(): pass def",
"disk_size = int(disk.size) gig = 1024 * 1024 uid = disk.serialnumber sector_size =",
"1 else: for disk in disks: disk_size = int(disk.size) gig = 1024 *",
"addr2 = int(addr2, 16) print(\" Flashing...\", end=\"\") booster.seek(addr2) for piece in read_in_chunks(f): booster.write(piece)",
"* 1024 uid = disk.serialnumber sector_size = disk.BytesPerSector return True, disk.name, disk_size, sector_size",
"reading(): pass def writing(d, image, addr): f = open(image, \"rb\") booster = open(d,",
"read a file piece by piece. Default chunk size: 64kB. \"\"\" while True:",
"import wmi __author__ = \"Oz\" __copyright__ = \"Disk Reader WMI\" def read_in_chunks(fileobj, chunksize=65536):",
"== []: disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if disks == []: time.sleep(2) print (\"Please",
"count = 0 disks = [] while disks == []: disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable",
"1024 uid = disk.serialnumber sector_size = disk.BytesPerSector return True, disk.name, disk_size, sector_size def",
"a file piece by piece. Default chunk size: 64kB. \"\"\" while True: data",
"function to read a file piece by piece. Default chunk size: 64kB. \"\"\"",
"__future__ import print_function import sys import time import wmi __author__ = \"Oz\" __copyright__",
"int(addr2, 16) print(\" Flashing...\", end=\"\") booster.seek(addr2) for piece in read_in_chunks(f): booster.write(piece) print (\"Completed\")",
"\"a\", \"b\", \"c\" count += 1 else: for disk in disks: disk_size =",
"size: 64kB. \"\"\" while True: data = fileobj.read(chunksize) if not data: break yield",
"sector_size def reading(): pass def writing(d, image, addr): f = open(image, \"rb\") booster",
"== []: time.sleep(2) print (\"Please connect \") if count == 10: return False,",
"= disk.BytesPerSector return True, disk.name, disk_size, sector_size def reading(): pass def writing(d, image,",
"1024 * 1024 uid = disk.serialnumber sector_size = disk.BytesPerSector return True, disk.name, disk_size,",
"return True, disk.name, disk_size, sector_size def reading(): pass def writing(d, image, addr): f",
"piece by piece. Default chunk size: 64kB. \"\"\" while True: data = fileobj.read(chunksize)",
"open(d, \"r+b\") addr2 = addr.strip(\"L\") addr2 = int(addr2, 16) print(\" Flashing...\", end=\"\") booster.seek(addr2)",
"\"b\", \"c\" count += 1 else: for disk in disks: disk_size = int(disk.size)",
"not data: break yield data def detect_disk(): count = 0 disks = []",
"file piece by piece. Default chunk size: 64kB. \"\"\" while True: data =",
"\"rb\") booster = open(d, \"r+b\") addr2 = addr.strip(\"L\") addr2 = int(addr2, 16) print(\"",
"= addr.strip(\"L\") addr2 = int(addr2, 16) print(\" Flashing...\", end=\"\") booster.seek(addr2) for piece in",
"in disks: disk_size = int(disk.size) gig = 1024 * 1024 uid = disk.serialnumber",
"data = fileobj.read(chunksize) if not data: break yield data def detect_disk(): count =",
"for disk in disks: disk_size = int(disk.size) gig = 1024 * 1024 uid",
"True, disk.name, disk_size, sector_size def reading(): pass def writing(d, image, addr): f =",
"sys import time import wmi __author__ = \"Oz\" __copyright__ = \"Disk Reader WMI\"",
"if not data: break yield data def detect_disk(): count = 0 disks =",
"(\"Please connect \") if count == 10: return False, \"a\", \"b\", \"c\" count",
"\"\"\" Lazy function to read a file piece by piece. Default chunk size:",
"sector_size = disk.BytesPerSector return True, disk.name, disk_size, sector_size def reading(): pass def writing(d,",
"data: break yield data def detect_disk(): count = 0 disks = [] while",
"gig = 1024 * 1024 uid = disk.serialnumber sector_size = disk.BytesPerSector return True,",
"while True: data = fileobj.read(chunksize) if not data: break yield data def detect_disk():",
"disks == []: disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if disks == []: time.sleep(2) print",
"\"Disk Reader WMI\" def read_in_chunks(fileobj, chunksize=65536): \"\"\" Lazy function to read a file",
"= \"Oz\" __copyright__ = \"Disk Reader WMI\" def read_in_chunks(fileobj, chunksize=65536): \"\"\" Lazy function",
"addr): f = open(image, \"rb\") booster = open(d, \"r+b\") addr2 = addr.strip(\"L\") addr2",
"<gh_stars>1-10 from __future__ import print_function import sys import time import wmi __author__ =",
"[]: disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if disks == []: time.sleep(2) print (\"Please connect",
"Media\") if disks == []: time.sleep(2) print (\"Please connect \") if count ==",
"while disks == []: disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if disks == []: time.sleep(2)",
"disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if disks == []: time.sleep(2) print (\"Please connect \")",
"wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if disks == []: time.sleep(2) print (\"Please connect \") if count",
"[]: time.sleep(2) print (\"Please connect \") if count == 10: return False, \"a\",",
"True: data = fileobj.read(chunksize) if not data: break yield data def detect_disk(): count",
"fileobj.read(chunksize) if not data: break yield data def detect_disk(): count = 0 disks",
"= \"Disk Reader WMI\" def read_in_chunks(fileobj, chunksize=65536): \"\"\" Lazy function to read a",
"uid = disk.serialnumber sector_size = disk.BytesPerSector return True, disk.name, disk_size, sector_size def reading():",
"count == 10: return False, \"a\", \"b\", \"c\" count += 1 else: for",
"= fileobj.read(chunksize) if not data: break yield data def detect_disk(): count = 0",
"pass def writing(d, image, addr): f = open(image, \"rb\") booster = open(d, \"r+b\")",
"open(image, \"rb\") booster = open(d, \"r+b\") addr2 = addr.strip(\"L\") addr2 = int(addr2, 16)",
"= int(disk.size) gig = 1024 * 1024 uid = disk.serialnumber sector_size = disk.BytesPerSector",
"wmi __author__ = \"Oz\" __copyright__ = \"Disk Reader WMI\" def read_in_chunks(fileobj, chunksize=65536): \"\"\"",
"16) print(\" Flashing...\", end=\"\") booster.seek(addr2) for piece in read_in_chunks(f): booster.write(piece) print (\"Completed\") return",
"\"c\" count += 1 else: for disk in disks: disk_size = int(disk.size) gig",
"Default chunk size: 64kB. \"\"\" while True: data = fileobj.read(chunksize) if not data:",
"int(disk.size) gig = 1024 * 1024 uid = disk.serialnumber sector_size = disk.BytesPerSector return",
"\"Oz\" __copyright__ = \"Disk Reader WMI\" def read_in_chunks(fileobj, chunksize=65536): \"\"\" Lazy function to",
"\") if count == 10: return False, \"a\", \"b\", \"c\" count += 1",
"disk.BytesPerSector return True, disk.name, disk_size, sector_size def reading(): pass def writing(d, image, addr):",
"read_in_chunks(fileobj, chunksize=65536): \"\"\" Lazy function to read a file piece by piece. Default",
"False, \"a\", \"b\", \"c\" count += 1 else: for disk in disks: disk_size",
"booster = open(d, \"r+b\") addr2 = addr.strip(\"L\") addr2 = int(addr2, 16) print(\" Flashing...\",",
"import time import wmi __author__ = \"Oz\" __copyright__ = \"Disk Reader WMI\" def",
"disks = [] while disks == []: disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\") if disks",
"addr2 = addr.strip(\"L\") addr2 = int(addr2, 16) print(\" Flashing...\", end=\"\") booster.seek(addr2) for piece",
"\"r+b\") addr2 = addr.strip(\"L\") addr2 = int(addr2, 16) print(\" Flashing...\", end=\"\") booster.seek(addr2) for",
"64kB. \"\"\" while True: data = fileobj.read(chunksize) if not data: break yield data",
"__copyright__ = \"Disk Reader WMI\" def read_in_chunks(fileobj, chunksize=65536): \"\"\" Lazy function to read",
"addr.strip(\"L\") addr2 = int(addr2, 16) print(\" Flashing...\", end=\"\") booster.seek(addr2) for piece in read_in_chunks(f):",
"break yield data def detect_disk(): count = 0 disks = [] while disks",
"connect \") if count == 10: return False, \"a\", \"b\", \"c\" count +=",
"chunksize=65536): \"\"\" Lazy function to read a file piece by piece. Default chunk",
"chunk size: 64kB. \"\"\" while True: data = fileobj.read(chunksize) if not data: break",
"time import wmi __author__ = \"Oz\" __copyright__ = \"Disk Reader WMI\" def read_in_chunks(fileobj,",
"\"\"\" while True: data = fileobj.read(chunksize) if not data: break yield data def",
"= open(d, \"r+b\") addr2 = addr.strip(\"L\") addr2 = int(addr2, 16) print(\" Flashing...\", end=\"\")",
"= disk.serialnumber sector_size = disk.BytesPerSector return True, disk.name, disk_size, sector_size def reading(): pass",
"def reading(): pass def writing(d, image, addr): f = open(image, \"rb\") booster =",
"data def detect_disk(): count = 0 disks = [] while disks == []:",
"disk in disks: disk_size = int(disk.size) gig = 1024 * 1024 uid =",
"import print_function import sys import time import wmi __author__ = \"Oz\" __copyright__ =",
"import sys import time import wmi __author__ = \"Oz\" __copyright__ = \"Disk Reader",
"def writing(d, image, addr): f = open(image, \"rb\") booster = open(d, \"r+b\") addr2",
"def read_in_chunks(fileobj, chunksize=65536): \"\"\" Lazy function to read a file piece by piece.",
"else: for disk in disks: disk_size = int(disk.size) gig = 1024 * 1024",
"disk.name, disk_size, sector_size def reading(): pass def writing(d, image, addr): f = open(image,",
"disks: disk_size = int(disk.size) gig = 1024 * 1024 uid = disk.serialnumber sector_size",
"f = open(image, \"rb\") booster = open(d, \"r+b\") addr2 = addr.strip(\"L\") addr2 =",
"= 0 disks = [] while disks == []: disks = wmi.WMI().Win32_DiskDrive(MediaType=\"Removable Media\")",
"if count == 10: return False, \"a\", \"b\", \"c\" count += 1 else:",
"detect_disk(): count = 0 disks = [] while disks == []: disks =",
"Reader WMI\" def read_in_chunks(fileobj, chunksize=65536): \"\"\" Lazy function to read a file piece",
"disks == []: time.sleep(2) print (\"Please connect \") if count == 10: return",
"Lazy function to read a file piece by piece. Default chunk size: 64kB.",
"by piece. Default chunk size: 64kB. \"\"\" while True: data = fileobj.read(chunksize) if",
"writing(d, image, addr): f = open(image, \"rb\") booster = open(d, \"r+b\") addr2 ="
] |
[
"print(\"RES: \", res.get_shape()) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op = tf.train.AdamOptimizer().minimize(cost) with tf.Session() as",
"np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W = tf.Variable(tf.random_normal([10,1], stddev=0.01)) B = tf.Variable(tf.zeros([25,1])) x =",
"2*10]) outputs, _states = rnn.rnn(lstm,X_split, init_state) res = tf.matmul(outputs[-1], W) + B print(\"XT:",
"25, XR) init_state = tf.placeholder(\"float\", [None, 2*10]) outputs, _states = rnn.rnn(lstm,X_split, init_state) res",
"rnn.rnn(lstm,X_split, init_state) res = tf.matmul(outputs[-1], W) + B print(\"XT: \", XT) print(\"XR: \",XR)",
"from tensorflow.models.rnn import rnn, rnn_cell if __name__ == '__main__': X = np.random.randint(0,2,(50000,25,10)) Y",
"XR) init_state = tf.placeholder(\"float\", [None, 2*10]) outputs, _states = rnn.rnn(lstm,X_split, init_state) res =",
"= tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op = tf.train.AdamOptimizer().minimize(cost) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for i",
"x = tf.placeholder(tf.float32, [None,25,10]) y = tf.placeholder(tf.float32, [None,25,1]) lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT =",
"+ B print(\"XT: \", XT) print(\"XR: \",XR) print(\"X_SPLIT: \",X_split) print(\"RES: \", res.get_shape()) cost",
"= tf.placeholder(tf.float32, [None,25,10]) y = tf.placeholder(tf.float32, [None,25,1]) lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT = tf.transpose(x,",
"rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT = tf.transpose(x, [1, 0, 2]) XR = tf.reshape(XT, [-1, 10]) X_split",
"stddev=0.01)) B = tf.Variable(tf.zeros([25,1])) x = tf.placeholder(tf.float32, [None,25,10]) y = tf.placeholder(tf.float32, [None,25,1]) lstm",
"as np from tensorflow.models.rnn import rnn, rnn_cell if __name__ == '__main__': X =",
"with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for i in range(100): for start in range(0,50000,500):",
"2]) XR = tf.reshape(XT, [-1, 10]) X_split = tf.split(0, 25, XR) init_state =",
"= tf.train.AdamOptimizer().minimize(cost) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for i in range(100): for start",
"print(\"XT: \", XT) print(\"XR: \",XR) print(\"X_SPLIT: \",X_split) print(\"RES: \", res.get_shape()) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res,",
"\", res.get_shape()) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op = tf.train.AdamOptimizer().minimize(cost) with tf.Session() as sess:",
"tf import numpy as np from tensorflow.models.rnn import rnn, rnn_cell if __name__ ==",
"res = tf.matmul(outputs[-1], W) + B print(\"XT: \", XT) print(\"XR: \",XR) print(\"X_SPLIT: \",X_split)",
"B print(\"XT: \", XT) print(\"XR: \",XR) print(\"X_SPLIT: \",X_split) print(\"RES: \", res.get_shape()) cost =",
"B = tf.Variable(tf.zeros([25,1])) x = tf.placeholder(tf.float32, [None,25,10]) y = tf.placeholder(tf.float32, [None,25,1]) lstm =",
"0, 2]) XR = tf.reshape(XT, [-1, 10]) X_split = tf.split(0, 25, XR) init_state",
"= tf.reshape(XT, [-1, 10]) X_split = tf.split(0, 25, XR) init_state = tf.placeholder(\"float\", [None,",
"__name__ == '__main__': X = np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10)) Y_test",
"y = tf.placeholder(tf.float32, [None,25,1]) lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT = tf.transpose(x, [1, 0, 2])",
"= tf.split(0, 25, XR) init_state = tf.placeholder(\"float\", [None, 2*10]) outputs, _states = rnn.rnn(lstm,X_split,",
"[None,25,10]) y = tf.placeholder(tf.float32, [None,25,1]) lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT = tf.transpose(x, [1, 0,",
"= np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W = tf.Variable(tf.random_normal([10,1], stddev=0.01)) B = tf.Variable(tf.zeros([25,1])) x",
"train_op = tf.train.AdamOptimizer().minimize(cost) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for i in range(100): for",
"tf.split(0, 25, XR) init_state = tf.placeholder(\"float\", [None, 2*10]) outputs, _states = rnn.rnn(lstm,X_split, init_state)",
"import tensorflow as tf import numpy as np from tensorflow.models.rnn import rnn, rnn_cell",
"[-1, 10]) X_split = tf.split(0, 25, XR) init_state = tf.placeholder(\"float\", [None, 2*10]) outputs,",
"rnn, rnn_cell if __name__ == '__main__': X = np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test",
"numpy as np from tensorflow.models.rnn import rnn, rnn_cell if __name__ == '__main__': X",
"XR = tf.reshape(XT, [-1, 10]) X_split = tf.split(0, 25, XR) init_state = tf.placeholder(\"float\",",
"X = np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W",
"init_state) res = tf.matmul(outputs[-1], W) + B print(\"XT: \", XT) print(\"XR: \",XR) print(\"X_SPLIT:",
"\", XT) print(\"XR: \",XR) print(\"X_SPLIT: \",X_split) print(\"RES: \", res.get_shape()) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y))",
"in range(0,50000,500): sess.run(train_op, feed_dict = {x: X[start:start+500], y: Y[start:start+500], init_state: np.zeros([50000, 20])}) print(sess.run(outputs))",
"np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W = tf.Variable(tf.random_normal([10,1], stddev=0.01)) B = tf.Variable(tf.zeros([25,1])) x = tf.placeholder(tf.float32, [None,25,10]) y",
"sess: sess.run(tf.initialize_all_variables()) for i in range(100): for start in range(0,50000,500): sess.run(train_op, feed_dict =",
"cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op = tf.train.AdamOptimizer().minimize(cost) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for",
"= tf.Variable(tf.zeros([25,1])) x = tf.placeholder(tf.float32, [None,25,10]) y = tf.placeholder(tf.float32, [None,25,1]) lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0)",
"\",XR) print(\"X_SPLIT: \",X_split) print(\"RES: \", res.get_shape()) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op = tf.train.AdamOptimizer().minimize(cost)",
"tensorflow.models.rnn import rnn, rnn_cell if __name__ == '__main__': X = np.random.randint(0,2,(50000,25,10)) Y =",
"i in range(100): for start in range(0,50000,500): sess.run(train_op, feed_dict = {x: X[start:start+500], y:",
"= rnn.rnn(lstm,X_split, init_state) res = tf.matmul(outputs[-1], W) + B print(\"XT: \", XT) print(\"XR:",
"'__main__': X = np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1))",
"print(\"XR: \",XR) print(\"X_SPLIT: \",X_split) print(\"RES: \", res.get_shape()) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op =",
"XT) print(\"XR: \",XR) print(\"X_SPLIT: \",X_split) print(\"RES: \", res.get_shape()) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op",
"sess.run(tf.initialize_all_variables()) for i in range(100): for start in range(0,50000,500): sess.run(train_op, feed_dict = {x:",
"init_state = tf.placeholder(\"float\", [None, 2*10]) outputs, _states = rnn.rnn(lstm,X_split, init_state) res = tf.matmul(outputs[-1],",
"rnn_cell if __name__ == '__main__': X = np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test =",
"tf.Session() as sess: sess.run(tf.initialize_all_variables()) for i in range(100): for start in range(0,50000,500): sess.run(train_op,",
"tf.placeholder(\"float\", [None, 2*10]) outputs, _states = rnn.rnn(lstm,X_split, init_state) res = tf.matmul(outputs[-1], W) +",
"tf.matmul(outputs[-1], W) + B print(\"XT: \", XT) print(\"XR: \",XR) print(\"X_SPLIT: \",X_split) print(\"RES: \",",
"_states = rnn.rnn(lstm,X_split, init_state) res = tf.matmul(outputs[-1], W) + B print(\"XT: \", XT)",
"W) + B print(\"XT: \", XT) print(\"XR: \",XR) print(\"X_SPLIT: \",X_split) print(\"RES: \", res.get_shape())",
"[None,25,1]) lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT = tf.transpose(x, [1, 0, 2]) XR = tf.reshape(XT,",
"X_test = np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W = tf.Variable(tf.random_normal([10,1], stddev=0.01)) B = tf.Variable(tf.zeros([25,1]))",
"import rnn, rnn_cell if __name__ == '__main__': X = np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1))",
"= np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W = tf.Variable(tf.random_normal([10,1], stddev=0.01)) B",
"as tf import numpy as np from tensorflow.models.rnn import rnn, rnn_cell if __name__",
"= tf.placeholder(tf.float32, [None,25,1]) lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT = tf.transpose(x, [1, 0, 2]) XR",
"= tf.Variable(tf.random_normal([10,1], stddev=0.01)) B = tf.Variable(tf.zeros([25,1])) x = tf.placeholder(tf.float32, [None,25,10]) y = tf.placeholder(tf.float32,",
"in range(100): for start in range(0,50000,500): sess.run(train_op, feed_dict = {x: X[start:start+500], y: Y[start:start+500],",
"Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W = tf.Variable(tf.random_normal([10,1], stddev=0.01))",
"[None, 2*10]) outputs, _states = rnn.rnn(lstm,X_split, init_state) res = tf.matmul(outputs[-1], W) + B",
"tf.placeholder(tf.float32, [None,25,1]) lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT = tf.transpose(x, [1, 0, 2]) XR =",
"y)) train_op = tf.train.AdamOptimizer().minimize(cost) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for i in range(100):",
"= tf.matmul(outputs[-1], W) + B print(\"XT: \", XT) print(\"XR: \",XR) print(\"X_SPLIT: \",X_split) print(\"RES:",
"tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op = tf.train.AdamOptimizer().minimize(cost) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for i in",
"Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W = tf.Variable(tf.random_normal([10,1], stddev=0.01)) B = tf.Variable(tf.zeros([25,1])) x = tf.placeholder(tf.float32,",
"= rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT = tf.transpose(x, [1, 0, 2]) XR = tf.reshape(XT, [-1, 10])",
"<reponame>hanskrupakar/Tensorflow-Beginner import tensorflow as tf import numpy as np from tensorflow.models.rnn import rnn,",
"outputs, _states = rnn.rnn(lstm,X_split, init_state) res = tf.matmul(outputs[-1], W) + B print(\"XT: \",",
"W = tf.Variable(tf.random_normal([10,1], stddev=0.01)) B = tf.Variable(tf.zeros([25,1])) x = tf.placeholder(tf.float32, [None,25,10]) y =",
"== '__main__': X = np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10)) Y_test =",
"tf.reshape(XT, [-1, 10]) X_split = tf.split(0, 25, XR) init_state = tf.placeholder(\"float\", [None, 2*10])",
"as sess: sess.run(tf.initialize_all_variables()) for i in range(100): for start in range(0,50000,500): sess.run(train_op, feed_dict",
"import numpy as np from tensorflow.models.rnn import rnn, rnn_cell if __name__ == '__main__':",
"= tf.transpose(x, [1, 0, 2]) XR = tf.reshape(XT, [-1, 10]) X_split = tf.split(0,",
"for start in range(0,50000,500): sess.run(train_op, feed_dict = {x: X[start:start+500], y: Y[start:start+500], init_state: np.zeros([50000,",
"np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W = tf.Variable(tf.random_normal([10,1],",
"tf.Variable(tf.zeros([25,1])) x = tf.placeholder(tf.float32, [None,25,10]) y = tf.placeholder(tf.float32, [None,25,1]) lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT",
"= tf.placeholder(\"float\", [None, 2*10]) outputs, _states = rnn.rnn(lstm,X_split, init_state) res = tf.matmul(outputs[-1], W)",
"tf.transpose(x, [1, 0, 2]) XR = tf.reshape(XT, [-1, 10]) X_split = tf.split(0, 25,",
"lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT = tf.transpose(x, [1, 0, 2]) XR = tf.reshape(XT, [-1,",
"range(100): for start in range(0,50000,500): sess.run(train_op, feed_dict = {x: X[start:start+500], y: Y[start:start+500], init_state:",
"= np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W = tf.Variable(tf.random_normal([10,1], stddev=0.01)) B = tf.Variable(tf.zeros([25,1])) x = tf.placeholder(tf.float32, [None,25,10])",
"tensorflow as tf import numpy as np from tensorflow.models.rnn import rnn, rnn_cell if",
"XT = tf.transpose(x, [1, 0, 2]) XR = tf.reshape(XT, [-1, 10]) X_split =",
"[1, 0, 2]) XR = tf.reshape(XT, [-1, 10]) X_split = tf.split(0, 25, XR)",
"\",X_split) print(\"RES: \", res.get_shape()) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op = tf.train.AdamOptimizer().minimize(cost) with tf.Session()",
"np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W = tf.Variable(tf.random_normal([10,1], stddev=0.01)) B =",
"tf.train.AdamOptimizer().minimize(cost) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for i in range(100): for start in",
"tf.Variable(tf.random_normal([10,1], stddev=0.01)) B = tf.Variable(tf.zeros([25,1])) x = tf.placeholder(tf.float32, [None,25,10]) y = tf.placeholder(tf.float32, [None,25,1])",
"tf.placeholder(tf.float32, [None,25,10]) y = tf.placeholder(tf.float32, [None,25,1]) lstm = rnn_cell.BasicLSTMCell(10,forget_bias=1.0) XT = tf.transpose(x, [1,",
"res.get_shape()) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op = tf.train.AdamOptimizer().minimize(cost) with tf.Session() as sess: sess.run(tf.initialize_all_variables())",
"np from tensorflow.models.rnn import rnn, rnn_cell if __name__ == '__main__': X = np.random.randint(0,2,(50000,25,10))",
"10]) X_split = tf.split(0, 25, XR) init_state = tf.placeholder(\"float\", [None, 2*10]) outputs, _states",
"X_split = tf.split(0, 25, XR) init_state = tf.placeholder(\"float\", [None, 2*10]) outputs, _states =",
"for i in range(100): for start in range(0,50000,500): sess.run(train_op, feed_dict = {x: X[start:start+500],",
"print(\"X_SPLIT: \",X_split) print(\"RES: \", res.get_shape()) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(res, y)) train_op = tf.train.AdamOptimizer().minimize(cost) with",
"if __name__ == '__main__': X = np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10))",
"start in range(0,50000,500): sess.run(train_op, feed_dict = {x: X[start:start+500], y: Y[start:start+500], init_state: np.zeros([50000, 20])})",
"= np.random.randint(0,2,(50000,25,10)) Y = np.reshape(np.sum(X,axis=2),(50000,25,1)) X_test = np.random.randint(0,2,(1000,25,10)) Y_test = np.reshape(np.sum(X_test,axis=2),(1000,25,1)) W ="
] |
[
"= name1.lower() # name2 = \"John\" if name1 is name2: print(f\"{id(name1)} is {id(name2)}\")",
"else: print(\"Temperature is NOT same\") living_room_temperature = 18 # is if living_room_temperature is",
"# It does not compare the value, but it checks if has same",
"# name2 = \"John\" if name1 is name2: print(f\"{id(name1)} is {id(name2)}\") else: print(f\"{id(name1)}",
"is not if living_room_temperature is not kitchen_room_temperature: print(\"Temperature is NOT same\") else: print(\"Temperature",
"of the value must be same # It does not compare the value,",
"name1.lower() # name2 = \"John\" if name1 is name2: print(f\"{id(name1)} is {id(name2)}\") else:",
"It does not compare the value, but it checks if has same id.",
"the value must be same # It does not compare the value, but",
"print(\"Temperature is same\") # The id of the value must be same #",
"name2 = name1.lower() # name2 = \"John\" if name1 is name2: print(f\"{id(name1)} is",
"NOT same\") # is not if living_room_temperature is not kitchen_room_temperature: print(\"Temperature is NOT",
"compare the value, but it checks if has same id. name1 = \"John\"",
"# \"is\" and \"is not\" living_room_temperature = 23 kitchen_room_temperature = 23 # is",
"if living_room_temperature is not kitchen_room_temperature: print(\"Temperature is NOT same\") else: print(\"Temperature is same\")",
"value must be same # It does not compare the value, but it",
"must be same # It does not compare the value, but it checks",
"same\") # is not if living_room_temperature is not kitchen_room_temperature: print(\"Temperature is NOT same\")",
"living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is NOT same\") living_room_temperature =",
"is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is NOT same\") # is not",
"is same\") else: print(\"Temperature is NOT same\") living_room_temperature = 18 # is if",
"23 kitchen_room_temperature = 23 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\")",
"is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is NOT same\")",
"kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is NOT same\") # is not if",
"same\") # The id of the value must be same # It does",
"kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is NOT same\") living_room_temperature = 18 #",
"else: print(\"Temperature is same\") # The id of the value must be same",
"id of the value must be same # It does not compare the",
"same\") else: print(\"Temperature is same\") # The id of the value must be",
"= 23 kitchen_room_temperature = 23 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is",
"is NOT same\") else: print(\"Temperature is same\") # The id of the value",
"operator # \"is\" and \"is not\" living_room_temperature = 23 kitchen_room_temperature = 23 #",
"is not kitchen_room_temperature: print(\"Temperature is NOT same\") else: print(\"Temperature is same\") # The",
"= \"John\" if name1 is name2: print(f\"{id(name1)} is {id(name2)}\") else: print(f\"{id(name1)} is NOT",
"living_room_temperature = 23 kitchen_room_temperature = 23 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature",
"The id of the value must be same # It does not compare",
"not\" living_room_temperature = 23 kitchen_room_temperature = 23 # is if living_room_temperature is kitchen_room_temperature:",
"be same # It does not compare the value, but it checks if",
"same id. name1 = \"John\" name2 = name1.lower() # name2 = \"John\" if",
"checks if has same id. name1 = \"John\" name2 = name1.lower() # name2",
"not if living_room_temperature is not kitchen_room_temperature: print(\"Temperature is NOT same\") else: print(\"Temperature is",
"same\") else: print(\"Temperature is NOT same\") living_room_temperature = 18 # is if living_room_temperature",
"is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is NOT same\") living_room_temperature = 18",
"print(\"Temperature is same\") else: print(\"Temperature is NOT same\") # is not if living_room_temperature",
"print(\"Temperature is same\") else: print(\"Temperature is NOT same\") living_room_temperature = 18 # is",
"\"is\" and \"is not\" living_room_temperature = 23 kitchen_room_temperature = 23 # is if",
"print(\"Temperature is NOT same\") living_room_temperature = 18 # is if living_room_temperature is kitchen_room_temperature:",
"is same\") # The id of the value must be same # It",
"# is not if living_room_temperature is not kitchen_room_temperature: print(\"Temperature is NOT same\") else:",
"living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is NOT same\") # is",
"is same\") else: print(\"Temperature is NOT same\") # is not if living_room_temperature is",
"print(\"Temperature is NOT same\") else: print(\"Temperature is same\") # The id of the",
"\"John\" name2 = name1.lower() # name2 = \"John\" if name1 is name2: print(f\"{id(name1)}",
"living_room_temperature is not kitchen_room_temperature: print(\"Temperature is NOT same\") else: print(\"Temperature is same\") #",
"NOT same\") else: print(\"Temperature is same\") # The id of the value must",
"# The id of the value must be same # It does not",
"\"John\" if name1 is name2: print(f\"{id(name1)} is {id(name2)}\") else: print(f\"{id(name1)} is NOT {id(name2)}\")",
"if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is NOT same\") living_room_temperature",
"same\") else: print(\"Temperature is NOT same\") # is not if living_room_temperature is not",
"18 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is",
"print(\"Temperature is NOT same\") # is not if living_room_temperature is not kitchen_room_temperature: print(\"Temperature",
"does not compare the value, but it checks if has same id. name1",
"not kitchen_room_temperature: print(\"Temperature is NOT same\") else: print(\"Temperature is same\") # The id",
"same # It does not compare the value, but it checks if has",
"same\") living_room_temperature = 18 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\")",
"else: print(\"Temperature is NOT same\") # is not if living_room_temperature is not kitchen_room_temperature:",
"# is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is NOT",
"NOT same\") living_room_temperature = 18 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is",
"id. name1 = \"John\" name2 = name1.lower() # name2 = \"John\" if name1",
"not compare the value, but it checks if has same id. name1 =",
"Identity operator # \"is\" and \"is not\" living_room_temperature = 23 kitchen_room_temperature = 23",
"and \"is not\" living_room_temperature = 23 kitchen_room_temperature = 23 # is if living_room_temperature",
"\"is not\" living_room_temperature = 23 kitchen_room_temperature = 23 # is if living_room_temperature is",
"if has same id. name1 = \"John\" name2 = name1.lower() # name2 =",
"kitchen_room_temperature = 23 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else:",
"is NOT same\") # is not if living_room_temperature is not kitchen_room_temperature: print(\"Temperature is",
"value, but it checks if has same id. name1 = \"John\" name2 =",
"it checks if has same id. name1 = \"John\" name2 = name1.lower() #",
"# Identity operator # \"is\" and \"is not\" living_room_temperature = 23 kitchen_room_temperature =",
"has same id. name1 = \"John\" name2 = name1.lower() # name2 = \"John\"",
"the value, but it checks if has same id. name1 = \"John\" name2",
"kitchen_room_temperature: print(\"Temperature is NOT same\") else: print(\"Temperature is same\") # The id of",
"living_room_temperature = 18 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else:",
"= 18 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature",
"= \"John\" name2 = name1.lower() # name2 = \"John\" if name1 is name2:",
"is NOT same\") living_room_temperature = 18 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature",
"= 23 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature",
"name2 = \"John\" if name1 is name2: print(f\"{id(name1)} is {id(name2)}\") else: print(f\"{id(name1)} is",
"if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is NOT same\") #",
"23 # is if living_room_temperature is kitchen_room_temperature: print(\"Temperature is same\") else: print(\"Temperature is",
"but it checks if has same id. name1 = \"John\" name2 = name1.lower()",
"name1 = \"John\" name2 = name1.lower() # name2 = \"John\" if name1 is"
] |
[
"= Atividade('Diagrama de Atividades', 'Atividade de Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome",
"\"__main__\": unittest.main() \"\"\" if __name__ == \"__main__\" and __package__ is None: from os",
"['Nodo Decisao'] ,['Nodo Final']) nodoFinal = NodoFinal('Nodo Final', ['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal)",
"= NodoDecisao('Nodo Decisao', ['Nodo Inicial'] ,['Nodo Fusao']) nodoFusao = NodoFusao('Nodo Fusao', ['Nodo Decisao']",
"testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self): nodoInicial = Nodo('Nodo Inicial', ['proximo']) nodoDecisao = NodoDecisao('Nodo Decisao', ['Nodo",
"nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não criados') atividade = Atividade('Diagrama de Atividades', 'Atividade",
"['Nodo Inicial'] ,['Nodo Fusao']) nodoFusao = NodoFusao('Nodo Fusao', ['Nodo Decisao'] ,['Nodo Final']) nodoFinal",
"from usecases.Nodos import Nodo, NodoDecisao, NodoFusao, NodoFinal class testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self): nodoInicial =",
"NodoFusao, NodoFinal class testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self): nodoInicial = Nodo('Nodo Inicial', ['proximo']) nodoDecisao =",
"usecases.Atividades import Atividade from usecases.Nodos import Nodo, NodoDecisao, NodoFusao, NodoFinal class testeAtividade(unittest.TestCase): def",
"unittest from usecases.Atividades import Atividade from usecases.Nodos import Nodo, NodoDecisao, NodoFusao, NodoFinal class",
"diagrama não criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da atividade não criado') self.assertEqual(len(nodoInicial['arrayAtividades']),",
"atividade = Atividade('Diagrama de Atividades', 'Atividade de Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades',",
"__name__ == \"__main__\": unittest.main() \"\"\" if __name__ == \"__main__\" and __package__ is None:",
"nodoFinal = NodoFinal('Nodo Final', ['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não",
"Atividades', 'Atividade de Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do diagrama não",
"['proximo']) nodoDecisao = NodoDecisao('Nodo Decisao', ['Nodo Inicial'] ,['Nodo Fusao']) nodoFusao = NodoFusao('Nodo Fusao',",
"não criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram",
"do diagrama não criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da atividade não criado')",
"Decisao'] ,['Nodo Final']) nodoFinal = NodoFinal('Nodo Final', ['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo),",
"'Nodos não criados') atividade = Atividade('Diagrama de Atividades', 'Atividade de Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'],",
"Monitoramento', 'Nome da atividade não criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']),",
"unittest.main() \"\"\" if __name__ == \"__main__\" and __package__ is None: from os import",
"Nodo('Nodo Inicial', ['proximo']) nodoDecisao = NodoDecisao('Nodo Decisao', ['Nodo Inicial'] ,['Nodo Fusao']) nodoFusao =",
"NodoFinal class testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self): nodoInicial = Nodo('Nodo Inicial', ['proximo']) nodoDecisao = NodoDecisao('Nodo",
"4, 'Transicoes não foram criadas') if __name__ == \"__main__\": unittest.main() \"\"\" if __name__",
"criadas') if __name__ == \"__main__\": unittest.main() \"\"\" if __name__ == \"__main__\" and __package__",
"Fusao']) nodoFusao = NodoFusao('Nodo Fusao', ['Nodo Decisao'] ,['Nodo Final']) nodoFinal = NodoFinal('Nodo Final',",
"'Atividade de Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do diagrama não criado')",
"nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não criados') atividade = Atividade('Diagrama de Atividades',",
"def testCriacaoDiagrama(self): nodoInicial = Nodo('Nodo Inicial', ['proximo']) nodoDecisao = NodoDecisao('Nodo Decisao', ['Nodo Inicial']",
"= NodoFinal('Nodo Final', ['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não criados')",
"['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não criados') atividade = Atividade('Diagrama",
"'Atividades não foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas') if __name__ ==",
"Inicial'] ,['Nodo Fusao']) nodoFusao = NodoFusao('Nodo Fusao', ['Nodo Decisao'] ,['Nodo Final']) nodoFinal =",
"import Atividade from usecases.Nodos import Nodo, NodoDecisao, NodoFusao, NodoFinal class testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self):",
"não criados') atividade = Atividade('Diagrama de Atividades', 'Atividade de Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama",
"NodoDecisao, NodoFusao, NodoFinal class testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self): nodoInicial = Nodo('Nodo Inicial', ['proximo']) nodoDecisao",
"Nodo, NodoDecisao, NodoFusao, NodoFinal class testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self): nodoInicial = Nodo('Nodo Inicial', ['proximo'])",
"__name__ == \"__main__\" and __package__ is None: from os import sys, path sys.path.append(path.dirname(path.dsirname(path.abspath(__file__))))",
"from usecases.Atividades import Atividade from usecases.Nodos import Nodo, NodoDecisao, NodoFusao, NodoFinal class testeAtividade(unittest.TestCase):",
"nodoDecisao = NodoDecisao('Nodo Decisao', ['Nodo Inicial'] ,['Nodo Fusao']) nodoFusao = NodoFusao('Nodo Fusao', ['Nodo",
"atividade não criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não",
"não criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da atividade não criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4,",
",['Nodo Fusao']) nodoFusao = NodoFusao('Nodo Fusao', ['Nodo Decisao'] ,['Nodo Final']) nodoFinal = NodoFinal('Nodo",
"'Nome da atividade não criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4,",
"self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não criados') atividade = Atividade('Diagrama de Atividades', 'Atividade de Monitoramento',",
"criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da atividade não criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades",
"nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do diagrama não criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade de",
"Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não criados') atividade = Atividade('Diagrama de",
"NodoDecisao('Nodo Decisao', ['Nodo Inicial'] ,['Nodo Fusao']) nodoFusao = NodoFusao('Nodo Fusao', ['Nodo Decisao'] ,['Nodo",
"'Diagrama de Atividades', 'Nome do diagrama não criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome",
"foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas') if __name__ == \"__main__\": unittest.main()",
"Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do diagrama não criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade",
"\"\"\" if __name__ == \"__main__\" and __package__ is None: from os import sys,",
"'Atividade de Monitoramento', 'Nome da atividade não criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram",
"nodoInicial = Nodo('Nodo Inicial', ['proximo']) nodoDecisao = NodoDecisao('Nodo Decisao', ['Nodo Inicial'] ,['Nodo Fusao'])",
"NodoFinal('Nodo Final', ['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não criados') atividade",
"da atividade não criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes",
"import unittest from usecases.Atividades import Atividade from usecases.Nodos import Nodo, NodoDecisao, NodoFusao, NodoFinal",
"criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas')",
"= NodoFusao('Nodo Fusao', ['Nodo Decisao'] ,['Nodo Final']) nodoFinal = NodoFinal('Nodo Final', ['Nodo Fusao'])",
"de Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do diagrama não criado') self.assertEqual(Atividades['nomeAtividade'],",
"de Atividades', 'Nome do diagrama não criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da",
"nodoFusao = NodoFusao('Nodo Fusao', ['Nodo Decisao'] ,['Nodo Final']) nodoFinal = NodoFinal('Nodo Final', ['Nodo",
"Atividade from usecases.Nodos import Nodo, NodoDecisao, NodoFusao, NodoFinal class testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self): nodoInicial",
"foram criadas') if __name__ == \"__main__\": unittest.main() \"\"\" if __name__ == \"__main__\" and",
"self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas') if __name__ == \"__main__\": unittest.main() \"\"\" if",
"self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas') if",
"usecases.Nodos import Nodo, NodoDecisao, NodoFusao, NodoFinal class testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self): nodoInicial = Nodo('Nodo",
"4, 'Atividades não foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas') if __name__",
"class testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self): nodoInicial = Nodo('Nodo Inicial', ['proximo']) nodoDecisao = NodoDecisao('Nodo Decisao',",
"Final', ['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não criados') atividade =",
"if __name__ == \"__main__\": unittest.main() \"\"\" if __name__ == \"__main__\" and __package__ is",
"nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não criados') atividade = Atividade('Diagrama de Atividades', 'Atividade de",
"\"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do diagrama não criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento',",
"Inicial', ['proximo']) nodoDecisao = NodoDecisao('Nodo Decisao', ['Nodo Inicial'] ,['Nodo Fusao']) nodoFusao = NodoFusao('Nodo",
"de Monitoramento', 'Nome da atividade não criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas')",
"self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da atividade não criado') self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não",
"criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas') if __name__ == \"__main__\": unittest.main() \"\"\"",
"'Transicoes não foram criadas') if __name__ == \"__main__\": unittest.main() \"\"\" if __name__ ==",
"import Nodo, NodoDecisao, NodoFusao, NodoFinal class testeAtividade(unittest.TestCase): def testCriacaoDiagrama(self): nodoInicial = Nodo('Nodo Inicial',",
",['Nodo Final']) nodoFinal = NodoFinal('Nodo Final', ['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4,",
"4, 'Nodos não criados') atividade = Atividade('Diagrama de Atividades', 'Atividade de Monitoramento', nodoInicial.arrayNodo)",
"if __name__ == \"__main__\" and __package__ is None: from os import sys, path",
"criados') atividade = Atividade('Diagrama de Atividades', 'Atividade de Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de",
"= Nodo('Nodo Inicial', ['proximo']) nodoDecisao = NodoDecisao('Nodo Decisao', ['Nodo Inicial'] ,['Nodo Fusao']) nodoFusao",
"Atividade('Diagrama de Atividades', 'Atividade de Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do",
"Decisao', ['Nodo Inicial'] ,['Nodo Fusao']) nodoFusao = NodoFusao('Nodo Fusao', ['Nodo Decisao'] ,['Nodo Final'])",
"== \"__main__\": unittest.main() \"\"\" if __name__ == \"__main__\" and __package__ is None: from",
"não foram criadas') if __name__ == \"__main__\": unittest.main() \"\"\" if __name__ == \"__main__\"",
"NodoFusao('Nodo Fusao', ['Nodo Decisao'] ,['Nodo Final']) nodoFinal = NodoFinal('Nodo Final', ['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao)",
"<reponame>leticiaarj/TrabalhoTPPE<filename>tests/test_atividade.py<gh_stars>0 import unittest from usecases.Atividades import Atividade from usecases.Nodos import Nodo, NodoDecisao, NodoFusao,",
"não foram criadas') self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas') if __name__ == \"__main__\":",
"'Nome do diagrama não criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da atividade não",
"Atividades', 'Nome do diagrama não criado') self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da atividade",
"Fusao', ['Nodo Decisao'] ,['Nodo Final']) nodoFinal = NodoFinal('Nodo Final', ['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao)",
"de Atividades', 'Atividade de Monitoramento', nodoInicial.arrayNodo) \"\"\"self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do diagrama",
"Final']) nodoFinal = NodoFinal('Nodo Final', ['Nodo Fusao']) nodoInicial.addNodo(nodoDecisao) nodoInicial.addNodo(nodoFusao) nodoInicial.addNodo(nodoFinal) self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos",
"testCriacaoDiagrama(self): nodoInicial = Nodo('Nodo Inicial', ['proximo']) nodoDecisao = NodoDecisao('Nodo Decisao', ['Nodo Inicial'] ,['Nodo"
] |
[
"dois números inteiros e gere os números inteiros que estão no intervalo compreendido",
"eles.''' number1 = int(input(\"Digite o primeiro numero: \")) + 1 number2 = int(input(\"Digite",
"gere os números inteiros que estão no intervalo compreendido por eles.''' number1 =",
"um programa que receba dois números inteiros e gere os números inteiros que",
"os números inteiros que estão no intervalo compreendido por eles.''' number1 = int(input(\"Digite",
"o primeiro numero: \")) + 1 number2 = int(input(\"Digite o segundo numero: \"))",
"number1 = int(input(\"Digite o primeiro numero: \")) + 1 number2 = int(input(\"Digite o",
"int(input(\"Digite o primeiro numero: \")) + 1 number2 = int(input(\"Digite o segundo numero:",
"que estão no intervalo compreendido por eles.''' number1 = int(input(\"Digite o primeiro numero:",
"no intervalo compreendido por eles.''' number1 = int(input(\"Digite o primeiro numero: \")) +",
"primeiro numero: \")) + 1 number2 = int(input(\"Digite o segundo numero: \")) print(list(range(number1,",
"inteiros e gere os números inteiros que estão no intervalo compreendido por eles.'''",
"intervalo compreendido por eles.''' number1 = int(input(\"Digite o primeiro numero: \")) + 1",
"que receba dois números inteiros e gere os números inteiros que estão no",
"'''Faça um programa que receba dois números inteiros e gere os números inteiros",
"e gere os números inteiros que estão no intervalo compreendido por eles.''' number1",
"compreendido por eles.''' number1 = int(input(\"Digite o primeiro numero: \")) + 1 number2",
"inteiros que estão no intervalo compreendido por eles.''' number1 = int(input(\"Digite o primeiro",
"= int(input(\"Digite o primeiro numero: \")) + 1 number2 = int(input(\"Digite o segundo",
"receba dois números inteiros e gere os números inteiros que estão no intervalo",
"números inteiros e gere os números inteiros que estão no intervalo compreendido por",
"por eles.''' number1 = int(input(\"Digite o primeiro numero: \")) + 1 number2 =",
"números inteiros que estão no intervalo compreendido por eles.''' number1 = int(input(\"Digite o",
"programa que receba dois números inteiros e gere os números inteiros que estão",
"estão no intervalo compreendido por eles.''' number1 = int(input(\"Digite o primeiro numero: \"))",
"numero: \")) + 1 number2 = int(input(\"Digite o segundo numero: \")) print(list(range(number1, number2)))"
] |
[] |
[
"\"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption = PyEmbeddedImage(",
"\"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\"",
"\"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\"",
"\"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\" \"hcRt4LC8ZIFeSYnfgC5V6gUy8hArAW2SrmOcU6U2YD6m+nYBU5LexrjYrFWmgN2q7zQwIikN\" \"fKUqI0BK9UTOYvRIDfMwt1ZVPsZIReQqOsayl6XXgG9V7SWWjUblZgij0CXpEHBKNd4vYAzJ\"",
"import PyEmbeddedImage AmericanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\"",
"\"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"PyEmbeddedImage AmericanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\"",
"= PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol",
"\"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"# This file was generated by img2py.py # from wx.lib.embeddedimage import PyEmbeddedImage AmericanOption",
"\"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\"",
"PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\"",
"\"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\"",
"\"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\"",
"\"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\" \"hcRt4LC8ZIFeSYnfgC5V6gUy8hArAW2SrmOcU6U2YD6m+nYBU5LexrjYrFWmgN2q7zQwIikN\" \"fKUqI0BK9UTOYvRIDfMwt1ZVPsZIReQqOsayl6XXgG9V7SWWjUblZgij0CXpEHBKNd4vYAzJ\" \"xV4HSG+S9MoUMKBam9KAs1d240A2JumNPMZHsohlgXFZtQOFZkmNf2PcaJJNcwFol80wMCij\" \"<KEY>\" \"<KEY>\" \"unfbYqbEM91ydXAaT9MHVUd8IE9d+YG46kskj52/OfPYYubm+WPJhP4fvvthbNRiLP29/PkZ\"",
"EuropeanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\"",
"\"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\")",
"\"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\" \"hcRt4LC8ZIFeSYnfgC5V6gUy8hArAW2SrmOcU6U2YD6m+nYBU5LexrjYrFWmgN2q7zQwIikN\" \"fKUqI0BK9UTOYvRIDfMwt1ZVPsZIReQqOsayl6XXgG9V7SWWjUblZgij0CXpEHBKNd4vYAzJ\" \"xV4HSG+S9MoUMKBam9KAs1d240A2JumNPMZHsohlgXFZtQOFZkmNf2PcaJJNcwFol80wMCij\" \"<KEY>\" \"<KEY>\" \"unfbYqbEM91ydXAaT9MHVUd8IE9d+YG46kskj52/OfPYYubm+WPJhP4fvvthbNRiLP29/PkZ\" \"Fz/Jn/dw8a78iYxj9Yv86sbqgPxaM4nFxHPyrQ+LHvkX/Ysa0w0K4Cg1PlEQz89S5UGjAjlJ\" \"lRMKpukRq8wlFNAQq3ymoJofU+HfDQpsmAqfK7jWBVYstCiEr1kxojBedShztimUUcquKJx2\"",
"\"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\" \"hcRt4LC8ZIFeSYnfgC5V6gUy8hArAW2SrmOcU6U2YD6m+nYBU5LexrjYrFWmgN2q7zQwIikN\" \"fKUqI0BK9UTOYvRIDfMwt1ZVPsZIReQqOsayl6XXgG9V7SWWjUblZgij0CXpEHBKNd4vYAzJ\" \"xV4HSG+S9MoUMKBam9KAs1d240A2JumNPMZHsohlgXFZtQOFZkmNf2PcaJJNcwFol80wMCij\" \"<KEY>\" \"<KEY>\" \"unfbYqbEM91ydXAaT9MHVUd8IE9d+YG46kskj52/OfPYYubm+WPJhP4fvvthbNRiLP29/PkZ\" \"Fz/Jn/dw8a78iYxj9Yv86sbqgPxaM4nFxHPyrQ+LHvkX/Ysa0w0K4Cg1PlEQz89S5UGjAjlJ\" \"lRMKpukRq8wlFNAQq3ymoJofU+HfDQpsmAqfK7jWBVYstCiEr1kxojBedShztimUUcquKJx2\" \"ynYqpDRP/aiw3uKpDoWWxcgqvH0Y+xReJAOZiP6DllyuRXU9AXB3E/FsJnLpAAAAAElFTkSu\" \"QmCC\")",
"\"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\"",
"was generated by img2py.py # from wx.lib.embeddedimage import PyEmbeddedImage AmericanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\"",
"\"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\"",
"\"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\"",
"AsianOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\"",
"\"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\"",
"#---------------------------------------------------------------------- # This file was generated by img2py.py # from wx.lib.embeddedimage import PyEmbeddedImage",
"\"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\"",
"= PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\"",
"\"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\"",
"\"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #---------------------------------------------------------------------- LookBackOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption =",
"\"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #---------------------------------------------------------------------- LookBackOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\"",
"\"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\"",
"\"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\"",
"#---------------------------------------------------------------------- LookBackOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption = PyEmbeddedImage(",
"file was generated by img2py.py # from wx.lib.embeddedimage import PyEmbeddedImage AmericanOption = PyEmbeddedImage(",
"\"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #---------------------------------------------------------------------- LookBackOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\"",
"\"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\"",
"\"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\"",
"\"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\"",
"PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\"",
"\"gg==\") #---------------------------------------------------------------------- LookBackOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\"",
"\"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\"",
"\"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\"",
"#---------------------------------------------------------------------- EuropeanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\"",
"\"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\"",
"= PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\"",
"\"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\"",
"\"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\"",
"generated by img2py.py # from wx.lib.embeddedimage import PyEmbeddedImage AmericanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\"",
"\"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\"",
"\"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\"",
"\"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\"",
"\"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\"",
"\"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\" \"hcRt4LC8ZIFeSYnfgC5V6gUy8hArAW2SrmOcU6U2YD6m+nYBU5LexrjYrFWmgN2q7zQwIikN\" \"fKUqI0BK9UTOYvRIDfMwt1ZVPsZIReQqOsayl6XXgG9V7SWWjUblZgij0CXpEHBKNd4vYAzJ\" \"xV4HSG+S9MoUMKBam9KAs1d240A2JumNPMZHsohlgXFZtQOFZkmNf2PcaJJNcwFol80wMCij\" \"<KEY>\"",
"\"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\"",
"\"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\"",
"\"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\"",
"\"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\"",
"\"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\"",
"\"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"#---------------------------------------------------------------------- ImpliedVol = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\"",
"\"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\"",
"\"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption =",
"\"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\"",
"#---------------------------------------------------------------------- VanillaOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\"",
"# from wx.lib.embeddedimage import PyEmbeddedImage AmericanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\"",
"\"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol = PyEmbeddedImage(",
"\"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\"",
"\"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\"",
"\"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #---------------------------------------------------------------------- LookBackOption",
"\"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\"",
"\"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #---------------------------------------------------------------------- LookBackOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\"",
"\"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\"",
"\"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #---------------------------------------------------------------------- LookBackOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\"",
"\"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\"",
"\"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\" \"hcRt4LC8ZIFeSYnfgC5V6gUy8hArAW2SrmOcU6U2YD6m+nYBU5LexrjYrFWmgN2q7zQwIikN\" \"fKUqI0BK9UTOYvRIDfMwt1ZVPsZIReQqOsayl6XXgG9V7SWWjUblZgij0CXpEHBKNd4vYAzJ\" \"xV4HSG+S9MoUMKBam9KAs1d240A2JumNPMZHsohlgXFZtQOFZkmNf2PcaJJNcwFol80wMCij\" \"<KEY>\" \"<KEY>\" \"unfbYqbEM91ydXAaT9MHVUd8IE9d+YG46kskj52/OfPYYubm+WPJhP4fvvthbNRiLP29/PkZ\" \"Fz/Jn/dw8a78iYxj9Yv86sbqgPxaM4nFxHPyrQ+LHvkX/Ysa0w0K4Cg1PlEQz89S5UGjAjlJ\"",
"\"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\"",
"\"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\"",
"\"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption = PyEmbeddedImage(",
"LookBackOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\"",
"\"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"VanillaOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\"",
"\"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\"",
"wx.lib.embeddedimage import PyEmbeddedImage AmericanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\"",
"\"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\"",
"\"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\" \"hcRt4LC8ZIFeSYnfgC5V6gUy8hArAW2SrmOcU6U2YD6m+nYBU5LexrjYrFWmgN2q7zQwIikN\"",
"\"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\"",
"\"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\"",
"\"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\"",
"\"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #----------------------------------------------------------------------",
"= PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\"",
"\"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #----------------------------------------------------------------------",
"\"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\"",
"\"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\"",
"#---------------------------------------------------------------------- AsianOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\"",
"\"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption =",
"PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\"",
"PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\"",
"PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\"",
"\"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\"",
"\"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #---------------------------------------------------------------------- LookBackOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\"",
"\"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\"",
"\"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #----------------------------------------------------------------------",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\"",
"\"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\"",
"\"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\"",
"\"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #---------------------------------------------------------------------- LookBackOption = PyEmbeddedImage(",
"\"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\"",
"\"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\"",
"\"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\"",
"\"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\")",
"\"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\" \"hcRt4LC8ZIFeSYnfgC5V6gUy8hArAW2SrmOcU6U2YD6m+nYBU5LexrjYrFWmgN2q7zQwIikN\" \"fKUqI0BK9UTOYvRIDfMwt1ZVPsZIReQqOsayl6XXgG9V7SWWjUblZgij0CXpEHBKNd4vYAzJ\" \"xV4HSG+S9MoUMKBam9KAs1d240A2JumNPMZHsohlgXFZtQOFZkmNf2PcaJJNcwFol80wMCij\"",
"\"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\" \"hcRt4LC8ZIFeSYnfgC5V6gUy8hArAW2SrmOcU6U2YD6m+nYBU5LexrjYrFWmgN2q7zQwIikN\" \"fKUqI0BK9UTOYvRIDfMwt1ZVPsZIReQqOsayl6XXgG9V7SWWjUblZgij0CXpEHBKNd4vYAzJ\" \"xV4HSG+S9MoUMKBam9KAs1d240A2JumNPMZHsohlgXFZtQOFZkmNf2PcaJJNcwFol80wMCij\" \"<KEY>\" \"<KEY>\" \"unfbYqbEM91ydXAaT9MHVUd8IE9d+YG46kskj52/OfPYYubm+WPJhP4fvvthbNRiLP29/PkZ\" \"Fz/Jn/dw8a78iYxj9Yv86sbqgPxaM4nFxHPyrQ+LHvkX/Ysa0w0K4Cg1PlEQz89S5UGjAjlJ\" \"lRMKpukRq8wlFNAQq3ymoJofU+HfDQpsmAqfK7jWBVYstCiEr1kxojBedShztimUUcquKJx2\" \"ynYqpDRP/aiw3uKpDoWWxcgqvH0Y+xReJAOZiP6DllyuRXU9AXB3E/FsJnLpAAAAAElFTkSu\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\"",
"\"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\"",
"by img2py.py # from wx.lib.embeddedimage import PyEmbeddedImage AmericanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\"",
"\"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\")",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\"",
"\"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol =",
"img2py.py # from wx.lib.embeddedimage import PyEmbeddedImage AmericanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\"",
"\"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAwfQAAMH0BS0BPwgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AALNSURBVHic7Zs9axRRFIafExfcBGFVNCiBoIKsCGpEiHaKlZUfoJjSwkp/gZ1dLFMGK0GE\" \"BAQFFQKCHxBBKz8KXUWyq5WiYgISVyQei5mNN9fBmN2ZOca5DwwsZ+fcee+7c+7cuTMrqkqR\" \"6bIWYE2p9UFENgMnDbXkybiq1iE2QER2A/uBYUtVOdIUkbuq+pR4DGgAWrCtpqrzY8DHjvxc\" \"nnwCEFVFRFYDn40F5c0aVZ0u/FUgGGAtwJpggLUAawpvQCm+BFashRhQEREEmAReu18Ag8Bt\" \"L+EwcAuYc2IDwAxQd2Jr4/gdL/8YcM2L7QE+AG+9/B3A/Tbz1wNVon65HAeuerFBgFOqSmsD\" \"tgETbiyOPwHKXuw8MOTFBoDrCfm1hNgF4GhC/lgH+fuASwn7NhJiI4UfAwS4THTKtVgJ9AFT\" \"<KEY>\" <KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\"",
"\"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #---------------------------------------------------------------------- LookBackOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #----------------------------------------------------------------------",
"\"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\"",
"\"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\"",
"\"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\")",
"This file was generated by img2py.py # from wx.lib.embeddedimage import PyEmbeddedImage AmericanOption =",
"\"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"pDWJ71EhAGQnwqgRABKL0BbHp7M5QESqgXofG4d5vvi3yAa0xM5jzgn9mDlhV6ivJBzstvc8\" \"oBVYYI9zMBWepBsjhQevPmAv0IHJ9DqAA6p6JoKLExEiBbChdD9mvb8cqA69wDwYHQWO2eMg\" \"JhImYoSaSPSGzBBGlE+A123o+3GLK8IKVd3p+2vA2luPqQPuIHjtPQ18DbyA2RBZBEyIubY3\" \"ANcCDwIvAz9G9PMpsAqoLjFP6AMWxkqEgKuAv0Kc9WAqQ9McJzxtwCuYiAnqewfQ6FKEYkdj\" \"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\"",
"\"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption",
"from wx.lib.embeddedimage import PyEmbeddedImage AmericanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\"",
"\"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\"",
"\"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\"",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\"",
"\"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\" \"Hm8EVuUd+gU7lwqLyN3A2yFa9QLzVbUnpM2ogzcPOBHR9mLgqQy5nIOITBWRDSKyVUResnNI\" \"JvBmgsUCbAXexDzfn7DHfVkRKUBEGoGdwBT71XLgDhFZoap7nHfoGaNLMWP9OLAa+6QYc3xf\" \"<KEY>\" \"<KEY>\"",
"\"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\" \"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #----------------------------------------------------------------------",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\" \"R4OpboK+/YdjwNgOizzWvyKkL+THnmYnCiL1e7958N5Vxc9OpvkfrN91edzjSxcM+saPbtr3\" \"Yw1yKN3vDez9uE6/1n3Oz95EMLrh5jIP39Xo17znCcNJdcLOSZ7Qq44/YdGVi9riTWb5OOxT\" \"Rbv5MHd4TH0fw2GPiWZ40nZF/cywWJcwk/gbZ4W0QUaNBg2GWeQGmA2izxm3169vZfx43GIA\"",
"\"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\"",
"\"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\"",
"\"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\"",
"\"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\" \"ZGdpamxtbnBxdHV3eH2AgYKGiImKjI+QkpSWnJ2en6GjpaanqaqrrK2xuLm6vr/Aw8XGx8jJ\" \"y8zQ0dTX2Nna3N3e4OLj6Onq6+zu7/L09fb3+fr7/P3+brfoEQAAAnpJREFUWMPtV2lD00AQ\" \"HVraKlYqHlW8UBAVUPFWVFRUsIp4n2BVPFFQEW21gAeUo+RX285u0t1kj0m/6vuUvJn3kmxm\" \"d2cB/oOCRDpVV6N0defQ6KdfjuMs5t+OXGmLhFOvO/9y0ZFQuNW5iixvujbvKDDTEyPJU4NF\"",
"\"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\"",
"\"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\" \"kfYf4Cfgp6QtccingNdU9TkRmY7Z2WJsmbVjthXa41herqq/ZxnI1QGdmDNd4lpPi1KwUBE5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\"",
"\"MPl1kJNBoC2LjM/D4d6IG/kiRcZ4ngjFTi7EjOEgB91AfcYCzANOhXDYHXJtYhH8nDyB/2Nu\" \"wT4D5mVw44JZ47tC+h4A2iP8xBGhH1jkK4B1shL4EjMBBTn5AXgEuI4SNz4xe5IrgXWY5Cao\" \"r+PARmBuTL9xI6EpdBm0Fdo7Me8DLApsaPAbppLTT/QyOBmYj8nagnAG2Aa8C3ykCbfSYi6R\" \"<KEY>lILtGC2u/3S4LBUuGA/\" \"<KEY>3ArZgw3wd0q+pZh0THWpJzrD2rqlG71nF9N2GSttmer08CS5IIsBSj\" \"ZAFDmLDdB/yKfcDxWOH8JObFizpr9Z7PE4FmzA03MzLNHq+qQ/FvM5J/PfAksBj4HXhOVfem\" \"ESBrOBUgCKOqHpAFKgLkTSBvVATIm0DeqAiQN4G8UREgbwJ5oyJA3gTyRkWAvAnkjYoACdo6\" \"KU7ExFlrmSOJAN8Dm7IiUoRHVfVUWXpKWMauAW4C3sFUfcPKzkntMPAisCTLjZdiK7koamt4\" \"hfpdiz1OY2TJqw7zNukJRpbLjmGKoV2YkloXcEjTVGhLxH+OUEeDxifcOAAAAABJRU5ErkJg\" \"gg==\") #---------------------------------------------------------------------- LookBackOption =",
"\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\" \"Uk5TAAECAwUGBwgJCgsNDhAREhMXGBkbHh8gISIjJCYoKisuMDEzNTY3ODs+P0FCQ0RISU1O\" \"UVNUVVZXWV1eX2BhYmNkZWZoam9ydnh6fH6BgoOEhYaHiImLlZeYmZudoqOlpqipqq2ur7Cx\" \"tbe4ubq7vL/Cw8XHyMzP0NHS09fY2dvc4OHj5OXm5+jp6+zt7u/w8vP09vf4+fr7/P3+JuId\" \"/QAAAqhJREFUGBnlwftbk2UAx+Hvkm1SjlQ0wMwsRS2ygwyNskCRxHPTICrJNA3MbNraMipC\" \"MFFpE1cy4P38sT7oLq6xPe/eQz9235KrdZ1fZCaLxcnMl/tfVHDbLiywYuny6wpm/TcOq13Z\" \"oAA67lD2sEDZvXfk2wdLGE763P4tEbV1nb3uYDiH5VNyEePPN7Viz+8YzofyZUcJWBxcqwqx\" \"T0vA4h750PAr8M9uVdlRBP6Iy9txjCOq0YNxRp7is8BlLdvZoUqXgEKjvPQCU02SNl5w5l9Q\" \"hcRt4LC8ZIFeSYnfgC5V6gUy8hArAW2SrmOcU6U2YD6m+nYBU5LexrjYrFWmgN2q7zQwIikN\" \"fKUqI0BK9UTOYvRIDfMwt1ZVPsZIReQqOsayl6XXgG9V7SWWjUblZgij0CXpEHBKNd4vYAzJ\" \"xV4HSG+S9MoUMKBam9KAs1d240A2JumNPMZHsohlgXFZtQOFZkmNf2PcaJJNcwFol80wMCij\" \"<KEY>\" \"<KEY>\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"= PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAGcAAABnAH6gGQJAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AaFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxZP4DgAAAIp0\" \"Uk5TAAECAwQFBwgJDQ4PEBIUFhcZGhscHh8iIyYnKCorLTM0Njc6PEZJTE1OT1BRU1VWXF5f\"",
"\"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\"",
"AmericanOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAHIQAAByEBauL93wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAcESURBVHic7ZpbaB1VFIa/ld7S1t7UYmq8JDWpWOut0lqLiCCCPgjewBel9EEpiAiC2Bcf\" \"fFFBvIEoivgkIihFQQShUhBbsGhbtWrTS1Jr29TWS7SX2Jhk+bD2zpmzz5w5M3MmmVbzw2LP\" \"mbNn7bXX7HXbe1BVVBVgBvAI8AOgwCDwNrDM9/kvkrjJIyIPAW9Si16gW1VHY/4769ESuX64\" \"Tp/FwO0TIEspmBq5PpnQ7+/xFiQtRGQBcKGjRY5aMBkHI+0g8CuwTVXryh9VwEvAamBa0OcL\" \"RxMGEZkFXAEsA6507RKgHWjNyG5IRL4GNntS1WNjY3kf4AZeDzwbMDgP6ATWAFuALap6IKMQ\" \"sYhMdGmErnTjtSQ82iy2q+pyqF4BAAMxnU8BC4FHHSEih3DKAL7BzCe6/Hx7DpXlGqWLsYlf\" \"CkgDYUeAXcAeYB+wN9L2A6OOFFBVHRWReUAX0O3IX18PTMf8miEaEoB1nlGEWjEnGN4fDxoF\" \"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\"",
"\"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\" \"NTY3ODk6Ozw9PkBBQkNERUZHSUpLTE1PUFFSU1RVVldYWVpbXF1fYGFiY2RlZmdoaWprbW9w\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"D8+ndNutL0Q3pcWEPN2ErvPOka4GikrOPwx80kwN4Hoou/gSfkm6QS37jJ275RQ1Fuh6udze\" \"1FnrjxFgt6Rps8b1jw6VM5e7W1LGh0uLD1biqFTSCoyKPasWzZmWPX7UkJSXxk6cMmPekuVr\" \"<KEY>PJKSaZhdkzvL4j5IQ1QN1xWbaZBtsjXuN3ziN9ywSbpa5MubuC7VpT988fH7\" \"E0enPN5MtUVVU6eS6a+PTh62H2OQ6rQfS2UllvIpowb3S9mH32b5dffBKtUt5onuHVs3Udgi\" \"jARZEvEbrsu+g9mqX/RFWCG/u/DrIL8JGG+7JYXH9n9lXKTqEHkAdkXJ7wRGdVMZrT7lsoPF\" \"h6swMuUsfD3GpvZSWPME/IrmF67dXkGAqQpwX95n+<KEY>uLYhCjCL6+I7UbZj/Vf5\"",
"= PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"AddQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/rhuQAAAJx0\"",
"\"eoB3gMcwk5xVVMgDdrhxBvy9cAWUjftV9f2JHPBMU8A/SX+KyEzMP1yGLeNFwBRHLZHrv4Dd\" \"nlT1aD2eZ5oCxiAiXcBKR8sxO26jsc+I4/UnpozO8L8iFPAz5tTqQYGjwAUpeK0RkXXACuDc\" \"AmTzmOd4RmUCmlPAaaxW2AC8gHn1MIf4DfgM+BRYC9zUgOddde4PAfuxtLwXiwK9WBQYcTQa\" \"uZ6L5Q1R6gZmh4ybUcAMYKGqbhSRjcDVMX0UU85+4NWUfEeA74GtEdqpqiMZ5fsy+kNEBAvZ\" \"<KEY>\" \"<KEY>\" \"<KEY>/LJrdi6XD49qdiE1qGTS4c/11gZsqxfiHZCcY6vRBFK2ARNrkTwB11+nQB\" \"mzBBQ4ST/xtLX7dhub+PAr1p/ISItFMdCdYCC6J9ilDAINWCrwfmYEWUxxBWhIAVQFBt+x69\" \"wOdUvP+3qpqYHSZBVQ8BhzCFIyK3UqACTgNfAR9gewkec1zr7XYf8AlwJxYNkvC4qn6UVgAR\" \"aSXeCZ5Q1VNJz3o0mwfsUNWXRUQxxxZ62R7gXsxW02yr1aS5bgfoOuKjwPw6fFREDmMl9B7M\" \"fPZQcCIElge8gdl+TYjBwtfdbuC2FPxmiMgqqqNAdw65BNs9agduSerYrAJuc23SjvHTpN/d\" \"eS/j+McwRzmEVZK+nYb5mnl1niukFogiaYLNbm0dp5LI9ERod6NIICLzsQqww9GTWFFWWCpc\" \"FEaweqFqgkCPqh7Oy1RVB4DtjhCRNQRVaR4F/OzadrK/3V8JJuhon6oOZWEkInOwt9qKhdhp\"",
"\"STaSE/7p+RDpP1vBZgAtrDCPyPqNS8geBbsB/1vfZHIAyQ9AMdjGCqpF5CKzyJ0jGcBtZC9J\" \"NcZKaBPNYA8bb5E6gdRroBlEppFOC9QDZHqIBnAH6eMCk8cKb6IaHEB6AK7mXCCx7N3mHkVF\" \"<KEY>\" \"<KEY>IIA+go+Q3Ogt3A+4QyTvmyroPdwBtEREZKGhHmeTwnI/AbGeoeC/o3pC3YLST3\" \"Tavl8KWRtP/6S9krh+ktJH1wMvFymG+l9Q+K6YzlUOqi6VULCpbDaaJetaRVyiFD1KsXVYBD\" \"1HZOvazTodtYqNBubVToN1fa8w3bO+n7jQ2GHbYWxwJ7k2UEqc3Tgd5oKrA+XKurmDkhm22z\" \"Aand1xtQDxxqg1BHHtmgpkNXFbGaj33/Bv4C7Cs45u1y0kgAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- VanillaOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAAAJbAAACWwFBeK9IAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\"",
"<KEY>//<KEY>\" \"YAuwC9gLnAFW5aBFANxpYdbX3Qlgqz8dTZie9gHjOegpq2puBpxerOMJRhwBvv8PBgwvtfOO\" \"prPL3YCbQFe7BsS6RrM0IMupsAKbVNW/KVkSItIDvCf9gTHzqfBkp50HUNVZfl8ISY0sDbjy\" \"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"q3oUKhrJVgB88C3GmbbhOXAuVMEKAd+Ggm0YVesOAbGybaBGxUngpBz8RaDBsm2ltj/lYCOB\" \"hsm2DLhQhd8F4JgcZMDZ5NjOn2OsHlgAxMo2A+iZimVtxEdwVA56wNeSojFa6U4475ItE2ga\" \"jSVDT8IhOXgAlktyY0jycU41xgEtPFgy1Qt+l4NYWCfJjSHpIpdUIw1ofQ+WbHWD3+TgXtgq\" \"yY0h6V9wyTYS8NyNZaruh31y0Ap2SXJjhEhnIEK2F4GYNlhmKAbK5CAaTkt6BKOtGgMxso0E\" \"uruxzFUPqAxTsCFAV0XMxFjwcBYwQLb3gBEPYikJyQQ6Klguxu7T/C9LtkLAdxy/coxEBSsl\" \"UJ5s2wiQqmD5XGX/UWC8bD8SoKeCJQJvteu0EuNURAwQL9t04PC7ZzGq4nKAWAWLg79DpD4Y\" \"P0sXwSNbNpClhRjligc6KVgX+ENSe4yV0uR/vlSNEUBvJVQDG+Xawq9hChayvXq2jEkb1izq\" \"pNrCBo3pLal93769wiVFuuSouW67Zf0HmwyT/NCKhBoAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- EuropeanOption",
"ImpliedVol = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\" \"7cBPwGDBROQ+R74zhSsBinEE2JyRb6dII8DtIb89rKpHU/guG6SUSVBEWoBdwFifnz9X1fa0\" \"xMqFxBEgIgK8hv/NA+xPxajMqCnxml+AXnteBdwAjHdFqpxILICqDgN3eb8TkVnAq8AyQNxQ\" \"Kw9Ch4CIzBKRt0SkLqydqh5S1eXAPcAWlwQzh6r6GvAQcBxQYHZQu7gGNKT1kYXViMgkoBEz\" \"hicAtcDjmHFdgIvM7oCIdALfAFOBNaraG3FNWfAV5l8Os8UOIqDT468fqMv731dVqoA1wOkI\" \"kVJFgIhcAszwfPW+qg6k8ekKVaq6HXg6ot0DKfu5GRgD9NjzSSn9uYMNzxpgO+HD4LaUQ6DG\"",
"PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\"",
"\"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>aHBwaHhwaHRwaHRwaHR<KEY>\" \"HRwbHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwaHRsaHBwaHRwaHRwaHRwaHRwaHRwaHRwa\" \"HRwaHRwaHhwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaHRwaDWpeAgAA\" \"AOV0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMVFxgaGxwdHh8gISIjJCUmJygpKissLS8wMTM0\"",
"\"j7a1kIzGgEdApZPa98aBFcDDlDWW1Xk4mjZ1VZ1ZfLe/Q1XniBcv0sZ6KmxOMMBagDXBAGsB\" \"1gQDrAVYEwywFmBNMMBagDXBAGsB1gQDrAVYEwywFmBNMMBagDXBAGsB1hTegFL8j7Fqyu32\" \"i8gQcE9V33XSkIj0AgeB/lSU/eKEiLwAGCG7J7CHUngociBDfaOFL4HCG1ACbgAd1ekfeJlC\" \"G1PAuRTaSeLx/PsBRaXwJfAT3BK6v9OwyUMAAAAASUVORK5CYII=\") #---------------------------------------------------------------------- ImpliedVol = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlw\" \"SFlzAAAdmwAAHZsBHYZu2AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoA\" \"AAWcSURBVHic7ZpdiFVVFMd/a2Y0dWZ0orRGRtRJy1FzRkELKjA1oSkjCKqHoogICguKHgr1\" \"IaSHPh8Ci3roGwPLosKi0oIoAoV0FGf8oqYya2pmSBud0VFXD3tfOXM9n/fsc08D9w+Lc8+9\" \"+6z9P/+79t7rrH1EVSkFInIp8B2wTlXfK8nJ/wBVKa5tAC4DNorIFhGZKSLjCuaIX+ZII4AX\"",
"\"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\") #---------------------------------------------------------------------- AsianOption = PyEmbeddedImage( \"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBI\" \"WXMAABIFAAASBQEoPImrAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA\" \"ArJQTFRF////AAAAAAAAAAAAAAAAMzMzKysrJCQkICAgHBwcGhoaFxcXFRUVFBQUJCQSIiIi\" \"ICAgHh4eHBwcGxsbGB<KEY>\" \"<KEY>\"",
"\"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>\" \"<KEY>oUkgi5hCPuXLEu3MFoN/FOcW4RcoVDElNs5VHAWhHppuL8eoE+Vf0FxmJ3nBMM\" \"3+hFcQIloJ9aE0qKAp1UTNSb680Emy55FOAnUwURGca8fDO5/0kqviLqM3ar6vGMvP7AdpKi\" \"Mu4gcNhF1gJpeY1iDimuuDlYoDypkEcBT2Gbl9EokCoVxia6V1VPZxlQRFqwZCZ0ilmiQB8F\" \"bYgMq6pnWihE5FzinWIXdTK5OphK5YuThh0nFK6I6iI+zJ2fg+UAlQ85Wsl4epxHAc+IyKME\" \"UYDGqbCfcAfxO8JxGMZMZ6dr+yN0BDgS5hgiMgPz9DMxhd6AfWmympgTrLQK6Mc86tXuGf+t\" \"T6PT3rQYwRS5EzsY9W1P1rzf+ZfT2MroB74D3gIQkfOwqvBa3z/8Smwd8HrAc6bXsojMxjYq\" \"vUZXkf4cfwQrcPqBg9gnuX6yu7Jmi0Uhkwm4PbhNVA4aBPs4Yja25FqD9iSVJXvsTPzctikn\" \"6AqZQr4ZLAvj+THiWYFJBZQtQNmYVEDZApSNSQWULUDZmFRA2QKUjUkFlC1A2ZhUQNkClI1J\" \"BZQtQNmYVEDZApSN/70C/gVDTFLx+fxz1wAAAABJRU5ErkJggg==\")"
] |
[
"class NoAuthenticationError(Exception): \"\"\" If a method is called that requires an access token",
"a method is called that requires an access token and none is yet",
"is called that requires an access token and none is yet set then",
"auth \"\"\" class NoAuthenticationError(Exception): \"\"\" If a method is called that requires an",
"\"\"\" class NoAuthenticationError(Exception): \"\"\" If a method is called that requires an access",
"\"\"\" If a method is called that requires an access token and none",
"relating to auth \"\"\" class NoAuthenticationError(Exception): \"\"\" If a method is called that",
"If a method is called that requires an access token and none is",
"and none is yet set then raise this error \"\"\" # pylint: disable=unnecessary-pass",
"NoAuthenticationError(Exception): \"\"\" If a method is called that requires an access token and",
"<filename>reposit/auth/exceptions.py \"\"\" Exceptions relating to auth \"\"\" class NoAuthenticationError(Exception): \"\"\" If a method",
"access token and none is yet set then raise this error \"\"\" #",
"called that requires an access token and none is yet set then raise",
"Exceptions relating to auth \"\"\" class NoAuthenticationError(Exception): \"\"\" If a method is called",
"token and none is yet set then raise this error \"\"\" # pylint:",
"to auth \"\"\" class NoAuthenticationError(Exception): \"\"\" If a method is called that requires",
"requires an access token and none is yet set then raise this error",
"none is yet set then raise this error \"\"\" # pylint: disable=unnecessary-pass pass",
"method is called that requires an access token and none is yet set",
"\"\"\" Exceptions relating to auth \"\"\" class NoAuthenticationError(Exception): \"\"\" If a method is",
"an access token and none is yet set then raise this error \"\"\"",
"that requires an access token and none is yet set then raise this"
] |
[
"def build_config(self): \"\"\"Do something to build the config.\"\"\" self._build_config() def start(self): \"\"\"Do something",
"start the stack.\"\"\" pass def stop(self): \"\"\"Do something to stop the stack.\"\"\" pass",
"the config.\"\"\" pass def build_config(self): \"\"\"Do something to build the config.\"\"\" self._build_config() def",
"\"\"\"Do something to stop the stack.\"\"\" pass def restart(self): \"\"\"Do something to restart",
"to restart the stack.\"\"\" self.stop() self.start() class Molecule(MoleculeInterface, Handler): \"\"\"FIXME: Put all common",
"abc import abstractmethod from cement import Interface, Handler class MoleculeInterface(Interface): class Meta: interface",
"import Interface, Handler class MoleculeInterface(Interface): class Meta: interface = 'stack' @abstractmethod def _build_config(self):",
"something to restart the stack.\"\"\" self.stop() self.start() class Molecule(MoleculeInterface, Handler): \"\"\"FIXME: Put all",
"from abc import abstractmethod from cement import Interface, Handler class MoleculeInterface(Interface): class Meta:",
"cement import Interface, Handler class MoleculeInterface(Interface): class Meta: interface = 'stack' @abstractmethod def",
"= 'stack' @abstractmethod def _build_config(self): \"\"\"Do something to build the config.\"\"\" pass def",
"pass def build_config(self): \"\"\"Do something to build the config.\"\"\" self._build_config() def start(self): \"\"\"Do",
"config.\"\"\" self._build_config() def start(self): \"\"\"Do something to start the stack.\"\"\" pass def stop(self):",
"something to start the stack.\"\"\" pass def stop(self): \"\"\"Do something to stop the",
"import abstractmethod from cement import Interface, Handler class MoleculeInterface(Interface): class Meta: interface =",
"\"\"\"Do something to build the config.\"\"\" self._build_config() def start(self): \"\"\"Do something to start",
"something to build the config.\"\"\" self._build_config() def start(self): \"\"\"Do something to start the",
"interface = 'stack' @abstractmethod def _build_config(self): \"\"\"Do something to build the config.\"\"\" pass",
"Meta: interface = 'stack' @abstractmethod def _build_config(self): \"\"\"Do something to build the config.\"\"\"",
"to build the config.\"\"\" self._build_config() def start(self): \"\"\"Do something to start the stack.\"\"\"",
"def start(self): \"\"\"Do something to start the stack.\"\"\" pass def stop(self): \"\"\"Do something",
"to stop the stack.\"\"\" pass def restart(self): \"\"\"Do something to restart the stack.\"\"\"",
"the stack.\"\"\" pass def stop(self): \"\"\"Do something to stop the stack.\"\"\" pass def",
"to build the config.\"\"\" pass def build_config(self): \"\"\"Do something to build the config.\"\"\"",
"\"\"\"Do something to start the stack.\"\"\" pass def stop(self): \"\"\"Do something to stop",
"stop the stack.\"\"\" pass def restart(self): \"\"\"Do something to restart the stack.\"\"\" self.stop()",
"something to stop the stack.\"\"\" pass def restart(self): \"\"\"Do something to restart the",
"the stack.\"\"\" pass def restart(self): \"\"\"Do something to restart the stack.\"\"\" self.stop() self.start()",
"pass def restart(self): \"\"\"Do something to restart the stack.\"\"\" self.stop() self.start() class Molecule(MoleculeInterface,",
"class Meta: interface = 'stack' @abstractmethod def _build_config(self): \"\"\"Do something to build the",
"\"\"\"Do something to restart the stack.\"\"\" self.stop() self.start() class Molecule(MoleculeInterface, Handler): \"\"\"FIXME: Put",
"abstractmethod from cement import Interface, Handler class MoleculeInterface(Interface): class Meta: interface = 'stack'",
"the config.\"\"\" self._build_config() def start(self): \"\"\"Do something to start the stack.\"\"\" pass def",
"something to build the config.\"\"\" pass def build_config(self): \"\"\"Do something to build the",
"build the config.\"\"\" self._build_config() def start(self): \"\"\"Do something to start the stack.\"\"\" pass",
"restart(self): \"\"\"Do something to restart the stack.\"\"\" self.stop() self.start() class Molecule(MoleculeInterface, Handler): \"\"\"FIXME:",
"MoleculeInterface(Interface): class Meta: interface = 'stack' @abstractmethod def _build_config(self): \"\"\"Do something to build",
"start(self): \"\"\"Do something to start the stack.\"\"\" pass def stop(self): \"\"\"Do something to",
"restart the stack.\"\"\" self.stop() self.start() class Molecule(MoleculeInterface, Handler): \"\"\"FIXME: Put all common operations",
"stack.\"\"\" self.stop() self.start() class Molecule(MoleculeInterface, Handler): \"\"\"FIXME: Put all common operations here.\"\"\" pass",
"config.\"\"\" pass def build_config(self): \"\"\"Do something to build the config.\"\"\" self._build_config() def start(self):",
"'stack' @abstractmethod def _build_config(self): \"\"\"Do something to build the config.\"\"\" pass def build_config(self):",
"class MoleculeInterface(Interface): class Meta: interface = 'stack' @abstractmethod def _build_config(self): \"\"\"Do something to",
"Interface, Handler class MoleculeInterface(Interface): class Meta: interface = 'stack' @abstractmethod def _build_config(self): \"\"\"Do",
"pass def stop(self): \"\"\"Do something to stop the stack.\"\"\" pass def restart(self): \"\"\"Do",
"def _build_config(self): \"\"\"Do something to build the config.\"\"\" pass def build_config(self): \"\"\"Do something",
"from cement import Interface, Handler class MoleculeInterface(Interface): class Meta: interface = 'stack' @abstractmethod",
"def restart(self): \"\"\"Do something to restart the stack.\"\"\" self.stop() self.start() class Molecule(MoleculeInterface, Handler):",
"build the config.\"\"\" pass def build_config(self): \"\"\"Do something to build the config.\"\"\" self._build_config()",
"@abstractmethod def _build_config(self): \"\"\"Do something to build the config.\"\"\" pass def build_config(self): \"\"\"Do",
"def stop(self): \"\"\"Do something to stop the stack.\"\"\" pass def restart(self): \"\"\"Do something",
"\"\"\"Do something to build the config.\"\"\" pass def build_config(self): \"\"\"Do something to build",
"Handler class MoleculeInterface(Interface): class Meta: interface = 'stack' @abstractmethod def _build_config(self): \"\"\"Do something",
"_build_config(self): \"\"\"Do something to build the config.\"\"\" pass def build_config(self): \"\"\"Do something to",
"build_config(self): \"\"\"Do something to build the config.\"\"\" self._build_config() def start(self): \"\"\"Do something to",
"stack.\"\"\" pass def stop(self): \"\"\"Do something to stop the stack.\"\"\" pass def restart(self):",
"stop(self): \"\"\"Do something to stop the stack.\"\"\" pass def restart(self): \"\"\"Do something to",
"stack.\"\"\" pass def restart(self): \"\"\"Do something to restart the stack.\"\"\" self.stop() self.start() class",
"to start the stack.\"\"\" pass def stop(self): \"\"\"Do something to stop the stack.\"\"\"",
"the stack.\"\"\" self.stop() self.start() class Molecule(MoleculeInterface, Handler): \"\"\"FIXME: Put all common operations here.\"\"\"",
"self._build_config() def start(self): \"\"\"Do something to start the stack.\"\"\" pass def stop(self): \"\"\"Do"
] |
[
"history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", global_atts[\"History\"] + \"\\n\" + \"{histtime:%B %d,",
"type=str, help=\"quick description of source of salinity for correction\", ) parser.add_argument( \"-aanderaa\", \"--aanderaa\",",
"if args.aanderaa: O2_corr_umkg = O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0,",
"\"<EMAIL>\" __created__ = datetime.datetime(2016, 11, 1) __modified__ = datetime.datetime(2016, 11, 1) __version__ =",
"nchandle.setncattr( \"History\", global_atts[\"History\"] + \"\\n\" + \"{histtime:%B %d, %Y %H:%M} UTC - {history}\".format(",
"\"-sbe43\", \"--sbe43\", action=\"store_true\", help=\"sbe43 optode with Mmkg output\" ) args = parser.parse_args() ncfile",
"0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.aanderaa: O2_corr_umkg = O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0,",
"= 1e35 nchandle.variables[\"O_65\"][:, 0, 0, 0] = O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0, 0, 0] =",
"O2_sal_corr from io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __created__ =",
"for correction\", ) parser.add_argument( \"-aanderaa\", \"--aanderaa\", action=\"store_true\", help=\"aanderaa optode with Molar output\", )",
"args = parser.parse_args() ncfile = args.sourcefile df = EcoFOCI_netCDF(ncfile) global_atts = df.get_global_atts() nchandle",
"Dataset import numpy as np import seawater as sw # Relative User Stack",
"without updates python 2.7 - Tested and developed for \"\"\" import datetime import",
"action=\"store_true\", help=\"sbe43 optode with Mmkg output\" ) args = parser.parse_args() ncfile = args.sourcefile",
"2019-01-03 Put in flag for correcting Aandera optode values vs SBE-43 values (mmole/l",
"valid for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35 nchandle.variables[\"O_65\"][:, 0, 0, 0]",
"for salinity using {0}\".format( args.sal_source ) if not \"History\" in global_atts.keys(): print(\"adding history",
"unlikely to work without updates python 2.7 - Tested and developed for \"\"\"",
"seawater as sw # Relative User Stack parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir) import",
"nchandle.variables[\"OST_62\"][:, 0, 0, 0] = O2psat_corr update = \"Oxygen Concentration and Saturation corrected",
"import seawater as sw # Relative User Stack parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir)",
"and developed for \"\"\" import datetime import argparse import sys import os #",
"vs umole/kg) Compatibility: ============== python >=3.6 - not tested, unlikely to work without",
"0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], temperature=ncdata[\"T_20\"][:, 0, 0, 0], ) O2psat_corr = O2_sal_corr.O2PercentSat(",
"args.sal_source ) if not \"History\" in global_atts.keys(): print(\"adding history attribute\") histtime = datetime.datetime.utcnow()",
"- {history} \".format( histtime=histtime, history=update ), ) else: print(\"updating history attribute\") histtime =",
"metavar=\"sal_source\", type=str, help=\"quick description of source of salinity for correction\", ) parser.add_argument( \"-aanderaa\",",
"Stack from netCDF4 import Dataset import numpy as np import seawater as sw",
"import Dataset import numpy as np import seawater as sw # Relative User",
"depth\" ) parser.add_argument( \"sourcefile\", metavar=\"sourcefile\", type=str, help=\"complete path to epic file\" ) parser.add_argument(",
"datetime.datetime.utcnow() nchandle.setncattr( \"History\", \"{histtime:%B %d, %Y %H:%M} UTC - {history} \".format( histtime=histtime, history=update",
"salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.sbe43: sys.exit(\"Correction not currently valid for",
"0, 0, 0] = O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0, 0, 0] = O2psat_corr update =",
"0, 0, 0], temperature=ncdata[\"T_20\"][:, 0, 0, 0], ) O2psat_corr = O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:,",
") parser.add_argument( \"-sbe43\", \"--sbe43\", action=\"store_true\", help=\"sbe43 optode with Mmkg output\" ) args =",
"0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.aanderaa: O2_corr_umkg = O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr,",
"= df.get_global_atts() nchandle = df._getnchandle_() vars_dic = df.get_vars() ncdata = df.ncreadfile_dic() O2_corr =",
") if not \"History\" in global_atts.keys(): print(\"adding history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr(",
"= \"<EMAIL>\" __created__ = datetime.datetime(2016, 11, 1) __modified__ = datetime.datetime(2016, 11, 1) __version__",
"O2_corr = O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], temperature=ncdata[\"T_20\"][:, 0,",
"help=\"quick description of source of salinity for correction\", ) parser.add_argument( \"-aanderaa\", \"--aanderaa\", action=\"store_true\",",
"nchandle.variables[\"O_65\"][:, 0, 0, 0] = O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0, 0, 0] = O2psat_corr update",
"= \"O2\", \"salinity correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser = argparse.ArgumentParser( description=\"Correct Oxygen in Timeseries",
"for correcting Aandera optode values vs SBE-43 values (mmole/l vs umole/kg) Compatibility: ==============",
"print(\"updating history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", global_atts[\"History\"] + \"\\n\" + \"{histtime:%B",
"Tested and developed for \"\"\" import datetime import argparse import sys import os",
"help=\"aanderaa optode with Molar output\", ) parser.add_argument( \"-sbe43\", \"--sbe43\", action=\"store_true\", help=\"sbe43 optode with",
"history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", \"{histtime:%B %d, %Y %H:%M} UTC -",
") parser.add_argument( \"sourcefile\", metavar=\"sourcefile\", type=str, help=\"complete path to epic file\" ) parser.add_argument( \"sal_source\",",
"oxygen_conc=ncdata[\"O_65\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], temperature=ncdata[\"T_20\"][:, 0, 0, 0], )",
"parser.parse_args() ncfile = args.sourcefile df = EcoFOCI_netCDF(ncfile) global_atts = df.get_global_atts() nchandle = df._getnchandle_()",
"0], pressure=ncdata[\"depth\"][:], ) if args.sbe43: sys.exit(\"Correction not currently valid for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] =",
"__modified__ = datetime.datetime(2016, 11, 1) __version__ = \"0.1.0\" __status__ = \"Development\" __keywords__ =",
"as np import seawater as sw # Relative User Stack parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))",
"= datetime.datetime(2016, 11, 1) __modified__ = datetime.datetime(2016, 11, 1) __version__ = \"0.1.0\" __status__",
"\"History\", global_atts[\"History\"] + \"\\n\" + \"{histtime:%B %d, %Y %H:%M} UTC - {history}\".format( histtime=histtime,",
"developed for \"\"\" import datetime import argparse import sys import os # Science",
"datetime.datetime(2016, 11, 1) __modified__ = datetime.datetime(2016, 11, 1) __version__ = \"0.1.0\" __status__ =",
"EcoFOCI_netCDF __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __created__ = datetime.datetime(2016, 11, 1) __modified__",
"__version__ = \"0.1.0\" __status__ = \"Development\" __keywords__ = \"O2\", \"salinity correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\"",
"\"salinity correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser = argparse.ArgumentParser( description=\"Correct Oxygen in Timeseries using salinity",
"import sys import os # Science Stack from netCDF4 import Dataset import numpy",
"O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35 nchandle.variables[\"O_65\"][:, 0, 0, 0] = O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0, 0, 0]",
"path to epic file\" ) parser.add_argument( \"sal_source\", metavar=\"sal_source\", type=str, help=\"quick description of source",
"= datetime.datetime(2016, 11, 1) __version__ = \"0.1.0\" __status__ = \"Development\" __keywords__ = \"O2\",",
"11, 1) __version__ = \"0.1.0\" __status__ = \"Development\" __keywords__ = \"O2\", \"salinity correction\"",
"Relative User Stack parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir) import calc.aanderaa_corrO2_sal as O2_sal_corr from",
"action=\"store_true\", help=\"aanderaa optode with Molar output\", ) parser.add_argument( \"-sbe43\", \"--sbe43\", action=\"store_true\", help=\"sbe43 optode",
"python \"\"\" NetCDF_O2_corr.py calculate salinity from conductivity. History: ======== 2019-01-03 Put in flag",
"optode with Mmkg output\" ) args = parser.parse_args() ncfile = args.sourcefile df =",
"parent_dir) import calc.aanderaa_corrO2_sal as O2_sal_corr from io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF __author__ = \"<NAME>\" __email__",
"= \"<NAME>\" __email__ = \"<EMAIL>\" __created__ = datetime.datetime(2016, 11, 1) __modified__ = datetime.datetime(2016,",
"0, 0] = O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0, 0, 0] = O2psat_corr update = \"Oxygen",
"__created__ = datetime.datetime(2016, 11, 1) __modified__ = datetime.datetime(2016, 11, 1) __version__ = \"0.1.0\"",
"Concentration and Saturation corrected for salinity using {0}\".format( args.sal_source ) if not \"History\"",
"correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser = argparse.ArgumentParser( description=\"Correct Oxygen in Timeseries using salinity but",
"values vs SBE-43 values (mmole/l vs umole/kg) Compatibility: ============== python >=3.6 - not",
"= df.ncreadfile_dic() O2_corr = O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0],",
"optode values vs SBE-43 values (mmole/l vs umole/kg) Compatibility: ============== python >=3.6 -",
"if args.sbe43: sys.exit(\"Correction not currently valid for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] =",
"corrected for salinity using {0}\".format( args.sal_source ) if not \"History\" in global_atts.keys(): print(\"adding",
"calculate salinity from conductivity. History: ======== 2019-01-03 Put in flag for correcting Aandera",
"User Stack parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir) import calc.aanderaa_corrO2_sal as O2_sal_corr from io_utils.EcoFOCI_netCDF_read",
"MAIN--------------------------------------------\"\"\" parser = argparse.ArgumentParser( description=\"Correct Oxygen in Timeseries using salinity but not depth\"",
"Stack parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir) import calc.aanderaa_corrO2_sal as O2_sal_corr from io_utils.EcoFOCI_netCDF_read import",
"description=\"Correct Oxygen in Timeseries using salinity but not depth\" ) parser.add_argument( \"sourcefile\", metavar=\"sourcefile\",",
"args.sbe43: sys.exit(\"Correction not currently valid for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35",
"np import seawater as sw # Relative User Stack parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1,",
"0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], temperature=ncdata[\"T_20\"][:, 0, 0, 0], ) O2psat_corr",
"= O2psat_corr update = \"Oxygen Concentration and Saturation corrected for salinity using {0}\".format(",
"0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.aanderaa: O2_corr_umkg = O2_sal_corr.O2_molar2umkg(",
"temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.sbe43: sys.exit(\"Correction",
"{history} \".format( histtime=histtime, history=update ), ) else: print(\"updating history attribute\") histtime = datetime.datetime.utcnow()",
"__keywords__ = \"O2\", \"salinity correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser = argparse.ArgumentParser( description=\"Correct Oxygen in",
"python 2.7 - Tested and developed for \"\"\" import datetime import argparse import",
"salinity for correction\", ) parser.add_argument( \"-aanderaa\", \"--aanderaa\", action=\"store_true\", help=\"aanderaa optode with Molar output\",",
"O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], temperature=ncdata[\"T_20\"][:, 0, 0, 0],",
"\"Development\" __keywords__ = \"O2\", \"salinity correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser = argparse.ArgumentParser( description=\"Correct Oxygen",
"args.aanderaa: O2_corr_umkg = O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0],",
"sys.exit(\"Correction not currently valid for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35 nchandle.variables[\"O_65\"][:,",
"not depth\" ) parser.add_argument( \"sourcefile\", metavar=\"sourcefile\", type=str, help=\"complete path to epic file\" )",
"1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35 nchandle.variables[\"O_65\"][:, 0, 0, 0] = O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0, 0,",
"0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.sbe43: sys.exit(\"Correction not currently valid for SBE-43.\")",
"= args.sourcefile df = EcoFOCI_netCDF(ncfile) global_atts = df.get_global_atts() nchandle = df._getnchandle_() vars_dic =",
"vars_dic = df.get_vars() ncdata = df.ncreadfile_dic() O2_corr = O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0, 0, 0],",
"else: print(\"updating history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", global_atts[\"History\"] + \"\\n\" +",
"io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __created__ = datetime.datetime(2016, 11,",
"O2_corr_umkg = O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:],",
"O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if",
"pressure=ncdata[\"depth\"][:], ) if args.sbe43: sys.exit(\"Correction not currently valid for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35",
"sys import os # Science Stack from netCDF4 import Dataset import numpy as",
"values (mmole/l vs umole/kg) Compatibility: ============== python >=3.6 - not tested, unlikely to",
"SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35 nchandle.variables[\"O_65\"][:, 0, 0, 0] = O2_corr_umkg",
"11, 1) __modified__ = datetime.datetime(2016, 11, 1) __version__ = \"0.1.0\" __status__ = \"Development\"",
"in Timeseries using salinity but not depth\" ) parser.add_argument( \"sourcefile\", metavar=\"sourcefile\", type=str, help=\"complete",
"oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.sbe43:",
"as O2_sal_corr from io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __created__",
"__email__ = \"<EMAIL>\" __created__ = datetime.datetime(2016, 11, 1) __modified__ = datetime.datetime(2016, 11, 1)",
"======== 2019-01-03 Put in flag for correcting Aandera optode values vs SBE-43 values",
"pressure=ncdata[\"depth\"][:], ) if args.aanderaa: O2_corr_umkg = O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:,",
"#!/usr/bin/env python \"\"\" NetCDF_O2_corr.py calculate salinity from conductivity. History: ======== 2019-01-03 Put in",
"os.sys.path.insert(1, parent_dir) import calc.aanderaa_corrO2_sal as O2_sal_corr from io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF __author__ = \"<NAME>\"",
"\"\"\" import datetime import argparse import sys import os # Science Stack from",
"= EcoFOCI_netCDF(ncfile) global_atts = df.get_global_atts() nchandle = df._getnchandle_() vars_dic = df.get_vars() ncdata =",
"umole/kg) Compatibility: ============== python >=3.6 - not tested, unlikely to work without updates",
"= argparse.ArgumentParser( description=\"Correct Oxygen in Timeseries using salinity but not depth\" ) parser.add_argument(",
"History: ======== 2019-01-03 Put in flag for correcting Aandera optode values vs SBE-43",
"%Y %H:%M} UTC - {history} \".format( histtime=histtime, history=update ), ) else: print(\"updating history",
"histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", global_atts[\"History\"] + \"\\n\" + \"{histtime:%B %d, %Y %H:%M}",
"Mmkg output\" ) args = parser.parse_args() ncfile = args.sourcefile df = EcoFOCI_netCDF(ncfile) global_atts",
"= \"0.1.0\" __status__ = \"Development\" __keywords__ = \"O2\", \"salinity correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser",
"import argparse import sys import os # Science Stack from netCDF4 import Dataset",
"= \"Oxygen Concentration and Saturation corrected for salinity using {0}\".format( args.sal_source ) if",
"work without updates python 2.7 - Tested and developed for \"\"\" import datetime",
"\"0.1.0\" __status__ = \"Development\" __keywords__ = \"O2\", \"salinity correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser =",
"# Relative User Stack parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir) import calc.aanderaa_corrO2_sal as O2_sal_corr",
"not tested, unlikely to work without updates python 2.7 - Tested and developed",
"attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", \"{histtime:%B %d, %Y %H:%M} UTC - {history}",
"datetime import argparse import sys import os # Science Stack from netCDF4 import",
"O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0, 0, 0] = O2psat_corr update = \"Oxygen Concentration and Saturation",
") args = parser.parse_args() ncfile = args.sourcefile df = EcoFOCI_netCDF(ncfile) global_atts = df.get_global_atts()",
"0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.sbe43: sys.exit(\"Correction not",
"0], pressure=ncdata[\"depth\"][:], ) if args.aanderaa: O2_corr_umkg = O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0],",
"parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir) import calc.aanderaa_corrO2_sal as O2_sal_corr from io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF",
"EcoFOCI_netCDF(ncfile) global_atts = df.get_global_atts() nchandle = df._getnchandle_() vars_dic = df.get_vars() ncdata = df.ncreadfile_dic()",
"parser = argparse.ArgumentParser( description=\"Correct Oxygen in Timeseries using salinity but not depth\" )",
"for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35 nchandle.variables[\"O_65\"][:, 0, 0, 0] =",
"\"<NAME>\" __email__ = \"<EMAIL>\" __created__ = datetime.datetime(2016, 11, 1) __modified__ = datetime.datetime(2016, 11,",
"= datetime.datetime.utcnow() nchandle.setncattr( \"History\", global_atts[\"History\"] + \"\\n\" + \"{histtime:%B %d, %Y %H:%M} UTC",
">=3.6 - not tested, unlikely to work without updates python 2.7 - Tested",
"0, 0], pressure=ncdata[\"depth\"][:], ) if args.aanderaa: O2_corr_umkg = O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0,",
"and Saturation corrected for salinity using {0}\".format( args.sal_source ) if not \"History\" in",
"), ) else: print(\"updating history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", global_atts[\"History\"] +",
"to work without updates python 2.7 - Tested and developed for \"\"\" import",
"0], ) O2psat_corr = O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0,",
"= os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir) import calc.aanderaa_corrO2_sal as O2_sal_corr from io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF __author__",
"not currently valid for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35 nchandle.variables[\"O_65\"][:, 0,",
"type=str, help=\"complete path to epic file\" ) parser.add_argument( \"sal_source\", metavar=\"sal_source\", type=str, help=\"quick description",
"UTC - {history} \".format( histtime=histtime, history=update ), ) else: print(\"updating history attribute\") histtime",
"in flag for correcting Aandera optode values vs SBE-43 values (mmole/l vs umole/kg)",
"0], temperature=ncdata[\"T_20\"][:, 0, 0, 0], ) O2psat_corr = O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0,",
"0, 0], temperature=ncdata[\"T_20\"][:, 0, 0, 0], ) O2psat_corr = O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0,",
"= \"Development\" __keywords__ = \"O2\", \"salinity correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser = argparse.ArgumentParser( description=\"Correct",
"__status__ = \"Development\" __keywords__ = \"O2\", \"salinity correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser = argparse.ArgumentParser(",
"python >=3.6 - not tested, unlikely to work without updates python 2.7 -",
"(mmole/l vs umole/kg) Compatibility: ============== python >=3.6 - not tested, unlikely to work",
"parser.add_argument( \"-sbe43\", \"--sbe43\", action=\"store_true\", help=\"sbe43 optode with Mmkg output\" ) args = parser.parse_args()",
"source of salinity for correction\", ) parser.add_argument( \"-aanderaa\", \"--aanderaa\", action=\"store_true\", help=\"aanderaa optode with",
"netCDF4 import Dataset import numpy as np import seawater as sw # Relative",
"0] = O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0, 0, 0] = O2psat_corr update = \"Oxygen Concentration",
"help=\"sbe43 optode with Mmkg output\" ) args = parser.parse_args() ncfile = args.sourcefile df",
"= O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], temperature=ncdata[\"T_20\"][:, 0, 0,",
"\"--sbe43\", action=\"store_true\", help=\"sbe43 optode with Mmkg output\" ) args = parser.parse_args() ncfile =",
"oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.aanderaa:",
"temperature=ncdata[\"T_20\"][:, 0, 0, 0], ) O2psat_corr = O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0],",
"salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.aanderaa: O2_corr_umkg = O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:,",
"df._getnchandle_() vars_dic = df.get_vars() ncdata = df.ncreadfile_dic() O2_corr = O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0, 0,",
"\"\\n\" + \"{histtime:%B %d, %Y %H:%M} UTC - {history}\".format( histtime=histtime, history=update ), )",
"description of source of salinity for correction\", ) parser.add_argument( \"-aanderaa\", \"--aanderaa\", action=\"store_true\", help=\"aanderaa",
"salinity using {0}\".format( args.sal_source ) if not \"History\" in global_atts.keys(): print(\"adding history attribute\")",
"histtime=histtime, history=update ), ) else: print(\"updating history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\",",
"- Tested and developed for \"\"\" import datetime import argparse import sys import",
"= O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], )",
"# Science Stack from netCDF4 import Dataset import numpy as np import seawater",
"O2psat_corr = O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:],",
"\".format( histtime=histtime, history=update ), ) else: print(\"updating history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr(",
"\"--aanderaa\", action=\"store_true\", help=\"aanderaa optode with Molar output\", ) parser.add_argument( \"-sbe43\", \"--sbe43\", action=\"store_true\", help=\"sbe43",
"\"\"\" NetCDF_O2_corr.py calculate salinity from conductivity. History: ======== 2019-01-03 Put in flag for",
"parser.add_argument( \"sal_source\", metavar=\"sal_source\", type=str, help=\"quick description of source of salinity for correction\", )",
"0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.aanderaa: O2_corr_umkg =",
"import EcoFOCI_netCDF __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __created__ = datetime.datetime(2016, 11, 1)",
"Oxygen in Timeseries using salinity but not depth\" ) parser.add_argument( \"sourcefile\", metavar=\"sourcefile\", type=str,",
"\"History\" in global_atts.keys(): print(\"adding history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", \"{histtime:%B %d,",
"= df._getnchandle_() vars_dic = df.get_vars() ncdata = df.ncreadfile_dic() O2_corr = O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0,",
") if args.sbe43: sys.exit(\"Correction not currently valid for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))]",
"Science Stack from netCDF4 import Dataset import numpy as np import seawater as",
"df.get_vars() ncdata = df.ncreadfile_dic() O2_corr = O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0,",
") if args.aanderaa: O2_corr_umkg = O2_sal_corr.O2_molar2umkg( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0,",
"2.7 - Tested and developed for \"\"\" import datetime import argparse import sys",
"optode with Molar output\", ) parser.add_argument( \"-sbe43\", \"--sbe43\", action=\"store_true\", help=\"sbe43 optode with Mmkg",
"salinity from conductivity. History: ======== 2019-01-03 Put in flag for correcting Aandera optode",
"history=update ), ) else: print(\"updating history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", global_atts[\"History\"]",
"argparse import sys import os # Science Stack from netCDF4 import Dataset import",
"0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.sbe43: sys.exit(\"Correction not currently",
"%d, %Y %H:%M} UTC - {history} \".format( histtime=histtime, history=update ), ) else: print(\"updating",
"output\", ) parser.add_argument( \"-sbe43\", \"--sbe43\", action=\"store_true\", help=\"sbe43 optode with Mmkg output\" ) args",
"global_atts.keys(): print(\"adding history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", \"{histtime:%B %d, %Y %H:%M}",
"0] = O2psat_corr update = \"Oxygen Concentration and Saturation corrected for salinity using",
"ncdata = df.ncreadfile_dic() O2_corr = O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0,",
"conductivity. History: ======== 2019-01-03 Put in flag for correcting Aandera optode values vs",
"\"-aanderaa\", \"--aanderaa\", action=\"store_true\", help=\"aanderaa optode with Molar output\", ) parser.add_argument( \"-sbe43\", \"--sbe43\", action=\"store_true\",",
"metavar=\"sourcefile\", type=str, help=\"complete path to epic file\" ) parser.add_argument( \"sal_source\", metavar=\"sal_source\", type=str, help=\"quick",
"for \"\"\" import datetime import argparse import sys import os # Science Stack",
"from conductivity. History: ======== 2019-01-03 Put in flag for correcting Aandera optode values",
"SBE-43 values (mmole/l vs umole/kg) Compatibility: ============== python >=3.6 - not tested, unlikely",
"============== python >=3.6 - not tested, unlikely to work without updates python 2.7",
"args.sourcefile df = EcoFOCI_netCDF(ncfile) global_atts = df.get_global_atts() nchandle = df._getnchandle_() vars_dic = df.get_vars()",
"0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], temperature=ncdata[\"T_20\"][:, 0, 0, 0], ) O2psat_corr =",
") O2psat_corr = O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0],",
"but not depth\" ) parser.add_argument( \"sourcefile\", metavar=\"sourcefile\", type=str, help=\"complete path to epic file\"",
"= O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], )",
"\"{histtime:%B %d, %Y %H:%M} UTC - {history} \".format( histtime=histtime, history=update ), ) else:",
"file\" ) parser.add_argument( \"sal_source\", metavar=\"sal_source\", type=str, help=\"quick description of source of salinity for",
"\"Oxygen Concentration and Saturation corrected for salinity using {0}\".format( args.sal_source ) if not",
"sw # Relative User Stack parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir) import calc.aanderaa_corrO2_sal as",
"1) __modified__ = datetime.datetime(2016, 11, 1) __version__ = \"0.1.0\" __status__ = \"Development\" __keywords__",
"nchandle = df._getnchandle_() vars_dic = df.get_vars() ncdata = df.ncreadfile_dic() O2_corr = O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:,",
"+ \"\\n\" + \"{histtime:%B %d, %Y %H:%M} UTC - {history}\".format( histtime=histtime, history=update ),",
"update = \"Oxygen Concentration and Saturation corrected for salinity using {0}\".format( args.sal_source )",
"\"sourcefile\", metavar=\"sourcefile\", type=str, help=\"complete path to epic file\" ) parser.add_argument( \"sal_source\", metavar=\"sal_source\", type=str,",
"with Mmkg output\" ) args = parser.parse_args() ncfile = args.sourcefile df = EcoFOCI_netCDF(ncfile)",
"correcting Aandera optode values vs SBE-43 values (mmole/l vs umole/kg) Compatibility: ============== python",
"0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.sbe43: sys.exit(\"Correction not currently valid",
"parser.add_argument( \"sourcefile\", metavar=\"sourcefile\", type=str, help=\"complete path to epic file\" ) parser.add_argument( \"sal_source\", metavar=\"sal_source\",",
"\"sal_source\", metavar=\"sal_source\", type=str, help=\"quick description of source of salinity for correction\", ) parser.add_argument(",
"= O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0, 0, 0] = O2psat_corr update = \"Oxygen Concentration and",
"= 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35 nchandle.variables[\"O_65\"][:, 0, 0, 0] = O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0,",
"O2psat_corr update = \"Oxygen Concentration and Saturation corrected for salinity using {0}\".format( args.sal_source",
"correction\", ) parser.add_argument( \"-aanderaa\", \"--aanderaa\", action=\"store_true\", help=\"aanderaa optode with Molar output\", ) parser.add_argument(",
"import calc.aanderaa_corrO2_sal as O2_sal_corr from io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF __author__ = \"<NAME>\" __email__ =",
") else: print(\"updating history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", global_atts[\"History\"] + \"\\n\"",
"%H:%M} UTC - {history} \".format( histtime=histtime, history=update ), ) else: print(\"updating history attribute\")",
"global_atts = df.get_global_atts() nchandle = df._getnchandle_() vars_dic = df.get_vars() ncdata = df.ncreadfile_dic() O2_corr",
"os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir) import calc.aanderaa_corrO2_sal as O2_sal_corr from io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF __author__ =",
") parser.add_argument( \"sal_source\", metavar=\"sal_source\", type=str, help=\"quick description of source of salinity for correction\",",
"datetime.datetime(2016, 11, 1) __version__ = \"0.1.0\" __status__ = \"Development\" __keywords__ = \"O2\", \"salinity",
"O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if",
"Molar output\", ) parser.add_argument( \"-sbe43\", \"--sbe43\", action=\"store_true\", help=\"sbe43 optode with Mmkg output\" )",
"O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35 nchandle.variables[\"O_65\"][:, 0, 0, 0] = O2_corr_umkg nchandle.variables[\"OST_62\"][:,",
"attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", global_atts[\"History\"] + \"\\n\" + \"{histtime:%B %d, %Y",
"datetime.datetime.utcnow() nchandle.setncattr( \"History\", global_atts[\"History\"] + \"\\n\" + \"{histtime:%B %d, %Y %H:%M} UTC -",
"NetCDF_O2_corr.py calculate salinity from conductivity. History: ======== 2019-01-03 Put in flag for correcting",
"Timeseries using salinity but not depth\" ) parser.add_argument( \"sourcefile\", metavar=\"sourcefile\", type=str, help=\"complete path",
"epic file\" ) parser.add_argument( \"sal_source\", metavar=\"sal_source\", type=str, help=\"quick description of source of salinity",
"salinity but not depth\" ) parser.add_argument( \"sourcefile\", metavar=\"sourcefile\", type=str, help=\"complete path to epic",
"not \"History\" in global_atts.keys(): print(\"adding history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", \"{histtime:%B",
"= datetime.datetime.utcnow() nchandle.setncattr( \"History\", \"{histtime:%B %d, %Y %H:%M} UTC - {history} \".format( histtime=histtime,",
"parser.add_argument( \"-aanderaa\", \"--aanderaa\", action=\"store_true\", help=\"aanderaa optode with Molar output\", ) parser.add_argument( \"-sbe43\", \"--sbe43\",",
"calc.aanderaa_corrO2_sal as O2_sal_corr from io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF __author__ = \"<NAME>\" __email__ = \"<EMAIL>\"",
"df.ncreadfile_dic() O2_corr = O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], temperature=ncdata[\"T_20\"][:,",
"__author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __created__ = datetime.datetime(2016, 11, 1) __modified__ =",
"updates python 2.7 - Tested and developed for \"\"\" import datetime import argparse",
"0, 0, 0] = O2psat_corr update = \"Oxygen Concentration and Saturation corrected for",
"temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0, 0, 0], pressure=ncdata[\"depth\"][:], ) if args.aanderaa: O2_corr_umkg",
"import datetime import argparse import sys import os # Science Stack from netCDF4",
"argparse.ArgumentParser( description=\"Correct Oxygen in Timeseries using salinity but not depth\" ) parser.add_argument( \"sourcefile\",",
"Saturation corrected for salinity using {0}\".format( args.sal_source ) if not \"History\" in global_atts.keys():",
"with Molar output\", ) parser.add_argument( \"-sbe43\", \"--sbe43\", action=\"store_true\", help=\"sbe43 optode with Mmkg output\"",
"of salinity for correction\", ) parser.add_argument( \"-aanderaa\", \"--aanderaa\", action=\"store_true\", help=\"aanderaa optode with Molar",
"- not tested, unlikely to work without updates python 2.7 - Tested and",
"\"O2\", \"salinity correction\" \"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser = argparse.ArgumentParser( description=\"Correct Oxygen in Timeseries using",
"0, 0, 0], ) O2psat_corr = O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:,",
"as sw # Relative User Stack parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(1, parent_dir) import calc.aanderaa_corrO2_sal",
"<reponame>shaunwbell/EcoFOCI_MooringAnalysis #!/usr/bin/env python \"\"\" NetCDF_O2_corr.py calculate salinity from conductivity. History: ======== 2019-01-03 Put",
"import numpy as np import seawater as sw # Relative User Stack parent_dir",
"in global_atts.keys(): print(\"adding history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", \"{histtime:%B %d, %Y",
"using salinity but not depth\" ) parser.add_argument( \"sourcefile\", metavar=\"sourcefile\", type=str, help=\"complete path to",
"tested, unlikely to work without updates python 2.7 - Tested and developed for",
"1) __version__ = \"0.1.0\" __status__ = \"Development\" __keywords__ = \"O2\", \"salinity correction\" \"\"\"-------------------------------",
"0, 0] = O2psat_corr update = \"Oxygen Concentration and Saturation corrected for salinity",
"= parser.parse_args() ncfile = args.sourcefile df = EcoFOCI_netCDF(ncfile) global_atts = df.get_global_atts() nchandle =",
"salinity=ncdata[\"S_41\"][:, 0, 0, 0], temperature=ncdata[\"T_20\"][:, 0, 0, 0], ) O2psat_corr = O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr,",
") parser.add_argument( \"-aanderaa\", \"--aanderaa\", action=\"store_true\", help=\"aanderaa optode with Molar output\", ) parser.add_argument( \"-sbe43\",",
"if not \"History\" in global_atts.keys(): print(\"adding history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\",",
"using {0}\".format( args.sal_source ) if not \"History\" in global_atts.keys(): print(\"adding history attribute\") histtime",
"from netCDF4 import Dataset import numpy as np import seawater as sw #",
"\"\"\"------------------------------- MAIN--------------------------------------------\"\"\" parser = argparse.ArgumentParser( description=\"Correct Oxygen in Timeseries using salinity but not",
"nchandle.setncattr( \"History\", \"{histtime:%B %d, %Y %H:%M} UTC - {history} \".format( histtime=histtime, history=update ),",
"1e35 nchandle.variables[\"O_65\"][:, 0, 0, 0] = O2_corr_umkg nchandle.variables[\"OST_62\"][:, 0, 0, 0] = O2psat_corr",
"help=\"complete path to epic file\" ) parser.add_argument( \"sal_source\", metavar=\"sal_source\", type=str, help=\"quick description of",
"to epic file\" ) parser.add_argument( \"sal_source\", metavar=\"sal_source\", type=str, help=\"quick description of source of",
"{0}\".format( args.sal_source ) if not \"History\" in global_atts.keys(): print(\"adding history attribute\") histtime =",
"Aandera optode values vs SBE-43 values (mmole/l vs umole/kg) Compatibility: ============== python >=3.6",
"output\" ) args = parser.parse_args() ncfile = args.sourcefile df = EcoFOCI_netCDF(ncfile) global_atts =",
"histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", \"{histtime:%B %d, %Y %H:%M} UTC - {history} \".format(",
"vs SBE-43 values (mmole/l vs umole/kg) Compatibility: ============== python >=3.6 - not tested,",
"of source of salinity for correction\", ) parser.add_argument( \"-aanderaa\", \"--aanderaa\", action=\"store_true\", help=\"aanderaa optode",
"print(\"adding history attribute\") histtime = datetime.datetime.utcnow() nchandle.setncattr( \"History\", \"{histtime:%B %d, %Y %H:%M} UTC",
"Put in flag for correcting Aandera optode values vs SBE-43 values (mmole/l vs",
"numpy as np import seawater as sw # Relative User Stack parent_dir =",
"flag for correcting Aandera optode values vs SBE-43 values (mmole/l vs umole/kg) Compatibility:",
"currently valid for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))] = 1e35 O2psat_corr[np.where(np.isnan(O2psat_corr))] = 1e35 nchandle.variables[\"O_65\"][:, 0, 0,",
"df = EcoFOCI_netCDF(ncfile) global_atts = df.get_global_atts() nchandle = df._getnchandle_() vars_dic = df.get_vars() ncdata",
"ncfile = args.sourcefile df = EcoFOCI_netCDF(ncfile) global_atts = df.get_global_atts() nchandle = df._getnchandle_() vars_dic",
"= df.get_vars() ncdata = df.ncreadfile_dic() O2_corr = O2_sal_corr.O2_sal_comp( oxygen_conc=ncdata[\"O_65\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:,",
"global_atts[\"History\"] + \"\\n\" + \"{histtime:%B %d, %Y %H:%M} UTC - {history}\".format( histtime=histtime, history=update",
"df.get_global_atts() nchandle = df._getnchandle_() vars_dic = df.get_vars() ncdata = df.ncreadfile_dic() O2_corr = O2_sal_corr.O2_sal_comp(",
"\"History\", \"{histtime:%B %d, %Y %H:%M} UTC - {history} \".format( histtime=histtime, history=update ), )",
"os # Science Stack from netCDF4 import Dataset import numpy as np import",
"import os # Science Stack from netCDF4 import Dataset import numpy as np",
"from io_utils.EcoFOCI_netCDF_read import EcoFOCI_netCDF __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __created__ = datetime.datetime(2016,",
"Compatibility: ============== python >=3.6 - not tested, unlikely to work without updates python",
"0, 0], pressure=ncdata[\"depth\"][:], ) if args.sbe43: sys.exit(\"Correction not currently valid for SBE-43.\") O2_corr_umkg[np.where(np.isnan(O2_corr_umkg))]",
"+ \"{histtime:%B %d, %Y %H:%M} UTC - {history}\".format( histtime=histtime, history=update ), ) df.close()",
"0, 0], ) O2psat_corr = O2_sal_corr.O2PercentSat( oxygen_conc=O2_corr, temperature=ncdata[\"T_20\"][:, 0, 0, 0], salinity=ncdata[\"S_41\"][:, 0,"
] |
[] |
[
"{ 'gpu_perf': (498.2, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (498.2, -0.05, None,",
"None, 1.05, 's'), }, } elif self.subtest == 'zgemm': self.perf_patterns = { 'magma':",
"modules = ['magma'] maintainers = ['AJ', 'SK'] tags = {'scs', 'production', 'maintenance'} @run_before('compile')",
"self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float ) }",
"'gpu_perf': (254.7, -0.05, None, 'Gflop/s'), }, 'dom:gpu': { 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'),",
"'gpu_perf': sn.extractsingle(r'GPU performance: (\\S+)', self.stdout, 1, float), } self.reference = { 'daint:gpu': {",
"= 'Make' self.build_system.makefile = f'Makefile_{self.subtest}' self.build_system.cxxflags = ['-std=c++11'] self.build_system.ldflags = ['-lcusparse', '-lcublas', '-lmagma',",
"-O0 since with a higher level a # segmentation fault is thrown if",
"'daint:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), },",
"elif self.subtest == 'zunmbr': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout,",
"1.05, 's'), }, 'dom:gpu': { 'duration': (0.10, None, 1.05, 's'), }, } elif",
"class MagmaCheck(rfm.RegressionTest): subtest = parameter(['cblas_z', 'zgemm', 'zsymmetrize', 'ztranspose', 'zunmbr']) valid_systems = ['daint:gpu', 'dom:gpu']",
"== 'cblas_z': self.build_system.cxxflags += ['-O0'] @run_before('run') def set_exec_opts(self): if self.subtest == 'zgemm': self.executable_opts",
"} } elif self.subtest == 'zunmbr': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance:",
"'Make' self.build_system.makefile = f'Makefile_{self.subtest}' self.build_system.cxxflags = ['-std=c++11'] self.build_system.ldflags = ['-lcusparse', '-lcublas', '-lmagma', '-lmagma_sparse']",
"num_gpus_per_node = 1 prebuild_cmds = ['patch < patch.txt'] modules = ['magma'] maintainers =",
"'Gflop/s'), } } elif self.subtest == 'zsymmetrize': self.perf_patterns = { 'gpu_perf': sn.extractsingle(r'GPU performance:",
"}, 'dom:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), } } elif self.subtest ==",
"elif self.subtest == 'zsymmetrize': self.perf_patterns = { 'gpu_perf': sn.extractsingle(r'GPU performance: (\\S+)', self.stdout, 1,",
"valid_prog_environs = ['builtin'] num_gpus_per_node = 1 prebuild_cmds = ['patch < patch.txt'] modules =",
"(158.3, -0.05, None, 'GB/s'), } } elif self.subtest == 'ztranspose': self.perf_patterns = {",
"{ 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'), }, 'dom:gpu': { 'gpu_perf': (254.7, -0.05, None,",
"(CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details.",
"GFlops: (?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops', float, 2) } self.reference = { 'daint:gpu': { 'magma':",
"'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), } } elif self.subtest == 'zsymmetrize': self.perf_patterns",
"None, 'Gflop/s'), } } elif self.subtest == 'zsymmetrize': self.perf_patterns = { 'gpu_perf': sn.extractsingle(r'GPU",
"set_build_system_opts(self): self.build_system = 'Make' self.build_system.makefile = f'Makefile_{self.subtest}' self.build_system.cxxflags = ['-std=c++11'] self.build_system.ldflags = ['-lcusparse',",
"1, float) } self.reference = { 'daint:gpu': { 'duration': (0.10, None, 1.05, 's'),",
"self.perf_patterns = { 'duration': sn.extractsingle(r'Duration: (\\S+)', self.stdout, 1, float) } self.reference = {",
"fault is thrown if self.subtest == 'cblas_z': self.build_system.cxxflags += ['-O0'] @run_before('run') def set_exec_opts(self):",
"f'./testing_{self.subtest}' # FIXME: Compile cblas_z with -O0 since with a higher level a",
"), 'cublas': sn.extractsingle( r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops', float, 2) } self.reference =",
"self.build_system.cxxflags += ['-O0'] @run_before('run') def set_exec_opts(self): if self.subtest == 'zgemm': self.executable_opts = ['--range",
"self.stdout, 1, float) } self.reference = { 'daint:gpu': { 'duration': (0.10, None, 1.05,",
"= ['--range 1088:3136:1024'] @sanity_function def assert_success(self): return sn.assert_found(r'Result = PASS', self.stdout) @run_before('performance') def",
"'maintenance'} @run_before('compile') def set_build_system_opts(self): self.build_system = 'Make' self.build_system.makefile = f'Makefile_{self.subtest}' self.build_system.cxxflags = ['-std=c++11']",
"['-std=c++11'] self.build_system.ldflags = ['-lcusparse', '-lcublas', '-lmagma', '-lmagma_sparse'] self.executable = f'./testing_{self.subtest}' # FIXME: Compile",
"= { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float ) } self.reference",
"level a # segmentation fault is thrown if self.subtest == 'cblas_z': self.build_system.cxxflags +=",
"None, 'GB/s'), } } elif self.subtest == 'zunmbr': self.perf_patterns = { 'gpu_perf': sn.extractsingle(",
"set_performance_patterns(self): if self.subtest == 'cblas_z': self.perf_patterns = { 'duration': sn.extractsingle(r'Duration: (\\S+)', self.stdout, 1,",
"= f'./testing_{self.subtest}' # FIXME: Compile cblas_z with -O0 since with a higher level",
"-0.05, None, 'GB/s'), } } elif self.subtest == 'ztranspose': self.perf_patterns = { 'gpu_perf':",
"return sn.assert_found(r'Result = PASS', self.stdout) @run_before('performance') def set_performance_patterns(self): if self.subtest == 'cblas_z': self.perf_patterns",
"details. # # SPDX-License-Identifier: BSD-3-Clause import reframe as rfm import reframe.utility.sanity as sn",
"None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), }, 'dom:gpu': { 'magma': (3692.65, -0.05,",
"'zunmbr']) valid_systems = ['daint:gpu', 'dom:gpu'] valid_prog_environs = ['builtin'] num_gpus_per_node = 1 prebuild_cmds =",
"['AJ', 'SK'] tags = {'scs', 'production', 'maintenance'} @run_before('compile') def set_build_system_opts(self): self.build_system = 'Make'",
"sn.assert_found(r'Result = PASS', self.stdout) @run_before('performance') def set_performance_patterns(self): if self.subtest == 'cblas_z': self.perf_patterns =",
"2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the",
"@sanity_function def assert_success(self): return sn.assert_found(r'Result = PASS', self.stdout) @run_before('performance') def set_performance_patterns(self): if self.subtest",
"'SK'] tags = {'scs', 'production', 'maintenance'} @run_before('compile') def set_build_system_opts(self): self.build_system = 'Make' self.build_system.makefile",
"self.reference = { 'daint:gpu': { 'duration': (0.10, None, 1.05, 's'), }, 'dom:gpu': {",
"= ['daint:gpu', 'dom:gpu'] valid_prog_environs = ['builtin'] num_gpus_per_node = 1 prebuild_cmds = ['patch <",
"self.subtest == 'cblas_z': self.perf_patterns = { 'duration': sn.extractsingle(r'Duration: (\\S+)', self.stdout, 1, float) }",
"= 1 prebuild_cmds = ['patch < patch.txt'] modules = ['magma'] maintainers = ['AJ',",
"{ 'daint:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'),",
"'cublas': (4269.31, -0.09, None, 'Gflop/s'), } } elif self.subtest == 'zsymmetrize': self.perf_patterns =",
"reframe.utility.sanity as sn @rfm.simple_test class MagmaCheck(rfm.RegressionTest): subtest = parameter(['cblas_z', 'zgemm', 'zsymmetrize', 'ztranspose', 'zunmbr'])",
"'duration': (0.10, None, 1.05, 's'), }, } elif self.subtest == 'zgemm': self.perf_patterns =",
"'cblas_z': self.perf_patterns = { 'duration': sn.extractsingle(r'Duration: (\\S+)', self.stdout, 1, float) } self.reference =",
"'cublas': (4269.31, -0.09, None, 'Gflop/s'), }, 'dom:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'),",
"None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), } } elif self.subtest == 'zsymmetrize':",
"elif self.subtest == 'ztranspose': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout,",
"'gpu_performance', float ) } self.reference = { 'daint:gpu': { 'gpu_perf': (498.2, -0.05, None,",
"} elif self.subtest == 'zgemm': self.perf_patterns = { 'magma': sn.extractsingle( r'MAGMA GFlops: (?P<magma_gflops>\\S+)',",
"# FIXME: Compile cblas_z with -O0 since with a higher level a #",
"cblas_z with -O0 since with a higher level a # segmentation fault is",
"= ['-std=c++11'] self.build_system.ldflags = ['-lcusparse', '-lcublas', '-lmagma', '-lmagma_sparse'] self.executable = f'./testing_{self.subtest}' # FIXME:",
"See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import reframe",
"@run_before('compile') def set_build_system_opts(self): self.build_system = 'Make' self.build_system.makefile = f'Makefile_{self.subtest}' self.build_system.cxxflags = ['-std=c++11'] self.build_system.ldflags",
"1, float), } self.reference = { 'daint:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'),",
"}, 'dom:gpu': { 'duration': (0.10, None, 1.05, 's'), }, } elif self.subtest ==",
"'gpu_performance', float ) } self.reference = { 'daint:gpu': { 'gpu_perf': (254.7, -0.05, None,",
"float), } self.reference = { 'daint:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), },",
") } self.reference = { 'daint:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), },",
"== 'zgemm': self.perf_patterns = { 'magma': sn.extractsingle( r'MAGMA GFlops: (?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops', float,",
"} } elif self.subtest == 'zsymmetrize': self.perf_patterns = { 'gpu_perf': sn.extractsingle(r'GPU performance: (\\S+)',",
"float ) } self.reference = { 'daint:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'),",
"self.subtest == 'zgemm': self.executable_opts = ['--range 1088:3136:1024'] @sanity_function def assert_success(self): return sn.assert_found(r'Result =",
"= ['AJ', 'SK'] tags = {'scs', 'production', 'maintenance'} @run_before('compile') def set_build_system_opts(self): self.build_system =",
"float, 2) } self.reference = { 'daint:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'),",
"1 prebuild_cmds = ['patch < patch.txt'] modules = ['magma'] maintainers = ['AJ', 'SK']",
"-0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), } }",
"# ReFrame Project Developers. See the top-level LICENSE file for details. # #",
"import reframe.utility.sanity as sn @rfm.simple_test class MagmaCheck(rfm.RegressionTest): subtest = parameter(['cblas_z', 'zgemm', 'zsymmetrize', 'ztranspose',",
"MagmaCheck(rfm.RegressionTest): subtest = parameter(['cblas_z', 'zgemm', 'zsymmetrize', 'ztranspose', 'zunmbr']) valid_systems = ['daint:gpu', 'dom:gpu'] valid_prog_environs",
"'-lmagma_sparse'] self.executable = f'./testing_{self.subtest}' # FIXME: Compile cblas_z with -O0 since with a",
"= parameter(['cblas_z', 'zgemm', 'zsymmetrize', 'ztranspose', 'zunmbr']) valid_systems = ['daint:gpu', 'dom:gpu'] valid_prog_environs = ['builtin']",
"{ 'daint:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (498.2,",
"{ 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float ) } self.reference =",
"'magma': sn.extractsingle( r'MAGMA GFlops: (?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops', float, 2 ), 'cublas': sn.extractsingle( r'cuBLAS",
"-0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), }, 'dom:gpu': { 'magma': (3692.65,",
"Compile cblas_z with -O0 since with a higher level a # segmentation fault",
"(\\S+)', self.stdout, 1, float) } self.reference = { 'daint:gpu': { 'duration': (0.10, None,",
"elif self.subtest == 'zgemm': self.perf_patterns = { 'magma': sn.extractsingle( r'MAGMA GFlops: (?P<magma_gflops>\\S+)', self.stdout,",
"'cublas': sn.extractsingle( r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops', float, 2) } self.reference = {",
"{ 'duration': (0.10, None, 1.05, 's'), }, } elif self.subtest == 'zgemm': self.perf_patterns",
"}, 'dom:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), } } elif self.subtest ==",
") } self.reference = { 'daint:gpu': { 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'), },",
"'zgemm', 'zsymmetrize', 'ztranspose', 'zunmbr']) valid_systems = ['daint:gpu', 'dom:gpu'] valid_prog_environs = ['builtin'] num_gpus_per_node =",
"(498.2, -0.05, None, 'GB/s'), } } elif self.subtest == 'zunmbr': self.perf_patterns = {",
"if self.subtest == 'cblas_z': self.perf_patterns = { 'duration': sn.extractsingle(r'Duration: (\\S+)', self.stdout, 1, float)",
"# # SPDX-License-Identifier: BSD-3-Clause import reframe as rfm import reframe.utility.sanity as sn @rfm.simple_test",
"self.reference = { 'daint:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), }, 'dom:gpu': {",
"(\\S+)', self.stdout, 1, float), } self.reference = { 'daint:gpu': { 'gpu_perf': (158.3, -0.05,",
"{ 'daint:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (158.3,",
"= { 'daint:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf':",
"'dom:gpu'] valid_prog_environs = ['builtin'] num_gpus_per_node = 1 prebuild_cmds = ['patch < patch.txt'] modules",
"< patch.txt'] modules = ['magma'] maintainers = ['AJ', 'SK'] tags = {'scs', 'production',",
"@run_before('run') def set_exec_opts(self): if self.subtest == 'zgemm': self.executable_opts = ['--range 1088:3136:1024'] @sanity_function def",
"= ['patch < patch.txt'] modules = ['magma'] maintainers = ['AJ', 'SK'] tags =",
"self.subtest == 'cblas_z': self.build_system.cxxflags += ['-O0'] @run_before('run') def set_exec_opts(self): if self.subtest == 'zgemm':",
"float) } self.reference = { 'daint:gpu': { 'duration': (0.10, None, 1.05, 's'), },",
"(?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops', float, 2) } self.reference = { 'daint:gpu': { 'magma': (3692.65,",
"self.build_system.ldflags = ['-lcusparse', '-lcublas', '-lmagma', '-lmagma_sparse'] self.executable = f'./testing_{self.subtest}' # FIXME: Compile cblas_z",
"'cublas_gflops', float, 2) } self.reference = { 'daint:gpu': { 'magma': (3692.65, -0.05, None,",
"'zgemm': self.perf_patterns = { 'magma': sn.extractsingle( r'MAGMA GFlops: (?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops', float, 2",
"self.executable_opts = ['--range 1088:3136:1024'] @sanity_function def assert_success(self): return sn.assert_found(r'Result = PASS', self.stdout) @run_before('performance')",
"= {'scs', 'production', 'maintenance'} @run_before('compile') def set_build_system_opts(self): self.build_system = 'Make' self.build_system.makefile = f'Makefile_{self.subtest}'",
"'s'), }, 'dom:gpu': { 'duration': (0.10, None, 1.05, 's'), }, } elif self.subtest",
"'zsymmetrize': self.perf_patterns = { 'gpu_perf': sn.extractsingle(r'GPU performance: (\\S+)', self.stdout, 1, float), } self.reference",
"@run_before('performance') def set_performance_patterns(self): if self.subtest == 'cblas_z': self.perf_patterns = { 'duration': sn.extractsingle(r'Duration: (\\S+)',",
"'magma_gflops', float, 2 ), 'cublas': sn.extractsingle( r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops', float, 2)",
"sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float ) } self.reference = { 'daint:gpu':",
"'dom:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), } } elif self.subtest == 'ztranspose':",
"'duration': (0.10, None, 1.05, 's'), }, 'dom:gpu': { 'duration': (0.10, None, 1.05, 's'),",
"'daint:gpu': { 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'), }, 'dom:gpu': { 'gpu_perf': (254.7, -0.05,",
"BSD-3-Clause import reframe as rfm import reframe.utility.sanity as sn @rfm.simple_test class MagmaCheck(rfm.RegressionTest): subtest",
"= { 'daint:gpu': { 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'), }, 'dom:gpu': { 'gpu_perf':",
"def set_exec_opts(self): if self.subtest == 'zgemm': self.executable_opts = ['--range 1088:3136:1024'] @sanity_function def assert_success(self):",
"{ 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), }, 'dom:gpu':",
"'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float ) } self.reference = {",
"'daint:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (498.2, -0.05,",
"} self.reference = { 'daint:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31,",
"= { 'daint:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None,",
"def assert_success(self): return sn.assert_found(r'Result = PASS', self.stdout) @run_before('performance') def set_performance_patterns(self): if self.subtest ==",
"performance: (\\S+)', self.stdout, 1, float), } self.reference = { 'daint:gpu': { 'gpu_perf': (158.3,",
"'gpu_perf': (498.2, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'),",
"parameter(['cblas_z', 'zgemm', 'zsymmetrize', 'ztranspose', 'zunmbr']) valid_systems = ['daint:gpu', 'dom:gpu'] valid_prog_environs = ['builtin'] num_gpus_per_node",
"None, 1.05, 's'), }, 'dom:gpu': { 'duration': (0.10, None, 1.05, 's'), }, }",
"<gh_stars>100-1000 # Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project",
"None, 'GB/s'), } } elif self.subtest == 'ztranspose': self.perf_patterns = { 'gpu_perf': sn.extractsingle(",
"} elif self.subtest == 'zunmbr': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)',",
"PASS', self.stdout) @run_before('performance') def set_performance_patterns(self): if self.subtest == 'cblas_z': self.perf_patterns = { 'duration':",
"{ 'magma': sn.extractsingle( r'MAGMA GFlops: (?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops', float, 2 ), 'cublas': sn.extractsingle(",
"file for details. # # SPDX-License-Identifier: BSD-3-Clause import reframe as rfm import reframe.utility.sanity",
"'s'), }, } elif self.subtest == 'zgemm': self.perf_patterns = { 'magma': sn.extractsingle( r'MAGMA",
"(498.2, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), }",
"a higher level a # segmentation fault is thrown if self.subtest == 'cblas_z':",
"(3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), } } elif self.subtest",
"Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file",
"(?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float ) } self.reference = { 'daint:gpu': { 'gpu_perf': (498.2,",
"-0.09, None, 'Gflop/s'), }, 'dom:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31,",
"Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See",
"with -O0 since with a higher level a # segmentation fault is thrown",
"self.build_system = 'Make' self.build_system.makefile = f'Makefile_{self.subtest}' self.build_system.cxxflags = ['-std=c++11'] self.build_system.ldflags = ['-lcusparse', '-lcublas',",
"} self.reference = { 'daint:gpu': { 'duration': (0.10, None, 1.05, 's'), }, 'dom:gpu':",
"self.stdout) @run_before('performance') def set_performance_patterns(self): if self.subtest == 'cblas_z': self.perf_patterns = { 'duration': sn.extractsingle(r'Duration:",
"(?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float ) } self.reference = { 'daint:gpu': { 'gpu_perf': (254.7,",
"is thrown if self.subtest == 'cblas_z': self.build_system.cxxflags += ['-O0'] @run_before('run') def set_exec_opts(self): if",
"self.executable = f'./testing_{self.subtest}' # FIXME: Compile cblas_z with -O0 since with a higher",
"SPDX-License-Identifier: BSD-3-Clause import reframe as rfm import reframe.utility.sanity as sn @rfm.simple_test class MagmaCheck(rfm.RegressionTest):",
"def set_performance_patterns(self): if self.subtest == 'cblas_z': self.perf_patterns = { 'duration': sn.extractsingle(r'Duration: (\\S+)', self.stdout,",
"'zunmbr': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float )",
"= ['-lcusparse', '-lcublas', '-lmagma', '-lmagma_sparse'] self.executable = f'./testing_{self.subtest}' # FIXME: Compile cblas_z with",
"Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause",
"== 'zunmbr': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float",
"'GB/s'), } } elif self.subtest == 'ztranspose': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU",
"{ 'daint:gpu': { 'duration': (0.10, None, 1.05, 's'), }, 'dom:gpu': { 'duration': (0.10,",
"'-lcublas', '-lmagma', '-lmagma_sparse'] self.executable = f'./testing_{self.subtest}' # FIXME: Compile cblas_z with -O0 since",
"import reframe as rfm import reframe.utility.sanity as sn @rfm.simple_test class MagmaCheck(rfm.RegressionTest): subtest =",
"self.subtest == 'zgemm': self.perf_patterns = { 'magma': sn.extractsingle( r'MAGMA GFlops: (?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops',",
"['-O0'] @run_before('run') def set_exec_opts(self): if self.subtest == 'zgemm': self.executable_opts = ['--range 1088:3136:1024'] @sanity_function",
"LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import reframe as rfm import",
"self.stdout, 'cublas_gflops', float, 2) } self.reference = { 'daint:gpu': { 'magma': (3692.65, -0.05,",
"r'MAGMA GFlops: (?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops', float, 2 ), 'cublas': sn.extractsingle( r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)',",
"['builtin'] num_gpus_per_node = 1 prebuild_cmds = ['patch < patch.txt'] modules = ['magma'] maintainers",
"['--range 1088:3136:1024'] @sanity_function def assert_success(self): return sn.assert_found(r'Result = PASS', self.stdout) @run_before('performance') def set_performance_patterns(self):",
"(0.10, None, 1.05, 's'), }, } elif self.subtest == 'zgemm': self.perf_patterns = {",
"(3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), }, 'dom:gpu': { 'magma':",
"patch.txt'] modules = ['magma'] maintainers = ['AJ', 'SK'] tags = {'scs', 'production', 'maintenance'}",
"'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), }, 'dom:gpu': { 'magma': (3692.65, -0.05, None,",
"performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float ) } self.reference = { 'daint:gpu': { 'gpu_perf':",
"{ 'gpu_perf': sn.extractsingle(r'GPU performance: (\\S+)', self.stdout, 1, float), } self.reference = { 'daint:gpu':",
"'daint:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (158.3, -0.05,",
"'cblas_z': self.build_system.cxxflags += ['-O0'] @run_before('run') def set_exec_opts(self): if self.subtest == 'zgemm': self.executable_opts =",
"with a higher level a # segmentation fault is thrown if self.subtest ==",
"-0.09, None, 'Gflop/s'), } } elif self.subtest == 'zsymmetrize': self.perf_patterns = { 'gpu_perf':",
"sn.extractsingle(r'GPU performance: (\\S+)', self.stdout, 1, float), } self.reference = { 'daint:gpu': { 'gpu_perf':",
"(4269.31, -0.09, None, 'Gflop/s'), } } elif self.subtest == 'zsymmetrize': self.perf_patterns = {",
"{ 'gpu_perf': (158.3, -0.05, None, 'GB/s'), } } elif self.subtest == 'ztranspose': self.perf_patterns",
"National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE",
"'duration': sn.extractsingle(r'Duration: (\\S+)', self.stdout, 1, float) } self.reference = { 'daint:gpu': { 'duration':",
"self.perf_patterns = { 'magma': sn.extractsingle( r'MAGMA GFlops: (?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops', float, 2 ),",
"= { 'duration': sn.extractsingle(r'Duration: (\\S+)', self.stdout, 1, float) } self.reference = { 'daint:gpu':",
"'gpu_perf': (158.3, -0.05, None, 'GB/s'), } } elif self.subtest == 'ztranspose': self.perf_patterns =",
"sn.extractsingle(r'Duration: (\\S+)', self.stdout, 1, float) } self.reference = { 'daint:gpu': { 'duration': (0.10,",
"(0.10, None, 1.05, 's'), }, 'dom:gpu': { 'duration': (0.10, None, 1.05, 's'), },",
"{ 'gpu_perf': (498.2, -0.05, None, 'GB/s'), } } elif self.subtest == 'zunmbr': self.perf_patterns",
"r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float ) } self.reference = { 'daint:gpu': {",
"valid_systems = ['daint:gpu', 'dom:gpu'] valid_prog_environs = ['builtin'] num_gpus_per_node = 1 prebuild_cmds = ['patch",
"ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier:",
"'GB/s'), }, 'dom:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), } } elif self.subtest",
"'-lmagma', '-lmagma_sparse'] self.executable = f'./testing_{self.subtest}' # FIXME: Compile cblas_z with -O0 since with",
"== 'zsymmetrize': self.perf_patterns = { 'gpu_perf': sn.extractsingle(r'GPU performance: (\\S+)', self.stdout, 1, float), }",
"= { 'daint:gpu': { 'duration': (0.10, None, 1.05, 's'), }, 'dom:gpu': { 'duration':",
"prebuild_cmds = ['patch < patch.txt'] modules = ['magma'] maintainers = ['AJ', 'SK'] tags",
"a # segmentation fault is thrown if self.subtest == 'cblas_z': self.build_system.cxxflags += ['-O0']",
"@rfm.simple_test class MagmaCheck(rfm.RegressionTest): subtest = parameter(['cblas_z', 'zgemm', 'zsymmetrize', 'ztranspose', 'zunmbr']) valid_systems = ['daint:gpu',",
"} self.reference = { 'daint:gpu': { 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'), }, 'dom:gpu':",
"GFlops: (?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops', float, 2 ), 'cublas': sn.extractsingle( r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)', self.stdout,",
"== 'zgemm': self.executable_opts = ['--range 1088:3136:1024'] @sanity_function def assert_success(self): return sn.assert_found(r'Result = PASS',",
"'ztranspose': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float )",
"(?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops', float, 2 ), 'cublas': sn.extractsingle( r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops',",
"}, 'dom:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'),",
"sn.extractsingle( r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops', float, 2) } self.reference = { 'daint:gpu':",
"for details. # # SPDX-License-Identifier: BSD-3-Clause import reframe as rfm import reframe.utility.sanity as",
"# SPDX-License-Identifier: BSD-3-Clause import reframe as rfm import reframe.utility.sanity as sn @rfm.simple_test class",
"reframe as rfm import reframe.utility.sanity as sn @rfm.simple_test class MagmaCheck(rfm.RegressionTest): subtest = parameter(['cblas_z',",
"self.reference = { 'daint:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09,",
"(254.7, -0.05, None, 'Gflop/s'), }, 'dom:gpu': { 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'), }",
"'ztranspose', 'zunmbr']) valid_systems = ['daint:gpu', 'dom:gpu'] valid_prog_environs = ['builtin'] num_gpus_per_node = 1 prebuild_cmds",
"Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import",
"Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level",
"self.stdout, 'magma_gflops', float, 2 ), 'cublas': sn.extractsingle( r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops', float,",
"'gpu_perf': (498.2, -0.05, None, 'GB/s'), } } elif self.subtest == 'zunmbr': self.perf_patterns =",
"self.build_system.cxxflags = ['-std=c++11'] self.build_system.ldflags = ['-lcusparse', '-lcublas', '-lmagma', '-lmagma_sparse'] self.executable = f'./testing_{self.subtest}' #",
"= ['magma'] maintainers = ['AJ', 'SK'] tags = {'scs', 'production', 'maintenance'} @run_before('compile') def",
"['magma'] maintainers = ['AJ', 'SK'] tags = {'scs', 'production', 'maintenance'} @run_before('compile') def set_build_system_opts(self):",
"'dom:gpu': { 'duration': (0.10, None, 1.05, 's'), }, } elif self.subtest == 'zgemm':",
"{ 'daint:gpu': { 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'), }, 'dom:gpu': { 'gpu_perf': (254.7,",
"'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), } } elif",
"= { 'daint:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf':",
"= ['builtin'] num_gpus_per_node = 1 prebuild_cmds = ['patch < patch.txt'] modules = ['magma']",
"'Gflop/s'), }, 'dom:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None,",
"self.perf_patterns = { 'gpu_perf': sn.extractsingle(r'GPU performance: (\\S+)', self.stdout, 1, float), } self.reference =",
"sn @rfm.simple_test class MagmaCheck(rfm.RegressionTest): subtest = parameter(['cblas_z', 'zgemm', 'zsymmetrize', 'ztranspose', 'zunmbr']) valid_systems =",
"-0.05, None, 'GB/s'), } } elif self.subtest == 'zunmbr': self.perf_patterns = { 'gpu_perf':",
"as sn @rfm.simple_test class MagmaCheck(rfm.RegressionTest): subtest = parameter(['cblas_z', 'zgemm', 'zsymmetrize', 'ztranspose', 'zunmbr']) valid_systems",
"-0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), } } elif self.subtest ==",
"self.build_system.makefile = f'Makefile_{self.subtest}' self.build_system.cxxflags = ['-std=c++11'] self.build_system.ldflags = ['-lcusparse', '-lcublas', '-lmagma', '-lmagma_sparse'] self.executable",
"None, 'Gflop/s'), }, 'dom:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09,",
"-0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), } }",
"} } elif self.subtest == 'ztranspose': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance:",
"{ 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), } }",
"def set_build_system_opts(self): self.build_system = 'Make' self.build_system.makefile = f'Makefile_{self.subtest}' self.build_system.cxxflags = ['-std=c++11'] self.build_system.ldflags =",
"== 'cblas_z': self.perf_patterns = { 'duration': sn.extractsingle(r'Duration: (\\S+)', self.stdout, 1, float) } self.reference",
"self.stdout, 'gpu_performance', float ) } self.reference = { 'daint:gpu': { 'gpu_perf': (498.2, -0.05,",
"None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), } } elif",
"maintainers = ['AJ', 'SK'] tags = {'scs', 'production', 'maintenance'} @run_before('compile') def set_build_system_opts(self): self.build_system",
"'daint:gpu': { 'duration': (0.10, None, 1.05, 's'), }, 'dom:gpu': { 'duration': (0.10, None,",
"== 'ztranspose': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance', float",
"['patch < patch.txt'] modules = ['magma'] maintainers = ['AJ', 'SK'] tags = {'scs',",
"higher level a # segmentation fault is thrown if self.subtest == 'cblas_z': self.build_system.cxxflags",
"Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for",
"+= ['-O0'] @run_before('run') def set_exec_opts(self): if self.subtest == 'zgemm': self.executable_opts = ['--range 1088:3136:1024']",
"Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. #",
"None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), } } elif",
"'dom:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), } } elif self.subtest == 'zunmbr':",
"FIXME: Compile cblas_z with -O0 since with a higher level a # segmentation",
"{ 'duration': sn.extractsingle(r'Duration: (\\S+)', self.stdout, 1, float) } self.reference = { 'daint:gpu': {",
"}, } elif self.subtest == 'zgemm': self.perf_patterns = { 'magma': sn.extractsingle( r'MAGMA GFlops:",
"} self.reference = { 'daint:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), }, 'dom:gpu':",
"float, 2 ), 'cublas': sn.extractsingle( r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops', float, 2) }",
"thrown if self.subtest == 'cblas_z': self.build_system.cxxflags += ['-O0'] @run_before('run') def set_exec_opts(self): if self.subtest",
"(158.3, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), }",
"float ) } self.reference = { 'daint:gpu': { 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'),",
"self.subtest == 'zsymmetrize': self.perf_patterns = { 'gpu_perf': sn.extractsingle(r'GPU performance: (\\S+)', self.stdout, 1, float),",
"(4269.31, -0.09, None, 'Gflop/s'), }, 'dom:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas':",
"['daint:gpu', 'dom:gpu'] valid_prog_environs = ['builtin'] num_gpus_per_node = 1 prebuild_cmds = ['patch < patch.txt']",
"as rfm import reframe.utility.sanity as sn @rfm.simple_test class MagmaCheck(rfm.RegressionTest): subtest = parameter(['cblas_z', 'zgemm',",
"= f'Makefile_{self.subtest}' self.build_system.cxxflags = ['-std=c++11'] self.build_system.ldflags = ['-lcusparse', '-lcublas', '-lmagma', '-lmagma_sparse'] self.executable =",
"the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import reframe as",
"self.reference = { 'daint:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), }, 'dom:gpu': {",
"self.subtest == 'ztranspose': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance',",
"{ 'gpu_perf': (158.3, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (158.3, -0.05, None,",
"} self.reference = { 'daint:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'), }, 'dom:gpu':",
"since with a higher level a # segmentation fault is thrown if self.subtest",
"subtest = parameter(['cblas_z', 'zgemm', 'zsymmetrize', 'ztranspose', 'zunmbr']) valid_systems = ['daint:gpu', 'dom:gpu'] valid_prog_environs =",
"= PASS', self.stdout) @run_before('performance') def set_performance_patterns(self): if self.subtest == 'cblas_z': self.perf_patterns = {",
"1088:3136:1024'] @sanity_function def assert_success(self): return sn.assert_found(r'Result = PASS', self.stdout) @run_before('performance') def set_performance_patterns(self): if",
"self.stdout, 1, float), } self.reference = { 'daint:gpu': { 'gpu_perf': (158.3, -0.05, None,",
"rfm import reframe.utility.sanity as sn @rfm.simple_test class MagmaCheck(rfm.RegressionTest): subtest = parameter(['cblas_z', 'zgemm', 'zsymmetrize',",
"'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), }, 'dom:gpu': {",
"2) } self.reference = { 'daint:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas':",
"segmentation fault is thrown if self.subtest == 'cblas_z': self.build_system.cxxflags += ['-O0'] @run_before('run') def",
"'gpu_perf': (158.3, -0.05, None, 'GB/s'), }, 'dom:gpu': { 'gpu_perf': (158.3, -0.05, None, 'GB/s'),",
"tags = {'scs', 'production', 'maintenance'} @run_before('compile') def set_build_system_opts(self): self.build_system = 'Make' self.build_system.makefile =",
"'GB/s'), }, 'dom:gpu': { 'gpu_perf': (498.2, -0.05, None, 'GB/s'), } } elif self.subtest",
"2 ), 'cublas': sn.extractsingle( r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops', float, 2) } self.reference",
"-0.05, None, 'Gflop/s'), }, 'dom:gpu': { 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'), } }",
"'zsymmetrize', 'ztranspose', 'zunmbr']) valid_systems = ['daint:gpu', 'dom:gpu'] valid_prog_environs = ['builtin'] num_gpus_per_node = 1",
"= { 'magma': sn.extractsingle( r'MAGMA GFlops: (?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops', float, 2 ), 'cublas':",
"if self.subtest == 'cblas_z': self.build_system.cxxflags += ['-O0'] @run_before('run') def set_exec_opts(self): if self.subtest ==",
"} elif self.subtest == 'zsymmetrize': self.perf_patterns = { 'gpu_perf': sn.extractsingle(r'GPU performance: (\\S+)', self.stdout,",
"} elif self.subtest == 'ztranspose': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)',",
"self.subtest == 'zunmbr': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU performance: (?P<gpu_performance>\\S+)', self.stdout, 'gpu_performance',",
"r'cuBLAS GFlops: (?P<cublas_gflops>\\S+)', self.stdout, 'cublas_gflops', float, 2) } self.reference = { 'daint:gpu': {",
"sn.extractsingle( r'MAGMA GFlops: (?P<magma_gflops>\\S+)', self.stdout, 'magma_gflops', float, 2 ), 'cublas': sn.extractsingle( r'cuBLAS GFlops:",
"{'scs', 'production', 'maintenance'} @run_before('compile') def set_build_system_opts(self): self.build_system = 'Make' self.build_system.makefile = f'Makefile_{self.subtest}' self.build_system.cxxflags",
"'dom:gpu': { 'magma': (3692.65, -0.05, None, 'Gflop/s'), 'cublas': (4269.31, -0.09, None, 'Gflop/s'), }",
"'zgemm': self.executable_opts = ['--range 1088:3136:1024'] @sanity_function def assert_success(self): return sn.assert_found(r'Result = PASS', self.stdout)",
"['-lcusparse', '-lcublas', '-lmagma', '-lmagma_sparse'] self.executable = f'./testing_{self.subtest}' # FIXME: Compile cblas_z with -O0",
"if self.subtest == 'zgemm': self.executable_opts = ['--range 1088:3136:1024'] @sanity_function def assert_success(self): return sn.assert_found(r'Result",
"set_exec_opts(self): if self.subtest == 'zgemm': self.executable_opts = ['--range 1088:3136:1024'] @sanity_function def assert_success(self): return",
"{ 'duration': (0.10, None, 1.05, 's'), }, 'dom:gpu': { 'duration': (0.10, None, 1.05,",
"# segmentation fault is thrown if self.subtest == 'cblas_z': self.build_system.cxxflags += ['-O0'] @run_before('run')",
"# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers.",
"f'Makefile_{self.subtest}' self.build_system.cxxflags = ['-std=c++11'] self.build_system.ldflags = ['-lcusparse', '-lcublas', '-lmagma', '-lmagma_sparse'] self.executable = f'./testing_{self.subtest}'",
"= { 'gpu_perf': sn.extractsingle(r'GPU performance: (\\S+)', self.stdout, 1, float), } self.reference = {",
"'GB/s'), } } elif self.subtest == 'zunmbr': self.perf_patterns = { 'gpu_perf': sn.extractsingle( r'GPU",
"assert_success(self): return sn.assert_found(r'Result = PASS', self.stdout) @run_before('performance') def set_performance_patterns(self): if self.subtest == 'cblas_z':",
"self.stdout, 'gpu_performance', float ) } self.reference = { 'daint:gpu': { 'gpu_perf': (254.7, -0.05,",
"1.05, 's'), }, } elif self.subtest == 'zgemm': self.perf_patterns = { 'magma': sn.extractsingle(",
"'production', 'maintenance'} @run_before('compile') def set_build_system_opts(self): self.build_system = 'Make' self.build_system.makefile = f'Makefile_{self.subtest}' self.build_system.cxxflags =",
"top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import reframe as rfm",
"self.reference = { 'daint:gpu': { 'gpu_perf': (254.7, -0.05, None, 'Gflop/s'), }, 'dom:gpu': {"
] |
[
"# normalizing features scaler = MinMaxScaler(feature_range=(0, 1)) train_samples = scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples)",
"from keras.optimizers import Adam from keras.metrics import categorical_crossentropy from keras.utils import to_categorical trainFile",
"keras.metrics import categorical_crossentropy from keras.utils import to_categorical trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\")",
"model.fit(train_samples, train_labels, validation_split=0.1, batch_size=10, epochs=10, shuffle=True, verbose=2) model.save('model.h5') predictions = model.predict(test_samples) print(predictions) np.savetxt('predictions.csv',",
"pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train train_samples = trainFile.drop(columns='condition').to_numpy() train_labels = trainFile['condition'].to_numpy() #",
"import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from",
"one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() # build the model model = Sequential([ Dense(34, input_shape=[34, ], activation='relu'),",
"loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples, train_labels, validation_split=0.1, batch_size=10, epochs=10, shuffle=True, verbose=2) model.save('model.h5') predictions = model.predict(test_samples)",
"1)) train_samples = scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples) # one-hot-encoding labels one_hot_encoder = OneHotEncoder(categories='auto')",
"one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() # build the model model = Sequential([",
"testFile.drop(columns='condition').to_numpy() test_labels = testFile['condition'].to_numpy() # normalizing features scaler = MinMaxScaler(feature_range=(0, 1)) train_samples =",
"from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import OneHotEncoder import keras from keras import",
"labels one_hot_encoder = OneHotEncoder(categories='auto') train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() #",
"metrics=['accuracy']) model.fit(train_samples, train_labels, validation_split=0.1, batch_size=10, epochs=10, shuffle=True, verbose=2) model.save('model.h5') predictions = model.predict(test_samples) print(predictions)",
"= trainFile.drop(columns='condition').to_numpy() train_labels = trainFile['condition'].to_numpy() # test test_samples = testFile.drop(columns='condition').to_numpy() test_labels = testFile['condition'].to_numpy()",
"as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import",
"pd from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import OneHotEncoder import keras from keras",
"keras.layers import Activation from keras.layers.core import Dense from keras.optimizers import Adam from keras.metrics",
"1)).toarray() test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() # build the model model = Sequential([ Dense(34,",
"activation='relu'), Dense(10, activation='relu'), Dense(3, activation='softmax') ]) print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples, train_labels, validation_split=0.1,",
"np import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import OneHotEncoder",
"test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() # build the model model = Sequential([ Dense(34, input_shape=[34,",
"test_samples = testFile.drop(columns='condition').to_numpy() test_labels = testFile['condition'].to_numpy() # normalizing features scaler = MinMaxScaler(feature_range=(0, 1))",
"= OneHotEncoder(categories='auto') train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() # build the",
"from sklearn.preprocessing import OneHotEncoder import keras from keras import backend as K from",
"from keras import backend as K from keras.models import Sequential from keras.layers import",
"import backend as K from keras.models import Sequential from keras.layers import Activation from",
"normalizing features scaler = MinMaxScaler(feature_range=(0, 1)) train_samples = scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples) #",
"model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples, train_labels, validation_split=0.1, batch_size=10, epochs=10, shuffle=True, verbose=2) model.save('model.h5') predictions =",
"= scaler.fit_transform(test_samples) # one-hot-encoding labels one_hot_encoder = OneHotEncoder(categories='auto') train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels",
"Sequential([ Dense(34, input_shape=[34, ], activation='relu'), Dense(20, activation='relu'), Dense(10, activation='relu'), Dense(3, activation='softmax') ]) print(model.summary())",
"categorical_crossentropy from keras.utils import to_categorical trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train",
"build the model model = Sequential([ Dense(34, input_shape=[34, ], activation='relu'), Dense(20, activation='relu'), Dense(10,",
"from keras.models import Sequential from keras.layers import Activation from keras.layers.core import Dense from",
"keras.models import Sequential from keras.layers import Activation from keras.layers.core import Dense from keras.optimizers",
"trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train train_samples = trainFile.drop(columns='condition').to_numpy() train_labels =",
"import OneHotEncoder import keras from keras import backend as K from keras.models import",
"scaler = MinMaxScaler(feature_range=(0, 1)) train_samples = scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples) # one-hot-encoding labels",
"scaler.fit_transform(test_samples) # one-hot-encoding labels one_hot_encoder = OneHotEncoder(categories='auto') train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels =",
"OneHotEncoder import keras from keras import backend as K from keras.models import Sequential",
"keras.optimizers import Adam from keras.metrics import categorical_crossentropy from keras.utils import to_categorical trainFile =",
"keras import backend as K from keras.models import Sequential from keras.layers import Activation",
"= testFile['condition'].to_numpy() # normalizing features scaler = MinMaxScaler(feature_range=(0, 1)) train_samples = scaler.fit_transform(train_samples) test_samples",
"train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() # build the model model",
"keras.layers.core import Dense from keras.optimizers import Adam from keras.metrics import categorical_crossentropy from keras.utils",
"import Dense from keras.optimizers import Adam from keras.metrics import categorical_crossentropy from keras.utils import",
"import keras from keras import backend as K from keras.models import Sequential from",
"= Sequential([ Dense(34, input_shape=[34, ], activation='relu'), Dense(20, activation='relu'), Dense(10, activation='relu'), Dense(3, activation='softmax') ])",
"= testFile.drop(columns='condition').to_numpy() test_labels = testFile['condition'].to_numpy() # normalizing features scaler = MinMaxScaler(feature_range=(0, 1)) train_samples",
"numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing",
"Dense(20, activation='relu'), Dense(10, activation='relu'), Dense(3, activation='softmax') ]) print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples, train_labels,",
"model model = Sequential([ Dense(34, input_shape=[34, ], activation='relu'), Dense(20, activation='relu'), Dense(10, activation='relu'), Dense(3,",
"MinMaxScaler from sklearn.preprocessing import OneHotEncoder import keras from keras import backend as K",
"import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import OneHotEncoder import",
"= trainFile['condition'].to_numpy() # test test_samples = testFile.drop(columns='condition').to_numpy() test_labels = testFile['condition'].to_numpy() # normalizing features",
"# test test_samples = testFile.drop(columns='condition').to_numpy() test_labels = testFile['condition'].to_numpy() # normalizing features scaler =",
"pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train train_samples = trainFile.drop(columns='condition').to_numpy() train_labels = trainFile['condition'].to_numpy() # test test_samples =",
"MinMaxScaler(feature_range=(0, 1)) train_samples = scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples) # one-hot-encoding labels one_hot_encoder =",
"input_shape=[34, ], activation='relu'), Dense(20, activation='relu'), Dense(10, activation='relu'), Dense(3, activation='softmax') ]) print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy',",
"]) print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples, train_labels, validation_split=0.1, batch_size=10, epochs=10, shuffle=True, verbose=2) model.save('model.h5')",
"keras.utils import to_categorical trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train train_samples =",
"scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples) # one-hot-encoding labels one_hot_encoder = OneHotEncoder(categories='auto') train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1,",
"activation='relu'), Dense(3, activation='softmax') ]) print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples, train_labels, validation_split=0.1, batch_size=10, epochs=10,",
"print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples, train_labels, validation_split=0.1, batch_size=10, epochs=10, shuffle=True, verbose=2) model.save('model.h5') predictions",
"Dense(10, activation='relu'), Dense(3, activation='softmax') ]) print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples, train_labels, validation_split=0.1, batch_size=10,",
"pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import OneHotEncoder import keras",
"from keras.layers import Activation from keras.layers.core import Dense from keras.optimizers import Adam from",
"import to_categorical trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train train_samples = trainFile.drop(columns='condition').to_numpy()",
"], activation='relu'), Dense(20, activation='relu'), Dense(10, activation='relu'), Dense(3, activation='softmax') ]) print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy'])",
"from keras.utils import to_categorical trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train train_samples",
"train_samples = trainFile.drop(columns='condition').to_numpy() train_labels = trainFile['condition'].to_numpy() # test test_samples = testFile.drop(columns='condition').to_numpy() test_labels =",
"= MinMaxScaler(feature_range=(0, 1)) train_samples = scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples) # one-hot-encoding labels one_hot_encoder",
"test_labels = testFile['condition'].to_numpy() # normalizing features scaler = MinMaxScaler(feature_range=(0, 1)) train_samples = scaler.fit_transform(train_samples)",
"train_samples = scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples) # one-hot-encoding labels one_hot_encoder = OneHotEncoder(categories='auto') train_labels",
"import Sequential from keras.layers import Activation from keras.layers.core import Dense from keras.optimizers import",
"= scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples) # one-hot-encoding labels one_hot_encoder = OneHotEncoder(categories='auto') train_labels =",
"activation='relu'), Dense(20, activation='relu'), Dense(10, activation='relu'), Dense(3, activation='softmax') ]) print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples,",
"backend as K from keras.models import Sequential from keras.layers import Activation from keras.layers.core",
"activation='softmax') ]) print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples, train_labels, validation_split=0.1, batch_size=10, epochs=10, shuffle=True, verbose=2)",
"K from keras.models import Sequential from keras.layers import Activation from keras.layers.core import Dense",
"= pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train train_samples = trainFile.drop(columns='condition').to_numpy() train_labels = trainFile['condition'].to_numpy()",
"import MinMaxScaler from sklearn.preprocessing import OneHotEncoder import keras from keras import backend as",
"to_categorical trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train train_samples = trainFile.drop(columns='condition').to_numpy() train_labels",
"validation_split=0.1, batch_size=10, epochs=10, shuffle=True, verbose=2) model.save('model.h5') predictions = model.predict(test_samples) print(predictions) np.savetxt('predictions.csv', test_samples, delimiter=\",\")",
"Dense(34, input_shape=[34, ], activation='relu'), Dense(20, activation='relu'), Dense(10, activation='relu'), Dense(3, activation='softmax') ]) print(model.summary()) model.compile(Adam(lr=.0001),",
"Dense from keras.optimizers import Adam from keras.metrics import categorical_crossentropy from keras.utils import to_categorical",
"from keras.layers.core import Dense from keras.optimizers import Adam from keras.metrics import categorical_crossentropy from",
"sklearn.preprocessing import OneHotEncoder import keras from keras import backend as K from keras.models",
"1)).toarray() # build the model model = Sequential([ Dense(34, input_shape=[34, ], activation='relu'), Dense(20,",
"Sequential from keras.layers import Activation from keras.layers.core import Dense from keras.optimizers import Adam",
"one_hot_encoder = OneHotEncoder(categories='auto') train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() # build",
"train train_samples = trainFile.drop(columns='condition').to_numpy() train_labels = trainFile['condition'].to_numpy() # test test_samples = testFile.drop(columns='condition').to_numpy() test_labels",
"the model model = Sequential([ Dense(34, input_shape=[34, ], activation='relu'), Dense(20, activation='relu'), Dense(10, activation='relu'),",
"features scaler = MinMaxScaler(feature_range=(0, 1)) train_samples = scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples) # one-hot-encoding",
"as K from keras.models import Sequential from keras.layers import Activation from keras.layers.core import",
"= one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() # build the model model = Sequential([ Dense(34, input_shape=[34, ],",
"keras from keras import backend as K from keras.models import Sequential from keras.layers",
"test test_samples = testFile.drop(columns='condition').to_numpy() test_labels = testFile['condition'].to_numpy() # normalizing features scaler = MinMaxScaler(feature_range=(0,",
"from keras.metrics import categorical_crossentropy from keras.utils import to_categorical trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile =",
"OneHotEncoder(categories='auto') train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() # build the model",
"= pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train train_samples = trainFile.drop(columns='condition').to_numpy() train_labels = trainFile['condition'].to_numpy() # test test_samples",
"train_labels, validation_split=0.1, batch_size=10, epochs=10, shuffle=True, verbose=2) model.save('model.h5') predictions = model.predict(test_samples) print(predictions) np.savetxt('predictions.csv', test_samples,",
"Adam from keras.metrics import categorical_crossentropy from keras.utils import to_categorical trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile",
"sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import OneHotEncoder import keras from keras import backend",
"# build the model model = Sequential([ Dense(34, input_shape=[34, ], activation='relu'), Dense(20, activation='relu'),",
"import categorical_crossentropy from keras.utils import to_categorical trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\") testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") #",
"train_labels = trainFile['condition'].to_numpy() # test test_samples = testFile.drop(columns='condition').to_numpy() test_labels = testFile['condition'].to_numpy() # normalizing",
"import Activation from keras.layers.core import Dense from keras.optimizers import Adam from keras.metrics import",
"trainFile['condition'].to_numpy() # test test_samples = testFile.drop(columns='condition').to_numpy() test_labels = testFile['condition'].to_numpy() # normalizing features scaler",
"Dense(3, activation='softmax') ]) print(model.summary()) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_samples, train_labels, validation_split=0.1, batch_size=10, epochs=10, shuffle=True,",
"as pd from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import OneHotEncoder import keras from",
"model = Sequential([ Dense(34, input_shape=[34, ], activation='relu'), Dense(20, activation='relu'), Dense(10, activation='relu'), Dense(3, activation='softmax')",
"testFile['condition'].to_numpy() # normalizing features scaler = MinMaxScaler(feature_range=(0, 1)) train_samples = scaler.fit_transform(train_samples) test_samples =",
"testFile = pd.read_csv('./dataset/test.csv').drop(columns=\"datasetId\") # train train_samples = trainFile.drop(columns='condition').to_numpy() train_labels = trainFile['condition'].to_numpy() # test",
"trainFile.drop(columns='condition').to_numpy() train_labels = trainFile['condition'].to_numpy() # test test_samples = testFile.drop(columns='condition').to_numpy() test_labels = testFile['condition'].to_numpy() #",
"one-hot-encoding labels one_hot_encoder = OneHotEncoder(categories='auto') train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray()",
"test_samples = scaler.fit_transform(test_samples) # one-hot-encoding labels one_hot_encoder = OneHotEncoder(categories='auto') train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray()",
"= one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() # build the model model =",
"# one-hot-encoding labels one_hot_encoder = OneHotEncoder(categories='auto') train_labels = one_hot_encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels = one_hot_encoder.fit_transform(test_labels.reshape(-1,",
"Activation from keras.layers.core import Dense from keras.optimizers import Adam from keras.metrics import categorical_crossentropy",
"import Adam from keras.metrics import categorical_crossentropy from keras.utils import to_categorical trainFile = pd.read_csv('./dataset/train.csv').drop(columns=\"datasetId\")",
"# train train_samples = trainFile.drop(columns='condition').to_numpy() train_labels = trainFile['condition'].to_numpy() # test test_samples = testFile.drop(columns='condition').to_numpy()"
] |
[] |
[
"level+1) if not elem.tail or not elem.tail.strip(): elem.tail = j else: if level",
"rad, charge) #Todo: write the products and tss to the mollist reaclist =",
"args['y3'] = '{:.8f}'.format(geom[i][1]) args['z3'] = '{:.8f}'.format(geom[i][2]) at = ET.SubElement(atomarray, 'atom', args) bond_id =",
"level*\" \" j = \"\\n\" + (level-1)*\" \" if len(elem): if not elem.text",
"the U.S. Government retains certain ## ## rights to this software. ## ##",
"addReaction(reaclist, species, index, instance) st = ET.tostring(root,'utf-8') st = minidom.parseString(st) fout = open('test.xml','w')",
"write the products and tss to the mollist reaclist = ET.SubElement(root,'reactionList') #write the",
"= ET.SubElement(molecule, 'atomArray') for i,at in enumerate(atom): args = {'id':'a{}'.format(i+1)} args['elementType'] = at",
"= '{:.8f}'.format(geom[i][1]) args['z3'] = '{:.8f}'.format(geom[i][2]) at = ET.SubElement(atomarray, 'atom', args) bond_id = 1",
"zpe property = ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'}) scalar = ET.SubElement(property, 'scalar', {'units':'cm-1'}).text = str(15.5)",
"1 propertylist = ET.SubElement(molecule, 'propertyList') #add the zpe property = ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'})",
"[0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ] molecule = ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray = ET.SubElement(molecule, 'atomArray') for",
"The contents are covered by the terms of the ## ## BSD 3-clause",
"reaclist = ET.SubElement(root,'reactionList') #write the reactions for index, instance in enumerate(species.reac_inst): addReaction(reaclist, species,",
"args['z3'] = '{:.8f}'.format(geom[i][2]) at = ET.SubElement(atomarray, 'atom', args) bond_id = 1 bondarray =",
"= \"\\n\" + (level-1)*\" \" if len(elem): if not elem.text or not elem.text.strip():",
"] molecule = ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray = ET.SubElement(molecule, 'atomArray') for i,at in",
"ai in atom] charge = 0 addMolecule(mollist, species, atom, natom, rad, charge) #Todo:",
"or not elem.tail.strip()): elem.tail = j return elem species = 'a' barriers =",
"rad = [0 for ai in atom] charge = 0 addMolecule(mollist, species, atom,",
"= [ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ] molecule",
"elem.text.strip(): elem.text = i + \" \" if not elem.tail or not elem.tail.strip():",
"import xml.etree.cElementTree as ET import xml.dom.minidom as minidom import random def write_mesmer_input(species,barriers,products): root",
"## ## ## ################################################### import os,sys import xml.etree.cElementTree as ET import xml.dom.minidom as",
"ET import xml.dom.minidom as minidom import random def write_mesmer_input(species,barriers,products): root = ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema',",
"def addReaction(reaclist, species, index, instance): a = 1 def addMolecule(mollist,mol, atom, natom, rad,",
"ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray = ET.SubElement(molecule, 'atomArray') for i,at in enumerate(atom): args =",
"Technology & ## ## Engineering Solutions of Sandia, LLC (NTESS). ## ## Under",
"index, instance): a = 1 def addMolecule(mollist,mol, atom, natom, rad, charge): geom =",
"of Contract DE-NA0003525 with ## ## NTESS, the U.S. Government retains certain ##",
"addMolecule(mollist, species, atom, natom, rad, charge) #Todo: write the products and tss to",
"i,at in enumerate(atom): args = {'id':'a{}'.format(i+1)} args['elementType'] = at args['x3'] = '{:.8f}'.format(geom[i][0]) args['y3']",
"species, atom, natom, rad, charge) #Todo: write the products and tss to the",
"at = ET.SubElement(atomarray, 'atom', args) bond_id = 1 bondarray = ET.SubElement(molecule, 'bondArray') for",
"random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond = [ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0],",
"as minidom import random def write_mesmer_input(species,barriers,products): root = ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title",
"xml.dom.minidom as minidom import random def write_mesmer_input(species,barriers,products): root = ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'})",
"scalar = ET.SubElement(property, 'scalar', {'units':'cm-1'}).text = str(15.5) def indent(elem, level=0): i = \"\\n\"",
"= ET.SubElement(molecule, 'bondArray') for i in range(len(atom)-1): for j in range(i+1,len(atom)): if bond[i][j]",
"rad, charge): geom = [] for i,at in enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond",
"args['order']=\"{}\".format(bond[i][j]) b = ET.SubElement(bondarray,'bond',args) bond_id += 1 propertylist = ET.SubElement(molecule, 'propertyList') #add the",
"ET.SubElement(bondarray,'bond',args) bond_id += 1 propertylist = ET.SubElement(molecule, 'propertyList') #add the zpe property =",
"+ level*\" \" j = \"\\n\" + (level-1)*\" \" if len(elem): if not",
"elem.tail = j return elem species = 'a' barriers = ['b1','b2'] products =",
"bondarray = ET.SubElement(molecule, 'bondArray') for i in range(len(atom)-1): for j in range(i+1,len(atom)): if",
"code v2.0 ## ## ## ## The contents are covered by the terms",
"for index, instance in enumerate(species.reac_inst): addReaction(reaclist, species, index, instance) st = ET.tostring(root,'utf-8') st",
"= \"\\n\" + level*\" \" j = \"\\n\" + (level-1)*\" \" if len(elem):",
"j = \"\\n\" + (level-1)*\" \" if len(elem): if not elem.text or not",
"'property', {'dictRef':'me:ZPE'}) scalar = ET.SubElement(property, 'scalar', {'units':'cm-1'}).text = str(15.5) def indent(elem, level=0): i",
"1 bondarray = ET.SubElement(molecule, 'bondArray') for i in range(len(atom)-1): for j in range(i+1,len(atom)):",
"'propertyList') #add the zpe property = ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'}) scalar = ET.SubElement(property, 'scalar',",
"minidom.parseString(st) fout = open('test.xml','w') fout.write(st.toprettyxml(indent = ' ')) fout.close() #write st.toprettyxml(indent = '",
"= str(15.5) def indent(elem, level=0): i = \"\\n\" + level*\" \" j =",
"& ## ## Engineering Solutions of Sandia, LLC (NTESS). ## ## Under the",
"by the terms of the ## ## BSD 3-clause license included in the",
"the terms of Contract DE-NA0003525 with ## ## NTESS, the U.S. Government retains",
"species, index, instance) st = ET.tostring(root,'utf-8') st = minidom.parseString(st) fout = open('test.xml','w') fout.write(st.toprettyxml(indent",
"the ## ## BSD 3-clause license included in the LICENSE ## ## file,",
"to the mollist reaclist = ET.SubElement(root,'reactionList') #write the reactions for index, instance in",
"in enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond = [ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0],",
"i = \"\\n\" + level*\" \" j = \"\\n\" + (level-1)*\" \" if",
"enumerate(species.reac_inst): addReaction(reaclist, species, index, instance) st = ET.tostring(root,'utf-8') st = minidom.parseString(st) fout =",
"args) bond_id = 1 bondarray = ET.SubElement(molecule, 'bondArray') for i in range(len(atom)-1): for",
"instance): a = 1 def addMolecule(mollist,mol, atom, natom, rad, charge): geom = []",
"## ## This file is part of the KinBot code v2.0 ## ##",
"= ' ')) fout.close() #write st.toprettyxml(indent = ' ') #tree.write('test.xml', encoding='utf-8',xml_declaration=True) def addReaction(reaclist,",
"atom, natom, rad, charge): geom = [] for i,at in enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.),",
"args = {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b = ET.SubElement(bondarray,'bond',args) bond_id += 1 propertylist",
"')) fout.close() #write st.toprettyxml(indent = ' ') #tree.write('test.xml', encoding='utf-8',xml_declaration=True) def addReaction(reaclist, species, index,",
"\" j = \"\\n\" + (level-1)*\" \" if len(elem): if not elem.text or",
"if not elem.text or not elem.text.strip(): elem.text = i + \" \" if",
"= ET.SubElement(root,'moleculeList') #write the initial species atom = ['C','C','C','H','H','H','H','H','H'] natom = len(atom) rad",
"Government retains certain ## ## rights to this software. ## ## ## ##",
"[2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ] molecule = ET.SubElement(mollist, 'molecule',",
"charge) #Todo: write the products and tss to the mollist reaclist = ET.SubElement(root,'reactionList')",
"<NAME> ## ## ## ################################################### import os,sys import xml.etree.cElementTree as ET import xml.dom.minidom",
"Authors: ## ## <NAME> ## ## <NAME> ## ## ## ################################################### import os,sys",
"range(len(atom)-1): for j in range(i+1,len(atom)): if bond[i][j] > 0: args = {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{}",
"mollist reaclist = ET.SubElement(root,'reactionList') #write the reactions for index, instance in enumerate(species.reac_inst): addReaction(reaclist,",
"the mollist reaclist = ET.SubElement(root,'reactionList') #write the reactions for index, instance in enumerate(species.reac_inst):",
"[ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ] molecule =",
"j in range(i+1,len(atom)): if bond[i][j] > 0: args = {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j])",
"## ## ## This file is part of the KinBot code v2.0 ##",
"in enumerate(atom): args = {'id':'a{}'.format(i+1)} args['elementType'] = at args['x3'] = '{:.8f}'.format(geom[i][0]) args['y3'] =",
"= ['C','C','C','H','H','H','H','H','H'] natom = len(atom) rad = [0 for ai in atom] charge",
"args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b = ET.SubElement(bondarray,'bond',args) bond_id += 1 propertylist = ET.SubElement(molecule, 'propertyList')",
"if not elem.tail or not elem.tail.strip(): elem.tail = j else: if level and",
"not elem.tail.strip(): elem.tail = i for subelem in elem: indent(subelem, level+1) if not",
"species, index, instance): a = 1 def addMolecule(mollist,mol, atom, natom, rad, charge): geom",
"3-clause license included in the LICENSE ## ## file, found at the root.",
"################################################### ## ## ## This file is part of the KinBot code v2.0",
"## ## Authors: ## ## <NAME> ## ## <NAME> ## ## ## ###################################################",
"elem.tail = i for subelem in elem: indent(subelem, level+1) if not elem.tail or",
"= ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray = ET.SubElement(molecule, 'atomArray') for i,at in enumerate(atom): args",
"= j else: if level and (not elem.tail or not elem.tail.strip()): elem.tail =",
"> 0: args = {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b = ET.SubElement(bondarray,'bond',args) bond_id +=",
"= 'species.chemid' mollist = ET.SubElement(root,'moleculeList') #write the initial species atom = ['C','C','C','H','H','H','H','H','H'] natom",
"+ \" \" if not elem.tail or not elem.tail.strip(): elem.tail = i for",
"the terms of the ## ## BSD 3-clause license included in the LICENSE",
"natom, rad, charge) #Todo: write the products and tss to the mollist reaclist",
"propertylist = ET.SubElement(molecule, 'propertyList') #add the zpe property = ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'}) scalar",
"in atom] charge = 0 addMolecule(mollist, species, atom, natom, rad, charge) #Todo: write",
"#write the reactions for index, instance in enumerate(species.reac_inst): addReaction(reaclist, species, index, instance) st",
"index, instance) st = ET.tostring(root,'utf-8') st = minidom.parseString(st) fout = open('test.xml','w') fout.write(st.toprettyxml(indent =",
"the reactions for index, instance in enumerate(species.reac_inst): addReaction(reaclist, species, index, instance) st =",
"or not elem.text.strip(): elem.text = i + \" \" if not elem.tail or",
"LICENSE ## ## file, found at the root. ## ## ## ## Copyright",
"################################################### import os,sys import xml.etree.cElementTree as ET import xml.dom.minidom as minidom import random",
"'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title = ET.SubElement(root,'me:title').text = 'species.chemid' mollist = ET.SubElement(root,'moleculeList') #write the initial species",
"'atom', args) bond_id = 1 bondarray = ET.SubElement(molecule, 'bondArray') for i in range(len(atom)-1):",
"range(i+1,len(atom)): if bond[i][j] > 0: args = {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b =",
"## Under the terms of Contract DE-NA0003525 with ## ## NTESS, the U.S.",
"Copyright 2018 National Technology & ## ## Engineering Solutions of Sandia, LLC (NTESS).",
"[0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ] molecule = ET.SubElement(mollist,",
"args['elementType'] = at args['x3'] = '{:.8f}'.format(geom[i][0]) args['y3'] = '{:.8f}'.format(geom[i][1]) args['z3'] = '{:.8f}'.format(geom[i][2]) at",
"ET.SubElement(molecule, 'atomArray') for i,at in enumerate(atom): args = {'id':'a{}'.format(i+1)} args['elementType'] = at args['x3']",
"i,at in enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond = [ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0],",
"a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b = ET.SubElement(bondarray,'bond',args) bond_id += 1 propertylist = ET.SubElement(molecule, 'propertyList') #add",
"## ## ## ## The contents are covered by the terms of the",
"level and (not elem.tail or not elem.tail.strip()): elem.tail = j return elem species",
"are covered by the terms of the ## ## BSD 3-clause license included",
"xml.etree.cElementTree as ET import xml.dom.minidom as minidom import random def write_mesmer_input(species,barriers,products): root =",
"= ' ') #tree.write('test.xml', encoding='utf-8',xml_declaration=True) def addReaction(reaclist, species, index, instance): a = 1",
"with ## ## NTESS, the U.S. Government retains certain ## ## rights to",
"0 addMolecule(mollist, species, atom, natom, rad, charge) #Todo: write the products and tss",
"instance) st = ET.tostring(root,'utf-8') st = minidom.parseString(st) fout = open('test.xml','w') fout.write(st.toprettyxml(indent = '",
"(level-1)*\" \" if len(elem): if not elem.text or not elem.text.strip(): elem.text = i",
"## ## ## Authors: ## ## <NAME> ## ## <NAME> ## ## ##",
"not elem.text.strip(): elem.text = i + \" \" if not elem.tail or not",
"in elem: indent(subelem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = j",
"Contract DE-NA0003525 with ## ## NTESS, the U.S. Government retains certain ## ##",
"instance in enumerate(species.reac_inst): addReaction(reaclist, species, index, instance) st = ET.tostring(root,'utf-8') st = minidom.parseString(st)",
"included in the LICENSE ## ## file, found at the root. ## ##",
"## BSD 3-clause license included in the LICENSE ## ## file, found at",
"KinBot code v2.0 ## ## ## ## The contents are covered by the",
"') #tree.write('test.xml', encoding='utf-8',xml_declaration=True) def addReaction(reaclist, species, index, instance): a = 1 def addMolecule(mollist,mol,",
"fout.close() #write st.toprettyxml(indent = ' ') #tree.write('test.xml', encoding='utf-8',xml_declaration=True) def addReaction(reaclist, species, index, instance):",
"encoding='utf-8',xml_declaration=True) def addReaction(reaclist, species, index, instance): a = 1 def addMolecule(mollist,mol, atom, natom,",
"geom = [] for i,at in enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond = [",
"ET.SubElement(property, 'scalar', {'units':'cm-1'}).text = str(15.5) def indent(elem, level=0): i = \"\\n\" + level*\"",
"not elem.text or not elem.text.strip(): elem.text = i + \" \" if not",
"st.toprettyxml(indent = ' ') #tree.write('test.xml', encoding='utf-8',xml_declaration=True) def addReaction(reaclist, species, index, instance): a =",
"{'units':'cm-1'}).text = str(15.5) def indent(elem, level=0): i = \"\\n\" + level*\" \" j",
"{'dictRef':'me:ZPE'}) scalar = ET.SubElement(property, 'scalar', {'units':'cm-1'}).text = str(15.5) def indent(elem, level=0): i =",
"of the KinBot code v2.0 ## ## ## ## The contents are covered",
"= ET.SubElement(bondarray,'bond',args) bond_id += 1 propertylist = ET.SubElement(molecule, 'propertyList') #add the zpe property",
"Sandia, LLC (NTESS). ## ## Under the terms of Contract DE-NA0003525 with ##",
"bond_id = 1 bondarray = ET.SubElement(molecule, 'bondArray') for i in range(len(atom)-1): for j",
"atom = ['C','C','C','H','H','H','H','H','H'] natom = len(atom) rad = [0 for ai in atom]",
"bond[i][j] > 0: args = {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b = ET.SubElement(bondarray,'bond',args) bond_id",
"Engineering Solutions of Sandia, LLC (NTESS). ## ## Under the terms of Contract",
"= ET.SubElement(molecule, 'propertyList') #add the zpe property = ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'}) scalar =",
"+ (level-1)*\" \" if len(elem): if not elem.text or not elem.text.strip(): elem.text =",
"fout.write(st.toprettyxml(indent = ' ')) fout.close() #write st.toprettyxml(indent = ' ') #tree.write('test.xml', encoding='utf-8',xml_declaration=True) def",
"## ## Copyright 2018 National Technology & ## ## Engineering Solutions of Sandia,",
"elem.tail or not elem.tail.strip()): elem.tail = j return elem species = 'a' barriers",
"i for subelem in elem: indent(subelem, level+1) if not elem.tail or not elem.tail.strip():",
"rights to this software. ## ## ## ## Authors: ## ## <NAME> ##",
"= at args['x3'] = '{:.8f}'.format(geom[i][0]) args['y3'] = '{:.8f}'.format(geom[i][1]) args['z3'] = '{:.8f}'.format(geom[i][2]) at =",
"'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray = ET.SubElement(molecule, 'atomArray') for i,at in enumerate(atom): args = {'id':'a{}'.format(i+1)}",
"elem.text = i + \" \" if not elem.tail or not elem.tail.strip(): elem.tail",
"natom = len(atom) rad = [0 for ai in atom] charge = 0",
"## file, found at the root. ## ## ## ## Copyright 2018 National",
"for i,at in enumerate(atom): args = {'id':'a{}'.format(i+1)} args['elementType'] = at args['x3'] = '{:.8f}'.format(geom[i][0])",
"write_mesmer_input(species,barriers,products): root = ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title = ET.SubElement(root,'me:title').text = 'species.chemid' mollist",
"covered by the terms of the ## ## BSD 3-clause license included in",
"[0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ] molecule = ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray = ET.SubElement(molecule, 'atomArray')",
"title = ET.SubElement(root,'me:title').text = 'species.chemid' mollist = ET.SubElement(root,'moleculeList') #write the initial species atom",
"atomarray = ET.SubElement(molecule, 'atomArray') for i,at in enumerate(atom): args = {'id':'a{}'.format(i+1)} args['elementType'] =",
"args = {'id':'a{}'.format(i+1)} args['elementType'] = at args['x3'] = '{:.8f}'.format(geom[i][0]) args['y3'] = '{:.8f}'.format(geom[i][1]) args['z3']",
"Solutions of Sandia, LLC (NTESS). ## ## Under the terms of Contract DE-NA0003525",
"[0 for ai in atom] charge = 0 addMolecule(mollist, species, atom, natom, rad,",
"= minidom.parseString(st) fout = open('test.xml','w') fout.write(st.toprettyxml(indent = ' ')) fout.close() #write st.toprettyxml(indent =",
"indent(elem, level=0): i = \"\\n\" + level*\" \" j = \"\\n\" + (level-1)*\"",
"[0,0,1,0,0,0,0,0,0] ] molecule = ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray = ET.SubElement(molecule, 'atomArray') for i,at",
"atom, natom, rad, charge) #Todo: write the products and tss to the mollist",
"ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title = ET.SubElement(root,'me:title').text = 'species.chemid' mollist = ET.SubElement(root,'moleculeList') #write",
"enumerate(atom): args = {'id':'a{}'.format(i+1)} args['elementType'] = at args['x3'] = '{:.8f}'.format(geom[i][0]) args['y3'] = '{:.8f}'.format(geom[i][1])",
"the zpe property = ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'}) scalar = ET.SubElement(property, 'scalar', {'units':'cm-1'}).text =",
"ET.SubElement(atomarray, 'atom', args) bond_id = 1 bondarray = ET.SubElement(molecule, 'bondArray') for i in",
"def addMolecule(mollist,mol, atom, natom, rad, charge): geom = [] for i,at in enumerate(atom):",
"## rights to this software. ## ## ## ## Authors: ## ## <NAME>",
"## Engineering Solutions of Sandia, LLC (NTESS). ## ## Under the terms of",
"if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + \"",
"elem.tail or not elem.tail.strip(): elem.tail = i for subelem in elem: indent(subelem, level+1)",
"ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'}) scalar = ET.SubElement(property, 'scalar', {'units':'cm-1'}).text = str(15.5) def indent(elem, level=0):",
"= i for subelem in elem: indent(subelem, level+1) if not elem.tail or not",
"\"\\n\" + level*\" \" j = \"\\n\" + (level-1)*\" \" if len(elem): if",
"1 def addMolecule(mollist,mol, atom, natom, rad, charge): geom = [] for i,at in",
"= '{:.8f}'.format(geom[i][0]) args['y3'] = '{:.8f}'.format(geom[i][1]) args['z3'] = '{:.8f}'.format(geom[i][2]) at = ET.SubElement(atomarray, 'atom', args)",
"ET.SubElement(root,'me:title').text = 'species.chemid' mollist = ET.SubElement(root,'moleculeList') #write the initial species atom = ['C','C','C','H','H','H','H','H','H']",
"## ################################################### import os,sys import xml.etree.cElementTree as ET import xml.dom.minidom as minidom import",
"random.uniform(-3.,3.)]) bond = [ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0]",
"file, found at the root. ## ## ## ## Copyright 2018 National Technology",
"mollist = ET.SubElement(root,'moleculeList') #write the initial species atom = ['C','C','C','H','H','H','H','H','H'] natom = len(atom)",
"or not elem.tail.strip(): elem.tail = i for subelem in elem: indent(subelem, level+1) if",
"terms of the ## ## BSD 3-clause license included in the LICENSE ##",
"ET.SubElement(molecule, 'propertyList') #add the zpe property = ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'}) scalar = ET.SubElement(property,",
"## ## Under the terms of Contract DE-NA0003525 with ## ## NTESS, the",
"= ET.SubElement(root,'reactionList') #write the reactions for index, instance in enumerate(species.reac_inst): addReaction(reaclist, species, index,",
"not elem.tail or not elem.tail.strip(): elem.tail = j else: if level and (not",
"not elem.tail.strip(): elem.tail = j else: if level and (not elem.tail or not",
"elem: indent(subelem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = j else:",
"{'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray = ET.SubElement(molecule, 'atomArray') for i,at in enumerate(atom): args = {'id':'a{}'.format(i+1)} args['elementType']",
"\" \" if not elem.tail or not elem.tail.strip(): elem.tail = i for subelem",
"\" if len(elem): if not elem.text or not elem.text.strip(): elem.text = i +",
"## ## file, found at the root. ## ## ## ## Copyright 2018",
"[] for i,at in enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond = [ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0],",
"elem.tail = j else: if level and (not elem.tail or not elem.tail.strip()): elem.tail",
"(NTESS). ## ## Under the terms of Contract DE-NA0003525 with ## ## NTESS,",
"'scalar', {'units':'cm-1'}).text = str(15.5) def indent(elem, level=0): i = \"\\n\" + level*\" \"",
"len(atom) rad = [0 for ai in atom] charge = 0 addMolecule(mollist, species,",
"'species.chemid' mollist = ET.SubElement(root,'moleculeList') #write the initial species atom = ['C','C','C','H','H','H','H','H','H'] natom =",
"## NTESS, the U.S. Government retains certain ## ## rights to this software.",
"ET.SubElement(root,'moleculeList') #write the initial species atom = ['C','C','C','H','H','H','H','H','H'] natom = len(atom) rad =",
"## ## ################################################### import os,sys import xml.etree.cElementTree as ET import xml.dom.minidom as minidom",
"if bond[i][j] > 0: args = {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b = ET.SubElement(bondarray,'bond',args)",
"'{:.8f}'.format(geom[i][2]) at = ET.SubElement(atomarray, 'atom', args) bond_id = 1 bondarray = ET.SubElement(molecule, 'bondArray')",
"or not elem.tail.strip(): elem.tail = j else: if level and (not elem.tail or",
"## <NAME> ## ## ## ################################################### import os,sys import xml.etree.cElementTree as ET import",
"for ai in atom] charge = 0 addMolecule(mollist, species, atom, natom, rad, charge)",
"NTESS, the U.S. Government retains certain ## ## rights to this software. ##",
"= {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b = ET.SubElement(bondarray,'bond',args) bond_id += 1 propertylist =",
"property = ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'}) scalar = ET.SubElement(property, 'scalar', {'units':'cm-1'}).text = str(15.5) def",
"## This file is part of the KinBot code v2.0 ## ## ##",
"contents are covered by the terms of the ## ## BSD 3-clause license",
"= ET.SubElement(property, 'scalar', {'units':'cm-1'}).text = str(15.5) def indent(elem, level=0): i = \"\\n\" +",
"and tss to the mollist reaclist = ET.SubElement(root,'reactionList') #write the reactions for index,",
"= ET.SubElement(root,'me:title').text = 'species.chemid' mollist = ET.SubElement(root,'moleculeList') #write the initial species atom =",
"in the LICENSE ## ## file, found at the root. ## ## ##",
"[1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ] molecule = ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray",
"addReaction(reaclist, species, index, instance): a = 1 def addMolecule(mollist,mol, atom, natom, rad, charge):",
"os,sys import xml.etree.cElementTree as ET import xml.dom.minidom as minidom import random def write_mesmer_input(species,barriers,products):",
"root. ## ## ## ## Copyright 2018 National Technology & ## ## Engineering",
"{'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b = ET.SubElement(bondarray,'bond',args) bond_id += 1 propertylist = ET.SubElement(molecule,",
"and (not elem.tail or not elem.tail.strip()): elem.tail = j return elem species =",
"certain ## ## rights to this software. ## ## ## ## Authors: ##",
"args['x3'] = '{:.8f}'.format(geom[i][0]) args['y3'] = '{:.8f}'.format(geom[i][1]) args['z3'] = '{:.8f}'.format(geom[i][2]) at = ET.SubElement(atomarray, 'atom',",
"National Technology & ## ## Engineering Solutions of Sandia, LLC (NTESS). ## ##",
"root = ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title = ET.SubElement(root,'me:title').text = 'species.chemid' mollist =",
"[0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ] molecule = ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))})",
"is part of the KinBot code v2.0 ## ## ## ## The contents",
"fout = open('test.xml','w') fout.write(st.toprettyxml(indent = ' ')) fout.close() #write st.toprettyxml(indent = ' ')",
"{'id':'a{}'.format(i+1)} args['elementType'] = at args['x3'] = '{:.8f}'.format(geom[i][0]) args['y3'] = '{:.8f}'.format(geom[i][1]) args['z3'] = '{:.8f}'.format(geom[i][2])",
"bond_id += 1 propertylist = ET.SubElement(molecule, 'propertyList') #add the zpe property = ET.SubElement(propertylist,",
"## <NAME> ## ## <NAME> ## ## ## ################################################### import os,sys import xml.etree.cElementTree",
"natom, rad, charge): geom = [] for i,at in enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)])",
"this software. ## ## ## ## Authors: ## ## <NAME> ## ## <NAME>",
"= [0 for ai in atom] charge = 0 addMolecule(mollist, species, atom, natom,",
"terms of Contract DE-NA0003525 with ## ## NTESS, the U.S. Government retains certain",
"<NAME> ## ## <NAME> ## ## ## ################################################### import os,sys import xml.etree.cElementTree as",
"= '{:.8f}'.format(geom[i][2]) at = ET.SubElement(atomarray, 'atom', args) bond_id = 1 bondarray = ET.SubElement(molecule,",
"i + \" \" if not elem.tail or not elem.tail.strip(): elem.tail = i",
"at the root. ## ## ## ## Copyright 2018 National Technology & ##",
"part of the KinBot code v2.0 ## ## ## ## The contents are",
"= ET.SubElement(atomarray, 'atom', args) bond_id = 1 bondarray = ET.SubElement(molecule, 'bondArray') for i",
"import xml.dom.minidom as minidom import random def write_mesmer_input(species,barriers,products): root = ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer',",
"2018 National Technology & ## ## Engineering Solutions of Sandia, LLC (NTESS). ##",
"## ## The contents are covered by the terms of the ## ##",
"= 1 bondarray = ET.SubElement(molecule, 'bondArray') for i in range(len(atom)-1): for j in",
"for i in range(len(atom)-1): for j in range(i+1,len(atom)): if bond[i][j] > 0: args",
"software. ## ## ## ## Authors: ## ## <NAME> ## ## <NAME> ##",
"ET.tostring(root,'utf-8') st = minidom.parseString(st) fout = open('test.xml','w') fout.write(st.toprettyxml(indent = ' ')) fout.close() #write",
"= 1 def addMolecule(mollist,mol, atom, natom, rad, charge): geom = [] for i,at",
"= ET.tostring(root,'utf-8') st = minidom.parseString(st) fout = open('test.xml','w') fout.write(st.toprettyxml(indent = ' ')) fout.close()",
"in range(i+1,len(atom)): if bond[i][j] > 0: args = {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b",
"+= 1 propertylist = ET.SubElement(molecule, 'propertyList') #add the zpe property = ET.SubElement(propertylist, 'property',",
"as ET import xml.dom.minidom as minidom import random def write_mesmer_input(species,barriers,products): root = ET.Element(",
"addMolecule(mollist,mol, atom, natom, rad, charge): geom = [] for i,at in enumerate(atom): geom.append([random.uniform(-3.,3.),",
"#tree.write('test.xml', encoding='utf-8',xml_declaration=True) def addReaction(reaclist, species, index, instance): a = 1 def addMolecule(mollist,mol, atom,",
"products and tss to the mollist reaclist = ET.SubElement(root,'reactionList') #write the reactions for",
"j else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = j",
"else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = j return",
"str(15.5) def indent(elem, level=0): i = \"\\n\" + level*\" \" j = \"\\n\"",
"## ## <NAME> ## ## ## ################################################### import os,sys import xml.etree.cElementTree as ET",
"## ## ## ## Copyright 2018 National Technology & ## ## Engineering Solutions",
"## Authors: ## ## <NAME> ## ## <NAME> ## ## ## ################################################### import",
"in range(len(atom)-1): for j in range(i+1,len(atom)): if bond[i][j] > 0: args = {'id':'b{}'.format(bond_id)}",
"= {'id':'a{}'.format(i+1)} args['elementType'] = at args['x3'] = '{:.8f}'.format(geom[i][0]) args['y3'] = '{:.8f}'.format(geom[i][1]) args['z3'] =",
"#Todo: write the products and tss to the mollist reaclist = ET.SubElement(root,'reactionList') #write",
"[0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ] molecule = ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray = ET.SubElement(molecule,",
"found at the root. ## ## ## ## Copyright 2018 National Technology &",
"ET.SubElement(molecule, 'bondArray') for i in range(len(atom)-1): for j in range(i+1,len(atom)): if bond[i][j] >",
"not elem.tail.strip()): elem.tail = j return elem species = 'a' barriers = ['b1','b2']",
"U.S. Government retains certain ## ## rights to this software. ## ## ##",
"\" if not elem.tail or not elem.tail.strip(): elem.tail = i for subelem in",
"elem.tail.strip(): elem.tail = j else: if level and (not elem.tail or not elem.tail.strip()):",
"the products and tss to the mollist reaclist = ET.SubElement(root,'reactionList') #write the reactions",
"= [] for i,at in enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond = [ [0,2,0,1,1,0,0,0,0],",
"elem.text or not elem.text.strip(): elem.text = i + \" \" if not elem.tail",
"BSD 3-clause license included in the LICENSE ## ## file, found at the",
"= i + \" \" if not elem.tail or not elem.tail.strip(): elem.tail =",
"retains certain ## ## rights to this software. ## ## ## ## Authors:",
"random def write_mesmer_input(species,barriers,products): root = ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title = ET.SubElement(root,'me:title').text =",
"'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title = ET.SubElement(root,'me:title').text = 'species.chemid' mollist = ET.SubElement(root,'moleculeList') #write the",
"elem.tail.strip()): elem.tail = j return elem species = 'a' barriers = ['b1','b2'] products",
"len(elem): if not elem.text or not elem.text.strip(): elem.text = i + \" \"",
"charge = 0 addMolecule(mollist, species, atom, natom, rad, charge) #Todo: write the products",
"file is part of the KinBot code v2.0 ## ## ## ## The",
"' ')) fout.close() #write st.toprettyxml(indent = ' ') #tree.write('test.xml', encoding='utf-8',xml_declaration=True) def addReaction(reaclist, species,",
"'atomArray') for i,at in enumerate(atom): args = {'id':'a{}'.format(i+1)} args['elementType'] = at args['x3'] =",
"## ## <NAME> ## ## <NAME> ## ## ## ################################################### import os,sys import",
"= 0 addMolecule(mollist, species, atom, natom, rad, charge) #Todo: write the products and",
"LLC (NTESS). ## ## Under the terms of Contract DE-NA0003525 with ## ##",
"'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title = ET.SubElement(root,'me:title').text = 'species.chemid' mollist = ET.SubElement(root,'moleculeList') #write the initial",
"the initial species atom = ['C','C','C','H','H','H','H','H','H'] natom = len(atom) rad = [0 for",
"for subelem in elem: indent(subelem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail",
"not elem.tail or not elem.tail.strip(): elem.tail = i for subelem in elem: indent(subelem,",
"## ## ## Copyright 2018 National Technology & ## ## Engineering Solutions of",
"## ## rights to this software. ## ## ## ## Authors: ## ##",
"## ## ## The contents are covered by the terms of the ##",
"st = minidom.parseString(st) fout = open('test.xml','w') fout.write(st.toprettyxml(indent = ' ')) fout.close() #write st.toprettyxml(indent",
"the KinBot code v2.0 ## ## ## ## The contents are covered by",
"## ## Engineering Solutions of Sandia, LLC (NTESS). ## ## Under the terms",
"#write the initial species atom = ['C','C','C','H','H','H','H','H','H'] natom = len(atom) rad = [0",
"minidom import random def write_mesmer_input(species,barriers,products): root = ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title =",
"of Sandia, LLC (NTESS). ## ## Under the terms of Contract DE-NA0003525 with",
"for j in range(i+1,len(atom)): if bond[i][j] > 0: args = {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1)",
"#add the zpe property = ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'}) scalar = ET.SubElement(property, 'scalar', {'units':'cm-1'}).text",
"## ## ## ## Authors: ## ## <NAME> ## ## <NAME> ## ##",
"DE-NA0003525 with ## ## NTESS, the U.S. Government retains certain ## ## rights",
"molecule = ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray = ET.SubElement(molecule, 'atomArray') for i,at in enumerate(atom):",
"'{:.8f}'.format(geom[i][1]) args['z3'] = '{:.8f}'.format(geom[i][2]) at = ET.SubElement(atomarray, 'atom', args) bond_id = 1 bondarray",
"v2.0 ## ## ## ## The contents are covered by the terms of",
"elem.tail or not elem.tail.strip(): elem.tail = j else: if level and (not elem.tail",
"to this software. ## ## ## ## Authors: ## ## <NAME> ## ##",
"level=0): i = \"\\n\" + level*\" \" j = \"\\n\" + (level-1)*\" \"",
"= len(atom) rad = [0 for ai in atom] charge = 0 addMolecule(mollist,",
"import random def write_mesmer_input(species,barriers,products): root = ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title = ET.SubElement(root,'me:title').text",
"## Copyright 2018 National Technology & ## ## Engineering Solutions of Sandia, LLC",
"= open('test.xml','w') fout.write(st.toprettyxml(indent = ' ')) fout.close() #write st.toprettyxml(indent = ' ') #tree.write('test.xml',",
"index, instance in enumerate(species.reac_inst): addReaction(reaclist, species, index, instance) st = ET.tostring(root,'utf-8') st =",
"elem.tail.strip(): elem.tail = i for subelem in elem: indent(subelem, level+1) if not elem.tail",
"subelem in elem: indent(subelem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail =",
"indent(subelem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = j else: if",
"charge): geom = [] for i,at in enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond =",
"= ET.SubElement(propertylist, 'property', {'dictRef':'me:ZPE'}) scalar = ET.SubElement(property, 'scalar', {'units':'cm-1'}).text = str(15.5) def indent(elem,",
"a = 1 def addMolecule(mollist,mol, atom, natom, rad, charge): geom = [] for",
"atom] charge = 0 addMolecule(mollist, species, atom, natom, rad, charge) #Todo: write the",
"[1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ] molecule = ET.SubElement(mollist, 'molecule', {'id':'species.chemid','spinMultiplicity':'{}'.format(sum(rad))}) atomarray =",
"of the ## ## BSD 3-clause license included in the LICENSE ## ##",
"j return elem species = 'a' barriers = ['b1','b2'] products = [['p1','p2'],['p3']] write_mesmer_input(species,barriers,products)",
"at args['x3'] = '{:.8f}'.format(geom[i][0]) args['y3'] = '{:.8f}'.format(geom[i][1]) args['z3'] = '{:.8f}'.format(geom[i][2]) at = ET.SubElement(atomarray,",
"b = ET.SubElement(bondarray,'bond',args) bond_id += 1 propertylist = ET.SubElement(molecule, 'propertyList') #add the zpe",
"' ') #tree.write('test.xml', encoding='utf-8',xml_declaration=True) def addReaction(reaclist, species, index, instance): a = 1 def",
"This file is part of the KinBot code v2.0 ## ## ## ##",
"import os,sys import xml.etree.cElementTree as ET import xml.dom.minidom as minidom import random def",
"geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond = [ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0],",
"'bondArray') for i in range(len(atom)-1): for j in range(i+1,len(atom)): if bond[i][j] > 0:",
"0: args = {'id':'b{}'.format(bond_id)} args['atomRefs2']=\"a{} a{}\".format(i+1,j+1) args['order']=\"{}\".format(bond[i][j]) b = ET.SubElement(bondarray,'bond',args) bond_id += 1",
"## ## BSD 3-clause license included in the LICENSE ## ## file, found",
"in enumerate(species.reac_inst): addReaction(reaclist, species, index, instance) st = ET.tostring(root,'utf-8') st = minidom.parseString(st) fout",
"= j return elem species = 'a' barriers = ['b1','b2'] products = [['p1','p2'],['p3']]",
"i in range(len(atom)-1): for j in range(i+1,len(atom)): if bond[i][j] > 0: args =",
"if not elem.tail or not elem.tail.strip(): elem.tail = i for subelem in elem:",
"enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond = [ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0],",
"bond = [ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1], [1,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ]",
"the LICENSE ## ## file, found at the root. ## ## ## ##",
"ET.SubElement(root,'reactionList') #write the reactions for index, instance in enumerate(species.reac_inst): addReaction(reaclist, species, index, instance)",
"st = ET.tostring(root,'utf-8') st = minidom.parseString(st) fout = open('test.xml','w') fout.write(st.toprettyxml(indent = ' '))",
"def indent(elem, level=0): i = \"\\n\" + level*\" \" j = \"\\n\" +",
"license included in the LICENSE ## ## file, found at the root. ##",
"if level and (not elem.tail or not elem.tail.strip()): elem.tail = j return elem",
"## ## NTESS, the U.S. Government retains certain ## ## rights to this",
"## The contents are covered by the terms of the ## ## BSD",
"reactions for index, instance in enumerate(species.reac_inst): addReaction(reaclist, species, index, instance) st = ET.tostring(root,'utf-8')",
"tss to the mollist reaclist = ET.SubElement(root,'reactionList') #write the reactions for index, instance",
"the root. ## ## ## ## Copyright 2018 National Technology & ## ##",
"species atom = ['C','C','C','H','H','H','H','H','H'] natom = len(atom) rad = [0 for ai in",
"\"\\n\" + (level-1)*\" \" if len(elem): if not elem.text or not elem.text.strip(): elem.text",
"open('test.xml','w') fout.write(st.toprettyxml(indent = ' ')) fout.close() #write st.toprettyxml(indent = ' ') #tree.write('test.xml', encoding='utf-8',xml_declaration=True)",
"Under the terms of Contract DE-NA0003525 with ## ## NTESS, the U.S. Government",
"#write st.toprettyxml(indent = ' ') #tree.write('test.xml', encoding='utf-8',xml_declaration=True) def addReaction(reaclist, species, index, instance): a",
"for i,at in enumerate(atom): geom.append([random.uniform(-3.,3.), random.uniform(-3.,3.), random.uniform(-3.,3.)]) bond = [ [0,2,0,1,1,0,0,0,0], [2,0,1,0,0,1,0,0,0], [0,1,0,0,0,0,1,1,1],",
"= ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title = ET.SubElement(root,'me:title').text = 'species.chemid' mollist = ET.SubElement(root,'moleculeList')",
"initial species atom = ['C','C','C','H','H','H','H','H','H'] natom = len(atom) rad = [0 for ai",
"['C','C','C','H','H','H','H','H','H'] natom = len(atom) rad = [0 for ai in atom] charge =",
"(not elem.tail or not elem.tail.strip()): elem.tail = j return elem species = 'a'",
"'{:.8f}'.format(geom[i][0]) args['y3'] = '{:.8f}'.format(geom[i][1]) args['z3'] = '{:.8f}'.format(geom[i][2]) at = ET.SubElement(atomarray, 'atom', args) bond_id",
"def write_mesmer_input(species,barriers,products): root = ET.Element( 'me:mesmer',{'xmlns':'http://www.xml-cml.org/schema', 'xmlns:me':'http://www.chem.leeds.ac.uk/mesmer', 'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance'}) title = ET.SubElement(root,'me:title').text = 'species.chemid'"
] |
[
"if is_valid: unsigned_access_list_transaction.validate() else: with pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", ( # While ethereum",
"chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),),",
"validation ), False), (UnsignedAccessListTransaction( chain_id='1', # chain_id fails validation nonce=0, gas_price=0, gas=0, to=b'\\xf0'",
"# While ethereum tests do not yet have Berlin or London transaction tests,",
"access_list=(), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'',",
"# access_list address fails validation ), False), (UnsignedDynamicFeeTransaction( chain_id='1', # chain_id fails validation",
"20, value=0, data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_dynamic_fee_transaction(unsigned_dynamic_fee_transaction, is_valid): if is_valid:",
"gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedAccessListTransaction(",
"ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", ( # While ethereum tests do not yet have Berlin",
"cases. (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0'",
"* 20, value=0, data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if",
"gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ),",
"chain_id='1', # chain_id fails validation nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'',",
"), False), ) ) def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if is_valid: unsigned_access_list_transaction.validate() else: with pytest.raises(ValidationError):",
"(1, 2)),), ), True), (UnsignedDynamicFeeTransaction( chain_id=0, nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0, to=b'\\xf0' * 20,",
"20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedDynamicFeeTransaction( chain_id=0, nonce=0,",
"True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' *",
"transaction tests, # this adds a few tests to test some obvious cases,",
"nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),),",
"access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0'",
"test cases. (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0'",
"False), ) ) def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if is_valid: unsigned_access_list_transaction.validate() else: with pytest.raises(ValidationError): unsigned_access_list_transaction.validate()",
"data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedDynamicFeeTransaction( chain_id=0, nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0,",
"max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False), ) )",
"max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False), ) ) def",
"nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),), #",
"especially positive test cases. (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0,",
"Berlin or London transaction tests, # this adds a few tests to test",
"max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),), # access_list",
"(1,)),), # access_list address fails validation ), False), (UnsignedDynamicFeeTransaction( chain_id='1', # chain_id fails",
"access_list=((b'\\xf0' * 19, (1,)),), # access_list address fails validation ), False), (UnsignedDynamicFeeTransaction( chain_id='1',",
"value=0, data=b'', access_list=(), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20,",
"chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1,",
"nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True), (UnsignedAccessListTransaction( chain_id=123456789,",
"value=0, data=b'', access_list=(), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' *",
"value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000,",
"access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedDynamicFeeTransaction( chain_id=0, nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0,",
"obvious cases, especially positive test cases. (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' *",
"()),), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'',",
"gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False), ) ) def",
"to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),), # access_list address fails",
"chain_id fails validation nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(),",
"access_list=(), ), False), ) ) def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if is_valid: unsigned_access_list_transaction.validate() else: with",
"pytest from eth.vm.forks.london.transactions import UnsignedDynamicFeeTransaction from eth.vm.forks.berlin.transactions import UnsignedAccessListTransaction from eth_utils import ValidationError",
"test cases. (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'',",
"data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_dynamic_fee_transaction(unsigned_dynamic_fee_transaction, is_valid): if is_valid: unsigned_dynamic_fee_transaction.validate() else:",
"London transaction tests, # this adds a few tests to test some obvious",
"), False), ) ) def test_validate_unsigned_dynamic_fee_transaction(unsigned_dynamic_fee_transaction, is_valid): if is_valid: unsigned_dynamic_fee_transaction.validate() else: with pytest.raises(ValidationError):",
"\"unsigned_dynamic_fee_transaction,is_valid\", ( # While ethereum tests do not yet have Berlin or London",
"nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False), )",
"data=b'', access_list=((b'\\xf0' * 19, (1,)),), # access_list address fails validation ), False), (UnsignedDynamicFeeTransaction(",
"* 19, (1,)),), # access_list address fails validation ), False), (UnsignedAccessListTransaction( chain_id='1', #",
"20, ()),), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0,",
"with pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", ( # While ethereum tests do not yet",
"data=b'', access_list=(), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0,",
"(UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20,",
"19, (1,)),), # access_list address fails validation ), False), (UnsignedAccessListTransaction( chain_id='1', # chain_id",
"value=0, data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_dynamic_fee_transaction(unsigned_dynamic_fee_transaction, is_valid): if is_valid: unsigned_dynamic_fee_transaction.validate()",
"to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000,",
"gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedDynamicFeeTransaction(",
"(UnsignedAccessListTransaction( chain_id='1', # chain_id fails validation nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0,",
"max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ),",
"(UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 19,",
"gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),), # access_list address",
"20, value=0, data=b'', access_list=(), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0'",
"test some obvious cases, especially positive test cases. (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000,",
"def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if is_valid: unsigned_access_list_transaction.validate() else: with pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", (",
"gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True),",
"gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000,",
"test some obvious cases, especially positive test cases. (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000,",
"eth.vm.forks.berlin.transactions import UnsignedAccessListTransaction from eth_utils import ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", ( # While ethereum",
"True), (UnsignedDynamicFeeTransaction( chain_id=0, nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(),",
"False), (UnsignedDynamicFeeTransaction( chain_id='1', # chain_id fails validation nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0' *",
"chain_id fails validation nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ),",
"obvious cases, especially positive test cases. (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0'",
"data=b'', access_list=(), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20,",
"access_list=(), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0,",
"# chain_id fails validation nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0' * 20, value=0, data=b'',",
"cases, especially positive test cases. (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' *",
"to test some obvious cases, especially positive test cases. (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000,",
"fails validation ), False), (UnsignedDynamicFeeTransaction( chain_id='1', # chain_id fails validation nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000,",
"address fails validation ), False), (UnsignedAccessListTransaction( chain_id='1', # chain_id fails validation nonce=0, gas_price=0,",
"import UnsignedDynamicFeeTransaction from eth.vm.forks.berlin.transactions import UnsignedAccessListTransaction from eth_utils import ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", (",
"While ethereum tests do not yet have Berlin or London transaction tests, #",
"access_list address fails validation ), False), (UnsignedAccessListTransaction( chain_id='1', # chain_id fails validation nonce=0,",
"nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),),",
"# chain_id fails validation nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(),",
"to test some obvious cases, especially positive test cases. (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000,",
"data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedAccessListTransaction( chain_id=0, nonce=0, gas_price=0, gas=0,",
"some obvious cases, especially positive test cases. (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000,",
"(1, 2)),), ), True), (UnsignedAccessListTransaction( chain_id=0, nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0,",
"pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", ( # While ethereum tests do not yet have",
"(UnsignedDynamicFeeTransaction( chain_id='1', # chain_id fails validation nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0' * 20,",
"), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0'",
"access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedAccessListTransaction( chain_id=0, nonce=0, gas_price=0, gas=0, to=b'\\xf0'",
"value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000,",
"fails validation ), False), (UnsignedAccessListTransaction( chain_id='1', # chain_id fails validation nonce=0, gas_price=0, gas=0,",
"20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000,",
"to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000,",
"eth_utils import ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", ( # While ethereum tests do not yet",
"test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if is_valid: unsigned_access_list_transaction.validate() else: with pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", ( #",
"chain_id=0, nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True),",
"or London transaction tests, # this adds a few tests to test some",
"else: with pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", ( # While ethereum tests do not",
"to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_dynamic_fee_transaction(unsigned_dynamic_fee_transaction, is_valid):",
"* 20, value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),), # access_list address fails validation",
"yet have Berlin or London transaction tests, # this adds a few tests",
"to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedAccessListTransaction( chain_id=123456789,",
"data=b'', access_list=((b'\\xf0' * 19, (1,)),), # access_list address fails validation ), False), (UnsignedAccessListTransaction(",
"few tests to test some obvious cases, especially positive test cases. (UnsignedDynamicFeeTransaction( chain_id=123456789,",
"20, ()),), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20,",
"@pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", ( # While ethereum tests do not yet have Berlin or",
"19, (1,)),), # access_list address fails validation ), False), (UnsignedDynamicFeeTransaction( chain_id='1', # chain_id",
"gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000,",
"gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_dynamic_fee_transaction(unsigned_dynamic_fee_transaction,",
"not yet have Berlin or London transaction tests, # this adds a few",
"@pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", ( # While ethereum tests do not yet have Berlin or",
"max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),),",
"is_valid): if is_valid: unsigned_access_list_transaction.validate() else: with pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", ( # While",
"), False), (UnsignedAccessListTransaction( chain_id='1', # chain_id fails validation nonce=0, gas_price=0, gas=0, to=b'\\xf0' *",
"value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedDynamicFeeTransaction( chain_id=0, nonce=0, max_fee_per_gas=0,",
"adds a few tests to test some obvious cases, especially positive test cases.",
"nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1,",
"max_priority_fee_per_gas=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0,",
"2)),), ), True), (UnsignedAccessListTransaction( chain_id=0, nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'',",
"data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000,",
"access_list address fails validation ), False), (UnsignedDynamicFeeTransaction( chain_id='1', # chain_id fails validation nonce=0,",
"gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction,",
"especially positive test cases. (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20,",
"validation ), False), (UnsignedDynamicFeeTransaction( chain_id='1', # chain_id fails validation nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0,",
"unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", ( # While ethereum tests do not yet have Berlin",
"False), ) ) def test_validate_unsigned_dynamic_fee_transaction(unsigned_dynamic_fee_transaction, is_valid): if is_valid: unsigned_dynamic_fee_transaction.validate() else: with pytest.raises(ValidationError): unsigned_dynamic_fee_transaction.validate()",
"import pytest from eth.vm.forks.london.transactions import UnsignedDynamicFeeTransaction from eth.vm.forks.berlin.transactions import UnsignedAccessListTransaction from eth_utils import",
"False), (UnsignedAccessListTransaction( chain_id='1', # chain_id fails validation nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20,",
"some obvious cases, especially positive test cases. (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0'",
"* 20, ()),), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' *",
"* 20, (1, 2)),), ), True), (UnsignedDynamicFeeTransaction( chain_id=0, nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0, to=b'\\xf0'",
"nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),),",
"address fails validation ), False), (UnsignedDynamicFeeTransaction( chain_id='1', # chain_id fails validation nonce=0, max_fee_per_gas=1000000000,",
"True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0'",
"cases, especially positive test cases. (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20,",
"gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),), # access_list",
"is_valid: unsigned_access_list_transaction.validate() else: with pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", ( # While ethereum tests",
"ethereum tests do not yet have Berlin or London transaction tests, # this",
"data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0'",
"20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedAccessListTransaction( chain_id=0, nonce=0,",
"chain_id=0, nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True), (UnsignedAccessListTransaction(",
"data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if is_valid: unsigned_access_list_transaction.validate() else:",
"from eth.vm.forks.berlin.transactions import UnsignedAccessListTransaction from eth_utils import ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", ( # While",
"nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ),",
"20, (1, 2)),), ), True), (UnsignedAccessListTransaction( chain_id=0, nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20,",
"from eth.vm.forks.london.transactions import UnsignedDynamicFeeTransaction from eth.vm.forks.berlin.transactions import UnsignedAccessListTransaction from eth_utils import ValidationError @pytest.mark.parametrize(",
"UnsignedAccessListTransaction from eth_utils import ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", ( # While ethereum tests do",
"to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedDynamicFeeTransaction(",
"tests to test some obvious cases, especially positive test cases. (UnsignedAccessListTransaction( chain_id=123456789, nonce=0,",
"* 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedAccessListTransaction( chain_id=0,",
"tests do not yet have Berlin or London transaction tests, # this adds",
"2)),), ), True), (UnsignedDynamicFeeTransaction( chain_id=0, nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0, to=b'\\xf0' * 20, value=0,",
"* 20, value=0, data=b'', access_list=(), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000,",
"* 19, (1,)),), # access_list address fails validation ), False), (UnsignedDynamicFeeTransaction( chain_id='1', #",
"UnsignedDynamicFeeTransaction from eth.vm.forks.berlin.transactions import UnsignedAccessListTransaction from eth_utils import ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", ( #",
"value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedAccessListTransaction( chain_id=0, nonce=0, gas_price=0,",
"access_list=((b'\\xf0' * 19, (1,)),), # access_list address fails validation ), False), (UnsignedAccessListTransaction( chain_id='1',",
"a few tests to test some obvious cases, especially positive test cases. (UnsignedDynamicFeeTransaction(",
"chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20,",
"tests, # this adds a few tests to test some obvious cases, especially",
"* 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0,",
"eth.vm.forks.london.transactions import UnsignedDynamicFeeTransaction from eth.vm.forks.berlin.transactions import UnsignedAccessListTransaction from eth_utils import ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\",",
"(UnsignedAccessListTransaction( chain_id=0, nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True),",
"(UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' *",
"unsigned_access_list_transaction.validate() else: with pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\", ( # While ethereum tests do",
"), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'',",
"), True), (UnsignedDynamicFeeTransaction( chain_id=0, nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'',",
"* 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedDynamicFeeTransaction( chain_id=0,",
"chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),),",
"# this adds a few tests to test some obvious cases, especially positive",
"do not yet have Berlin or London transaction tests, # this adds a",
"gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True),",
"gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0,",
"20, value=0, data=b'', access_list=(), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' *",
"* 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0,",
"( # While ethereum tests do not yet have Berlin or London transaction",
"), True), (UnsignedAccessListTransaction( chain_id=0, nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(),",
") def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if is_valid: unsigned_access_list_transaction.validate() else: with pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize( \"unsigned_dynamic_fee_transaction,is_valid\",",
"access_list=(), ), False), ) ) def test_validate_unsigned_dynamic_fee_transaction(unsigned_dynamic_fee_transaction, is_valid): if is_valid: unsigned_dynamic_fee_transaction.validate() else: with",
"this adds a few tests to test some obvious cases, especially positive test",
"True), (UnsignedAccessListTransaction( chain_id=0, nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ),",
"positive test cases. (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'',",
"access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' *",
"max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789,",
"# access_list address fails validation ), False), (UnsignedAccessListTransaction( chain_id='1', # chain_id fails validation",
"cases. (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' *",
"validation nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False), )",
"to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, (1, 2)),), ), True), (UnsignedAccessListTransaction(",
"* 20, value=0, data=b'', access_list=(), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0'",
"\"unsigned_access_list_transaction,is_valid\", ( # While ethereum tests do not yet have Berlin or London",
"20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000,",
"to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid):",
"tests to test some obvious cases, especially positive test cases. (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0,",
"import ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", ( # While ethereum tests do not yet have",
"20, value=0, data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if is_valid:",
"fails validation nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False),",
") ) def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if is_valid: unsigned_access_list_transaction.validate() else: with pytest.raises(ValidationError): unsigned_access_list_transaction.validate() @pytest.mark.parametrize(",
"<reponame>dbfreem/py-evm import pytest from eth.vm.forks.london.transactions import UnsignedDynamicFeeTransaction from eth.vm.forks.berlin.transactions import UnsignedAccessListTransaction from eth_utils",
"few tests to test some obvious cases, especially positive test cases. (UnsignedAccessListTransaction( chain_id=123456789,",
"chain_id='1', # chain_id fails validation nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0' * 20, value=0,",
"have Berlin or London transaction tests, # this adds a few tests to",
"positive test cases. (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0,",
"()),), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0,",
"nonce=0, gas_price=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False), ) )",
"chain_id=123456789, nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 19,",
"(UnsignedDynamicFeeTransaction( chain_id=0, nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ),",
"to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True), (UnsignedDynamicFeeTransaction( chain_id=123456789,",
"max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),), #",
"validation nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), False),",
"fails validation nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ),",
"a few tests to test some obvious cases, especially positive test cases. (UnsignedAccessListTransaction(",
"20, (1, 2)),), ), True), (UnsignedDynamicFeeTransaction( chain_id=0, nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0, to=b'\\xf0' *",
"max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ), True),",
"value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),), # access_list address fails validation ), False),",
"max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=40000, to=b'\\xf0' * 20, value=0, data=b'', access_list=((b'\\xf0' * 20, ()),), ),",
"* 20, ()),), ), True), (UnsignedAccessListTransaction( chain_id=123456789, nonce=0, gas_price=1000000000, gas=40000, to=b'\\xf0' * 20,",
"nonce=0, max_fee_per_gas=0, max_priority_fee_per_gas=0, gas=0, to=b'\\xf0' * 20, value=0, data=b'', access_list=(), ), True), (UnsignedDynamicFeeTransaction(",
"* 20, value=0, data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_dynamic_fee_transaction(unsigned_dynamic_fee_transaction, is_valid): if",
"20, value=0, data=b'', access_list=((b'\\xf0' * 19, (1,)),), # access_list address fails validation ),",
"import UnsignedAccessListTransaction from eth_utils import ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", ( # While ethereum tests",
"), False), (UnsignedDynamicFeeTransaction( chain_id='1', # chain_id fails validation nonce=0, max_fee_per_gas=1000000000, max_priority_fee_per_gas=1000000000, gas=0, to=b'\\xf0'",
"* 20, (1, 2)),), ), True), (UnsignedAccessListTransaction( chain_id=0, nonce=0, gas_price=0, gas=0, to=b'\\xf0' *",
"(1,)),), # access_list address fails validation ), False), (UnsignedAccessListTransaction( chain_id='1', # chain_id fails",
"from eth_utils import ValidationError @pytest.mark.parametrize( \"unsigned_access_list_transaction,is_valid\", ( # While ethereum tests do not",
"value=0, data=b'', access_list=(), ), False), ) ) def test_validate_unsigned_access_list_transaction(unsigned_access_list_transaction, is_valid): if is_valid: unsigned_access_list_transaction.validate()"
] |
[
"calculate viable tumor burden slides_dir = os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir) # load calcualted burden",
"burden return burden_dict if __name__ == \"__main__\": # extract prepared ground truth viable",
"format.json_to_dict(cal_burden_path) # compare gt & cal for ind, key in enumerate(gt_burden_dict): if key",
"burden source_slides_dir = \"../data/SourceData\" phase1_path = os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path = os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict",
"= os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask = io.imread(cur_whole_path) cur_viable_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask = io.imread(cur_viable_path)",
"= \"../data/SourceData\" phase1_path = os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path = os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict = {}",
"[] slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"svs\" in ele]) slide_list.extend([ele[6:-4] for ele",
"<filename>burden/validate_burden.py<gh_stars>10-100 # -*- coding: utf-8 -*- import os, sys import numpy as np",
"__name__ == \"__main__\": # extract prepared ground truth viable tumor burden source_slides_dir =",
"os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict = format.json_to_dict(cal_burden_path) # compare gt & cal for ind, key",
"slide_burden): burden_dict[str(int(id)).zfill(4)] = burden return burden_dict if __name__ == \"__main__\": # extract prepared",
"= {} phase1_burden_dict = extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict = extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict) #",
"calcualted burden cal_burden_path = os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict = format.json_to_dict(cal_burden_path) # compare gt &",
"if __name__ == \"__main__\": # extract prepared ground truth viable tumor burden source_slides_dir",
"phase2_path = os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict = {} phase1_burden_dict = extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict",
"key not in cal_burden_dict: print(\"Error: {}\".format(key)) gt_burden = gt_burden_dict[key] cal_burden = cal_burden_dict[key] if",
"\"calculated_tumor_burden.json\") cal_burden_dict = format.json_to_dict(cal_burden_path) # compare gt & cal for ind, key in",
"ind, key in enumerate(gt_burden_dict): if key not in cal_burden_dict: print(\"Error: {}\".format(key)) gt_burden =",
"for ind, cur_slide in enumerate(slide_list): cur_slide = str(cur_slide) print(\"Processing {}/{}\".format(ind+1, len(slide_list))) cur_whole_path =",
"cur_burden = np.sum(viable_mask) * 1.0 / np.sum(whole_mask) burden_dict[cur_slide] = cur_burden save_json_path = os.path.join(os.path.dirname(slides_dir),",
"from pydaily import format def cal_train_burden(slides_dir): slide_list = [] slide_list.extend([ele[6:-4] for ele in",
"ind, cur_slide in enumerate(slide_list): cur_slide = str(cur_slide) print(\"Processing {}/{}\".format(ind+1, len(slide_list))) cur_whole_path = os.path.join(slides_dir,",
"& cal for ind, key in enumerate(gt_burden_dict): if key not in cal_burden_dict: print(\"Error:",
"print(\"Processing {}/{}\".format(ind+1, len(slide_list))) cur_whole_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask = io.imread(cur_whole_path) cur_viable_path = os.path.join(slides_dir,",
"truth viable tumor burden source_slides_dir = \"../data/SourceData\" phase1_path = os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path =",
"cal_train_burden(slides_dir): slide_list = [] slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"svs\" in ele])",
"import numpy as np import pandas as pd from skimage import io from",
"for ind, key in enumerate(gt_burden_dict): if key not in cal_burden_dict: print(\"Error: {}\".format(key)) gt_burden",
"{} for ind, cur_slide in enumerate(slide_list): cur_slide = str(cur_slide) print(\"Processing {}/{}\".format(ind+1, len(slide_list))) cur_whole_path",
"str(cur_slide) print(\"Processing {}/{}\".format(ind+1, len(slide_list))) cur_whole_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask = io.imread(cur_whole_path) cur_viable_path =",
"= cur_burden save_json_path = os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path) def extract_csv_burden(csv_path, case_num): df",
"= df['wsi_id'].values.tolist()[:case_num] slide_burden = df['pixel ratio'].values.tolist()[:case_num] burden_dict = {} for id, burden in",
"phase1_burden_dict = extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict = extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict) # get calculate",
"= extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict = extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict) # get calculate viable",
"cur_burden save_json_path = os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path) def extract_csv_burden(csv_path, case_num): df =",
"as np import pandas as pd from skimage import io from pydaily import",
"np.sum(whole_mask) burden_dict[cur_slide] = cur_burden save_json_path = os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path) def extract_csv_burden(csv_path,",
"gt_burden_dict[key] cal_burden = cal_burden_dict[key] if np.absolute(gt_burden-cal_burden) > 0.001: print(\"{}/{} {} gt:{:.3f}, cal:{:.3f}\".format(ind+1, len(gt_burden_dict),",
"extract_csv_burden(csv_path, case_num): df = pd.read_csv(csv_path) slide_ids = df['wsi_id'].values.tolist()[:case_num] slide_burden = df['pixel ratio'].values.tolist()[:case_num] burden_dict",
"* 1.0 / np.sum(whole_mask) burden_dict[cur_slide] = cur_burden save_json_path = os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict,",
"= burden return burden_dict if __name__ == \"__main__\": # extract prepared ground truth",
"== \"__main__\": # extract prepared ground truth viable tumor burden source_slides_dir = \"../data/SourceData\"",
"{}/{}\".format(ind+1, len(slide_list))) cur_whole_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask = io.imread(cur_whole_path) cur_viable_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\")",
"ele]) slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"SVS\" in ele]) burden_dict = {}",
"skimage import io from pydaily import format def cal_train_burden(slides_dir): slide_list = [] slide_list.extend([ele[6:-4]",
"viable_mask = io.imread(cur_viable_path) cur_burden = np.sum(viable_mask) * 1.0 / np.sum(whole_mask) burden_dict[cur_slide] = cur_burden",
"gt_burden_dict = {} phase1_burden_dict = extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict = extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict)",
"def cal_train_burden(slides_dir): slide_list = [] slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"svs\" in",
"if \"SVS\" in ele]) burden_dict = {} for ind, cur_slide in enumerate(slide_list): cur_slide",
"= os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path) def extract_csv_burden(csv_path, case_num): df = pd.read_csv(csv_path) slide_ids",
"case_num=30) gt_burden_dict.update(phase2_burden_dict) # get calculate viable tumor burden slides_dir = os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir)",
"ele in os.listdir(slides_dir) if \"svs\" in ele]) slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if",
"save_json_path) def extract_csv_burden(csv_path, case_num): df = pd.read_csv(csv_path) slide_ids = df['wsi_id'].values.tolist()[:case_num] slide_burden = df['pixel",
"as pd from skimage import io from pydaily import format def cal_train_burden(slides_dir): slide_list",
"\"__main__\": # extract prepared ground truth viable tumor burden source_slides_dir = \"../data/SourceData\" phase1_path",
"burden in zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)] = burden return burden_dict if __name__ == \"__main__\":",
"get calculate viable tumor burden slides_dir = os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir) # load calcualted",
"\"LiverImages\") cal_train_burden(slides_dir) # load calcualted burden cal_burden_path = os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict = format.json_to_dict(cal_burden_path)",
"\"Phase_1_tumor_burden.csv\") phase2_path = os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict = {} phase1_burden_dict = extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict)",
"# extract prepared ground truth viable tumor burden source_slides_dir = \"../data/SourceData\" phase1_path =",
"pydaily import format def cal_train_burden(slides_dir): slide_list = [] slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir)",
"cal_burden_dict = format.json_to_dict(cal_burden_path) # compare gt & cal for ind, key in enumerate(gt_burden_dict):",
"\"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path) def extract_csv_burden(csv_path, case_num): df = pd.read_csv(csv_path) slide_ids = df['wsi_id'].values.tolist()[:case_num] slide_burden",
"pd.read_csv(csv_path) slide_ids = df['wsi_id'].values.tolist()[:case_num] slide_burden = df['pixel ratio'].values.tolist()[:case_num] burden_dict = {} for id,",
"return burden_dict if __name__ == \"__main__\": # extract prepared ground truth viable tumor",
"{} phase1_burden_dict = extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict = extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict) # get",
"slide_burden = df['pixel ratio'].values.tolist()[:case_num] burden_dict = {} for id, burden in zip(slide_ids, slide_burden):",
"phase1_path = os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path = os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict = {} phase1_burden_dict =",
"numpy as np import pandas as pd from skimage import io from pydaily",
"in os.listdir(slides_dir) if \"SVS\" in ele]) burden_dict = {} for ind, cur_slide in",
"gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict = extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict) # get calculate viable tumor burden slides_dir",
"df['wsi_id'].values.tolist()[:case_num] slide_burden = df['pixel ratio'].values.tolist()[:case_num] burden_dict = {} for id, burden in zip(slide_ids,",
"= io.imread(cur_viable_path) cur_burden = np.sum(viable_mask) * 1.0 / np.sum(whole_mask) burden_dict[cur_slide] = cur_burden save_json_path",
"case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict = extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict) # get calculate viable tumor burden",
"= os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path = os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict = {} phase1_burden_dict = extract_csv_burden(phase1_path,",
"= cal_burden_dict[key] if np.absolute(gt_burden-cal_burden) > 0.001: print(\"{}/{} {} gt:{:.3f}, cal:{:.3f}\".format(ind+1, len(gt_burden_dict), key, gt_burden,",
"= str(cur_slide) print(\"Processing {}/{}\".format(ind+1, len(slide_list))) cur_whole_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask = io.imread(cur_whole_path) cur_viable_path",
"cal_burden_path = os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict = format.json_to_dict(cal_burden_path) # compare gt & cal for",
"ele]) burden_dict = {} for ind, cur_slide in enumerate(slide_list): cur_slide = str(cur_slide) print(\"Processing",
"enumerate(slide_list): cur_slide = str(cur_slide) print(\"Processing {}/{}\".format(ind+1, len(slide_list))) cur_whole_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask =",
"{}\".format(key)) gt_burden = gt_burden_dict[key] cal_burden = cal_burden_dict[key] if np.absolute(gt_burden-cal_burden) > 0.001: print(\"{}/{} {}",
"cur_viable_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask = io.imread(cur_viable_path) cur_burden = np.sum(viable_mask) * 1.0 /",
"/ np.sum(whole_mask) burden_dict[cur_slide] = cur_burden save_json_path = os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path) def",
"enumerate(gt_burden_dict): if key not in cal_burden_dict: print(\"Error: {}\".format(key)) gt_burden = gt_burden_dict[key] cal_burden =",
"utf-8 -*- import os, sys import numpy as np import pandas as pd",
"os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir) # load calcualted burden cal_burden_path = os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict =",
"format.dict_to_json(burden_dict, save_json_path) def extract_csv_burden(csv_path, case_num): df = pd.read_csv(csv_path) slide_ids = df['wsi_id'].values.tolist()[:case_num] slide_burden =",
"key in enumerate(gt_burden_dict): if key not in cal_burden_dict: print(\"Error: {}\".format(key)) gt_burden = gt_burden_dict[key]",
"= [] slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"svs\" in ele]) slide_list.extend([ele[6:-4] for",
"viable tumor burden slides_dir = os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir) # load calcualted burden cal_burden_path",
"len(slide_list))) cur_whole_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask = io.imread(cur_whole_path) cur_viable_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask",
"ground truth viable tumor burden source_slides_dir = \"../data/SourceData\" phase1_path = os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path",
"\"svs\" in ele]) slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"SVS\" in ele]) burden_dict",
"ele in os.listdir(slides_dir) if \"SVS\" in ele]) burden_dict = {} for ind, cur_slide",
"burden_dict[cur_slide] = cur_burden save_json_path = os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path) def extract_csv_burden(csv_path, case_num):",
"os.listdir(slides_dir) if \"SVS\" in ele]) burden_dict = {} for ind, cur_slide in enumerate(slide_list):",
"= extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict) # get calculate viable tumor burden slides_dir = os.path.join(os.path.dirname(source_slides_dir),",
"phase2_burden_dict = extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict) # get calculate viable tumor burden slides_dir =",
"for ele in os.listdir(slides_dir) if \"SVS\" in ele]) burden_dict = {} for ind,",
"io from pydaily import format def cal_train_burden(slides_dir): slide_list = [] slide_list.extend([ele[6:-4] for ele",
"in enumerate(slide_list): cur_slide = str(cur_slide) print(\"Processing {}/{}\".format(ind+1, len(slide_list))) cur_whole_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask",
"tumor burden slides_dir = os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir) # load calcualted burden cal_burden_path =",
"np.sum(viable_mask) * 1.0 / np.sum(whole_mask) burden_dict[cur_slide] = cur_burden save_json_path = os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\")",
"slide_ids = df['wsi_id'].values.tolist()[:case_num] slide_burden = df['pixel ratio'].values.tolist()[:case_num] burden_dict = {} for id, burden",
"= np.sum(viable_mask) * 1.0 / np.sum(whole_mask) burden_dict[cur_slide] = cur_burden save_json_path = os.path.join(os.path.dirname(slides_dir), \"SourceData\",",
"whole_mask = io.imread(cur_whole_path) cur_viable_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask = io.imread(cur_viable_path) cur_burden = np.sum(viable_mask)",
"zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)] = burden return burden_dict if __name__ == \"__main__\": # extract",
"for id, burden in zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)] = burden return burden_dict if __name__",
"ratio'].values.tolist()[:case_num] burden_dict = {} for id, burden in zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)] = burden",
"burden_dict if __name__ == \"__main__\": # extract prepared ground truth viable tumor burden",
"os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path) def extract_csv_burden(csv_path, case_num): df = pd.read_csv(csv_path) slide_ids =",
"burden slides_dir = os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir) # load calcualted burden cal_burden_path = os.path.join(source_slides_dir,",
"for ele in os.listdir(slides_dir) if \"svs\" in ele]) slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir)",
"cal for ind, key in enumerate(gt_burden_dict): if key not in cal_burden_dict: print(\"Error: {}\".format(key))",
"import format def cal_train_burden(slides_dir): slide_list = [] slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if",
"not in cal_burden_dict: print(\"Error: {}\".format(key)) gt_burden = gt_burden_dict[key] cal_burden = cal_burden_dict[key] if np.absolute(gt_burden-cal_burden)",
"compare gt & cal for ind, key in enumerate(gt_burden_dict): if key not in",
"extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict) # get calculate viable tumor burden slides_dir = os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\")",
"in enumerate(gt_burden_dict): if key not in cal_burden_dict: print(\"Error: {}\".format(key)) gt_burden = gt_burden_dict[key] cal_burden",
"cal_burden_dict: print(\"Error: {}\".format(key)) gt_burden = gt_burden_dict[key] cal_burden = cal_burden_dict[key] if np.absolute(gt_burden-cal_burden) > 0.001:",
"viable tumor burden source_slides_dir = \"../data/SourceData\" phase1_path = os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path = os.path.join(source_slides_dir,",
"io.imread(cur_viable_path) cur_burden = np.sum(viable_mask) * 1.0 / np.sum(whole_mask) burden_dict[cur_slide] = cur_burden save_json_path =",
"burden_dict[str(int(id)).zfill(4)] = burden return burden_dict if __name__ == \"__main__\": # extract prepared ground",
"sys import numpy as np import pandas as pd from skimage import io",
"df['pixel ratio'].values.tolist()[:case_num] burden_dict = {} for id, burden in zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)] =",
"gt_burden = gt_burden_dict[key] cal_burden = cal_burden_dict[key] if np.absolute(gt_burden-cal_burden) > 0.001: print(\"{}/{} {} gt:{:.3f},",
"cal_burden = cal_burden_dict[key] if np.absolute(gt_burden-cal_burden) > 0.001: print(\"{}/{} {} gt:{:.3f}, cal:{:.3f}\".format(ind+1, len(gt_burden_dict), key,",
"= gt_burden_dict[key] cal_burden = cal_burden_dict[key] if np.absolute(gt_burden-cal_burden) > 0.001: print(\"{}/{} {} gt:{:.3f}, cal:{:.3f}\".format(ind+1,",
"slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"svs\" in ele]) slide_list.extend([ele[6:-4] for ele in",
"slide_list = [] slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"svs\" in ele]) slide_list.extend([ele[6:-4]",
"= {} for id, burden in zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)] = burden return burden_dict",
"in cal_burden_dict: print(\"Error: {}\".format(key)) gt_burden = gt_burden_dict[key] cal_burden = cal_burden_dict[key] if np.absolute(gt_burden-cal_burden) >",
"np import pandas as pd from skimage import io from pydaily import format",
"= os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask = io.imread(cur_viable_path) cur_burden = np.sum(viable_mask) * 1.0 / np.sum(whole_mask)",
"= io.imread(cur_whole_path) cur_viable_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask = io.imread(cur_viable_path) cur_burden = np.sum(viable_mask) *",
"\"Phase_2_tumor_burden.csv\") gt_burden_dict = {} phase1_burden_dict = extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict = extract_csv_burden(phase2_path, case_num=30)",
"burden_dict = {} for id, burden in zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)] = burden return",
"# load calcualted burden cal_burden_path = os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict = format.json_to_dict(cal_burden_path) # compare",
"# -*- coding: utf-8 -*- import os, sys import numpy as np import",
"{} for id, burden in zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)] = burden return burden_dict if",
"= pd.read_csv(csv_path) slide_ids = df['wsi_id'].values.tolist()[:case_num] slide_burden = df['pixel ratio'].values.tolist()[:case_num] burden_dict = {} for",
"prepared ground truth viable tumor burden source_slides_dir = \"../data/SourceData\" phase1_path = os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\")",
"print(\"Error: {}\".format(key)) gt_burden = gt_burden_dict[key] cal_burden = cal_burden_dict[key] if np.absolute(gt_burden-cal_burden) > 0.001: print(\"{}/{}",
"format def cal_train_burden(slides_dir): slide_list = [] slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"svs\"",
"pandas as pd from skimage import io from pydaily import format def cal_train_burden(slides_dir):",
"df = pd.read_csv(csv_path) slide_ids = df['wsi_id'].values.tolist()[:case_num] slide_burden = df['pixel ratio'].values.tolist()[:case_num] burden_dict = {}",
"= format.json_to_dict(cal_burden_path) # compare gt & cal for ind, key in enumerate(gt_burden_dict): if",
"import os, sys import numpy as np import pandas as pd from skimage",
"= {} for ind, cur_slide in enumerate(slide_list): cur_slide = str(cur_slide) print(\"Processing {}/{}\".format(ind+1, len(slide_list)))",
"1.0 / np.sum(whole_mask) burden_dict[cur_slide] = cur_burden save_json_path = os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path)",
"cur_slide in enumerate(slide_list): cur_slide = str(cur_slide) print(\"Processing {}/{}\".format(ind+1, len(slide_list))) cur_whole_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\")",
"burden_dict = {} for ind, cur_slide in enumerate(slide_list): cur_slide = str(cur_slide) print(\"Processing {}/{}\".format(ind+1,",
"id, burden in zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)] = burden return burden_dict if __name__ ==",
"cur_slide = str(cur_slide) print(\"Processing {}/{}\".format(ind+1, len(slide_list))) cur_whole_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask = io.imread(cur_whole_path)",
"\"../data/SourceData\" phase1_path = os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path = os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict = {} phase1_burden_dict",
"os, sys import numpy as np import pandas as pd from skimage import",
"slides_dir = os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir) # load calcualted burden cal_burden_path = os.path.join(source_slides_dir, \"calculated_tumor_burden.json\")",
"pd from skimage import io from pydaily import format def cal_train_burden(slides_dir): slide_list =",
"-*- import os, sys import numpy as np import pandas as pd from",
"os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask = io.imread(cur_viable_path) cur_burden = np.sum(viable_mask) * 1.0 / np.sum(whole_mask) burden_dict[cur_slide]",
"\"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path) def extract_csv_burden(csv_path, case_num): df = pd.read_csv(csv_path) slide_ids = df['wsi_id'].values.tolist()[:case_num]",
"in ele]) slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"SVS\" in ele]) burden_dict =",
"import pandas as pd from skimage import io from pydaily import format def",
"= df['pixel ratio'].values.tolist()[:case_num] burden_dict = {} for id, burden in zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)]",
"-*- coding: utf-8 -*- import os, sys import numpy as np import pandas",
"tumor burden source_slides_dir = \"../data/SourceData\" phase1_path = os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path = os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\")",
"os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask = io.imread(cur_whole_path) cur_viable_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask = io.imread(cur_viable_path) cur_burden",
"import io from pydaily import format def cal_train_burden(slides_dir): slide_list = [] slide_list.extend([ele[6:-4] for",
"# compare gt & cal for ind, key in enumerate(gt_burden_dict): if key not",
"in ele]) burden_dict = {} for ind, cur_slide in enumerate(slide_list): cur_slide = str(cur_slide)",
"slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"SVS\" in ele]) burden_dict = {} for",
"\"SVS\" in ele]) burden_dict = {} for ind, cur_slide in enumerate(slide_list): cur_slide =",
"coding: utf-8 -*- import os, sys import numpy as np import pandas as",
"load calcualted burden cal_burden_path = os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict = format.json_to_dict(cal_burden_path) # compare gt",
"if key not in cal_burden_dict: print(\"Error: {}\".format(key)) gt_burden = gt_burden_dict[key] cal_burden = cal_burden_dict[key]",
"from skimage import io from pydaily import format def cal_train_burden(slides_dir): slide_list = []",
"= os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict = format.json_to_dict(cal_burden_path) # compare gt & cal for ind,",
"in zip(slide_ids, slide_burden): burden_dict[str(int(id)).zfill(4)] = burden return burden_dict if __name__ == \"__main__\": #",
"burden cal_burden_path = os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict = format.json_to_dict(cal_burden_path) # compare gt & cal",
"\"01_01_\"+cur_slide+\"_whole.tif\") whole_mask = io.imread(cur_whole_path) cur_viable_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask = io.imread(cur_viable_path) cur_burden =",
"in os.listdir(slides_dir) if \"svs\" in ele]) slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"SVS\"",
"io.imread(cur_whole_path) cur_viable_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask = io.imread(cur_viable_path) cur_burden = np.sum(viable_mask) * 1.0",
"if \"svs\" in ele]) slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"SVS\" in ele])",
"os.listdir(slides_dir) if \"svs\" in ele]) slide_list.extend([ele[6:-4] for ele in os.listdir(slides_dir) if \"SVS\" in",
"= os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir) # load calcualted burden cal_burden_path = os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict",
"gt_burden_dict.update(phase2_burden_dict) # get calculate viable tumor burden slides_dir = os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir) #",
"cur_whole_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_whole.tif\") whole_mask = io.imread(cur_whole_path) cur_viable_path = os.path.join(slides_dir, \"01_01_\"+cur_slide+\"_viable.tif\") viable_mask =",
"cal_train_burden(slides_dir) # load calcualted burden cal_burden_path = os.path.join(source_slides_dir, \"calculated_tumor_burden.json\") cal_burden_dict = format.json_to_dict(cal_burden_path) #",
"def extract_csv_burden(csv_path, case_num): df = pd.read_csv(csv_path) slide_ids = df['wsi_id'].values.tolist()[:case_num] slide_burden = df['pixel ratio'].values.tolist()[:case_num]",
"os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict = {} phase1_burden_dict = extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict = extract_csv_burden(phase2_path,",
"save_json_path = os.path.join(os.path.dirname(slides_dir), \"SourceData\", \"calculated_tumor_burden.json\") format.dict_to_json(burden_dict, save_json_path) def extract_csv_burden(csv_path, case_num): df = pd.read_csv(csv_path)",
"source_slides_dir = \"../data/SourceData\" phase1_path = os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path = os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict =",
"= os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict = {} phase1_burden_dict = extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict =",
"extract_csv_burden(phase1_path, case_num=20) gt_burden_dict.update(phase1_burden_dict) phase2_burden_dict = extract_csv_burden(phase2_path, case_num=30) gt_burden_dict.update(phase2_burden_dict) # get calculate viable tumor",
"case_num): df = pd.read_csv(csv_path) slide_ids = df['wsi_id'].values.tolist()[:case_num] slide_burden = df['pixel ratio'].values.tolist()[:case_num] burden_dict =",
"os.path.join(source_slides_dir, \"Phase_1_tumor_burden.csv\") phase2_path = os.path.join(source_slides_dir, \"Phase_2_tumor_burden.csv\") gt_burden_dict = {} phase1_burden_dict = extract_csv_burden(phase1_path, case_num=20)",
"gt & cal for ind, key in enumerate(gt_burden_dict): if key not in cal_burden_dict:",
"extract prepared ground truth viable tumor burden source_slides_dir = \"../data/SourceData\" phase1_path = os.path.join(source_slides_dir,",
"\"01_01_\"+cur_slide+\"_viable.tif\") viable_mask = io.imread(cur_viable_path) cur_burden = np.sum(viable_mask) * 1.0 / np.sum(whole_mask) burden_dict[cur_slide] =",
"# get calculate viable tumor burden slides_dir = os.path.join(os.path.dirname(source_slides_dir), \"LiverImages\") cal_train_burden(slides_dir) # load",
"cal_burden_dict[key] if np.absolute(gt_burden-cal_burden) > 0.001: print(\"{}/{} {} gt:{:.3f}, cal:{:.3f}\".format(ind+1, len(gt_burden_dict), key, gt_burden, cal_burden))"
] |
[
"print(f'Clip {vid_path} has some unknown issue, failed') return None, None, None, None, None,",
"dim=0) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3,",
"= torch.stack(dense_clip0, dim=0) dense_clip1 = torch.stack(dense_clip1, dim=0) dense_clip2 = torch.stack(dense_clip2, dim=0) dense_clip3 =",
"size = (10,)) erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) random_color_dropped = np.random.randint(0,3,(10)) while(cap.isOpened()):",
"if ((count not in frames_sparse) and (count not in frames_dense[0]) \\ and (count",
"= params.num_frames - len(sparse_clip) sparse_clip = sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip = a_sparse_clip +",
"y_erase[8], cropping_factor1[8],\\ x0[8], y0[8], contrast_factor1[8], hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9],",
"image = trans.functional.to_grayscale(image, num_output_channels = 3) if random_array[5] > 0.25: image = trans.functional.adjust_gamma(image,",
"a_dense_clip2, a_dense_clip3, list_sparse, list_dense except: print(f'Clip {vid_path} has some frames reading issue, failed')",
"dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def process_data(self,",
"elif split ==3: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid split input: {split}') #####################",
"dim=0) dense_clip2 = torch.stack(dense_clip2, dim=0) dense_clip3 = torch.stack(dense_clip3, dim=0) a_sparse_clip = torch.stack(a_sparse_clip, dim=0)",
"\\ list_sparse, list_dense, vid_path) in enumerate(train_dataloader): if (i+1)%25 == 0: print(sparse_clip.shape) print(dense_clip3.shape) print()",
"frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8], y_erase[8], cropping_factor1[8],\\ x0[8], y0[8], contrast_factor1[8], hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8],",
"a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path = self.process_data(index) return sparse_clip, dense_clip0, dense_clip1,",
"brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3], y_erase[3], cropping_factor1[3],\\ x0[3], y0[3], contrast_factor1[3], hue_factor1[3], saturation_factor1[3],",
"y_erase[6], cropping_factor1[6],\\ x0[6], y0[6], contrast_factor1[6], hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7],",
"matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils",
"< 0.25: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[4]",
"provides 2 augmented version of a sparse clip (covering minimum 64 frames) and",
"for ii in range(10)] contrast_factor1 = np.random.uniform(0.75,1.25, size = (10,)) hue_factor1 = np.random.uniform(-0.1,0.1,",
"import torchvision.transforms as trans # from decord import VideoReader class ss_dataset_gen1(Dataset): def __init__(self,",
"split ==2: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split ==3: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines()",
"dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense except: print(f'Clip",
"0.5: image = trans.functional.hflip(image) image = trans.functional.to_tensor(image) if random_array[7] < 0.5 : image",
"{vid_path} has insufficient frames') return None, None, None, None, None, None, None, None,",
"start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip rate experiment # skip_max = int((frame_count - start_frame)/params.num_frames)",
"dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4], y_erase[4], cropping_factor1[4],\\ x0[4], y0[4], contrast_factor1[4], hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4]))",
"skip rate experiment # skip_max = int((frame_count - start_frame)/params.num_frames) # # here 4",
"torch.stack(dense_clip0, dim=0) dense_clip1 = torch.stack(dense_clip1, dim=0) dense_clip2 = torch.stack(dense_clip2, dim=0) dense_clip3 = torch.stack(dense_clip3,",
"dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path if __name__",
": image = trans.functional.adjust_saturation(image, saturation_factor = saturation_factor1) # brightness factor will be between",
"y0[0], contrast_factor1[0], hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1], y_erase[1], cropping_factor1[1],\\ x0[1],",
"[], [], [], [], [], [], [], [], [], [], [], [], []",
"= open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split == 1: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split ==2:",
"cv2 # from tqdm import tqdm import time import torchvision.transforms as trans #",
"[] list_sparse = [] list_dense = [[] for i in range(4)] count =",
"a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense = self.build_clip(vid_path) return sparse_clip, dense_clip0, dense_clip1,",
"torch.stack(sparse_clip, dim=0) dense_clip0 = torch.stack(dense_clip0, dim=0) dense_clip1 = torch.stack(dense_clip1, dim=0) dense_clip2 = torch.stack(dense_clip2,",
"frame_count > min_temporal_span_sparse: start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip rate experiment # skip_max =",
"plt from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils import config",
"np.random.uniform(0.75,1.25, size = (10,)) brightness_factor1 = np.random.uniform(0.75,1.25,size = (10,)) gamma1 = np.random.uniform(0.75,1.25, size",
"= open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split ==3: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid split",
"while(cap.isOpened()): count += 1 ret, frame = cap.read() if ((count not in frames_sparse)",
"between [-0.1, 0.1] if random_array[2] < 0.3 : image = trans.functional.adjust_saturation(image, saturation_factor =",
"random_array[4] > 0.70: if random_array[4] < 0.875: image = trans.functional.to_grayscale(image, num_output_channels = 3)",
"and len(dense_clip3)>7: # if params.num_frames - len(dense_clip3) >= 1: # print(f'dense_clip3 {vid_path} is",
"span minimum)''' import os import torch import numpy as np import matplotlib.pyplot as",
"dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 = a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return",
"= torch.stack(a_dense_clip3, dim=0) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1,",
"= a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return sparse_clip, dense_clip0,",
"x_erase[7], y_erase[7], cropping_factor1[7],\\ x0[7], y0[7], contrast_factor1[7], hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count) if",
"builder starts here ########################## sparse_clip = [] dense_clip0 = [] dense_clip1 = []",
"True: if (count in frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0], y_erase[0], cropping_factor1[0],\\ x0[0], y0[0], contrast_factor1[0],",
"x_erase[6], y_erase[6], cropping_factor1[6],\\ x0[6], y0[6], contrast_factor1[6], hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7],",
"< params.num_frames and len(dense_clip3)>7: # if params.num_frames - len(dense_clip3) >= 1: # print(f'dense_clip3",
"= (10,)) brightness_factor1 = np.random.uniform(0.75,1.25,size = (10,)) gamma1 = np.random.uniform(0.75,1.25, size = (10,))",
"shuffle=False, num_workers=4, collate_fn=collate_fn2) print(f'Step involved: {len(train_dataset)/24}') t=time.time() for i, (sparse_clip, dense_clip0, dense_clip1, dense_clip2,",
"in frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8], y_erase[8], cropping_factor1[8],\\ x0[8], y0[8], contrast_factor1[8], hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\",
"to make a master DL that provides 2 augmented version of a sparse",
"##################### self.shuffle = shuffle if self.shuffle: random.shuffle(self.all_paths) self.data_percentage = data_percentage self.data_limit = int(len(self.all_paths)*self.data_percentage)",
"brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7], y_erase[7], cropping_factor1[7],\\ x0[7], y0[7], contrast_factor1[7], hue_factor1[7], saturation_factor1[7],",
"contrast_factor1[7], hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count) if (count in frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8],",
"x_erase[8], y_erase[8], cropping_factor1[8],\\ x0[8], y0[8], contrast_factor1[8], hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9],",
"dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip =",
"= np.random.choice([4,8,12,16]) # elif (skip_max<16) and (skip_max>=12): # sr_sparse = np.random.choice([4,8,12]) # elif",
"= torch.stack(dense_clip1, dim=0) dense_clip2 = torch.stack(dense_clip2, dim=0) dense_clip3 = torch.stack(dense_clip3, dim=0) a_sparse_clip =",
"= torch.stack(dense_clip2, dim=0) dense_clip3 = torch.stack(dense_clip3, dim=0) a_sparse_clip = torch.stack(a_sparse_clip, dim=0) a_dense_clip0 =",
"saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count) else: break if len(sparse_clip) < params.num_frames and len(sparse_clip)>13:",
"brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count) if (count in frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4], y_erase[4], cropping_factor1[4],\\",
"self.TENSOR = trans.ToTensor() self.erase_size = 19 def __len__(self): return len(self.data) def __getitem__(self,index): sparse_clip,",
"else: print(f'Invalid split input: {split}') ##################### self.shuffle = shuffle if self.shuffle: random.shuffle(self.all_paths) self.data_percentage",
": image = trans.functional.adjust_brightness(image, brightness_factor = brightness_factor1) # brightness factor will be between",
"= DataLoader(train_dataset, batch_size=40, \\ shuffle=False, num_workers=4, collate_fn=collate_fn2) print(f'Step involved: {len(train_dataset)/24}') t=time.time() for i,",
"saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped): image = self.PIL(image) image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0] <",
"= np.random.randint(0,3,(10)) while(cap.isOpened()): count += 1 ret, frame = cap.read() if ((count not",
"trans.functional.adjust_brightness(image, brightness_factor = brightness_factor1) # brightness factor will be between [0.75, 1,25] if",
"in frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2], y_erase[2], cropping_factor1[2],\\ x0[2], y0[2], contrast_factor1[2], hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\",
"= trans.functional.to_tensor(image) image[random_color_dropped,:,:] = 0 image = self.PIL(image) if random_array[6] > 0.5: image",
"if random_array[0] > 0.125 and random_array[0] < 0.25: image = trans.functional.adjust_contrast(image, contrast_factor =",
"train_dataset = ss_dataset_gen1(shuffle = True, data_percentage = 1.0) train_dataloader = DataLoader(train_dataset, batch_size=40, \\",
"and 2 augmented versions of 4 dense clips (covering 16 frames temporal span",
"# on an average cropping factor is 80% i.e. covers 64% area x0",
"\\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path if __name__ == '__main__':",
"a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path = self.process_data(index) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3,",
"= [] dense_clip2 = [] dense_clip3 = [] a_sparse_clip = [] a_dense_clip0 =",
"= ss_dataset_gen1(shuffle = True, data_percentage = 1.0) train_dataloader = DataLoader(train_dataset, batch_size=40, \\ shuffle=False,",
"a_dense_clip3, list_sparse, list_dense except: print(f'Clip {vid_path} has some frames reading issue, failed') return",
"assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1,",
"i in range(4)] count = -1 random_array = np.random.rand(10,8) x_erase = np.random.randint(0,params.reso_h, size",
"= self.all_paths[0: self.data_limit] self.PIL = trans.ToPILImage() self.TENSOR = trans.ToTensor() self.erase_size = 19 def",
"np.random.uniform(0.75,1.25, size = (10,)) hue_factor1 = np.random.uniform(-0.1,0.1, size = (10,)) saturation_factor1 = np.random.uniform(0.75,1.25,",
"factor will be between [0.75, 1,25] if random_array[0] > 0.125 and random_array[0] <",
"image = trans.functional.to_tensor(image) image[random_color_dropped,:,:] = 0 image = self.PIL(image) if random_array[6] > 0.5:",
"saturation_factor = saturation_factor1) # brightness factor will be between [0.75, 1,25] if random_array[3]",
"{params.num_frames - len(dense_clip3)} frames') remaining_num_frames = params.num_frames - len(dense_clip3) dense_clip3 = dense_clip3 +",
"cfg import random import pickle import parameters as params import json import math",
"= (10,)) erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) random_color_dropped = np.random.randint(0,3,(10)) while(cap.isOpened()): count",
"None, None, None, None, None, None except: print(f'Clip {vid_path} has some unknown issue,",
"y_erase = np.random.randint(0,params.reso_w, size = (10,)) cropping_factor1 = np.random.uniform(0.6, 1, size = (10,))",
"16 frames temporal span minimum)''' import os import torch import numpy as np",
"########################### ################################ actual clip builder starts here ########################## sparse_clip = [] dense_clip0 =",
"if (count in frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6], y_erase[6], cropping_factor1[6],\\ x0[6], y0[6], contrast_factor1[6], hue_factor1[6],",
"brightness_factor1) # brightness factor will be between [0.75, 1,25] if random_array[0] > 0.125",
"list_sparse, list_dense, vid_path = self.process_data(index) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip,",
"a_dense_clip3, list_sparse, list_dense = self.build_clip(vid_path) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip,",
"== 1: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split ==2: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines()",
"brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count) if (count in frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6], y_erase[6], cropping_factor1[6],\\",
"# brightness factor will be between [0.75, 1,25] if random_array[0] > 0.125 and",
"trans.functional.to_tensor(image) if random_array[7] < 0.5 : image = trans.functional.erase(image, x_erase, y_erase, erase_size1, erase_size2,",
"a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def process_data(self, idx): vid_path = cfg.path_folder +",
"np.random.choice([4,8,12]) # elif (skip_max<12) and (skip_max>=8): # sr_sparse = np.random.choice([4,8]) # else: sr_sparse",
"params.num_frames*params.sr_ratio if frame_count > min_temporal_span_sparse: start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip rate experiment #",
"erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) random_color_dropped = np.random.randint(0,3,(10)) while(cap.isOpened()): count += 1",
"= np.random.uniform(0.75,1.25, size = (10,)) brightness_factor1 = np.random.uniform(0.75,1.25,size = (10,)) gamma1 = np.random.uniform(0.75,1.25,",
"contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[1] < 0.3 : image =",
"j in range(4)] ################################ frame list maker finishes here ########################### ################################ actual clip",
"dense_clip2 = [] dense_clip3 = [] a_sparse_clip = [] a_dense_clip0 = [] a_dense_clip1",
"cropping_factor1[0],\\ x0[0], y0[0], contrast_factor1[0], hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1], y_erase[1],",
"list_dense, vid_path) in enumerate(train_dataloader): if (i+1)%25 == 0: print(sparse_clip.shape) print(dense_clip3.shape) print() print(f'Time taken",
"if frame_count > min_temporal_span_sparse: start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip rate experiment # skip_max",
"16: # sr_sparse = np.random.choice([4,8,12,16]) # elif (skip_max<16) and (skip_max>=12): # sr_sparse =",
"None, None, None, None, None, None, None, None, None def augmentation(self, image, random_array,",
"not (None in item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0))",
"= [] a_dense_clip0 = [] a_dense_clip1 = [] a_dense_clip2 = [] a_dense_clip3 =",
"in frames_dense[2]) \\ and (count not in frames_dense[3])) and (ret == True): continue",
">= 16: # sr_sparse = np.random.choice([4,8,12,16]) # elif (skip_max<16) and (skip_max>=12): # sr_sparse",
"frames reading issue, failed') return None, None, None, None, None, None, None, None,",
"erase_size1, erase_size2, v=0) return image def collate_fn2(batch): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip,",
"list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip = torch.stack(sparse_clip, dim=0) dense_clip0 = torch.stack(dense_clip0, dim=0) dense_clip1 =",
"= trans.functional.adjust_brightness(image, brightness_factor = brightness_factor1) # brightness factor will be between [0.75, 1,25]",
"image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[4] > 0.70:",
"dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path if",
"erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) random_color_dropped",
"import transforms, utils import config as cfg import random import pickle import parameters",
"##################### # self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split == 1: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines()",
"= torch.stack(a_sparse_clip, dim=0) a_dense_clip0 = torch.stack(a_dense_clip0, dim=0) a_dense_clip1 = torch.stack(a_dense_clip1, dim=0) a_dense_clip2 =",
"<= 56: # print(f'Video {vid_path} has insufficient frames') return None, None, None, None,",
"np.random.choice([4,8]) # else: sr_sparse = 4 else: start_frame = 0 sr_sparse = 4",
"ratio = 4 chunks # if skip_max >= 16: # sr_sparse = np.random.choice([4,8,12,16])",
"is missing {params.num_frames - len(sparse_clip)} frames') remaining_num_frames = params.num_frames - len(sparse_clip) sparse_clip =",
"return len(self.data) def __getitem__(self,index): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1,",
"cropping_factor1[3],\\ x0[3], y0[3], contrast_factor1[3], hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count) if (count in",
"[] a_dense_clip0 = [] a_dense_clip1 = [] a_dense_clip2 = [] a_dense_clip3 = []",
"np.random.uniform(0.75,1.25,size = (10,)) gamma1 = np.random.uniform(0.75,1.25, size = (10,)) erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size, size",
"insufficient frames') return None, None, None, None, None, None, None, None, None, None,",
"contrast_factor1, hue_factor1, saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped): image = self.PIL(image) image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if",
"dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6], y_erase[6], cropping_factor1[6],\\ x0[6], y0[6], contrast_factor1[6], hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6]))",
"image = trans.functional.adjust_brightness(image, brightness_factor = brightness_factor1) # brightness factor will be between [0.75,",
"except: print(f'Clip {vid_path} has some frames reading issue, failed') return None, None, None,",
"the skip rate ratio = 4 chunks # if skip_max >= 16: #",
"gamma1 = np.random.uniform(0.75,1.25, size = (10,)) erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) erase_size2",
"(10,)) random_color_dropped = np.random.randint(0,3,(10)) while(cap.isOpened()): count += 1 ret, frame = cap.read() if",
"frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0], y_erase[0], cropping_factor1[0],\\ x0[0], y0[0], contrast_factor1[0], hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0],",
"input: {split}') ##################### self.shuffle = shuffle if self.shuffle: random.shuffle(self.all_paths) self.data_percentage = data_percentage self.data_limit",
"# if skip_max >= 16: # sr_sparse = np.random.choice([4,8,12,16]) # elif (skip_max<16) and",
"None, None, None, None, None, None, None, None, None, None, None def augmentation(self,",
"# brightness factor will be between [0.75, 1,25] if random_array[3] < 0.3 :",
"vid_path = [], [], [], [], [], [], [], [], [], [], [],",
"[], [], [], [], [], [], [], [], [], [] for item in",
"- len(dense_clip3)} frames') remaining_num_frames = params.num_frames - len(dense_clip3) dense_clip3 = dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1]",
"len(dense_clip3) >= 1: # print(f'dense_clip3 {vid_path} is missing {params.num_frames - len(dense_clip3)} frames') remaining_num_frames",
"1,25] if random_array[3] < 0.3 : image = trans.functional.adjust_brightness(image, brightness_factor = brightness_factor1) #",
"= 19 def __len__(self): return len(self.data) def __getitem__(self,index): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3,",
"None, None, None, None, None, None, None, None, None, None, None except: print(f'Clip",
"and random_array[0] < 0.25: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25",
"= shuffle if self.shuffle: random.shuffle(self.all_paths) self.data_percentage = data_percentage self.data_limit = int(len(self.all_paths)*self.data_percentage) self.data =",
"self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split == 1: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split",
"self.data = self.all_paths[0: self.data_limit] self.PIL = trans.ToPILImage() self.TENSOR = trans.ToTensor() self.erase_size = 19",
"print(f'sparse_clip {vid_path} is missing {params.num_frames - len(sparse_clip)} frames') remaining_num_frames = params.num_frames - len(sparse_clip)",
"= 1.0, split = 1): ##################### # self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split ==",
"+ a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3) < params.num_frames and len(dense_clip3)>7: # if params.num_frames - len(dense_clip3)",
"minimum)''' import os import torch import numpy as np import matplotlib.pyplot as plt",
"and (count not in frames_dense[3])) and (ret == True): continue if ret ==",
"dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip",
"range [0.8, 1.2] else: image = trans.functional.to_tensor(image) image[random_color_dropped,:,:] = 0 image = self.PIL(image)",
"4 dense clips (covering 16 frames temporal span minimum)''' import os import torch",
"if skip_max >= 16: # sr_sparse = np.random.choice([4,8,12,16]) # elif (skip_max<16) and (skip_max>=12):",
"frames_sparse = [start_frame] + [start_frame + i*sr_sparse for i in range(1,params.num_frames)] frames_dense =",
"= cfg.path_folder + '/UCF-101/' + self.data[idx].split(' ')[0] sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\",
"= self.process_data(index) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2,",
"for ii in range(10)] y0 = [np.random.randint(0, params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii] + 1) for",
"= trans.functional.adjust_hue(image, hue_factor = hue_factor1) # hue factor will be between [-0.1, 0.1]",
"random_array[8], x_erase[8], y_erase[8], cropping_factor1[8],\\ x0[8], y0[8], contrast_factor1[8], hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame,",
"'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid split input: {split}') ##################### self.shuffle = shuffle if self.shuffle: random.shuffle(self.all_paths)",
"a_dense_clip3, \\ list_sparse, list_dense, vid_path) in enumerate(train_dataloader): if (i+1)%25 == 0: print(sparse_clip.shape) print(dense_clip3.shape)",
"a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def process_data(self, idx): vid_path =",
"will be between [-0.1, 0.1] if random_array[2] < 0.3 : image = trans.functional.adjust_saturation(image,",
"# sr_sparse = np.random.choice([4,8,12,16]) # elif (skip_max<16) and (skip_max>=12): # sr_sparse = np.random.choice([4,8,12])",
"{vid_path} is missing {params.num_frames - len(sparse_clip)} frames') remaining_num_frames = params.num_frames - len(sparse_clip) sparse_clip",
"else: image = trans.functional.to_tensor(image) image[random_color_dropped,:,:] = 0 image = self.PIL(image) if random_array[6] >",
"a_dense_clip3, \\ list_sparse, list_dense, vid_path if __name__ == '__main__': train_dataset = ss_dataset_gen1(shuffle =",
"a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path = self.process_data(index) return sparse_clip, dense_clip0,",
"y0[2], contrast_factor1[2], hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3], y_erase[3], cropping_factor1[3],\\ x0[3],",
"size = (10,)) saturation_factor1 = np.random.uniform(0.75,1.25, size = (10,)) brightness_factor1 = np.random.uniform(0.75,1.25,size =",
"frames') remaining_num_frames = params.num_frames - len(sparse_clip) sparse_clip = sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip =",
"len(sparse_clip)>13: # if params.num_frames - len(sparse_clip) >= 1: # print(f'sparse_clip {vid_path} is missing",
"> 0.25: image = trans.functional.adjust_gamma(image, gamma = gamma1, gain=1) #gamma range [0.8, 1.2]",
"if len(dense_clip3) < params.num_frames and len(dense_clip3)>7: # if params.num_frames - len(dense_clip3) >= 1:",
"self.shuffle = shuffle if self.shuffle: random.shuffle(self.all_paths) self.data_percentage = data_percentage self.data_limit = int(len(self.all_paths)*self.data_percentage) self.data",
"random_array[0], x_erase[0], y_erase[0], cropping_factor1[0],\\ x0[0], y0[0], contrast_factor1[0], hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame,",
"None, None, None, None, None, None def augmentation(self, image, random_array, x_erase, y_erase, cropping_factor1,\\",
"hue_factor1) # hue factor will be between [-0.1, 0.1] if random_array[2] < 0.3",
"open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split ==3: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid split input:",
"frame_count <= 56: # print(f'Video {vid_path} has insufficient frames') return None, None, None,",
"None, None, None, None, None, None, None, None, None ############################# frame_list maker start",
"= 4 else: start_frame = 0 sr_sparse = 4 sr_dense = int(sr_sparse/4) frames_sparse",
"x_erase = np.random.randint(0,params.reso_h, size = (10,)) y_erase = np.random.randint(0,params.reso_w, size = (10,)) cropping_factor1",
"params.num_frames - len(sparse_clip) sparse_clip = sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip = a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1]",
"1.25 if random_array[1] < 0.3 : image = trans.functional.adjust_hue(image, hue_factor = hue_factor1) #",
"4 sr_dense = int(sr_sparse/4) frames_sparse = [start_frame] + [start_frame + i*sr_sparse for i",
"a_dense_clip2, a_dense_clip3, list_sparse, list_dense = self.build_clip(vid_path) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\",
"random_array[0] < 0.125: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if",
"True, data_percentage = 1.0, split = 1): ##################### # self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if",
"= cv2.VideoCapture(vid_path) cap.set(1, 0) frame_count = cap.get(7) if frame_count <= 56: # print(f'Video",
"(count not in frames_dense[1]) and (count not in frames_dense[2]) \\ and (count not",
"random.shuffle(self.all_paths) self.data_percentage = data_percentage self.data_limit = int(len(self.all_paths)*self.data_percentage) self.data = self.all_paths[0: self.data_limit] self.PIL =",
"for i, (sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3,",
"cap.get(7) if frame_count <= 56: # print(f'Video {vid_path} has insufficient frames') return None,",
"= (10,)) gamma1 = np.random.uniform(0.75,1.25, size = (10,)) erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size, size =",
"saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3], y_erase[3], cropping_factor1[3],\\ x0[3], y0[3], contrast_factor1[3], hue_factor1[3],",
"= trans.functional.erase(image, x_erase, y_erase, erase_size1, erase_size2, v=0) return image def collate_fn2(batch): sparse_clip, dense_clip0,",
"decord import VideoReader class ss_dataset_gen1(Dataset): def __init__(self, shuffle = True, data_percentage = 1.0,",
"np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision import",
"build_clip(self, vid_path): try: cap = cv2.VideoCapture(vid_path) cap.set(1, 0) frame_count = cap.get(7) if frame_count",
"= np.random.uniform(0.75,1.25, size = (10,)) hue_factor1 = np.random.uniform(-0.1,0.1, size = (10,)) saturation_factor1 =",
"saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count) if (count in frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6], y_erase[6],",
"{vid_path} is missing {params.num_frames - len(dense_clip3)} frames') remaining_num_frames = params.num_frames - len(dense_clip3) dense_clip3",
"hue_factor1, saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped): image = self.PIL(image) image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0]",
"== '__main__': train_dataset = ss_dataset_gen1(shuffle = True, data_percentage = 1.0) train_dataloader = DataLoader(train_dataset,",
"if random_array[5] > 0.25: image = trans.functional.adjust_gamma(image, gamma = gamma1, gain=1) #gamma range",
"sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0], y_erase[0], cropping_factor1[0],\\ x0[0], y0[0], contrast_factor1[0], hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0]))",
"missing {params.num_frames - len(dense_clip3)} frames') remaining_num_frames = params.num_frames - len(dense_clip3) dense_clip3 = dense_clip3",
"= 4 sr_dense = int(sr_sparse/4) frames_sparse = [start_frame] + [start_frame + i*sr_sparse for",
"random_array[6] > 0.5: image = trans.functional.hflip(image) image = trans.functional.to_tensor(image) if random_array[7] < 0.5",
"\\ list_sparse, list_dense, vid_path = [], [], [], [], [], [], [], [],",
"in range(10)] contrast_factor1 = np.random.uniform(0.75,1.25, size = (10,)) hue_factor1 = np.random.uniform(-0.1,0.1, size =",
"size = (10,)) hue_factor1 = np.random.uniform(-0.1,0.1, size = (10,)) saturation_factor1 = np.random.uniform(0.75,1.25, size",
"saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9], y_erase[9], cropping_factor1[9],\\ x0[9], y0[9], contrast_factor1[9], hue_factor1[9],",
"random_array, x_erase, y_erase, cropping_factor1,\\ x0, y0, contrast_factor1, hue_factor1, saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped): image",
"cropping_factor1[8],\\ x0[8], y0[8], contrast_factor1[8], hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9], y_erase[9],",
"idx): vid_path = cfg.path_folder + '/UCF-101/' + self.data[idx].split(' ')[0] sparse_clip, dense_clip0, dense_clip1, dense_clip2,",
"np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) random_color_dropped = np.random.randint(0,3,(10))",
"x0[1], y0[1], contrast_factor1[1], hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count) if (count in frames_dense[0]):",
"as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision",
"y0[6], contrast_factor1[6], hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7], y_erase[7], cropping_factor1[7],\\ x0[7],",
"dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path) in",
"a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense except: print(f'Clip {vid_path} has some frames reading",
"self.erase_size = 19 def __len__(self): return len(self.data) def __getitem__(self,index): sparse_clip, dense_clip0, dense_clip1, dense_clip2,",
"[] list_dense = [[] for i in range(4)] count = -1 random_array =",
"4 is the skip rate ratio = 4 chunks # if skip_max >=",
"from decord import VideoReader class ss_dataset_gen1(Dataset): def __init__(self, shuffle = True, data_percentage =",
"= 3) if random_array[5] > 0.25: image = trans.functional.adjust_gamma(image, gamma = gamma1, gain=1)",
"1.0) train_dataloader = DataLoader(train_dataset, batch_size=40, \\ shuffle=False, num_workers=4, collate_fn=collate_fn2) print(f'Step involved: {len(train_dataset)/24}') t=time.time()",
"\\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path) in enumerate(train_dataloader): if (i+1)%25",
"x0[0], y0[0], contrast_factor1[0], hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1], y_erase[1], cropping_factor1[1],\\",
"= open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split ==2: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split ==3:",
"not in frames_sparse) and (count not in frames_dense[0]) \\ and (count not in",
"= (10,)) cropping_factor1 = np.random.uniform(0.6, 1, size = (10,)) # on an average",
"torch.stack(a_dense_clip1, dim=0) a_dense_clip2 = torch.stack(a_dense_clip2, dim=0) a_dense_clip3 = torch.stack(a_dense_clip3, dim=0) return sparse_clip, dense_clip0,",
"continue if ret == True: if (count in frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0], y_erase[0],",
"x_erase[2], y_erase[2], cropping_factor1[2],\\ x0[2], y0[2], contrast_factor1[2], hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3],",
"gamma1, gain=1) #gamma range [0.8, 1.2] else: image = trans.functional.to_tensor(image) image[random_color_dropped,:,:] = 0",
"try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\",
"random_array[5] > 0.25: image = trans.functional.adjust_gamma(image, gamma = gamma1, gain=1) #gamma range [0.8,",
"sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense,",
"y_erase[2], cropping_factor1[2],\\ x0[2], y0[2], contrast_factor1[2], hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3],",
"in frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6], y_erase[6], cropping_factor1[6],\\ x0[6], y0[6], contrast_factor1[6], hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\",
"torch.stack(dense_clip3, dim=0) a_sparse_clip = torch.stack(a_sparse_clip, dim=0) a_dense_clip0 = torch.stack(a_dense_clip0, dim=0) a_dense_clip1 = torch.stack(a_dense_clip1,",
"> 0.5: image = trans.functional.hflip(image) image = trans.functional.to_tensor(image) if random_array[7] < 0.5 :",
"= 1): ##################### # self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split == 1: self.all_paths =",
"[] for item in batch: if not (None in item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0))",
"= torch.stack(a_dense_clip2, dim=0) a_dense_clip3 = torch.stack(a_dense_clip3, dim=0) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3,",
"gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5], y_erase[5], cropping_factor1[5],\\ x0[5], y0[5], contrast_factor1[5], hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\",
"image = trans.functional.adjust_saturation(image, saturation_factor = saturation_factor1) # brightness factor will be between [0.75,",
"a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1], y_erase[1], cropping_factor1[1],\\ x0[1], y0[1], contrast_factor1[1], hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1]))",
"issue, failed') return None, None, None, None, None, None, None, None, None, None,",
"a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path = [], [],",
"if params.num_frames - len(sparse_clip) >= 1: # print(f'sparse_clip {vid_path} is missing {params.num_frames -",
"(None in item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0))",
"torch.stack(a_sparse_clip, dim=0) a_dense_clip0 = torch.stack(a_dense_clip0, dim=0) a_dense_clip1 = torch.stack(a_dense_clip1, dim=0) a_dense_clip2 = torch.stack(a_dense_clip2,",
"torchvision import transforms, utils import config as cfg import random import pickle import",
"(skip_max>=8): # sr_sparse = np.random.choice([4,8]) # else: sr_sparse = 4 else: start_frame =",
"dense_clip2 = torch.stack(dense_clip2, dim=0) dense_clip3 = torch.stack(dense_clip3, dim=0) a_sparse_clip = torch.stack(a_sparse_clip, dim=0) a_dense_clip0",
"- len(sparse_clip)} frames') remaining_num_frames = params.num_frames - len(sparse_clip) sparse_clip = sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1]",
"open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split == 1: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split ==2: self.all_paths",
"minimum 64 frames) and 2 augmented versions of 4 dense clips (covering 16",
"size = (10,)) y_erase = np.random.randint(0,params.reso_w, size = (10,)) cropping_factor1 = np.random.uniform(0.6, 1,",
"< 0.5 : image = trans.functional.erase(image, x_erase, y_erase, erase_size1, erase_size2, v=0) return image",
"dim=0) a_sparse_clip = torch.stack(a_sparse_clip, dim=0) a_dense_clip0 = torch.stack(a_dense_clip0, dim=0) a_dense_clip1 = torch.stack(a_dense_clip1, dim=0)",
"(10,)) erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) random_color_dropped = np.random.randint(0,3,(10)) while(cap.isOpened()): count +=",
"self.data_limit = int(len(self.all_paths)*self.data_percentage) self.data = self.all_paths[0: self.data_limit] self.PIL = trans.ToPILImage() self.TENSOR = trans.ToTensor()",
"gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3], y_erase[3], cropping_factor1[3],\\ x0[3], y0[3], contrast_factor1[3], hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\",
"saturation_factor1 = np.random.uniform(0.75,1.25, size = (10,)) brightness_factor1 = np.random.uniform(0.75,1.25,size = (10,)) gamma1 =",
"len(dense_clip3) dense_clip3 = dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 = a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames)",
"x_erase[5], y_erase[5], cropping_factor1[5],\\ x0[5], y0[5], contrast_factor1[5], hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count) if",
"print(f'Clip {vid_path} has some frames reading issue, failed') return None, None, None, None,",
"size = (10,)) brightness_factor1 = np.random.uniform(0.75,1.25,size = (10,)) gamma1 = np.random.uniform(0.75,1.25, size =",
"dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def",
"frames_dense[2]) \\ and (count not in frames_dense[3])) and (ret == True): continue if",
"2 augmented versions of 4 dense clips (covering 16 frames temporal span minimum)'''",
"trans.functional.adjust_saturation(image, saturation_factor = saturation_factor1) # brightness factor will be between [0.75, 1,25] if",
"contrast_factor1[2], hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3], y_erase[3], cropping_factor1[3],\\ x0[3], y0[3],",
"params.num_frames and len(dense_clip3)>7: # if params.num_frames - len(dense_clip3) >= 1: # print(f'dense_clip3 {vid_path}",
"= saturation_factor1) # brightness factor will be between [0.75, 1,25] if random_array[3] <",
"+= 1 ret, frame = cap.read() if ((count not in frames_sparse) and (count",
"pickle import parameters as params import json import math import cv2 # from",
"cropping_factor1[9],\\ x0[9], y0[9], contrast_factor1[9], hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count) else: break if",
"cropping_factor1[2],\\ x0[2], y0[2], contrast_factor1[2], hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3], y_erase[3],",
"[], [], [] for item in batch: if not (None in item): sparse_clip.append(torch.stack(item[0],dim=0))",
"= [start_frame] + [start_frame + i*sr_sparse for i in range(1,params.num_frames)] frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4]",
">= 1: # print(f'sparse_clip {vid_path} is missing {params.num_frames - len(sparse_clip)} frames') remaining_num_frames =",
"len(sparse_clip) >= 1: # print(f'sparse_clip {vid_path} is missing {params.num_frames - len(sparse_clip)} frames') remaining_num_frames",
"(count in frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2], y_erase[2], cropping_factor1[2],\\ x0[2], y0[2], contrast_factor1[2], hue_factor1[2], saturation_factor1[2],",
"self.PIL = trans.ToPILImage() self.TENSOR = trans.ToTensor() self.erase_size = 19 def __len__(self): return len(self.data)",
"a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def process_data(self, idx): vid_path = cfg.path_folder + '/UCF-101/'",
"= [] a_dense_clip1 = [] a_dense_clip2 = [] a_dense_clip3 = [] list_sparse =",
"process_data(self, idx): vid_path = cfg.path_folder + '/UCF-101/' + self.data[idx].split(' ')[0] sparse_clip, dense_clip0, dense_clip1,",
"= data_percentage self.data_limit = int(len(self.all_paths)*self.data_percentage) self.data = self.all_paths[0: self.data_limit] self.PIL = trans.ToPILImage() self.TENSOR",
"skip rate ratio = 4 chunks # if skip_max >= 16: # sr_sparse",
"a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5], y_erase[5], cropping_factor1[5],\\ x0[5], y0[5], contrast_factor1[5], hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5]))",
"[] a_dense_clip1 = [] a_dense_clip2 = [] a_dense_clip3 = [] list_sparse = []",
"config as cfg import random import pickle import parameters as params import json",
"\\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense = self.build_clip(vid_path) return sparse_clip, dense_clip0,",
"frame list maker finishes here ########################### ################################ actual clip builder starts here ##########################",
"random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3], y_erase[3], cropping_factor1[3],\\ x0[3], y0[3], contrast_factor1[3], hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3],",
"random_color_dropped = np.random.randint(0,3,(10)) while(cap.isOpened()): count += 1 ret, frame = cap.read() if ((count",
"augmented version of a sparse clip (covering minimum 64 frames) and 2 augmented",
"a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip = torch.stack(sparse_clip, dim=0) dense_clip0 = torch.stack(dense_clip0, dim=0)",
"sr_sparse = np.random.choice([4,8,12]) # elif (skip_max<12) and (skip_max>=8): # sr_sparse = np.random.choice([4,8]) #",
"if __name__ == '__main__': train_dataset = ss_dataset_gen1(shuffle = True, data_percentage = 1.0) train_dataloader",
"def __init__(self, shuffle = True, data_percentage = 1.0, split = 1): ##################### #",
"'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split ==3: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid split input: {split}')",
"- len(sparse_clip) >= 1: # print(f'sparse_clip {vid_path} is missing {params.num_frames - len(sparse_clip)} frames')",
"==2: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split ==3: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else:",
"0.125 and random_array[0] < 0.25: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to",
"[] a_dense_clip3 = [] list_sparse = [] list_dense = [[] for i in",
"break if len(sparse_clip) < params.num_frames and len(sparse_clip)>13: # if params.num_frames - len(sparse_clip) >=",
"if (count in frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2], y_erase[2], cropping_factor1[2],\\ x0[2], y0[2], contrast_factor1[2], hue_factor1[2],",
"involved: {len(train_dataset)/24}') t=time.time() for i, (sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0,",
"i*sr_dense for i in range(1,params.num_frames)] for j in range(4)] ################################ frame list maker",
"shuffle = True, data_percentage = 1.0, split = 1): ##################### # self.all_paths =",
"frames_dense[0]) \\ and (count not in frames_dense[1]) and (count not in frames_dense[2]) \\",
"(10,)) gamma1 = np.random.uniform(0.75,1.25, size = (10,)) erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,))",
"# elif (skip_max<12) and (skip_max>=8): # sr_sparse = np.random.choice([4,8]) # else: sr_sparse =",
"enumerate(train_dataloader): if (i+1)%25 == 0: print(sparse_clip.shape) print(dense_clip3.shape) print() print(f'Time taken to load data",
"[np.random.randint(0, params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii] + 1) for ii in range(10)] y0 = [np.random.randint(0,",
"batch_size=40, \\ shuffle=False, num_workers=4, collate_fn=collate_fn2) print(f'Step involved: {len(train_dataset)/24}') t=time.time() for i, (sparse_clip, dense_clip0,",
"self.data[idx].split(' ')[0] sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3,",
"random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9], y_erase[9], cropping_factor1[9],\\ x0[9], y0[9], contrast_factor1[9], hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9],",
"#Dynamic skip rate experiment # skip_max = int((frame_count - start_frame)/params.num_frames) # # here",
"y0 = [np.random.randint(0, params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii] + 1) for ii in range(10)] contrast_factor1",
"contrast_factor1[3], hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count) if (count in frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4],",
"remaining_num_frames = params.num_frames - len(sparse_clip) sparse_clip = sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip = a_sparse_clip",
"a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip = torch.stack(sparse_clip, dim=0) dense_clip0 = torch.stack(dense_clip0,",
"has insufficient frames') return None, None, None, None, None, None, None, None, None,",
"import time import torchvision.transforms as trans # from decord import VideoReader class ss_dataset_gen1(Dataset):",
"else: start_frame = 0 sr_sparse = 4 sr_dense = int(sr_sparse/4) frames_sparse = [start_frame]",
"19 def __len__(self): return len(self.data) def __getitem__(self,index): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\",
"dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense = self.build_clip(vid_path) return",
"None, None, None, None, None, None, None def augmentation(self, image, random_array, x_erase, y_erase,",
"list_sparse, list_dense, vid_path = [], [], [], [], [], [], [], [], [],",
"params.ori_reso_w*cropping_factor1[ii] + 1) for ii in range(10)] y0 = [np.random.randint(0, params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii]",
"+ self.data[idx].split(' ')[0] sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2,",
"in range(10)] y0 = [np.random.randint(0, params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii] + 1) for ii in",
"in range(1,params.num_frames)] frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense for i in range(1,params.num_frames)] for j",
"frames_dense[3])) and (ret == True): continue if ret == True: if (count in",
"not in frames_dense[2]) \\ and (count not in frames_dense[3])) and (ret == True):",
"for i in range(4)] count = -1 random_array = np.random.rand(10,8) x_erase = np.random.randint(0,params.reso_h,",
"= dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 = a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames)",
"rate ratio = 4 chunks # if skip_max >= 16: # sr_sparse =",
"image def collate_fn2(batch): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2,",
"ret == True: if (count in frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0], y_erase[0], cropping_factor1[0],\\ x0[0],",
"import tqdm import time import torchvision.transforms as trans # from decord import VideoReader",
"random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1], y_erase[1], cropping_factor1[1],\\ x0[1], y0[1], contrast_factor1[1], hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1],",
"+ i*sr_sparse for i in range(1,params.num_frames)] frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense for i",
"params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii] + 1) for ii in range(10)] contrast_factor1 = np.random.uniform(0.75,1.25, size",
"(10,)) cropping_factor1 = np.random.uniform(0.6, 1, size = (10,)) # on an average cropping",
"self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split ==2: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split",
"saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7], y_erase[7], cropping_factor1[7],\\ x0[7], y0[7], contrast_factor1[7], hue_factor1[7],",
"gamma1,erase_size1,erase_size2, random_color_dropped): image = self.PIL(image) image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0] < 0.125: image",
"[-0.1, 0.1] if random_array[2] < 0.3 : image = trans.functional.adjust_saturation(image, saturation_factor = saturation_factor1)",
"80% i.e. covers 64% area x0 = [np.random.randint(0, params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii] + 1)",
"frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2], y_erase[2], cropping_factor1[2],\\ x0[2], y0[2], contrast_factor1[2], hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2],",
"= brightness_factor1) # brightness factor will be between [0.75, 1,25] if random_array[0] >",
"import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision import transforms,",
"cropping_factor1[4],\\ x0[4], y0[4], contrast_factor1[4], hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5], y_erase[5],",
"import cv2 # from tqdm import tqdm import time import torchvision.transforms as trans",
"assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2,",
"dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path = [],",
"None, None except: print(f'Clip {vid_path} has some unknown issue, failed') return None, None,",
"1.25 if random_array[4] > 0.70: if random_array[4] < 0.875: image = trans.functional.to_grayscale(image, num_output_channels",
"list_sparse, list_dense, vid_path if __name__ == '__main__': train_dataset = ss_dataset_gen1(shuffle = True, data_percentage",
"if ret == True: if (count in frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0], y_erase[0], cropping_factor1[0],\\",
"list_dense[0].append(count) if (count in frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4], y_erase[4], cropping_factor1[4],\\ x0[4], y0[4], contrast_factor1[4],",
"< params.num_frames and len(sparse_clip)>13: # if params.num_frames - len(sparse_clip) >= 1: # print(f'sparse_clip",
"finishes here ########################### ################################ actual clip builder starts here ########################## sparse_clip = []",
"between [0.75, 1,25] if random_array[0] > 0.125 and random_array[0] < 0.25: image =",
"\\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def process_data(self, idx): vid_path",
"= np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip rate experiment # skip_max = int((frame_count - start_frame)/params.num_frames) #",
"of a sparse clip (covering minimum 64 frames) and 2 augmented versions of",
"- params.ori_reso_w*cropping_factor1[ii] + 1) for ii in range(10)] y0 = [np.random.randint(0, params.ori_reso_h -",
"average cropping factor is 80% i.e. covers 64% area x0 = [np.random.randint(0, params.ori_reso_w",
"= np.random.uniform(0.6, 1, size = (10,)) # on an average cropping factor is",
"elif (skip_max<16) and (skip_max>=12): # sr_sparse = np.random.choice([4,8,12]) # elif (skip_max<12) and (skip_max>=8):",
"- params.ori_reso_h*cropping_factor1[ii] + 1) for ii in range(10)] contrast_factor1 = np.random.uniform(0.75,1.25, size =",
"############################# frame_list maker start here################################# min_temporal_span_sparse = params.num_frames*params.sr_ratio if frame_count > min_temporal_span_sparse: start_frame",
"a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3) < params.num_frames and len(dense_clip3)>7: # if params.num_frames -",
"# if params.num_frames - len(dense_clip3) >= 1: # print(f'dense_clip3 {vid_path} is missing {params.num_frames",
"image = self.PIL(image) image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0] < 0.125: image = trans.functional.adjust_contrast(image,",
"cv2.VideoCapture(vid_path) cap.set(1, 0) frame_count = cap.get(7) if frame_count <= 56: # print(f'Video {vid_path}",
"[] dense_clip3 = [] a_sparse_clip = [] a_dense_clip0 = [] a_dense_clip1 = []",
"return image def collate_fn2(batch): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1,",
"return None, None, None, None, None, None, None, None, None, None, None, None",
"dense_clip1 = [] dense_clip2 = [] dense_clip3 = [] a_sparse_clip = [] a_dense_clip0",
"int(sr_sparse/4) frames_sparse = [start_frame] + [start_frame + i*sr_sparse for i in range(1,params.num_frames)] frames_dense",
"= np.random.uniform(-0.1,0.1, size = (10,)) saturation_factor1 = np.random.uniform(0.75,1.25, size = (10,)) brightness_factor1 =",
"cropping_factor1[5],\\ x0[5], y0[5], contrast_factor1[5], hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count) if (count in",
"= a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3) < params.num_frames and len(dense_clip3)>7: # if params.num_frames",
"list_dense[3].append(count) else: break if len(sparse_clip) < params.num_frames and len(sparse_clip)>13: # if params.num_frames -",
"os import torch import numpy as np import matplotlib.pyplot as plt from torch.utils.data",
"cropping_factor1[6],\\ x0[6], y0[6], contrast_factor1[6], hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7], y_erase[7],",
"not in frames_dense[1]) and (count not in frames_dense[2]) \\ and (count not in",
"dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path = self.process_data(index)",
"None, None, None, None, None, None, None, None, None, None ############################# frame_list maker",
"(ret == True): continue if ret == True: if (count in frames_sparse): sparse_clip.append(self.augmentation(frame,",
"remaining_num_frames = params.num_frames - len(dense_clip3) dense_clip3 = dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 = a_dense_clip3",
"contrast_factor1) #0.75 to 1.25 if random_array[4] > 0.70: if random_array[4] < 0.875: image",
"i, (sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\",
"a_dense_clip3, list_sparse, list_dense, vid_path = self.process_data(index) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\",
"a master DL that provides 2 augmented version of a sparse clip (covering",
"a_dense_clip0 = [] a_dense_clip1 = [] a_dense_clip2 = [] a_dense_clip3 = [] list_sparse",
"and (count not in frames_dense[1]) and (count not in frames_dense[2]) \\ and (count",
"= contrast_factor1) #0.75 to 1.25 if random_array[1] < 0.3 : image = trans.functional.adjust_hue(image,",
"len(self.data) def __getitem__(self,index): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2,",
"list_dense[2].append(count) if (count in frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8], y_erase[8], cropping_factor1[8],\\ x0[8], y0[8], contrast_factor1[8],",
"image = trans.functional.hflip(image) image = trans.functional.to_tensor(image) if random_array[7] < 0.5 : image =",
"x0[4], y0[4], contrast_factor1[4], hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5], y_erase[5], cropping_factor1[5],\\",
"torch import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset,",
"# sr_sparse = np.random.choice([4,8,12]) # elif (skip_max<12) and (skip_max>=8): # sr_sparse = np.random.choice([4,8])",
"image, random_array, x_erase, y_erase, cropping_factor1,\\ x0, y0, contrast_factor1, hue_factor1, saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped):",
"= trans.functional.adjust_gamma(image, gamma = gamma1, gain=1) #gamma range [0.8, 1.2] else: image =",
"start here################################# min_temporal_span_sparse = params.num_frames*params.sr_ratio if frame_count > min_temporal_span_sparse: start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic",
"[start_frame + i*sr_sparse for i in range(1,params.num_frames)] frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense for",
"starts here ########################## sparse_clip = [] dense_clip0 = [] dense_clip1 = [] dense_clip2",
"sparse_clip = torch.stack(sparse_clip, dim=0) dense_clip0 = torch.stack(dense_clip0, dim=0) dense_clip1 = torch.stack(dense_clip1, dim=0) dense_clip2",
"t=time.time() for i, (sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2,",
"dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8], y_erase[8], cropping_factor1[8],\\ x0[8], y0[8], contrast_factor1[8], hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8]))",
"y_erase[7], cropping_factor1[7],\\ x0[7], y0[7], contrast_factor1[7], hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count) if (count",
"size = (10,)) cropping_factor1 = np.random.uniform(0.6, 1, size = (10,)) # on an",
"= [] list_sparse = [] list_dense = [[] for i in range(4)] count",
"brightness factor will be between [0.75, 1,25] if random_array[3] < 0.3 : image",
"missing {params.num_frames - len(sparse_clip)} frames') remaining_num_frames = params.num_frames - len(sparse_clip) sparse_clip = sparse_clip",
"int((frame_count - start_frame)/params.num_frames) # # here 4 is the skip rate ratio =",
"trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0] < 0.125: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to",
"return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse,",
"count = -1 random_array = np.random.rand(10,8) x_erase = np.random.randint(0,params.reso_h, size = (10,)) y_erase",
"')[0] sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse,",
"# # here 4 is the skip rate ratio = 4 chunks #",
"self.data_limit] self.PIL = trans.ToPILImage() self.TENSOR = trans.ToTensor() self.erase_size = 19 def __len__(self): return",
"= np.random.randint(0,params.reso_h, size = (10,)) y_erase = np.random.randint(0,params.reso_w, size = (10,)) cropping_factor1 =",
"a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7], y_erase[7], cropping_factor1[7],\\ x0[7], y0[7], contrast_factor1[7], hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7]))",
"if random_array[3] < 0.3 : image = trans.functional.adjust_brightness(image, brightness_factor = brightness_factor1) # brightness",
"def __len__(self): return len(self.data) def __getitem__(self,index): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip,",
"import math import cv2 # from tqdm import tqdm import time import torchvision.transforms",
"time import torchvision.transforms as trans # from decord import VideoReader class ss_dataset_gen1(Dataset): def",
"return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\",
"frame_list maker start here################################# min_temporal_span_sparse = params.num_frames*params.sr_ratio if frame_count > min_temporal_span_sparse: start_frame =",
"dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path =",
"'__main__': train_dataset = ss_dataset_gen1(shuffle = True, data_percentage = 1.0) train_dataloader = DataLoader(train_dataset, batch_size=40,",
"cropping_factor1[1],\\ x0[1], y0[1], contrast_factor1[1], hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count) if (count in",
"shuffle if self.shuffle: random.shuffle(self.all_paths) self.data_percentage = data_percentage self.data_limit = int(len(self.all_paths)*self.data_percentage) self.data = self.all_paths[0:",
"= [] list_dense = [[] for i in range(4)] count = -1 random_array",
"image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[1] < 0.3",
"==3: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid split input: {split}') ##################### self.shuffle =",
"split ==3: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid split input: {split}') ##################### self.shuffle",
"0.875: image = trans.functional.to_grayscale(image, num_output_channels = 3) if random_array[5] > 0.25: image =",
"a_dense_clip3, \\ list_sparse, list_dense, vid_path = [], [], [], [], [], [], [],",
"= (10,)) saturation_factor1 = np.random.uniform(0.75,1.25, size = (10,)) brightness_factor1 = np.random.uniform(0.75,1.25,size = (10,))",
"start_frame = 0 sr_sparse = 4 sr_dense = int(sr_sparse/4) frames_sparse = [start_frame] +",
"< 0.3 : image = trans.functional.adjust_hue(image, hue_factor = hue_factor1) # hue factor will",
"torch.stack(dense_clip1, dim=0) dense_clip2 = torch.stack(dense_clip2, dim=0) dense_clip3 = torch.stack(dense_clip3, dim=0) a_sparse_clip = torch.stack(a_sparse_clip,",
"start_frame)/params.num_frames) # # here 4 is the skip rate ratio = 4 chunks",
"#0.75 to 1.25 if random_array[1] < 0.3 : image = trans.functional.adjust_hue(image, hue_factor =",
"0.70: if random_array[4] < 0.875: image = trans.functional.to_grayscale(image, num_output_channels = 3) if random_array[5]",
"in enumerate(train_dataloader): if (i+1)%25 == 0: print(sparse_clip.shape) print(dense_clip3.shape) print() print(f'Time taken to load",
"in item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10]))",
"= -1 random_array = np.random.rand(10,8) x_erase = np.random.randint(0,params.reso_h, size = (10,)) y_erase =",
"x_erase[4], y_erase[4], cropping_factor1[4],\\ x0[4], y0[4], contrast_factor1[4], hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5],",
"= [] a_dense_clip3 = [] list_sparse = [] list_dense = [[] for i",
"0.1] if random_array[2] < 0.3 : image = trans.functional.adjust_saturation(image, saturation_factor = saturation_factor1) #",
"saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5], y_erase[5], cropping_factor1[5],\\ x0[5], y0[5], contrast_factor1[5], hue_factor1[5],",
"[], [], [], [], [], [] for item in batch: if not (None",
"{len(train_dataset)/24}') t=time.time() for i, (sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1,",
"(10,)) saturation_factor1 = np.random.uniform(0.75,1.25, size = (10,)) brightness_factor1 = np.random.uniform(0.75,1.25,size = (10,)) gamma1",
"= [] a_dense_clip2 = [] a_dense_clip3 = [] list_sparse = [] list_dense =",
"image[random_color_dropped,:,:] = 0 image = self.PIL(image) if random_array[6] > 0.5: image = trans.functional.hflip(image)",
"import torch import numpy as np import matplotlib.pyplot as plt from torch.utils.data import",
"version of a sparse clip (covering minimum 64 frames) and 2 augmented versions",
"as cfg import random import pickle import parameters as params import json import",
"master DL that provides 2 augmented version of a sparse clip (covering minimum",
"None, None, None, None, None, None ############################# frame_list maker start here################################# min_temporal_span_sparse =",
"# print(f'sparse_clip {vid_path} is missing {params.num_frames - len(sparse_clip)} frames') remaining_num_frames = params.num_frames -",
"a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path) in enumerate(train_dataloader): if (i+1)%25 ==",
"contrast_factor1[1], hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count) if (count in frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2],",
"if self.shuffle: random.shuffle(self.all_paths) self.data_percentage = data_percentage self.data_limit = int(len(self.all_paths)*self.data_percentage) self.data = self.all_paths[0: self.data_limit]",
"None, None, None, None, None def augmentation(self, image, random_array, x_erase, y_erase, cropping_factor1,\\ x0,",
"np.random.randint(0,3,(10)) while(cap.isOpened()): count += 1 ret, frame = cap.read() if ((count not in",
"dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense = self.build_clip(vid_path)",
"image = trans.functional.adjust_hue(image, hue_factor = hue_factor1) # hue factor will be between [-0.1,",
"dense_clip0 = torch.stack(dense_clip0, dim=0) dense_clip1 = torch.stack(dense_clip1, dim=0) dense_clip2 = torch.stack(dense_clip2, dim=0) dense_clip3",
"len(dense_clip3)} frames') remaining_num_frames = params.num_frames - len(dense_clip3) dense_clip3 = dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3",
"sparse clip (covering minimum 64 frames) and 2 augmented versions of 4 dense",
"len(sparse_clip) sparse_clip = sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip = a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3)",
"< 0.3 : image = trans.functional.adjust_saturation(image, saturation_factor = saturation_factor1) # brightness factor will",
"sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse,",
"augmented versions of 4 dense clips (covering 16 frames temporal span minimum)''' import",
"vid_path def process_data(self, idx): vid_path = cfg.path_folder + '/UCF-101/' + self.data[idx].split(' ')[0] sparse_clip,",
"list_sparse, list_dense, vid_path) in enumerate(train_dataloader): if (i+1)%25 == 0: print(sparse_clip.shape) print(dense_clip3.shape) print() print(f'Time",
"= 1.0) train_dataloader = DataLoader(train_dataset, batch_size=40, \\ shuffle=False, num_workers=4, collate_fn=collate_fn2) print(f'Step involved: {len(train_dataset)/24}')",
"a_sparse_clip = [] a_dense_clip0 = [] a_dense_clip1 = [] a_dense_clip2 = [] a_dense_clip3",
"\\ and (count not in frames_dense[1]) and (count not in frames_dense[2]) \\ and",
"sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip = a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3) < params.num_frames and len(dense_clip3)>7: #",
"'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split ==2: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split ==3: self.all_paths =",
"(count in frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4], y_erase[4], cropping_factor1[4],\\ x0[4], y0[4], contrast_factor1[4], hue_factor1[4], saturation_factor1[4],",
"params import json import math import cv2 # from tqdm import tqdm import",
"dense_clip3 = dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 = a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames)",
"factor will be between [-0.1, 0.1] if random_array[2] < 0.3 : image =",
"1.0, split = 1): ##################### # self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split == 1:",
"to 1.25 if random_array[4] > 0.70: if random_array[4] < 0.875: image = trans.functional.to_grayscale(image,",
": image = trans.functional.erase(image, x_erase, y_erase, erase_size1, erase_size2, v=0) return image def collate_fn2(batch):",
"a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip = torch.stack(sparse_clip, dim=0) dense_clip0",
"dense_clip3 = torch.stack(dense_clip3, dim=0) a_sparse_clip = torch.stack(a_sparse_clip, dim=0) a_dense_clip0 = torch.stack(a_dense_clip0, dim=0) a_dense_clip1",
"dense clips (covering 16 frames temporal span minimum)''' import os import torch import",
"if params.num_frames - len(dense_clip3) >= 1: # print(f'dense_clip3 {vid_path} is missing {params.num_frames -",
"if random_array[7] < 0.5 : image = trans.functional.erase(image, x_erase, y_erase, erase_size1, erase_size2, v=0)",
"= trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[1] < 0.3 :",
"dim=0) dense_clip3 = torch.stack(dense_clip3, dim=0) a_sparse_clip = torch.stack(a_sparse_clip, dim=0) a_dense_clip0 = torch.stack(a_dense_clip0, dim=0)",
"clip (covering minimum 64 frames) and 2 augmented versions of 4 dense clips",
"[], [], [], [], [], [], [] for item in batch: if not",
"trans.ToTensor() self.erase_size = 19 def __len__(self): return len(self.data) def __getitem__(self,index): sparse_clip, dense_clip0, dense_clip1,",
"params.num_frames - len(sparse_clip) >= 1: # print(f'sparse_clip {vid_path} is missing {params.num_frames - len(sparse_clip)}",
"x0[8], y0[8], contrast_factor1[8], hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9], y_erase[9], cropping_factor1[9],\\",
"utils import config as cfg import random import pickle import parameters as params",
"random_color_dropped[5])) list_dense[1].append(count) if (count in frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6], y_erase[6], cropping_factor1[6],\\ x0[6], y0[6],",
"= trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[4] > 0.70: if",
"random_array[7], x_erase[7], y_erase[7], cropping_factor1[7],\\ x0[7], y0[7], contrast_factor1[7], hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count)",
"cap.read() if ((count not in frames_sparse) and (count not in frames_dense[0]) \\ and",
"dataloader is an attemp to make a master DL that provides 2 augmented",
"[] dense_clip0 = [] dense_clip1 = [] dense_clip2 = [] dense_clip3 = []",
"# skip_max = int((frame_count - start_frame)/params.num_frames) # # here 4 is the skip",
"dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense except: print(f'Clip {vid_path} has",
"= trans.ToTensor() self.erase_size = 19 def __len__(self): return len(self.data) def __getitem__(self,index): sparse_clip, dense_clip0,",
"else: sr_sparse = 4 else: start_frame = 0 sr_sparse = 4 sr_dense =",
": image = trans.functional.adjust_hue(image, hue_factor = hue_factor1) # hue factor will be between",
"image = trans.functional.adjust_gamma(image, gamma = gamma1, gain=1) #gamma range [0.8, 1.2] else: image",
"dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip = torch.stack(sparse_clip, dim=0)",
"dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense except:",
"= gamma1, gain=1) #gamma range [0.8, 1.2] else: image = trans.functional.to_tensor(image) image[random_color_dropped,:,:] =",
"= self.PIL(image) if random_array[6] > 0.5: image = trans.functional.hflip(image) image = trans.functional.to_tensor(image) if",
"- len(dense_clip3) dense_clip3 = dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 = a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1] try:",
"vid_path def build_clip(self, vid_path): try: cap = cv2.VideoCapture(vid_path) cap.set(1, 0) frame_count = cap.get(7)",
"a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path) in enumerate(train_dataloader): if (i+1)%25 == 0:",
"here ########################## sparse_clip = [] dense_clip0 = [] dense_clip1 = [] dense_clip2 =",
"here 4 is the skip rate ratio = 4 chunks # if skip_max",
"= np.random.uniform(0.75,1.25,size = (10,)) gamma1 = np.random.uniform(0.75,1.25, size = (10,)) erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size,",
"random_array[3] < 0.3 : image = trans.functional.adjust_brightness(image, brightness_factor = brightness_factor1) # brightness factor",
"None, None, None, None, None, None, None, None, None, None, None ############################# frame_list",
"a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path = [], [], [], [], [], [],",
"dim=0) a_dense_clip0 = torch.stack(a_dense_clip0, dim=0) a_dense_clip1 = torch.stack(a_dense_clip1, dim=0) a_dense_clip2 = torch.stack(a_dense_clip2, dim=0)",
"= [] dense_clip3 = [] a_sparse_clip = [] a_dense_clip0 = [] a_dense_clip1 =",
"be between [0.75, 1,25] if random_array[0] > 0.125 and random_array[0] < 0.25: image",
"DataLoader(train_dataset, batch_size=40, \\ shuffle=False, num_workers=4, collate_fn=collate_fn2) print(f'Step involved: {len(train_dataset)/24}') t=time.time() for i, (sparse_clip,",
"as trans # from decord import VideoReader class ss_dataset_gen1(Dataset): def __init__(self, shuffle =",
"# if params.num_frames - len(sparse_clip) >= 1: # print(f'sparse_clip {vid_path} is missing {params.num_frames",
"params.num_frames - len(dense_clip3) dense_clip3 = dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 = a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1]",
"trans.functional.adjust_hue(image, hue_factor = hue_factor1) # hue factor will be between [-0.1, 0.1] if",
"= (10,)) hue_factor1 = np.random.uniform(-0.1,0.1, size = (10,)) saturation_factor1 = np.random.uniform(0.75,1.25, size =",
"random_array[2] < 0.3 : image = trans.functional.adjust_saturation(image, saturation_factor = saturation_factor1) # brightness factor",
"__name__ == '__main__': train_dataset = ss_dataset_gen1(shuffle = True, data_percentage = 1.0) train_dataloader =",
"a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def build_clip(self, vid_path): try: cap = cv2.VideoCapture(vid_path) cap.set(1,",
"= 0 sr_sparse = 4 sr_dense = int(sr_sparse/4) frames_sparse = [start_frame] + [start_frame",
"gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9], y_erase[9], cropping_factor1[9],\\ x0[9], y0[9], contrast_factor1[9], hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\",
"np.random.uniform(0.6, 1, size = (10,)) # on an average cropping factor is 80%",
"= torch.stack(a_dense_clip0, dim=0) a_dense_clip1 = torch.stack(a_dense_clip1, dim=0) a_dense_clip2 = torch.stack(a_dense_clip2, dim=0) a_dense_clip3 =",
"parameters as params import json import math import cv2 # from tqdm import",
"__getitem__(self,index): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse,",
"hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5], y_erase[5], cropping_factor1[5],\\ x0[5], y0[5], contrast_factor1[5],",
"x_erase[1], y_erase[1], cropping_factor1[1],\\ x0[1], y0[1], contrast_factor1[1], hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count) if",
"[0.75, 1,25] if random_array[0] > 0.125 and random_array[0] < 0.25: image = trans.functional.adjust_contrast(image,",
"skip_max >= 16: # sr_sparse = np.random.choice([4,8,12,16]) # elif (skip_max<16) and (skip_max>=12): #",
"def __getitem__(self,index): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3,",
"random_color_dropped[1])) list_sparse.append(count) if (count in frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2], y_erase[2], cropping_factor1[2],\\ x0[2], y0[2],",
"x0 = [np.random.randint(0, params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii] + 1) for ii in range(10)] y0",
"= [] dense_clip1 = [] dense_clip2 = [] dense_clip3 = [] a_sparse_clip =",
"[] dense_clip1 = [] dense_clip2 = [] dense_clip3 = [] a_sparse_clip = []",
"sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12])",
"hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9], y_erase[9], cropping_factor1[9],\\ x0[9], y0[9], contrast_factor1[9],",
"item in batch: if not (None in item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0))",
"print(f'Step involved: {len(train_dataset)/24}') t=time.time() for i, (sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\",
"dim=0) a_dense_clip2 = torch.stack(a_dense_clip2, dim=0) a_dense_clip3 = torch.stack(a_dense_clip3, dim=0) return sparse_clip, dense_clip0, dense_clip1,",
"a_dense_clip3, list_sparse, list_dense, vid_path def process_data(self, idx): vid_path = cfg.path_folder + '/UCF-101/' +",
"= torch.stack(a_dense_clip1, dim=0) a_dense_clip2 = torch.stack(a_dense_clip2, dim=0) a_dense_clip3 = torch.stack(a_dense_clip3, dim=0) return sparse_clip,",
"< 0.875: image = trans.functional.to_grayscale(image, num_output_channels = 3) if random_array[5] > 0.25: image",
"def process_data(self, idx): vid_path = cfg.path_folder + '/UCF-101/' + self.data[idx].split(' ')[0] sparse_clip, dense_clip0,",
"np.random.randint(0,params.reso_w, size = (10,)) cropping_factor1 = np.random.uniform(0.6, 1, size = (10,)) # on",
"= 0 image = self.PIL(image) if random_array[6] > 0.5: image = trans.functional.hflip(image) image",
"saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count) if (count in frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2], y_erase[2],",
"brightness_factor = brightness_factor1) # brightness factor will be between [0.75, 1,25] if random_array[0]",
"a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3) < params.num_frames and len(dense_clip3)>7: # if params.num_frames - len(dense_clip3) >=",
"# here 4 is the skip rate ratio = 4 chunks # if",
"elif (skip_max<12) and (skip_max>=8): # sr_sparse = np.random.choice([4,8]) # else: sr_sparse = 4",
"dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path",
"dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def build_clip(self,",
"if split == 1: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split ==2: self.all_paths =",
"open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split ==2: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split ==3: self.all_paths",
"(skip_max<16) and (skip_max>=12): # sr_sparse = np.random.choice([4,8,12]) # elif (skip_max<12) and (skip_max>=8): #",
"= trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0] < 0.125: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75",
"num_workers=4, collate_fn=collate_fn2) print(f'Step involved: {len(train_dataset)/24}') t=time.time() for i, (sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3,",
"y_erase[5], cropping_factor1[5],\\ x0[5], y0[5], contrast_factor1[5], hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count) if (count",
"56: # print(f'Video {vid_path} has insufficient frames') return None, None, None, None, None,",
"0.125: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[1] <",
"= [[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense for i in range(1,params.num_frames)] for j in range(4)] ################################",
"hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1], y_erase[1], cropping_factor1[1],\\ x0[1], y0[1], contrast_factor1[1],",
"has some frames reading issue, failed') return None, None, None, None, None, None,",
"random_array[0] < 0.25: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if",
"temporal span minimum)''' import os import torch import numpy as np import matplotlib.pyplot",
"frame_count = cap.get(7) if frame_count <= 56: # print(f'Video {vid_path} has insufficient frames')",
"some frames reading issue, failed') return None, None, None, None, None, None, None,",
"be between [0.75, 1,25] if random_array[3] < 0.3 : image = trans.functional.adjust_brightness(image, brightness_factor",
"contrast_factor1[4], hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5], y_erase[5], cropping_factor1[5],\\ x0[5], y0[5],",
"trans.functional.to_grayscale(image, num_output_channels = 3) if random_array[5] > 0.25: image = trans.functional.adjust_gamma(image, gamma =",
"count += 1 ret, frame = cap.read() if ((count not in frames_sparse) and",
"= trans.functional.to_tensor(image) if random_array[7] < 0.5 : image = trans.functional.erase(image, x_erase, y_erase, erase_size1,",
"image = self.PIL(image) if random_array[6] > 0.5: image = trans.functional.hflip(image) image = trans.functional.to_tensor(image)",
"dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense = self.build_clip(vid_path) return sparse_clip,",
"64% area x0 = [np.random.randint(0, params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii] + 1) for ii in",
"contrast_factor1[9], hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count) else: break if len(sparse_clip) < params.num_frames",
"True): continue if ret == True: if (count in frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0],",
"0 sr_sparse = 4 sr_dense = int(sr_sparse/4) frames_sparse = [start_frame] + [start_frame +",
"attemp to make a master DL that provides 2 augmented version of a",
"hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count) if (count in frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8],",
"torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils import config as cfg",
"None, None, None, None, None, None, None, None, None, None, None, None def",
"factor is 80% i.e. covers 64% area x0 = [np.random.randint(0, params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii]",
"a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip = torch.stack(sparse_clip, dim=0) dense_clip0 = torch.stack(dense_clip0, dim=0) dense_clip1",
"64 frames) and 2 augmented versions of 4 dense clips (covering 16 frames",
"random_array[7] < 0.5 : image = trans.functional.erase(image, x_erase, y_erase, erase_size1, erase_size2, v=0) return",
"2 augmented version of a sparse clip (covering minimum 64 frames) and 2",
"None, None, None, None def augmentation(self, image, random_array, x_erase, y_erase, cropping_factor1,\\ x0, y0,",
"= [np.random.randint(0, params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii] + 1) for ii in range(10)] y0 =",
"self.data_percentage = data_percentage self.data_limit = int(len(self.all_paths)*self.data_percentage) self.data = self.all_paths[0: self.data_limit] self.PIL = trans.ToPILImage()",
"if (count in frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8], y_erase[8], cropping_factor1[8],\\ x0[8], y0[8], contrast_factor1[8], hue_factor1[8],",
"and len(sparse_clip)>13: # if params.num_frames - len(sparse_clip) >= 1: # print(f'sparse_clip {vid_path} is",
"batch: if not (None in item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0))",
"i.e. covers 64% area x0 = [np.random.randint(0, params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii] + 1) for",
"{params.num_frames - len(sparse_clip)} frames') remaining_num_frames = params.num_frames - len(sparse_clip) sparse_clip = sparse_clip +",
"a_dense_clip3 = torch.stack(a_dense_clip3, dim=0) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0,",
"in range(1,params.num_frames)] for j in range(4)] ################################ frame list maker finishes here ###########################",
"y0, contrast_factor1, hue_factor1, saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped): image = self.PIL(image) image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2)",
"saturation_factor1) # brightness factor will be between [0.75, 1,25] if random_array[3] < 0.3",
"None, None, None, None, None, None, None, None except: print(f'Clip {vid_path} has some",
"dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2], y_erase[2], cropping_factor1[2],\\ x0[2], y0[2], contrast_factor1[2], hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2]))",
"cap.set(1, 0) frame_count = cap.get(7) if frame_count <= 56: # print(f'Video {vid_path} has",
"self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split ==3: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid",
"dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 = a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames)",
"# sr_sparse = np.random.choice([4,8]) # else: sr_sparse = 4 else: start_frame = 0",
"random_array[1], x_erase[1], y_erase[1], cropping_factor1[1],\\ x0[1], y0[1], contrast_factor1[1], hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count)",
"0) frame_count = cap.get(7) if frame_count <= 56: # print(f'Video {vid_path} has insufficient",
"= np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) random_color_dropped = np.random.randint(0,3,(10)) while(cap.isOpened()): count += 1 ret,",
"x_erase[9], y_erase[9], cropping_factor1[9],\\ x0[9], y0[9], contrast_factor1[9], hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count) else:",
"None, None, None, None, None, None, None except: print(f'Clip {vid_path} has some unknown",
"split == 1: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split ==2: self.all_paths = open(os.path.join(cfg.path_folder,",
"# self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split == 1: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif",
"open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid split input: {split}') ##################### self.shuffle = shuffle if self.shuffle:",
"params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii] + 1) for ii in range(10)] y0 = [np.random.randint(0, params.ori_reso_h",
"is missing {params.num_frames - len(dense_clip3)} frames') remaining_num_frames = params.num_frames - len(dense_clip3) dense_clip3 =",
"list_sparse, list_dense, vid_path def build_clip(self, vid_path): try: cap = cv2.VideoCapture(vid_path) cap.set(1, 0) frame_count",
"= int((frame_count - start_frame)/params.num_frames) # # here 4 is the skip rate ratio",
"frame = cap.read() if ((count not in frames_sparse) and (count not in frames_dense[0])",
"a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path if __name__ ==",
"tqdm import tqdm import time import torchvision.transforms as trans # from decord import",
"json import math import cv2 # from tqdm import tqdm import time import",
"item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11]))",
"list_dense = self.build_clip(vid_path) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1,",
"except: print(f'Clip {vid_path} has some unknown issue, failed') return None, None, None, None,",
"ss_dataset_gen1(Dataset): def __init__(self, shuffle = True, data_percentage = 1.0, split = 1): #####################",
"= np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) random_color_dropped =",
"= open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid split input: {split}') ##################### self.shuffle = shuffle if",
"= self.PIL(image) image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0] < 0.125: image = trans.functional.adjust_contrast(image, contrast_factor",
"[], [], [], [], [], [], [], [], [], [], [], [] for",
"print(f'Invalid split input: {split}') ##################### self.shuffle = shuffle if self.shuffle: random.shuffle(self.all_paths) self.data_percentage =",
"range(4)] ################################ frame list maker finishes here ########################### ################################ actual clip builder starts",
"= trans.functional.hflip(image) image = trans.functional.to_tensor(image) if random_array[7] < 0.5 : image = trans.functional.erase(image,",
"#0.75 to 1.25 if random_array[4] > 0.70: if random_array[4] < 0.875: image =",
"params.num_frames and len(sparse_clip)>13: # if params.num_frames - len(sparse_clip) >= 1: # print(f'sparse_clip {vid_path}",
"[0.75, 1,25] if random_array[3] < 0.3 : image = trans.functional.adjust_brightness(image, brightness_factor = brightness_factor1)",
"random_array[4], x_erase[4], y_erase[4], cropping_factor1[4],\\ x0[4], y0[4], contrast_factor1[4], hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame,",
"= hue_factor1) # hue factor will be between [-0.1, 0.1] if random_array[2] <",
"+ 1) for ii in range(10)] y0 = [np.random.randint(0, params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii] +",
"0.3 : image = trans.functional.adjust_hue(image, hue_factor = hue_factor1) # hue factor will be",
"random import pickle import parameters as params import json import math import cv2",
"i in range(1,params.num_frames)] frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense for i in range(1,params.num_frames)] for",
"dense_clip0 = [] dense_clip1 = [] dense_clip2 = [] dense_clip3 = [] a_sparse_clip",
"list_sparse, list_dense except: print(f'Clip {vid_path} has some frames reading issue, failed') return None,",
"= (10,)) # on an average cropping factor is 80% i.e. covers 64%",
"(10,)) brightness_factor1 = np.random.uniform(0.75,1.25,size = (10,)) gamma1 = np.random.uniform(0.75,1.25, size = (10,)) erase_size1",
"> 0.125 and random_array[0] < 0.25: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75",
"y0[1], contrast_factor1[1], hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count) if (count in frames_dense[0]): dense_clip0.append(self.augmentation(frame,",
"[[] for i in range(4)] count = -1 random_array = np.random.rand(10,8) x_erase =",
"= [np.random.randint(0, params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii] + 1) for ii in range(10)] contrast_factor1 =",
"len(dense_clip3) < params.num_frames and len(dense_clip3)>7: # if params.num_frames - len(dense_clip3) >= 1: #",
"None, None ############################# frame_list maker start here################################# min_temporal_span_sparse = params.num_frames*params.sr_ratio if frame_count >",
"some unknown issue, failed') return None, None, None, None, None, None, None, None,",
"self.PIL(image) image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0] < 0.125: image = trans.functional.adjust_contrast(image, contrast_factor =",
"if random_array[0] < 0.125: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25",
"if random_array[4] < 0.875: image = trans.functional.to_grayscale(image, num_output_channels = 3) if random_array[5] >",
"trans.ToPILImage() self.TENSOR = trans.ToTensor() self.erase_size = 19 def __len__(self): return len(self.data) def __getitem__(self,index):",
"None ############################# frame_list maker start here################################# min_temporal_span_sparse = params.num_frames*params.sr_ratio if frame_count > min_temporal_span_sparse:",
"if (count in frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0], y_erase[0], cropping_factor1[0],\\ x0[0], y0[0], contrast_factor1[0], hue_factor1[0],",
"brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count) else: break if len(sparse_clip) < params.num_frames and len(sparse_clip)>13: #",
"= True, data_percentage = 1.0, split = 1): ##################### # self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines()",
"None, None, None, None, None, None, None, None, None except: print(f'Clip {vid_path} has",
"contrast_factor1) #0.75 to 1.25 if random_array[1] < 0.3 : image = trans.functional.adjust_hue(image, hue_factor",
"gamma = gamma1, gain=1) #gamma range [0.8, 1.2] else: image = trans.functional.to_tensor(image) image[random_color_dropped,:,:]",
"(10,)) hue_factor1 = np.random.uniform(-0.1,0.1, size = (10,)) saturation_factor1 = np.random.uniform(0.75,1.25, size = (10,))",
"[0.8, 1.2] else: image = trans.functional.to_tensor(image) image[random_color_dropped,:,:] = 0 image = self.PIL(image) if",
"vid_path) in enumerate(train_dataloader): if (i+1)%25 == 0: print(sparse_clip.shape) print(dense_clip3.shape) print() print(f'Time taken to",
"y0[4], contrast_factor1[4], hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5], y_erase[5], cropping_factor1[5],\\ x0[5],",
"trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[1] < 0.3 : image",
"size = (10,)) erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size, size",
"list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip = torch.stack(sparse_clip, dim=0) dense_clip0 = torch.stack(dense_clip0, dim=0) dense_clip1 = torch.stack(dense_clip1,",
"y0[8], contrast_factor1[8], hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9], y_erase[9], cropping_factor1[9],\\ x0[9],",
"-1 random_array = np.random.rand(10,8) x_erase = np.random.randint(0,params.reso_h, size = (10,)) y_erase = np.random.randint(0,params.reso_w,",
"import config as cfg import random import pickle import parameters as params import",
"x0[7], y0[7], contrast_factor1[7], hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count) if (count in frames_dense[3]):",
"list_dense[1].append(count) if (count in frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6], y_erase[6], cropping_factor1[6],\\ x0[6], y0[6], contrast_factor1[6],",
"y_erase[9], cropping_factor1[9],\\ x0[9], y0[9], contrast_factor1[9], hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count) else: break",
"= contrast_factor1) #0.75 to 1.25 if random_array[4] > 0.70: if random_array[4] < 0.875:",
"frames') return None, None, None, None, None, None, None, None, None, None, None,",
"(10,)) y_erase = np.random.randint(0,params.reso_w, size = (10,)) cropping_factor1 = np.random.uniform(0.6, 1, size =",
"= torch.stack(dense_clip3, dim=0) a_sparse_clip = torch.stack(a_sparse_clip, dim=0) a_dense_clip0 = torch.stack(a_dense_clip0, dim=0) a_dense_clip1 =",
"np.random.uniform(0.75,1.25, size = (10,)) erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size,",
"make a master DL that provides 2 augmented version of a sparse clip",
"x0, y0, contrast_factor1, hue_factor1, saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped): image = self.PIL(image) image =",
"factor will be between [0.75, 1,25] if random_array[3] < 0.3 : image =",
"list_sparse, list_dense = self.build_clip(vid_path) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0,",
"assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0,",
"+ 1) for ii in range(10)] contrast_factor1 = np.random.uniform(0.75,1.25, size = (10,)) hue_factor1",
"len(sparse_clip)} frames') remaining_num_frames = params.num_frames - len(sparse_clip) sparse_clip = sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip",
"None, None, None def augmentation(self, image, random_array, x_erase, y_erase, cropping_factor1,\\ x0, y0, contrast_factor1,",
"= params.num_frames - len(dense_clip3) dense_clip3 = dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 = a_dense_clip3 +",
"list_sparse, list_dense, vid_path def process_data(self, idx): vid_path = cfg.path_folder + '/UCF-101/' + self.data[idx].split('",
"that provides 2 augmented version of a sparse clip (covering minimum 64 frames)",
"np.random.choice([4,8,12,16]) # elif (skip_max<16) and (skip_max>=12): # sr_sparse = np.random.choice([4,8,12]) # elif (skip_max<12)",
"dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense except: print(f'Clip {vid_path}",
"clips (covering 16 frames temporal span minimum)''' import os import torch import numpy",
"None, None, None, None ############################# frame_list maker start here################################# min_temporal_span_sparse = params.num_frames*params.sr_ratio if",
"in frames_sparse) and (count not in frames_dense[0]) \\ and (count not in frames_dense[1])",
"cropping_factor1,\\ x0, y0, contrast_factor1, hue_factor1, saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped): image = self.PIL(image) image",
"a_dense_clip3 = a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return sparse_clip,",
"3) if random_array[5] > 0.25: image = trans.functional.adjust_gamma(image, gamma = gamma1, gain=1) #gamma",
"in frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0], y_erase[0], cropping_factor1[0],\\ x0[0], y0[0], contrast_factor1[0], hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\",
"[], [], [], [], [], [], [], [], [], [], [] for item",
"brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped): image = self.PIL(image) image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0] < 0.125:",
"a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip = torch.stack(sparse_clip, dim=0) dense_clip0 =",
"[np.random.randint(0, params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii] + 1) for ii in range(10)] contrast_factor1 = np.random.uniform(0.75,1.25,",
"split = 1): ##################### # self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split == 1: self.all_paths",
"# print(f'dense_clip3 {vid_path} is missing {params.num_frames - len(dense_clip3)} frames') remaining_num_frames = params.num_frames -",
"\\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path = [], [], [],",
"assert(len(dense_clip3)==params.num_frames) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3,",
"a_dense_clip2 = [] a_dense_clip3 = [] list_sparse = [] list_dense = [[] for",
"in range(4)] count = -1 random_array = np.random.rand(10,8) x_erase = np.random.randint(0,params.reso_h, size =",
"data_percentage self.data_limit = int(len(self.all_paths)*self.data_percentage) self.data = self.all_paths[0: self.data_limit] self.PIL = trans.ToPILImage() self.TENSOR =",
"len(sparse_clip) < params.num_frames and len(sparse_clip)>13: # if params.num_frames - len(sparse_clip) >= 1: #",
"i in range(1,params.num_frames)] for j in range(4)] ################################ frame list maker finishes here",
"ii in range(10)] contrast_factor1 = np.random.uniform(0.75,1.25, size = (10,)) hue_factor1 = np.random.uniform(-0.1,0.1, size",
"r'''This dataloader is an attemp to make a master DL that provides 2",
"import Dataset, DataLoader from torchvision import transforms, utils import config as cfg import",
"gain=1) #gamma range [0.8, 1.2] else: image = trans.functional.to_tensor(image) image[random_color_dropped,:,:] = 0 image",
"sr_dense = int(sr_sparse/4) frames_sparse = [start_frame] + [start_frame + i*sr_sparse for i in",
"#gamma range [0.8, 1.2] else: image = trans.functional.to_tensor(image) image[random_color_dropped,:,:] = 0 image =",
"contrast_factor1[8], hue_factor1[8], saturation_factor1[8], brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9], y_erase[9], cropping_factor1[9],\\ x0[9], y0[9],",
"int(len(self.all_paths)*self.data_percentage) self.data = self.all_paths[0: self.data_limit] self.PIL = trans.ToPILImage() self.TENSOR = trans.ToTensor() self.erase_size =",
"1: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist01.txt'),'r').read().splitlines() elif split ==2: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif",
"list maker finishes here ########################### ################################ actual clip builder starts here ########################## sparse_clip",
"VideoReader class ss_dataset_gen1(Dataset): def __init__(self, shuffle = True, data_percentage = 1.0, split =",
"[start_frame] + [start_frame + i*sr_sparse for i in range(1,params.num_frames)] frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4] +",
"################################ frame list maker finishes here ########################### ################################ actual clip builder starts here",
"min_temporal_span_sparse: start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip rate experiment # skip_max = int((frame_count -",
"saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count) if (count in frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8], y_erase[8],",
"random_color_dropped): image = self.PIL(image) image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0] < 0.125: image =",
"for item in batch: if not (None in item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0))",
"((count not in frames_sparse) and (count not in frames_dense[0]) \\ and (count not",
"a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def build_clip(self, vid_path): try: cap = cv2.VideoCapture(vid_path)",
"vid_path = self.process_data(index) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1,",
"elif split ==2: self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist02.txt'),'r').read().splitlines() elif split ==3: self.all_paths = open(os.path.join(cfg.path_folder,",
"dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path",
"dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path)",
"num_output_channels = 3) if random_array[5] > 0.25: image = trans.functional.adjust_gamma(image, gamma = gamma1,",
"a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path if __name__ == '__main__': train_dataset",
"frames_sparse) and (count not in frames_dense[0]) \\ and (count not in frames_dense[1]) and",
"+ a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return sparse_clip, dense_clip0, dense_clip1, dense_clip2,",
"dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense,",
"+ '/UCF-101/' + self.data[idx].split(' ')[0] sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0,",
"reading issue, failed') return None, None, None, None, None, None, None, None, None,",
"vid_path = cfg.path_folder + '/UCF-101/' + self.data[idx].split(' ')[0] sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3,",
"transforms, utils import config as cfg import random import pickle import parameters as",
"x0[6], y0[6], contrast_factor1[6], hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7], y_erase[7], cropping_factor1[7],\\",
"self.PIL(image) if random_array[6] > 0.5: image = trans.functional.hflip(image) image = trans.functional.to_tensor(image) if random_array[7]",
"None, None, None, None, None, None, None, None, None, None def augmentation(self, image,",
"[[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense for i in range(1,params.num_frames)] for j in range(4)] ################################ frame",
"and (ret == True): continue if ret == True: if (count in frames_sparse):",
"def augmentation(self, image, random_array, x_erase, y_erase, cropping_factor1,\\ x0, y0, contrast_factor1, hue_factor1, saturation_factor1, brightness_factor1,\\",
"in range(4)] ################################ frame list maker finishes here ########################### ################################ actual clip builder",
"ii in range(10)] y0 = [np.random.randint(0, params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii] + 1) for ii",
"try: cap = cv2.VideoCapture(vid_path) cap.set(1, 0) frame_count = cap.get(7) if frame_count <= 56:",
"[], [] for item in batch: if not (None in item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0))",
"y0[9], contrast_factor1[9], hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count) else: break if len(sparse_clip) <",
"import random import pickle import parameters as params import json import math import",
"random_color_dropped[3])) list_dense[0].append(count) if (count in frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4], y_erase[4], cropping_factor1[4],\\ x0[4], y0[4],",
"[], [], [], [] for item in batch: if not (None in item):",
"random_array[9], x_erase[9], y_erase[9], cropping_factor1[9],\\ x0[9], y0[9], contrast_factor1[9], hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count)",
"a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense except: print(f'Clip {vid_path} has some frames reading issue,",
"\\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense except: print(f'Clip {vid_path} has some",
"for i in range(1,params.num_frames)] for j in range(4)] ################################ frame list maker finishes",
"'/UCF-101/' + self.data[idx].split(' ')[0] sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1,",
"collate_fn=collate_fn2) print(f'Step involved: {len(train_dataset)/24}') t=time.time() for i, (sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip,",
"from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils import config as",
"sr_sparse = 4 sr_dense = int(sr_sparse/4) frames_sparse = [start_frame] + [start_frame + i*sr_sparse",
"for j in range(4)] ################################ frame list maker finishes here ########################### ################################ actual",
"gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count) if (count in frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4], y_erase[4], cropping_factor1[4],\\ x0[4],",
"has some unknown issue, failed') return None, None, None, None, None, None, None,",
"self.all_paths[0: self.data_limit] self.PIL = trans.ToPILImage() self.TENSOR = trans.ToTensor() self.erase_size = 19 def __len__(self):",
"import VideoReader class ss_dataset_gen1(Dataset): def __init__(self, shuffle = True, data_percentage = 1.0, split",
"dense_clip3 = [] a_sparse_clip = [] a_dense_clip0 = [] a_dense_clip1 = [] a_dense_clip2",
"an attemp to make a master DL that provides 2 augmented version of",
"list_dense except: print(f'Clip {vid_path} has some frames reading issue, failed') return None, None,",
"brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count) if (count in frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8], y_erase[8], cropping_factor1[8],\\",
"< 0.125: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[1]",
"is 80% i.e. covers 64% area x0 = [np.random.randint(0, params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii] +",
"= np.random.choice([4,8,12]) # elif (skip_max<12) and (skip_max>=8): # sr_sparse = np.random.choice([4,8]) # else:",
"1,25] if random_array[0] > 0.125 and random_array[0] < 0.25: image = trans.functional.adjust_contrast(image, contrast_factor",
"a_sparse_clip = a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3) < params.num_frames and len(dense_clip3)>7: # if",
"torch.stack(a_dense_clip0, dim=0) a_dense_clip1 = torch.stack(a_dense_clip1, dim=0) a_dense_clip2 = torch.stack(a_dense_clip2, dim=0) a_dense_clip3 = torch.stack(a_dense_clip3,",
"random_array = np.random.rand(10,8) x_erase = np.random.randint(0,params.reso_h, size = (10,)) y_erase = np.random.randint(0,params.reso_w, size",
"x_erase, y_erase, erase_size1, erase_size2, v=0) return image def collate_fn2(batch): sparse_clip, dense_clip0, dense_clip1, dense_clip2,",
"saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count) if (count in frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4], y_erase[4],",
"gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7], y_erase[7], cropping_factor1[7],\\ x0[7], y0[7], contrast_factor1[7], hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\",
"assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip,",
"range(10)] y0 = [np.random.randint(0, params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii] + 1) for ii in range(10)]",
"# print(f'Video {vid_path} has insufficient frames') return None, None, None, None, None, None,",
"size = (10,)) # on an average cropping factor is 80% i.e. covers",
"0.25: image = trans.functional.adjust_gamma(image, gamma = gamma1, gain=1) #gamma range [0.8, 1.2] else:",
"hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3], y_erase[3], cropping_factor1[3],\\ x0[3], y0[3], contrast_factor1[3],",
"0.3 : image = trans.functional.adjust_saturation(image, saturation_factor = saturation_factor1) # brightness factor will be",
"= cap.read() if ((count not in frames_sparse) and (count not in frames_dense[0]) \\",
"x0[2], y0[2], contrast_factor1[2], hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3], y_erase[3], cropping_factor1[3],\\",
"a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9], y_erase[9], cropping_factor1[9],\\ x0[9], y0[9], contrast_factor1[9], hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9]))",
"of 4 dense clips (covering 16 frames temporal span minimum)''' import os import",
"x_erase[3], y_erase[3], cropping_factor1[3],\\ x0[3], y0[3], contrast_factor1[3], hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count) if",
"clip builder starts here ########################## sparse_clip = [] dense_clip0 = [] dense_clip1 =",
"(count not in frames_dense[0]) \\ and (count not in frames_dense[1]) and (count not",
"tqdm import time import torchvision.transforms as trans # from decord import VideoReader class",
"= int(sr_sparse/4) frames_sparse = [start_frame] + [start_frame + i*sr_sparse for i in range(1,params.num_frames)]",
"= (10,)) random_color_dropped = np.random.randint(0,3,(10)) while(cap.isOpened()): count += 1 ret, frame = cap.read()",
"in frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4], y_erase[4], cropping_factor1[4],\\ x0[4], y0[4], contrast_factor1[4], hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\",
"< 0.3 : image = trans.functional.adjust_brightness(image, brightness_factor = brightness_factor1) # brightness factor will",
"########################## sparse_clip = [] dense_clip0 = [] dense_clip1 = [] dense_clip2 = []",
"x0[5], y0[5], contrast_factor1[5], hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count) if (count in frames_dense[2]):",
"y0[5], contrast_factor1[5], hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count) if (count in frames_dense[2]): dense_clip2.append(self.augmentation(frame,",
"not in frames_dense[0]) \\ and (count not in frames_dense[1]) and (count not in",
"+ sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip = a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3) < params.num_frames and len(dense_clip3)>7:",
"versions of 4 dense clips (covering 16 frames temporal span minimum)''' import os",
"0.25: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[4] >",
"between [0.75, 1,25] if random_array[3] < 0.3 : image = trans.functional.adjust_brightness(image, brightness_factor =",
"cropping_factor1[7],\\ x0[7], y0[7], contrast_factor1[7], hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count) if (count in",
"if random_array[1] < 0.3 : image = trans.functional.adjust_hue(image, hue_factor = hue_factor1) # hue",
"will be between [0.75, 1,25] if random_array[0] > 0.125 and random_array[0] < 0.25:",
"if random_array[4] > 0.70: if random_array[4] < 0.875: image = trans.functional.to_grayscale(image, num_output_channels =",
"+ [start_frame + i*sr_sparse for i in range(1,params.num_frames)] frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense",
"y_erase[4], cropping_factor1[4],\\ x0[4], y0[4], contrast_factor1[4], hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5],",
"hue_factor = hue_factor1) # hue factor will be between [-0.1, 0.1] if random_array[2]",
"is the skip rate ratio = 4 chunks # if skip_max >= 16:",
"= trans.functional.to_grayscale(image, num_output_channels = 3) if random_array[5] > 0.25: image = trans.functional.adjust_gamma(image, gamma",
"a_dense_clip3, list_sparse, list_dense, vid_path def build_clip(self, vid_path): try: cap = cv2.VideoCapture(vid_path) cap.set(1, 0)",
"if not (None in item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0))",
"range(1,params.num_frames)] frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense for i in range(1,params.num_frames)] for j in",
"= np.random.randint(0,params.reso_w, size = (10,)) cropping_factor1 = np.random.uniform(0.6, 1, size = (10,)) #",
"in batch: if not (None in item): sparse_clip.append(torch.stack(item[0],dim=0)) dense_clip0.append(torch.stack(item[1],dim=0)) dense_clip1.append(torch.stack(item[2],dim=0)) dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0))",
"a_dense_clip0.append(self.augmentation(frame, random_array[3], x_erase[3], y_erase[3], cropping_factor1[3],\\ x0[3], y0[3], contrast_factor1[3], hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3]))",
"__init__(self, shuffle = True, data_percentage = 1.0, split = 1): ##################### # self.all_paths",
"y_erase, erase_size1, erase_size2, v=0) return image def collate_fn2(batch): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3,",
"dim=0) a_dense_clip3 = torch.stack(a_dense_clip3, dim=0) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\",
"gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1], y_erase[1], cropping_factor1[1],\\ x0[1], y0[1], contrast_factor1[1], hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\",
"frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4], y_erase[4], cropping_factor1[4],\\ x0[4], y0[4], contrast_factor1[4], hue_factor1[4], saturation_factor1[4], brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4],",
"rate experiment # skip_max = int((frame_count - start_frame)/params.num_frames) # # here 4 is",
"an average cropping factor is 80% i.e. covers 64% area x0 = [np.random.randint(0,",
"None, None, None except: print(f'Clip {vid_path} has some unknown issue, failed') return None,",
"cfg.path_folder + '/UCF-101/' + self.data[idx].split(' ')[0] sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip,",
"dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense =",
"random_array[0] > 0.125 and random_array[0] < 0.25: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1)",
"contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[4] > 0.70: if random_array[4] <",
"= (10,)) y_erase = np.random.randint(0,params.reso_w, size = (10,)) cropping_factor1 = np.random.uniform(0.6, 1, size",
"x_erase[0], y_erase[0], cropping_factor1[0],\\ x0[0], y0[0], contrast_factor1[0], hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1],",
"skip_max = int((frame_count - start_frame)/params.num_frames) # # here 4 is the skip rate",
"gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count) if (count in frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6], y_erase[6], cropping_factor1[6],\\ x0[6],",
"None, None, None, None, None, None, None, None, None, None, None, None except:",
"(i+1)%25 == 0: print(sparse_clip.shape) print(dense_clip3.shape) print() print(f'Time taken to load data is {time.time()-t}')",
"augmentation(self, image, random_array, x_erase, y_erase, cropping_factor1,\\ x0, y0, contrast_factor1, hue_factor1, saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2,",
"i*sr_sparse for i in range(1,params.num_frames)] frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense for i in",
"= [], [], [], [], [], [], [], [], [], [], [], [],",
"trans.functional.to_tensor(image) image[random_color_dropped,:,:] = 0 image = self.PIL(image) if random_array[6] > 0.5: image =",
"image = trans.functional.erase(image, x_erase, y_erase, erase_size1, erase_size2, v=0) return image def collate_fn2(batch): sparse_clip,",
"\\ shuffle=False, num_workers=4, collate_fn=collate_fn2) print(f'Step involved: {len(train_dataset)/24}') t=time.time() for i, (sparse_clip, dense_clip0, dense_clip1,",
"(count not in frames_dense[3])) and (ret == True): continue if ret == True:",
"list_dense, vid_path def build_clip(self, vid_path): try: cap = cv2.VideoCapture(vid_path) cap.set(1, 0) frame_count =",
"list_sparse = [] list_dense = [[] for i in range(4)] count = -1",
"vid_path if __name__ == '__main__': train_dataset = ss_dataset_gen1(shuffle = True, data_percentage = 1.0)",
"params.ori_reso_h*cropping_factor1[ii] + 1) for ii in range(10)] contrast_factor1 = np.random.uniform(0.75,1.25, size = (10,))",
"random_color_dropped[9])) list_dense[3].append(count) else: break if len(sparse_clip) < params.num_frames and len(sparse_clip)>13: # if params.num_frames",
"if len(sparse_clip) < params.num_frames and len(sparse_clip)>13: # if params.num_frames - len(sparse_clip) >= 1:",
"dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def process_data(self, idx):",
"random_array[1] < 0.3 : image = trans.functional.adjust_hue(image, hue_factor = hue_factor1) # hue factor",
"random_array[6], x_erase[6], y_erase[6], cropping_factor1[6],\\ x0[6], y0[6], contrast_factor1[6], hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame,",
"frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6], y_erase[6], cropping_factor1[6],\\ x0[6], y0[6], contrast_factor1[6], hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6],",
"= cap.get(7) if frame_count <= 56: # print(f'Video {vid_path} has insufficient frames') return",
"a_dense_clip2 = torch.stack(a_dense_clip2, dim=0) a_dense_clip3 = torch.stack(a_dense_clip3, dim=0) return sparse_clip, dense_clip0, dense_clip1, dense_clip2,",
"a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path if __name__ == '__main__': train_dataset = ss_dataset_gen1(shuffle",
"= True, data_percentage = 1.0) train_dataloader = DataLoader(train_dataset, batch_size=40, \\ shuffle=False, num_workers=4, collate_fn=collate_fn2)",
"a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path) in enumerate(train_dataloader): if",
"params.num_frames - len(dense_clip3) >= 1: # print(f'dense_clip3 {vid_path} is missing {params.num_frames - len(dense_clip3)}",
"(skip_max<12) and (skip_max>=8): # sr_sparse = np.random.choice([4,8]) # else: sr_sparse = 4 else:",
"DataLoader from torchvision import transforms, utils import config as cfg import random import",
"- len(sparse_clip) sparse_clip = sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip = a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1] if",
"a_sparse_clip = torch.stack(a_sparse_clip, dim=0) a_dense_clip0 = torch.stack(a_dense_clip0, dim=0) a_dense_clip1 = torch.stack(a_dense_clip1, dim=0) a_dense_clip2",
"len(dense_clip3)>7: # if params.num_frames - len(dense_clip3) >= 1: # print(f'dense_clip3 {vid_path} is missing",
"None, None, None ############################# frame_list maker start here################################# min_temporal_span_sparse = params.num_frames*params.sr_ratio if frame_count",
"frames) and 2 augmented versions of 4 dense clips (covering 16 frames temporal",
"import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader",
"self.all_paths = open(os.path.join(cfg.path_folder, 'ucfTrainTestlist/trainlist03.txt'),'r').read().splitlines() else: print(f'Invalid split input: {split}') ##################### self.shuffle = shuffle",
"and (skip_max>=8): # sr_sparse = np.random.choice([4,8]) # else: sr_sparse = 4 else: start_frame",
"list_sparse.append(count) if (count in frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2], y_erase[2], cropping_factor1[2],\\ x0[2], y0[2], contrast_factor1[2],",
"will be between [0.75, 1,25] if random_array[3] < 0.3 : image = trans.functional.adjust_brightness(image,",
"random_array[3], x_erase[3], y_erase[3], cropping_factor1[3],\\ x0[3], y0[3], contrast_factor1[3], hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count)",
"torchvision.transforms as trans # from decord import VideoReader class ss_dataset_gen1(Dataset): def __init__(self, shuffle",
"= [[] for i in range(4)] count = -1 random_array = np.random.rand(10,8) x_erase",
"if random_array[2] < 0.3 : image = trans.functional.adjust_saturation(image, saturation_factor = saturation_factor1) # brightness",
"x_erase, y_erase, cropping_factor1,\\ x0, y0, contrast_factor1, hue_factor1, saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped): image =",
"brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1], y_erase[1], cropping_factor1[1],\\ x0[1], y0[1], contrast_factor1[1], hue_factor1[1], saturation_factor1[1],",
"[], [], [], [], [], [], [], [] for item in batch: if",
"trans # from decord import VideoReader class ss_dataset_gen1(Dataset): def __init__(self, shuffle = True,",
"ss_dataset_gen1(shuffle = True, data_percentage = 1.0) train_dataloader = DataLoader(train_dataset, batch_size=40, \\ shuffle=False, num_workers=4,",
"and (count not in frames_dense[0]) \\ and (count not in frames_dense[1]) and (count",
"sr_sparse = np.random.choice([4,8]) # else: sr_sparse = 4 else: start_frame = 0 sr_sparse",
"dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path) in enumerate(train_dataloader):",
"None except: print(f'Clip {vid_path} has some unknown issue, failed') return None, None, None,",
"0.3 : image = trans.functional.adjust_brightness(image, brightness_factor = brightness_factor1) # brightness factor will be",
"train_dataloader = DataLoader(train_dataset, batch_size=40, \\ shuffle=False, num_workers=4, collate_fn=collate_fn2) print(f'Step involved: {len(train_dataset)/24}') t=time.time() for",
"numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from",
"range(4)] count = -1 random_array = np.random.rand(10,8) x_erase = np.random.randint(0,params.reso_h, size = (10,))",
"a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path) in enumerate(train_dataloader): if (i+1)%25 == 0: print(sparse_clip.shape)",
"\\ list_sparse, list_dense, vid_path if __name__ == '__main__': train_dataset = ss_dataset_gen1(shuffle = True,",
"(count not in frames_dense[2]) \\ and (count not in frames_dense[3])) and (ret ==",
"= self.build_clip(vid_path) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2,",
"in frames_dense[1]) and (count not in frames_dense[2]) \\ and (count not in frames_dense[3]))",
"if random_array[6] > 0.5: image = trans.functional.hflip(image) image = trans.functional.to_tensor(image) if random_array[7] <",
"unknown issue, failed') return None, None, None, None, None, None, None, None, None,",
"gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count) if (count in frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8], y_erase[8], cropping_factor1[8],\\ x0[8],",
"torch.stack(dense_clip2, dim=0) dense_clip3 = torch.stack(dense_clip3, dim=0) a_sparse_clip = torch.stack(a_sparse_clip, dim=0) a_dense_clip0 = torch.stack(a_dense_clip0,",
"dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path =",
"= np.random.choice([4,8]) # else: sr_sparse = 4 else: start_frame = 0 sr_sparse =",
"y_erase[0], cropping_factor1[0],\\ x0[0], y0[0], contrast_factor1[0], hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1],",
"y_erase[3], cropping_factor1[3],\\ x0[3], y0[3], contrast_factor1[3], hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count) if (count",
"hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count) if (count in frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4],",
"import pickle import parameters as params import json import math import cv2 #",
"- len(dense_clip3) >= 1: # print(f'dense_clip3 {vid_path} is missing {params.num_frames - len(dense_clip3)} frames')",
"sr_sparse = 4 else: start_frame = 0 sr_sparse = 4 sr_dense = int(sr_sparse/4)",
"not in frames_dense[3])) and (ret == True): continue if ret == True: if",
"a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path if __name__ == '__main__': train_dataset =",
"= [] dense_clip0 = [] dense_clip1 = [] dense_clip2 = [] dense_clip3 =",
"== True: if (count in frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0], y_erase[0], cropping_factor1[0],\\ x0[0], y0[0],",
"random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7], y_erase[7], cropping_factor1[7],\\ x0[7], y0[7], contrast_factor1[7], hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7],",
"contrast_factor1[6], hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7], y_erase[7], cropping_factor1[7],\\ x0[7], y0[7],",
">= 1: # print(f'dense_clip3 {vid_path} is missing {params.num_frames - len(dense_clip3)} frames') remaining_num_frames =",
"a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path = [], [], [], [], [],",
"True, data_percentage = 1.0) train_dataloader = DataLoader(train_dataset, batch_size=40, \\ shuffle=False, num_workers=4, collate_fn=collate_fn2) print(f'Step",
"if frame_count <= 56: # print(f'Video {vid_path} has insufficient frames') return None, None,",
"x0[9], y0[9], contrast_factor1[9], hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count) else: break if len(sparse_clip)",
"v=0) return image def collate_fn2(batch): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0,",
"self.process_data(index) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3,",
"for i in range(1,params.num_frames)] frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense for i in range(1,params.num_frames)]",
"np.random.rand(10,8) x_erase = np.random.randint(0,params.reso_h, size = (10,)) y_erase = np.random.randint(0,params.reso_w, size = (10,))",
"1.2] else: image = trans.functional.to_tensor(image) image[random_color_dropped,:,:] = 0 image = self.PIL(image) if random_array[6]",
"size = (10,)) random_color_dropped = np.random.randint(0,3,(10)) while(cap.isOpened()): count += 1 ret, frame =",
"experiment # skip_max = int((frame_count - start_frame)/params.num_frames) # # here 4 is the",
"if (count in frames_dense[1]): dense_clip1.append(self.augmentation(frame, random_array[4], x_erase[4], y_erase[4], cropping_factor1[4],\\ x0[4], y0[4], contrast_factor1[4], hue_factor1[4],",
"# from decord import VideoReader class ss_dataset_gen1(Dataset): def __init__(self, shuffle = True, data_percentage",
"list_dense, vid_path def process_data(self, idx): vid_path = cfg.path_folder + '/UCF-101/' + self.data[idx].split(' ')[0]",
"contrast_factor1[0], hue_factor1[0], saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1], y_erase[1], cropping_factor1[1],\\ x0[1], y0[1],",
"(covering minimum 64 frames) and 2 augmented versions of 4 dense clips (covering",
"a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def process_data(self, idx): vid_path = cfg.path_folder",
"random_color_dropped[7])) list_dense[2].append(count) if (count in frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8], y_erase[8], cropping_factor1[8],\\ x0[8], y0[8],",
"None def augmentation(self, image, random_array, x_erase, y_erase, cropping_factor1,\\ x0, y0, contrast_factor1, hue_factor1, saturation_factor1,",
"\\ and (count not in frames_dense[3])) and (ret == True): continue if ret",
"hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count) if (count in frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6],",
"[] a_dense_clip2 = [] a_dense_clip3 = [] list_sparse = [] list_dense = [[]",
"x0[3], y0[3], contrast_factor1[3], hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count) if (count in frames_dense[1]):",
"{split}') ##################### self.shuffle = shuffle if self.shuffle: random.shuffle(self.all_paths) self.data_percentage = data_percentage self.data_limit =",
"> 0.70: if random_array[4] < 0.875: image = trans.functional.to_grayscale(image, num_output_channels = 3) if",
"vid_path.append(item[12]) sparse_clip = torch.stack(sparse_clip, dim=0) dense_clip0 = torch.stack(dense_clip0, dim=0) dense_clip1 = torch.stack(dense_clip1, dim=0)",
"a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def build_clip(self, vid_path): try: cap =",
"a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return sparse_clip, dense_clip0, dense_clip1,",
"1 ret, frame = cap.read() if ((count not in frames_sparse) and (count not",
"frames_dense[1]) and (count not in frames_dense[2]) \\ and (count not in frames_dense[3])) and",
"data_percentage = 1.0, split = 1): ##################### # self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split",
"(count in frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6], x_erase[6], y_erase[6], cropping_factor1[6],\\ x0[6], y0[6], contrast_factor1[6], hue_factor1[6], saturation_factor1[6],",
"data_percentage = 1.0) train_dataloader = DataLoader(train_dataset, batch_size=40, \\ shuffle=False, num_workers=4, collate_fn=collate_fn2) print(f'Step involved:",
"be between [-0.1, 0.1] if random_array[2] < 0.3 : image = trans.functional.adjust_saturation(image, saturation_factor",
"(10,)) # on an average cropping factor is 80% i.e. covers 64% area",
"y0[7], contrast_factor1[7], hue_factor1[7], saturation_factor1[7], brightness_factor1[7],\\ gamma1[7],erase_size1[7],erase_size2[7], random_color_dropped[7])) list_dense[2].append(count) if (count in frames_dense[3]): dense_clip3.append(self.augmentation(frame,",
"cropping_factor1 = np.random.uniform(0.6, 1, size = (10,)) # on an average cropping factor",
"torch.stack(a_dense_clip2, dim=0) a_dense_clip3 = torch.stack(a_dense_clip3, dim=0) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip,",
"1: # print(f'dense_clip3 {vid_path} is missing {params.num_frames - len(dense_clip3)} frames') remaining_num_frames = params.num_frames",
"self.shuffle: random.shuffle(self.all_paths) self.data_percentage = data_percentage self.data_limit = int(len(self.all_paths)*self.data_percentage) self.data = self.all_paths[0: self.data_limit] self.PIL",
"ret, frame = cap.read() if ((count not in frames_sparse) and (count not in",
"sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip = a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3) < params.num_frames and",
"- start_frame)/params.num_frames) # # here 4 is the skip rate ratio = 4",
"y0[3], contrast_factor1[3], hue_factor1[3], saturation_factor1[3], brightness_factor1[3],\\ gamma1[3],erase_size1[3],erase_size2[3], random_color_dropped[3])) list_dense[0].append(count) if (count in frames_dense[1]): dense_clip1.append(self.augmentation(frame,",
"= np.random.uniform(0.75,1.25, size = (10,)) erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) erase_size2 =",
"frames') remaining_num_frames = params.num_frames - len(dense_clip3) dense_clip3 = dense_clip3 + dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 =",
"area x0 = [np.random.randint(0, params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii] + 1) for ii in range(10)]",
"maker start here################################# min_temporal_span_sparse = params.num_frames*params.sr_ratio if frame_count > min_temporal_span_sparse: start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse)",
"a_dense_clip1 = torch.stack(a_dense_clip1, dim=0) a_dense_clip2 = torch.stack(a_dense_clip2, dim=0) a_dense_clip3 = torch.stack(a_dense_clip3, dim=0) return",
"None, None, None, None, None ############################# frame_list maker start here################################# min_temporal_span_sparse = params.num_frames*params.sr_ratio",
"sparse_clip = sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip = a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3) <",
"def collate_fn2(batch): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3,",
"math import cv2 # from tqdm import tqdm import time import torchvision.transforms as",
"in frames_dense[0]) \\ and (count not in frames_dense[1]) and (count not in frames_dense[2])",
"random_array[5], x_erase[5], y_erase[5], cropping_factor1[5],\\ x0[5], y0[5], contrast_factor1[5], hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count)",
"collate_fn2(batch): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\",
"list_dense = [[] for i in range(4)] count = -1 random_array = np.random.rand(10,8)",
"= int(len(self.all_paths)*self.data_percentage) self.data = self.all_paths[0: self.data_limit] self.PIL = trans.ToPILImage() self.TENSOR = trans.ToTensor() self.erase_size",
"import os import torch import numpy as np import matplotlib.pyplot as plt from",
"> min_temporal_span_sparse: start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip rate experiment # skip_max = int((frame_count",
"in frames_dense[3])) and (ret == True): continue if ret == True: if (count",
"(count in frames_dense[3]): dense_clip3.append(self.augmentation(frame, random_array[8], x_erase[8], y_erase[8], cropping_factor1[8],\\ x0[8], y0[8], contrast_factor1[8], hue_factor1[8], saturation_factor1[8],",
"dense_clip1 = torch.stack(dense_clip1, dim=0) dense_clip2 = torch.stack(dense_clip2, dim=0) dense_clip3 = torch.stack(dense_clip3, dim=0) a_sparse_clip",
"cap = cv2.VideoCapture(vid_path) cap.set(1, 0) frame_count = cap.get(7) if frame_count <= 56: #",
"dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def build_clip(self, vid_path):",
"None, None, None, None, None, None, None, None, None, None except: print(f'Clip {vid_path}",
"to 1.25 if random_array[1] < 0.3 : image = trans.functional.adjust_hue(image, hue_factor = hue_factor1)",
"random_array[4] < 0.875: image = trans.functional.to_grayscale(image, num_output_channels = 3) if random_array[5] > 0.25:",
"gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count) if (count in frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2], y_erase[2], cropping_factor1[2],\\ x0[2],",
"None, None, None, None except: print(f'Clip {vid_path} has some unknown issue, failed') return",
"min_temporal_span_sparse = params.num_frames*params.sr_ratio if frame_count > min_temporal_span_sparse: start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip rate",
"(skip_max>=12): # sr_sparse = np.random.choice([4,8,12]) # elif (skip_max<12) and (skip_max>=8): # sr_sparse =",
"class ss_dataset_gen1(Dataset): def __init__(self, shuffle = True, data_percentage = 1.0, split = 1):",
"dim=0) a_dense_clip1 = torch.stack(a_dense_clip1, dim=0) a_dense_clip2 = torch.stack(a_dense_clip2, dim=0) a_dense_clip3 = torch.stack(a_dense_clip3, dim=0)",
"1): ##################### # self.all_paths = open(os.path.join(cfg.path_folder,'train_vids.txt'),'r').read().splitlines() if split == 1: self.all_paths = open(os.path.join(cfg.path_folder,",
"1) for ii in range(10)] contrast_factor1 = np.random.uniform(0.75,1.25, size = (10,)) hue_factor1 =",
"import parameters as params import json import math import cv2 # from tqdm",
"brightness factor will be between [0.75, 1,25] if random_array[0] > 0.125 and random_array[0]",
"= torch.stack(sparse_clip, dim=0) dense_clip0 = torch.stack(dense_clip0, dim=0) dense_clip1 = torch.stack(dense_clip1, dim=0) dense_clip2 =",
"\\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def build_clip(self, vid_path): try:",
"list_dense, vid_path if __name__ == '__main__': train_dataset = ss_dataset_gen1(shuffle = True, data_percentage =",
"list_dense, vid_path = [], [], [], [], [], [], [], [], [], [],",
"import json import math import cv2 # from tqdm import tqdm import time",
"np.random.randint(0,params.reso_h, size = (10,)) y_erase = np.random.randint(0,params.reso_w, size = (10,)) cropping_factor1 = np.random.uniform(0.6,",
"saturation_factor1[0], brightness_factor1[0],\\ gamma1[0],erase_size1[0],erase_size2[0], random_color_dropped[0])) a_sparse_clip.append(self.augmentation(frame, random_array[1], x_erase[1], y_erase[1], cropping_factor1[1],\\ x0[1], y0[1], contrast_factor1[1], hue_factor1[1],",
"on an average cropping factor is 80% i.e. covers 64% area x0 =",
"hue_factor1[6], saturation_factor1[6], brightness_factor1[6],\\ gamma1[6],erase_size1[6],erase_size2[6], random_color_dropped[6])) a_dense_clip2.append(self.augmentation(frame, random_array[7], x_erase[7], y_erase[7], cropping_factor1[7],\\ x0[7], y0[7], contrast_factor1[7],",
"None, None, None, None, None, None, None, None def augmentation(self, image, random_array, x_erase,",
"= sparse_clip + sparse_clip[::-1][1:remaining_num_frames+1] a_sparse_clip = a_sparse_clip + a_sparse_clip[::-1][1:remaining_num_frames+1] if len(dense_clip3) < params.num_frames",
"None, None, None, None, None, None, None, None, None, None, None, None #############################",
"# else: sr_sparse = 4 else: start_frame = 0 sr_sparse = 4 sr_dense",
"brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count) if (count in frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2], y_erase[2], cropping_factor1[2],\\",
"split input: {split}') ##################### self.shuffle = shuffle if self.shuffle: random.shuffle(self.all_paths) self.data_percentage = data_percentage",
"a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse, list_dense, vid_path = [], [], [], [],",
"################################ actual clip builder starts here ########################## sparse_clip = [] dense_clip0 = []",
"gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count) else: break if len(sparse_clip) < params.num_frames and len(sparse_clip)>13: # if",
"dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path = self.process_data(index) return",
"chunks # if skip_max >= 16: # sr_sparse = np.random.choice([4,8,12,16]) # elif (skip_max<16)",
"maker finishes here ########################### ################################ actual clip builder starts here ########################## sparse_clip =",
"hue_factor1[9], saturation_factor1[9], brightness_factor1[9],\\ gamma1[9],erase_size1[9],erase_size2[9], random_color_dropped[9])) list_dense[3].append(count) else: break if len(sparse_clip) < params.num_frames and",
"4 chunks # if skip_max >= 16: # sr_sparse = np.random.choice([4,8,12,16]) # elif",
"= (10,)) erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size, size =",
"0 image = self.PIL(image) if random_array[6] > 0.5: image = trans.functional.hflip(image) image =",
"here ########################### ################################ actual clip builder starts here ########################## sparse_clip = [] dense_clip0",
"0.5 : image = trans.functional.erase(image, x_erase, y_erase, erase_size1, erase_size2, v=0) return image def",
"dim=0) dense_clip1 = torch.stack(dense_clip1, dim=0) dense_clip2 = torch.stack(dense_clip2, dim=0) dense_clip3 = torch.stack(dense_clip3, dim=0)",
"hue_factor1 = np.random.uniform(-0.1,0.1, size = (10,)) saturation_factor1 = np.random.uniform(0.75,1.25, size = (10,)) brightness_factor1",
"(10,)) erase_size1 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) erase_size2 = np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,))",
"frames temporal span minimum)''' import os import torch import numpy as np import",
"and (count not in frames_dense[2]) \\ and (count not in frames_dense[3])) and (ret",
"self.build_clip(vid_path) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3,",
"print(f'dense_clip3 {vid_path} is missing {params.num_frames - len(dense_clip3)} frames') remaining_num_frames = params.num_frames - len(dense_clip3)",
"{vid_path} has some unknown issue, failed') return None, None, None, None, None, None,",
"1, size = (10,)) # on an average cropping factor is 80% i.e.",
"DL that provides 2 augmented version of a sparse clip (covering minimum 64",
"(count in frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0], x_erase[0], y_erase[0], cropping_factor1[0],\\ x0[0], y0[0], contrast_factor1[0], hue_factor1[0], saturation_factor1[0],",
"failed') return None, None, None, None, None, None, None, None, None, None, None,",
"hue factor will be between [-0.1, 0.1] if random_array[2] < 0.3 : image",
"\\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path = self.process_data(index) return sparse_clip,",
"print(f'Video {vid_path} has insufficient frames') return None, None, None, None, None, None, None,",
"a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense except: print(f'Clip {vid_path} has some frames",
"trans.functional.adjust_gamma(image, gamma = gamma1, gain=1) #gamma range [0.8, 1.2] else: image = trans.functional.to_tensor(image)",
"None, None, None, None, None, None, None, None ############################# frame_list maker start here#################################",
"# from tqdm import tqdm import time import torchvision.transforms as trans # from",
"else: break if len(sparse_clip) < params.num_frames and len(sparse_clip)>13: # if params.num_frames - len(sparse_clip)",
"+ i*sr_dense for i in range(1,params.num_frames)] for j in range(4)] ################################ frame list",
"erase_size2, v=0) return image def collate_fn2(batch): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\",
"np.random.randint(int(self.erase_size/2),self.erase_size, size = (10,)) random_color_dropped = np.random.randint(0,3,(10)) while(cap.isOpened()): count += 1 ret, frame",
"here################################# min_temporal_span_sparse = params.num_frames*params.sr_ratio if frame_count > min_temporal_span_sparse: start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip",
"cropping factor is 80% i.e. covers 64% area x0 = [np.random.randint(0, params.ori_reso_w -",
"None, None, None, None, None, None, None ############################# frame_list maker start here################################# min_temporal_span_sparse",
"covers 64% area x0 = [np.random.randint(0, params.ori_reso_w - params.ori_reso_w*cropping_factor1[ii] + 1) for ii",
"1) for ii in range(10)] y0 = [np.random.randint(0, params.ori_reso_h - params.ori_reso_h*cropping_factor1[ii] + 1)",
"torch.stack(a_dense_clip3, dim=0) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2,",
"a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path def build_clip(self, vid_path): try: cap",
"dense_clip2.append(torch.stack(item[3],dim=0)) dense_clip3.append(torch.stack(item[4],dim=0)) a_sparse_clip.append(torch.stack(item[5],dim=0)) a_dense_clip0.append(torch.stack(item[6],dim=0)) a_dense_clip1.append(torch.stack(item[7],dim=0)) a_dense_clip2.append(torch.stack(item[8],dim=0)) a_dense_clip3.append(torch.stack(item[9],dim=0)) list_sparse.append(np.asarray(item[10])) list_dense.append(np.asarray(item[11])) vid_path.append(item[12]) sparse_clip = torch.stack(sparse_clip,",
"from tqdm import tqdm import time import torchvision.transforms as trans # from decord",
"+ dense_clip3[::-1][1:remaining_num_frames+1] a_dense_clip3 = a_dense_clip3 + a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames)",
"dim=0) dense_clip0 = torch.stack(dense_clip0, dim=0) dense_clip1 = torch.stack(dense_clip1, dim=0) dense_clip2 = torch.stack(dense_clip2, dim=0)",
"__len__(self): return len(self.data) def __getitem__(self,index): sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0,",
"a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense, vid_path = self.process_data(index) return sparse_clip, dense_clip0, dense_clip1, dense_clip2,",
"brightness_factor1[4],\\ gamma1[4],erase_size1[4],erase_size2[4], random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5], y_erase[5], cropping_factor1[5],\\ x0[5], y0[5], contrast_factor1[5], hue_factor1[5], saturation_factor1[5],",
"a_dense_clip3[::-1][1:remaining_num_frames+1] try: assert(len(sparse_clip)==params.num_frames) assert(len(dense_clip0)==params.num_frames) assert(len(dense_clip1)==params.num_frames) assert(len(dense_clip2)==params.num_frames) assert(len(dense_clip3)==params.num_frames) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3,",
"y_erase[1], cropping_factor1[1],\\ x0[1], y0[1], contrast_factor1[1], hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count) if (count",
"a sparse clip (covering minimum 64 frames) and 2 augmented versions of 4",
"brightness_factor1 = np.random.uniform(0.75,1.25,size = (10,)) gamma1 = np.random.uniform(0.75,1.25, size = (10,)) erase_size1 =",
"contrast_factor1[5], hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5], random_color_dropped[5])) list_dense[1].append(count) if (count in frames_dense[2]): dense_clip2.append(self.augmentation(frame, random_array[6],",
"range(10)] contrast_factor1 = np.random.uniform(0.75,1.25, size = (10,)) hue_factor1 = np.random.uniform(-0.1,0.1, size = (10,))",
"None, None def augmentation(self, image, random_array, x_erase, y_erase, cropping_factor1,\\ x0, y0, contrast_factor1, hue_factor1,",
"# hue factor will be between [-0.1, 0.1] if random_array[2] < 0.3 :",
"trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1) #0.75 to 1.25 if random_array[4] > 0.70: if random_array[4]",
"random_array[2], x_erase[2], y_erase[2], cropping_factor1[2],\\ x0[2], y0[2], contrast_factor1[2], hue_factor1[2], saturation_factor1[2], brightness_factor1[2],\\ gamma1[2],erase_size1[2],erase_size2[2], random_color_dropped[2])) a_dense_clip0.append(self.augmentation(frame,",
"sparse_clip = [] dense_clip0 = [] dense_clip1 = [] dense_clip2 = [] dense_clip3",
"vid_path): try: cap = cv2.VideoCapture(vid_path) cap.set(1, 0) frame_count = cap.get(7) if frame_count <=",
"= trans.functional.adjust_saturation(image, saturation_factor = saturation_factor1) # brightness factor will be between [0.75, 1,25]",
"def build_clip(self, vid_path): try: cap = cv2.VideoCapture(vid_path) cap.set(1, 0) frame_count = cap.get(7) if",
"[], [], [], [], [], [], [], [], [] for item in batch:",
"a_dense_clip0 = torch.stack(a_dense_clip0, dim=0) a_dense_clip1 = torch.stack(a_dense_clip1, dim=0) a_dense_clip2 = torch.stack(a_dense_clip2, dim=0) a_dense_clip3",
"image = trans.functional.resized_crop(image,y0,x0,int(params.ori_reso_h*cropping_factor1),int(params.ori_reso_h*cropping_factor1),(params.reso_h,params.reso_w),interpolation=2) if random_array[0] < 0.125: image = trans.functional.adjust_contrast(image, contrast_factor = contrast_factor1)",
"and (skip_max>=12): # sr_sparse = np.random.choice([4,8,12]) # elif (skip_max<12) and (skip_max>=8): # sr_sparse",
"np.random.uniform(-0.1,0.1, size = (10,)) saturation_factor1 = np.random.uniform(0.75,1.25, size = (10,)) brightness_factor1 = np.random.uniform(0.75,1.25,size",
"list_dense, vid_path = self.process_data(index) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0,",
"= params.num_frames*params.sr_ratio if frame_count > min_temporal_span_sparse: start_frame = np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip rate experiment",
"Dataset, DataLoader from torchvision import transforms, utils import config as cfg import random",
"range(1,params.num_frames)] for j in range(4)] ################################ frame list maker finishes here ########################### ################################",
"frames_dense = [[frames_sparse[j*4]]+[frames_sparse[j*4] + i*sr_dense for i in range(1,params.num_frames)] for j in range(4)]",
"[] dense_clip2 = [] dense_clip3 = [] a_sparse_clip = [] a_dense_clip0 = []",
"actual clip builder starts here ########################## sparse_clip = [] dense_clip0 = [] dense_clip1",
"if (i+1)%25 == 0: print(sparse_clip.shape) print(dense_clip3.shape) print() print(f'Time taken to load data is",
"as params import json import math import cv2 # from tqdm import tqdm",
"# elif (skip_max<16) and (skip_max>=12): # sr_sparse = np.random.choice([4,8,12]) # elif (skip_max<12) and",
"a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense = self.build_clip(vid_path) return sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3,",
"a_dense_clip3 = [] list_sparse = [] list_dense = [[] for i in range(4)]",
"contrast_factor1 = np.random.uniform(0.75,1.25, size = (10,)) hue_factor1 = np.random.uniform(-0.1,0.1, size = (10,)) saturation_factor1",
"is an attemp to make a master DL that provides 2 augmented version",
"hue_factor1[1], saturation_factor1[1], brightness_factor1[1],\\ gamma1[1],erase_size1[1],erase_size2[1], random_color_dropped[1])) list_sparse.append(count) if (count in frames_dense[0]): dense_clip0.append(self.augmentation(frame, random_array[2], x_erase[2],",
"1: # print(f'sparse_clip {vid_path} is missing {params.num_frames - len(sparse_clip)} frames') remaining_num_frames = params.num_frames",
"[], [], [], [], [] for item in batch: if not (None in",
"= 4 chunks # if skip_max >= 16: # sr_sparse = np.random.choice([4,8,12,16]) #",
"sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, \\ a_sparse_clip, a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense",
"a_dense_clip1 = [] a_dense_clip2 = [] a_dense_clip3 = [] list_sparse = [] list_dense",
"y_erase, cropping_factor1,\\ x0, y0, contrast_factor1, hue_factor1, saturation_factor1, brightness_factor1,\\ gamma1,erase_size1,erase_size2, random_color_dropped): image = self.PIL(image)",
"np.random.randint(0,frame_count-min_temporal_span_sparse) #Dynamic skip rate experiment # skip_max = int((frame_count - start_frame)/params.num_frames) # #",
"a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, list_sparse, list_dense = self.build_clip(vid_path) return sparse_clip, dense_clip0, dense_clip1, dense_clip2,",
"from torchvision import transforms, utils import config as cfg import random import pickle",
"sr_sparse = np.random.choice([4,8,12,16]) # elif (skip_max<16) and (skip_max>=12): # sr_sparse = np.random.choice([4,8,12]) #",
"= [] a_sparse_clip = [] a_dense_clip0 = [] a_dense_clip1 = [] a_dense_clip2 =",
"brightness_factor1[8],\\ gamma1[8],erase_size1[8],erase_size2[8], random_color_dropped[8])) a_dense_clip3.append(self.augmentation(frame, random_array[9], x_erase[9], y_erase[9], cropping_factor1[9],\\ x0[9], y0[9], contrast_factor1[9], hue_factor1[9], saturation_factor1[9],",
"as plt from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils import",
"[] a_sparse_clip = [] a_dense_clip0 = [] a_dense_clip1 = [] a_dense_clip2 = []",
"random_color_dropped[4])) a_dense_clip1.append(self.augmentation(frame, random_array[5], x_erase[5], y_erase[5], cropping_factor1[5],\\ x0[5], y0[5], contrast_factor1[5], hue_factor1[5], saturation_factor1[5], brightness_factor1[5],\\ gamma1[5],erase_size1[5],erase_size2[5],",
"{vid_path} has some frames reading issue, failed') return None, None, None, None, None,",
"= trans.ToPILImage() self.TENSOR = trans.ToTensor() self.erase_size = 19 def __len__(self): return len(self.data) def",
"= np.random.rand(10,8) x_erase = np.random.randint(0,params.reso_h, size = (10,)) y_erase = np.random.randint(0,params.reso_w, size =",
"(covering 16 frames temporal span minimum)''' import os import torch import numpy as",
"== True): continue if ret == True: if (count in frames_sparse): sparse_clip.append(self.augmentation(frame, random_array[0],",
"image = trans.functional.to_tensor(image) if random_array[7] < 0.5 : image = trans.functional.erase(image, x_erase, y_erase,",
"(sparse_clip, dense_clip0, dense_clip1, dense_clip2, dense_clip3, a_sparse_clip, \\ a_dense_clip0, a_dense_clip1, a_dense_clip2, a_dense_clip3, \\ list_sparse,",
"trans.functional.hflip(image) image = trans.functional.to_tensor(image) if random_array[7] < 0.5 : image = trans.functional.erase(image, x_erase,",
"4 else: start_frame = 0 sr_sparse = 4 sr_dense = int(sr_sparse/4) frames_sparse =",
"trans.functional.erase(image, x_erase, y_erase, erase_size1, erase_size2, v=0) return image def collate_fn2(batch): sparse_clip, dense_clip0, dense_clip1,",
"None, None, None, None, None except: print(f'Clip {vid_path} has some unknown issue, failed')"
] |
[
"<reponame>whan6795/myweb<filename>exts.py # encoding:utf-8 from flask_sqlalchemy import SQLAlchemy from datetime import datetime db =",
"# encoding:utf-8 from flask_sqlalchemy import SQLAlchemy from datetime import datetime db = SQLAlchemy()"
] |
[] |
[
"from aws_cdk import core from the_cloudwatch_dashboard.the_cloudwatch_dashboard_stack import TheCloudwatchDashboardStack app = core.App() TheCloudwatchDashboardStack(app, \"the-cloudwatch-dashboard\")",
"aws_cdk import core from the_cloudwatch_dashboard.the_cloudwatch_dashboard_stack import TheCloudwatchDashboardStack app = core.App() TheCloudwatchDashboardStack(app, \"the-cloudwatch-dashboard\") app.synth()",
"#!/usr/bin/env python3 from aws_cdk import core from the_cloudwatch_dashboard.the_cloudwatch_dashboard_stack import TheCloudwatchDashboardStack app = core.App()",
"<reponame>mttfarmer/serverless #!/usr/bin/env python3 from aws_cdk import core from the_cloudwatch_dashboard.the_cloudwatch_dashboard_stack import TheCloudwatchDashboardStack app =",
"python3 from aws_cdk import core from the_cloudwatch_dashboard.the_cloudwatch_dashboard_stack import TheCloudwatchDashboardStack app = core.App() TheCloudwatchDashboardStack(app,"
] |
[
"1: self.strategy = \"sticker\" elif a == 2: self.strategy = \"predator\" elif a",
"self for p in parties: if biggest_party.count_voters() < p.count_voters(): biggest_party = p self.location.move_towards(biggest_party.location)",
"before prev move < voters after prev move # move same way as",
"return len(self.voters) def update_location(self): if self.strategy == \"sticker\": self.update_location_sticker() elif self.strategy == \"predator\":",
"== \"random\": self.update_location_random() else: print(\"Strategy \" + self.strategy + \" does not exist!\")",
"move # move same way as previous move again if self.previous_count == -1:",
"def random_strategy(self): # self.strategy = random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self): a = random.randint(1,5) if a",
"= random.random() * 360.0 elif self.previous_count <= self.count_voters(): direction = self.previous_direction else: lower_limit",
"self.location def get_strategy(self): return self.strategy def get_name(self): return self.name def get_colour(self): return self.colour",
"== \"sticker\": self.update_location_sticker() elif self.strategy == \"predator\": self.update_location_predator() elif self.strategy == \"hunter\": self.update_location_hunter()",
"in self.voters: sum_x += voter.location.x sum_y += voter.location.y target_location = Location() target_location.set_x(sum_x /",
"elif self.previous_count <= self.count_voters(): direction = self.previous_direction else: lower_limit = self.previous_direction + 90",
"+ lower_limit) % 360 self.location.move_angle(direction) self.previous_direction = direction self.previous_count = self.count_voters() # def",
"self.previous_direction = direction self.previous_count = self.count_voters() # def save_state(self): # self.previous_count = self.count_voters()",
"sum_y += voter.location.y target_location = Location() target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location)",
"self.voters.append(voter) def reset_voters(self): self.voters = [] def count_voters(self): return len(self.voters) def update_location(self): if",
"360 self.location.move_angle(direction) self.previous_direction = direction self.previous_count = self.count_voters() # def save_state(self): # self.previous_count",
"<= self.count_voters(): direction = self.previous_direction else: lower_limit = self.previous_direction + 90 direction =",
"update_location_hunter(self): #get previous move #if voters before prev move >= voters after prev",
"print(\"Strategy \" + self.strategy + \" does not exist!\") def update_location_predator(self): parties =",
"and move again anywhere 90 degrees either side #if voters before prev move",
"= name self.colour = colour # random_colour() ??? self.voters = [] self.previous_count =",
"voter.location.x sum_y += voter.location.y target_location = Location() target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y / len(self.voters))",
"previous move again if self.previous_count == -1: direction = random.random() * 360.0 elif",
"self.location = Location() self.simulation = simulation if strategy == \"\": self.random_strategy() else: self.strategy",
"= strategy self.name = name self.colour = colour # random_colour() ??? self.voters =",
"move # then turn 180 degrees and move again anywhere 90 degrees either",
"self.strategy = \"random\" def add_voter(self, voter): return self.voters.append(voter) def reset_voters(self): self.voters = []",
"self.previous_count = self.count_voters() def update_location_random(self): self.location.random_move() def update_location_sticker(self): pass def get_location(self): return self.location",
"move again if self.previous_count == -1: direction = random.random() * 360.0 elif self.previous_count",
"= \"random\" def add_voter(self, voter): return self.voters.append(voter) def reset_voters(self): self.voters = [] def",
"< voters after prev move # move same way as previous move again",
"% 360 self.location.move_angle(direction) self.previous_direction = direction self.previous_count = self.count_voters() # def save_state(self): #",
"self.location.move_towards(target_location) def update_location_hunter(self): #get previous move #if voters before prev move >= voters",
"+ \" does not exist!\") def update_location_predator(self): parties = self.simulation.get_parties() biggest_party = self",
"parties: if biggest_party.count_voters() < p.count_voters(): biggest_party = p self.location.move_towards(biggest_party.location) def update_location_aggregator(self): if len(self.voters)",
"def update_location_random(self): self.location.random_move() def update_location_sticker(self): pass def get_location(self): return self.location def get_strategy(self): return",
"= \"hunter\" elif a == 4: self.strategy = \"aggregator\" elif a == 5:",
"self.count_voters() def update_location_random(self): self.location.random_move() def update_location_sticker(self): pass def get_location(self): return self.location def get_strategy(self):",
"either side #if voters before prev move < voters after prev move #",
">= voters after prev move # then turn 180 degrees and move again",
"sum_y = 0 for voter in self.voters: sum_x += voter.location.x sum_y += voter.location.y",
"add_voter(self, voter): return self.voters.append(voter) def reset_voters(self): self.voters = [] def count_voters(self): return len(self.voters)",
"\"aggregator\" elif a == 5: self.strategy = \"random\" def add_voter(self, voter): return self.voters.append(voter)",
"turn 180 degrees and move again anywhere 90 degrees either side #if voters",
"after prev move # then turn 180 degrees and move again anywhere 90",
"= \"aggregator\" elif a == 5: self.strategy = \"random\" def add_voter(self, voter): return",
"[] self.previous_count = -1 # def random_strategy(self): # self.strategy = random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self):",
"\"sticker\" elif a == 2: self.strategy = \"predator\" elif a == 3: self.strategy",
"self.voters = [] def count_voters(self): return len(self.voters) def update_location(self): if self.strategy == \"sticker\":",
"save_state(self): # self.previous_count = self.count_voters() def update_location_random(self): self.location.random_move() def update_location_sticker(self): pass def get_location(self):",
"/ len(self.voters)) target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location) def update_location_hunter(self): #get previous move #if voters",
"random.randint(1,5) if a == 1: self.strategy = \"sticker\" elif a == 2: self.strategy",
"#if voters before prev move >= voters after prev move # then turn",
"self.update_location_random() else: print(\"Strategy \" + self.strategy + \" does not exist!\") def update_location_predator(self):",
"def update_location_hunter(self): #get previous move #if voters before prev move >= voters after",
"self.strategy = strategy self.name = name self.colour = colour # random_colour() ??? self.voters",
"after prev move # move same way as previous move again if self.previous_count",
"from location import Location import random class Party: def __init__(self, simulation, name, colour,",
"len(self.voters) def update_location(self): if self.strategy == \"sticker\": self.update_location_sticker() elif self.strategy == \"predator\": self.update_location_predator()",
"len(self.voters)) target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location) def update_location_hunter(self): #get previous move #if voters before",
"# then turn 180 degrees and move again anywhere 90 degrees either side",
"\"hunter\" elif a == 4: self.strategy = \"aggregator\" elif a == 5: self.strategy",
"#if voters before prev move < voters after prev move # move same",
"= 0 for voter in self.voters: sum_x += voter.location.x sum_y += voter.location.y target_location",
"random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self): a = random.randint(1,5) if a == 1: self.strategy = \"sticker\"",
"if self.previous_count == -1: direction = random.random() * 360.0 elif self.previous_count <= self.count_voters():",
"random_strategy(self): # self.strategy = random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self): a = random.randint(1,5) if a ==",
"target_location = Location() target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location) def update_location_hunter(self): #get",
"= direction self.previous_count = self.count_voters() # def save_state(self): # self.previous_count = self.count_voters() def",
"class Party: def __init__(self, simulation, name, colour, strategy=\"\"): self.location = Location() self.simulation =",
"def add_voter(self, voter): return self.voters.append(voter) def reset_voters(self): self.voters = [] def count_voters(self): return",
"again if self.previous_count == -1: direction = random.random() * 360.0 elif self.previous_count <=",
"return self.strategy def get_name(self): return self.name def get_colour(self): return self.colour def get_voters(self): return",
"p self.location.move_towards(biggest_party.location) def update_location_aggregator(self): if len(self.voters) > 0: sum_x = 0 sum_y =",
"= self.previous_direction + 90 direction = (random.random() * 180.0 + lower_limit) % 360",
"180.0 + lower_limit) % 360 self.location.move_angle(direction) self.previous_direction = direction self.previous_count = self.count_voters() #",
"= [] def count_voters(self): return len(self.voters) def update_location(self): if self.strategy == \"sticker\": self.update_location_sticker()",
"= \"predator\" elif a == 3: self.strategy = \"hunter\" elif a == 4:",
"= self.count_voters() # def save_state(self): # self.previous_count = self.count_voters() def update_location_random(self): self.location.random_move() def",
"< p.count_voters(): biggest_party = p self.location.move_towards(biggest_party.location) def update_location_aggregator(self): if len(self.voters) > 0: sum_x",
"self.strategy = \"hunter\" elif a == 4: self.strategy = \"aggregator\" elif a ==",
"biggest_party.count_voters() < p.count_voters(): biggest_party = p self.location.move_towards(biggest_party.location) def update_location_aggregator(self): if len(self.voters) > 0:",
"sum_x = 0 sum_y = 0 for voter in self.voters: sum_x += voter.location.x",
"move < voters after prev move # move same way as previous move",
"-1 # def random_strategy(self): # self.strategy = random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self): a = random.randint(1,5)",
"# self.strategy = random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self): a = random.randint(1,5) if a == 1:",
"reset_voters(self): self.voters = [] def count_voters(self): return len(self.voters) def update_location(self): if self.strategy ==",
"\"predator\" elif a == 3: self.strategy = \"hunter\" elif a == 4: self.strategy",
"def save_state(self): # self.previous_count = self.count_voters() def update_location_random(self): self.location.random_move() def update_location_sticker(self): pass def",
"degrees either side #if voters before prev move < voters after prev move",
"voter.location.y target_location = Location() target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location) def update_location_hunter(self):",
"elif self.strategy == \"hunter\": self.update_location_hunter() elif self.strategy == \"aggregator\": self.update_location_aggregator() elif self.strategy ==",
"= -1 # def random_strategy(self): # self.strategy = random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self): a =",
"voter in self.voters: sum_x += voter.location.x sum_y += voter.location.y target_location = Location() target_location.set_x(sum_x",
"== -1: direction = random.random() * 360.0 elif self.previous_count <= self.count_voters(): direction =",
"move >= voters after prev move # then turn 180 degrees and move",
"180 degrees and move again anywhere 90 degrees either side #if voters before",
"prev move < voters after prev move # move same way as previous",
"self.update_location_sticker() elif self.strategy == \"predator\": self.update_location_predator() elif self.strategy == \"hunter\": self.update_location_hunter() elif self.strategy",
"# move same way as previous move again if self.previous_count == -1: direction",
"* 180.0 + lower_limit) % 360 self.location.move_angle(direction) self.previous_direction = direction self.previous_count = self.count_voters()",
"before prev move >= voters after prev move # then turn 180 degrees",
"random_strategy(self): a = random.randint(1,5) if a == 1: self.strategy = \"sticker\" elif a",
"self.count_voters(): direction = self.previous_direction else: lower_limit = self.previous_direction + 90 direction = (random.random()",
"strategy self.name = name self.colour = colour # random_colour() ??? self.voters = []",
"elif a == 2: self.strategy = \"predator\" elif a == 3: self.strategy =",
"__init__(self, simulation, name, colour, strategy=\"\"): self.location = Location() self.simulation = simulation if strategy",
"prev move # move same way as previous move again if self.previous_count ==",
"def reset_voters(self): self.voters = [] def count_voters(self): return len(self.voters) def update_location(self): if self.strategy",
"name self.colour = colour # random_colour() ??? self.voters = [] self.previous_count = -1",
"-1: direction = random.random() * 360.0 elif self.previous_count <= self.count_voters(): direction = self.previous_direction",
"parties = self.simulation.get_parties() biggest_party = self for p in parties: if biggest_party.count_voters() <",
"then turn 180 degrees and move again anywhere 90 degrees either side #if",
"update_location_predator(self): parties = self.simulation.get_parties() biggest_party = self for p in parties: if biggest_party.count_voters()",
"/ len(self.voters)) self.location.move_towards(target_location) def update_location_hunter(self): #get previous move #if voters before prev move",
"\"hunter\": self.update_location_hunter() elif self.strategy == \"aggregator\": self.update_location_aggregator() elif self.strategy == \"random\": self.update_location_random() else:",
"Location() target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location) def update_location_hunter(self): #get previous move",
"= p self.location.move_towards(biggest_party.location) def update_location_aggregator(self): if len(self.voters) > 0: sum_x = 0 sum_y",
"a == 4: self.strategy = \"aggregator\" elif a == 5: self.strategy = \"random\"",
"self.strategy = random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self): a = random.randint(1,5) if a == 1: self.strategy",
"= random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self): a = random.randint(1,5) if a == 1: self.strategy =",
"def random_strategy(self): a = random.randint(1,5) if a == 1: self.strategy = \"sticker\" elif",
"p in parties: if biggest_party.count_voters() < p.count_voters(): biggest_party = p self.location.move_towards(biggest_party.location) def update_location_aggregator(self):",
"for p in parties: if biggest_party.count_voters() < p.count_voters(): biggest_party = p self.location.move_towards(biggest_party.location) def",
"\"random\" def add_voter(self, voter): return self.voters.append(voter) def reset_voters(self): self.voters = [] def count_voters(self):",
"biggest_party = p self.location.move_towards(biggest_party.location) def update_location_aggregator(self): if len(self.voters) > 0: sum_x = 0",
"as previous move again if self.previous_count == -1: direction = random.random() * 360.0",
"else: lower_limit = self.previous_direction + 90 direction = (random.random() * 180.0 + lower_limit)",
"random_colour() ??? self.voters = [] self.previous_count = -1 # def random_strategy(self): # self.strategy",
"colour # random_colour() ??? self.voters = [] self.previous_count = -1 # def random_strategy(self):",
"again anywhere 90 degrees either side #if voters before prev move < voters",
"elif self.strategy == \"predator\": self.update_location_predator() elif self.strategy == \"hunter\": self.update_location_hunter() elif self.strategy ==",
"self.strategy + \" does not exist!\") def update_location_predator(self): parties = self.simulation.get_parties() biggest_party =",
"elif a == 4: self.strategy = \"aggregator\" elif a == 5: self.strategy =",
"import random class Party: def __init__(self, simulation, name, colour, strategy=\"\"): self.location = Location()",
"== \"predator\": self.update_location_predator() elif self.strategy == \"hunter\": self.update_location_hunter() elif self.strategy == \"aggregator\": self.update_location_aggregator()",
"\"aggregator\": self.update_location_aggregator() elif self.strategy == \"random\": self.update_location_random() else: print(\"Strategy \" + self.strategy +",
"2: self.strategy = \"predator\" elif a == 3: self.strategy = \"hunter\" elif a",
"return self.voters.append(voter) def reset_voters(self): self.voters = [] def count_voters(self): return len(self.voters) def update_location(self):",
"self.previous_direction else: lower_limit = self.previous_direction + 90 direction = (random.random() * 180.0 +",
"self.update_location_hunter() elif self.strategy == \"aggregator\": self.update_location_aggregator() elif self.strategy == \"random\": self.update_location_random() else: print(\"Strategy",
"self.strategy = \"sticker\" elif a == 2: self.strategy = \"predator\" elif a ==",
"== 3: self.strategy = \"hunter\" elif a == 4: self.strategy = \"aggregator\" elif",
"voters after prev move # move same way as previous move again if",
"\"predator\": self.update_location_predator() elif self.strategy == \"hunter\": self.update_location_hunter() elif self.strategy == \"aggregator\": self.update_location_aggregator() elif",
"def update_location(self): if self.strategy == \"sticker\": self.update_location_sticker() elif self.strategy == \"predator\": self.update_location_predator() elif",
"+= voter.location.x sum_y += voter.location.y target_location = Location() target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y /",
"self.location.random_move() def update_location_sticker(self): pass def get_location(self): return self.location def get_strategy(self): return self.strategy def",
"== 4: self.strategy = \"aggregator\" elif a == 5: self.strategy = \"random\" def",
"self.strategy == \"hunter\": self.update_location_hunter() elif self.strategy == \"aggregator\": self.update_location_aggregator() elif self.strategy == \"random\":",
"move again anywhere 90 degrees either side #if voters before prev move <",
"same way as previous move again if self.previous_count == -1: direction = random.random()",
"(random.random() * 180.0 + lower_limit) % 360 self.location.move_angle(direction) self.previous_direction = direction self.previous_count =",
"self.previous_count = self.count_voters() # def save_state(self): # self.previous_count = self.count_voters() def update_location_random(self): self.location.random_move()",
"biggest_party = self for p in parties: if biggest_party.count_voters() < p.count_voters(): biggest_party =",
"voter): return self.voters.append(voter) def reset_voters(self): self.voters = [] def count_voters(self): return len(self.voters) def",
"get_location(self): return self.location def get_strategy(self): return self.strategy def get_name(self): return self.name def get_colour(self):",
"import Location import random class Party: def __init__(self, simulation, name, colour, strategy=\"\"): self.location",
"Location() self.simulation = simulation if strategy == \"\": self.random_strategy() else: self.strategy = strategy",
"a == 2: self.strategy = \"predator\" elif a == 3: self.strategy = \"hunter\"",
"direction = random.random() * 360.0 elif self.previous_count <= self.count_voters(): direction = self.previous_direction else:",
"def update_location_predator(self): parties = self.simulation.get_parties() biggest_party = self for p in parties: if",
"self.previous_count <= self.count_voters(): direction = self.previous_direction else: lower_limit = self.previous_direction + 90 direction",
"self.location.move_angle(direction) self.previous_direction = direction self.previous_count = self.count_voters() # def save_state(self): # self.previous_count =",
"update_location_sticker(self): pass def get_location(self): return self.location def get_strategy(self): return self.strategy def get_name(self): return",
"move #if voters before prev move >= voters after prev move # then",
"self.previous_count == -1: direction = random.random() * 360.0 elif self.previous_count <= self.count_voters(): direction",
"simulation if strategy == \"\": self.random_strategy() else: self.strategy = strategy self.name = name",
"= random.randint(1,5) if a == 1: self.strategy = \"sticker\" elif a == 2:",
"3: self.strategy = \"hunter\" elif a == 4: self.strategy = \"aggregator\" elif a",
"else: print(\"Strategy \" + self.strategy + \" does not exist!\") def update_location_predator(self): parties",
"def update_location_aggregator(self): if len(self.voters) > 0: sum_x = 0 sum_y = 0 for",
"get_strategy(self): return self.strategy def get_name(self): return self.name def get_colour(self): return self.colour def get_voters(self):",
"if a == 1: self.strategy = \"sticker\" elif a == 2: self.strategy =",
"elif self.strategy == \"random\": self.update_location_random() else: print(\"Strategy \" + self.strategy + \" does",
"self.colour = colour # random_colour() ??? self.voters = [] self.previous_count = -1 #",
"for voter in self.voters: sum_x += voter.location.x sum_y += voter.location.y target_location = Location()",
"\" + self.strategy + \" does not exist!\") def update_location_predator(self): parties = self.simulation.get_parties()",
"def update_location_sticker(self): pass def get_location(self): return self.location def get_strategy(self): return self.strategy def get_name(self):",
"== 5: self.strategy = \"random\" def add_voter(self, voter): return self.voters.append(voter) def reset_voters(self): self.voters",
"name, colour, strategy=\"\"): self.location = Location() self.simulation = simulation if strategy == \"\":",
"if self.strategy == \"sticker\": self.update_location_sticker() elif self.strategy == \"predator\": self.update_location_predator() elif self.strategy ==",
"voters after prev move # then turn 180 degrees and move again anywhere",
"\"\": self.random_strategy() else: self.strategy = strategy self.name = name self.colour = colour #",
"= 0 sum_y = 0 for voter in self.voters: sum_x += voter.location.x sum_y",
"move same way as previous move again if self.previous_count == -1: direction =",
"0 for voter in self.voters: sum_x += voter.location.x sum_y += voter.location.y target_location =",
"random.random() * 360.0 elif self.previous_count <= self.count_voters(): direction = self.previous_direction else: lower_limit =",
"return self.location def get_strategy(self): return self.strategy def get_name(self): return self.name def get_colour(self): return",
"location import Location import random class Party: def __init__(self, simulation, name, colour, strategy=\"\"):",
"else: self.strategy = strategy self.name = name self.colour = colour # random_colour() ???",
"= self.simulation.get_parties() biggest_party = self for p in parties: if biggest_party.count_voters() < p.count_voters():",
"#get previous move #if voters before prev move >= voters after prev move",
"== 2: self.strategy = \"predator\" elif a == 3: self.strategy = \"hunter\" elif",
"self.strategy == \"aggregator\": self.update_location_aggregator() elif self.strategy == \"random\": self.update_location_random() else: print(\"Strategy \" +",
"voters before prev move >= voters after prev move # then turn 180",
"direction = self.previous_direction else: lower_limit = self.previous_direction + 90 direction = (random.random() *",
"# self.previous_count = self.count_voters() def update_location_random(self): self.location.random_move() def update_location_sticker(self): pass def get_location(self): return",
"self.previous_direction + 90 direction = (random.random() * 180.0 + lower_limit) % 360 self.location.move_angle(direction)",
"anywhere 90 degrees either side #if voters before prev move < voters after",
"strategy=\"\"): self.location = Location() self.simulation = simulation if strategy == \"\": self.random_strategy() else:",
"self.previous_count = -1 # def random_strategy(self): # self.strategy = random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self): a",
"random class Party: def __init__(self, simulation, name, colour, strategy=\"\"): self.location = Location() self.simulation",
"in parties: if biggest_party.count_voters() < p.count_voters(): biggest_party = p self.location.move_towards(biggest_party.location) def update_location_aggregator(self): if",
"= Location() target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location) def update_location_hunter(self): #get previous",
"* 360.0 elif self.previous_count <= self.count_voters(): direction = self.previous_direction else: lower_limit = self.previous_direction",
"def __init__(self, simulation, name, colour, strategy=\"\"): self.location = Location() self.simulation = simulation if",
"not exist!\") def update_location_predator(self): parties = self.simulation.get_parties() biggest_party = self for p in",
"p.count_voters(): biggest_party = p self.location.move_towards(biggest_party.location) def update_location_aggregator(self): if len(self.voters) > 0: sum_x =",
"way as previous move again if self.previous_count == -1: direction = random.random() *",
"# def save_state(self): # self.previous_count = self.count_voters() def update_location_random(self): self.location.random_move() def update_location_sticker(self): pass",
"if biggest_party.count_voters() < p.count_voters(): biggest_party = p self.location.move_towards(biggest_party.location) def update_location_aggregator(self): if len(self.voters) >",
"+ 90 direction = (random.random() * 180.0 + lower_limit) % 360 self.location.move_angle(direction) self.previous_direction",
"self.strategy = \"aggregator\" elif a == 5: self.strategy = \"random\" def add_voter(self, voter):",
"self.strategy def get_name(self): return self.name def get_colour(self): return self.colour def get_voters(self): return self.voters",
"previous move #if voters before prev move >= voters after prev move #",
"self.voters = [] self.previous_count = -1 # def random_strategy(self): # self.strategy = random.choose(self.simulation.get_allowed_strategies())",
"Party: def __init__(self, simulation, name, colour, strategy=\"\"): self.location = Location() self.simulation = simulation",
"self.simulation = simulation if strategy == \"\": self.random_strategy() else: self.strategy = strategy self.name",
"+ self.strategy + \" does not exist!\") def update_location_predator(self): parties = self.simulation.get_parties() biggest_party",
"\"random\": self.update_location_random() else: print(\"Strategy \" + self.strategy + \" does not exist!\") def",
"0 sum_y = 0 for voter in self.voters: sum_x += voter.location.x sum_y +=",
"if strategy == \"\": self.random_strategy() else: self.strategy = strategy self.name = name self.colour",
"90 degrees either side #if voters before prev move < voters after prev",
"= [] self.previous_count = -1 # def random_strategy(self): # self.strategy = random.choose(self.simulation.get_allowed_strategies()) def",
"4: self.strategy = \"aggregator\" elif a == 5: self.strategy = \"random\" def add_voter(self,",
"== 1: self.strategy = \"sticker\" elif a == 2: self.strategy = \"predator\" elif",
"self.strategy == \"sticker\": self.update_location_sticker() elif self.strategy == \"predator\": self.update_location_predator() elif self.strategy == \"hunter\":",
"direction self.previous_count = self.count_voters() # def save_state(self): # self.previous_count = self.count_voters() def update_location_random(self):",
"self.strategy = \"predator\" elif a == 3: self.strategy = \"hunter\" elif a ==",
"a == 1: self.strategy = \"sticker\" elif a == 2: self.strategy = \"predator\"",
"elif self.strategy == \"aggregator\": self.update_location_aggregator() elif self.strategy == \"random\": self.update_location_random() else: print(\"Strategy \"",
"def count_voters(self): return len(self.voters) def update_location(self): if self.strategy == \"sticker\": self.update_location_sticker() elif self.strategy",
"self.random_strategy() else: self.strategy = strategy self.name = name self.colour = colour # random_colour()",
"self.simulation.get_parties() biggest_party = self for p in parties: if biggest_party.count_voters() < p.count_voters(): biggest_party",
"# def random_strategy(self): # self.strategy = random.choose(self.simulation.get_allowed_strategies()) def random_strategy(self): a = random.randint(1,5) if",
"0: sum_x = 0 sum_y = 0 for voter in self.voters: sum_x +=",
"a == 5: self.strategy = \"random\" def add_voter(self, voter): return self.voters.append(voter) def reset_voters(self):",
"self.update_location_aggregator() elif self.strategy == \"random\": self.update_location_random() else: print(\"Strategy \" + self.strategy + \"",
"> 0: sum_x = 0 sum_y = 0 for voter in self.voters: sum_x",
"sum_x += voter.location.x sum_y += voter.location.y target_location = Location() target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y",
"len(self.voters)) self.location.move_towards(target_location) def update_location_hunter(self): #get previous move #if voters before prev move >=",
"self.location.move_towards(biggest_party.location) def update_location_aggregator(self): if len(self.voters) > 0: sum_x = 0 sum_y = 0",
"prev move >= voters after prev move # then turn 180 degrees and",
"= self.previous_direction else: lower_limit = self.previous_direction + 90 direction = (random.random() * 180.0",
"self.update_location_predator() elif self.strategy == \"hunter\": self.update_location_hunter() elif self.strategy == \"aggregator\": self.update_location_aggregator() elif self.strategy",
"lower_limit = self.previous_direction + 90 direction = (random.random() * 180.0 + lower_limit) %",
"pass def get_location(self): return self.location def get_strategy(self): return self.strategy def get_name(self): return self.name",
"def get_location(self): return self.location def get_strategy(self): return self.strategy def get_name(self): return self.name def",
"self.name = name self.colour = colour # random_colour() ??? self.voters = [] self.previous_count",
"elif a == 5: self.strategy = \"random\" def add_voter(self, voter): return self.voters.append(voter) def",
"strategy == \"\": self.random_strategy() else: self.strategy = strategy self.name = name self.colour =",
"prev move # then turn 180 degrees and move again anywhere 90 degrees",
"degrees and move again anywhere 90 degrees either side #if voters before prev",
"side #if voters before prev move < voters after prev move # move",
"simulation, name, colour, strategy=\"\"): self.location = Location() self.simulation = simulation if strategy ==",
"self.strategy == \"predator\": self.update_location_predator() elif self.strategy == \"hunter\": self.update_location_hunter() elif self.strategy == \"aggregator\":",
"== \"aggregator\": self.update_location_aggregator() elif self.strategy == \"random\": self.update_location_random() else: print(\"Strategy \" + self.strategy",
"self.strategy == \"random\": self.update_location_random() else: print(\"Strategy \" + self.strategy + \" does not",
"update_location(self): if self.strategy == \"sticker\": self.update_location_sticker() elif self.strategy == \"predator\": self.update_location_predator() elif self.strategy",
"update_location_aggregator(self): if len(self.voters) > 0: sum_x = 0 sum_y = 0 for voter",
"count_voters(self): return len(self.voters) def update_location(self): if self.strategy == \"sticker\": self.update_location_sticker() elif self.strategy ==",
"== \"hunter\": self.update_location_hunter() elif self.strategy == \"aggregator\": self.update_location_aggregator() elif self.strategy == \"random\": self.update_location_random()",
"does not exist!\") def update_location_predator(self): parties = self.simulation.get_parties() biggest_party = self for p",
"self.voters: sum_x += voter.location.x sum_y += voter.location.y target_location = Location() target_location.set_x(sum_x / len(self.voters))",
"colour, strategy=\"\"): self.location = Location() self.simulation = simulation if strategy == \"\": self.random_strategy()",
"direction = (random.random() * 180.0 + lower_limit) % 360 self.location.move_angle(direction) self.previous_direction = direction",
"= (random.random() * 180.0 + lower_limit) % 360 self.location.move_angle(direction) self.previous_direction = direction self.previous_count",
"90 direction = (random.random() * 180.0 + lower_limit) % 360 self.location.move_angle(direction) self.previous_direction =",
"== \"\": self.random_strategy() else: self.strategy = strategy self.name = name self.colour = colour",
"elif a == 3: self.strategy = \"hunter\" elif a == 4: self.strategy =",
"360.0 elif self.previous_count <= self.count_voters(): direction = self.previous_direction else: lower_limit = self.previous_direction +",
"self.count_voters() # def save_state(self): # self.previous_count = self.count_voters() def update_location_random(self): self.location.random_move() def update_location_sticker(self):",
"target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location) def update_location_hunter(self): #get previous move #if",
"lower_limit) % 360 self.location.move_angle(direction) self.previous_direction = direction self.previous_count = self.count_voters() # def save_state(self):",
"= Location() self.simulation = simulation if strategy == \"\": self.random_strategy() else: self.strategy =",
"update_location_random(self): self.location.random_move() def update_location_sticker(self): pass def get_location(self): return self.location def get_strategy(self): return self.strategy",
"\" does not exist!\") def update_location_predator(self): parties = self.simulation.get_parties() biggest_party = self for",
"= colour # random_colour() ??? self.voters = [] self.previous_count = -1 # def",
"len(self.voters) > 0: sum_x = 0 sum_y = 0 for voter in self.voters:",
"exist!\") def update_location_predator(self): parties = self.simulation.get_parties() biggest_party = self for p in parties:",
"= self.count_voters() def update_location_random(self): self.location.random_move() def update_location_sticker(self): pass def get_location(self): return self.location def",
"if len(self.voters) > 0: sum_x = 0 sum_y = 0 for voter in",
"a = random.randint(1,5) if a == 1: self.strategy = \"sticker\" elif a ==",
"\"sticker\": self.update_location_sticker() elif self.strategy == \"predator\": self.update_location_predator() elif self.strategy == \"hunter\": self.update_location_hunter() elif",
"# random_colour() ??? self.voters = [] self.previous_count = -1 # def random_strategy(self): #",
"+= voter.location.y target_location = Location() target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location) def",
"target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location) def update_location_hunter(self): #get previous move #if voters before prev",
"voters before prev move < voters after prev move # move same way",
"def get_strategy(self): return self.strategy def get_name(self): return self.name def get_colour(self): return self.colour def",
"= simulation if strategy == \"\": self.random_strategy() else: self.strategy = strategy self.name =",
"[] def count_voters(self): return len(self.voters) def update_location(self): if self.strategy == \"sticker\": self.update_location_sticker() elif",
"= self for p in parties: if biggest_party.count_voters() < p.count_voters(): biggest_party = p",
"a == 3: self.strategy = \"hunter\" elif a == 4: self.strategy = \"aggregator\"",
"5: self.strategy = \"random\" def add_voter(self, voter): return self.voters.append(voter) def reset_voters(self): self.voters =",
"Location import random class Party: def __init__(self, simulation, name, colour, strategy=\"\"): self.location =",
"= \"sticker\" elif a == 2: self.strategy = \"predator\" elif a == 3:",
"??? self.voters = [] self.previous_count = -1 # def random_strategy(self): # self.strategy ="
] |
[
"import pickle import os,sys ''' print('starting readin of monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read",
"of monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in",
"import pandas from astropy.table import Table import pickle import os,sys ''' print('starting readin",
"pandas from astropy.table import Table import pickle import os,sys ''' print('starting readin of",
"feats_folder=os.path.join(out_folder,'features') print('data loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names))) print('extracting features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/'",
"#raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id'])",
"sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10]",
"set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1]) print('Performing feature",
"''' index=int(sys.argv[1]) print('Performing feature extraction on batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data') sys.stdout.flush() with",
"wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) ''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1: pickle.dump(wf.PCA_mean,f1)",
"pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2: pickle.dump(wf.PCA_eigenvals,f2) with open(os.path.join(feats_folder,'PCA_eigenvectors.pickle'),'wb') as f3: pickle.dump(wf.PCA_eigenvectors,f3) np.savetxt(os.path.join(feats_folder,'PCA_mean.txt'),wf.PCA_mean) np.savetxt(os.path.join(feats_folder,'PCA_eigenvals.txt'),wf.PCA_eigenvals)",
"print('extracting features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) ''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb')",
"sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) ''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1:",
"features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) ''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as",
"from snmachine import sndata,snfeatures import numpy as np import pandas from astropy.table import",
"out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data') sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data loaded')",
"f1: pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2: pickle.dump(wf.PCA_eigenvals,f2) with open(os.path.join(feats_folder,'PCA_eigenvectors.pickle'),'wb') as f3: pickle.dump(wf.PCA_eigenvectors,f3) np.savetxt(os.path.join(feats_folder,'PCA_mean.txt'),wf.PCA_mean)",
"data') sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder)",
"%d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data') sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data",
"int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names))) print('extracting features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100)",
"numpy as np import pandas from astropy.table import Table import pickle import os,sys",
"monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in metadata')",
"sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1]) print('Performing feature extraction on batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading",
"data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1]) print('Performing",
"loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names))) print('extracting features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False,",
"pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) ''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1: pickle.dump(wf.PCA_mean,f1) with",
"''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1: pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2: pickle.dump(wf.PCA_eigenvals,f2) with open(os.path.join(feats_folder,'PCA_eigenvectors.pickle'),'wb')",
"d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names))) print('extracting features') sys.stdout.flush()",
"readin of monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read",
"sndata,snfeatures import numpy as np import pandas from astropy.table import Table import pickle",
"'wavelet_features_%d.fits'%index),overwrite=True) ''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1: pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2: pickle.dump(wf.PCA_eigenvals,f2) with",
"print('data loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names))) print('extracting features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder,",
"pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) ''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1: pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2:",
"''' print('starting readin of monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv')",
"in data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1])",
"#raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1]) print('Performing feature extraction",
"np import pandas from astropy.table import Table import pickle import os,sys ''' print('starting",
"print('read in data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') '''",
"feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) ''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1: pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb')",
"snmachine import sndata,snfeatures import numpy as np import pandas from astropy.table import Table",
"metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1]) print('Performing feature extraction on batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/'",
"as f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names))) print('extracting",
"print('read in metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1]) print('Performing feature extraction on batch",
"with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2: pickle.dump(wf.PCA_eigenvals,f2) with open(os.path.join(feats_folder,'PCA_eigenvectors.pickle'),'wb') as f3: pickle.dump(wf.PCA_eigenvectors,f3) np.savetxt(os.path.join(feats_folder,'PCA_mean.txt'),wf.PCA_mean) np.savetxt(os.path.join(feats_folder,'PCA_eigenvals.txt'),wf.PCA_eigenvals) np.savetxt(os.path.join(feats_folder,'PCA_eigenvectors.txt'),wf.PCA_eigenvectors)",
"astropy.table import Table import pickle import os,sys ''' print('starting readin of monster files')",
"with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1: pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2: pickle.dump(wf.PCA_eigenvals,f2) with open(os.path.join(feats_folder,'PCA_eigenvectors.pickle'),'wb') as",
"os,sys ''' print('starting readin of monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in data set')",
"open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names)))",
"import Table import pickle import os,sys ''' print('starting readin of monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv')",
"import os,sys ''' print('starting readin of monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in data",
"#filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1]) print('Performing feature extraction on batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data') sys.stdout.flush()",
"pickle import os,sys ''' print('starting readin of monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in",
"in metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1]) print('Performing feature extraction on batch %d'%index)",
"Table import pickle import os,sys ''' print('starting readin of monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv')",
"extraction on batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data') sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f: d=pickle.load(f)",
"f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names))) print('extracting features')",
"sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names))) print('extracting features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100)",
"open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2: pickle.dump(wf.PCA_eigenvals,f2) with open(os.path.join(feats_folder,'PCA_eigenvectors.pickle'),'wb') as f3: pickle.dump(wf.PCA_eigenvectors,f3) np.savetxt(os.path.join(feats_folder,'PCA_mean.txt'),wf.PCA_mean) np.savetxt(os.path.join(feats_folder,'PCA_eigenvals.txt'),wf.PCA_eigenvals) np.savetxt(os.path.join(feats_folder,'PCA_eigenvectors.txt'),wf.PCA_eigenvectors) '''",
"'+str(len(d.object_names))) print('extracting features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) ''' with",
"import sndata,snfeatures import numpy as np import pandas from astropy.table import Table import",
"print('starting readin of monster files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv')",
"on batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data') sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int')",
"#objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1]) print('Performing feature extraction on batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data')",
"raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str')",
"import numpy as np import pandas from astropy.table import Table import pickle import",
"recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) ''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1: pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as",
"as f1: pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2: pickle.dump(wf.PCA_eigenvals,f2) with open(os.path.join(feats_folder,'PCA_eigenvectors.pickle'),'wb') as f3: pickle.dump(wf.PCA_eigenvectors,f3)",
"#d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names))) print('extracting features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True)",
"open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1: pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2: pickle.dump(wf.PCA_eigenvals,f2) with open(os.path.join(feats_folder,'PCA_eigenvectors.pickle'),'wb') as f3:",
"from astropy.table import Table import pickle import os,sys ''' print('starting readin of monster",
"index=int(sys.argv[1]) print('Performing feature extraction on batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data') sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb')",
"files') #raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set.csv') raw_data=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set.csv') print('read in data set') #raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/test_set_metadata.csv') raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in metadata') sys.stdout.flush()",
"raw_metadata=pandas.read_csv('/share/hypatia/snmachine_resources/data/plasticc/training_set_metadata.csv') print('read in metadata') sys.stdout.flush() #objects=np.unique(raw_data['object_id']) #filters=np.unique(raw_data['passband']).astype('str') ''' index=int(sys.argv[1]) print('Performing feature extraction on",
"#d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj: '+str(len(d.object_names))) print('extracting features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder,",
"print('loading data') sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data loaded') sys.stdout.flush()",
"feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) ''' with open(os.path.join(feats_folder,'PCA_mean.pickle'),'wb') as f1: pickle.dump(wf.PCA_mean,f1) with open(os.path.join(feats_folder,'PCA_eigenvals.pickle'),'wb') as f2: pickle.dump(wf.PCA_eigenvals,f2)",
"batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data') sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features')",
"print('Performing feature extraction on batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data') sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as",
"with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f: d=pickle.load(f) int_folder=os.path.join(out_folder,'int') feats_folder=os.path.join(out_folder,'features') print('data loaded') sys.stdout.flush() #d=sndata.EmptyDataset(filter_set=filters,survey_name='plasticc',folder=out_folder) #d.object_names=d.object_names[:10] print('nobj:",
"feature extraction on batch %d'%index) out_folder='/share/hypatia/snmachine_resources/data/plasticc/data_products/plasticc_test/with_nondetection_cutting/fullset/data/' print('loading data') sys.stdout.flush() with open(os.path.join(out_folder,'dataset_%d.pickle'%index),'rb') as f:",
"print('nobj: '+str(len(d.object_names))) print('extracting features') sys.stdout.flush() wf=snfeatures.WaveletFeatures(wavelet='sym2',ngp=1100) pca_folder='/share/hypatia/snmachine_resources/data/plasticc/dummy_pca/' feats=wf.extract_features(d,nprocesses=1,save_output='all',output_root=int_folder, recompute_pca=False, pca_path=pca_folder,xmax=1100) feats.write(os.path.join(feats_folder, 'wavelet_features_%d.fits'%index),overwrite=True) '''",
"as np import pandas from astropy.table import Table import pickle import os,sys '''"
] |
[
"json file else: json_name = os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name] = input_path return batch_runs if",
"all_runs = [file for file in os.listdir(input_path) if file.endswith('.json')] for json in all_runs:",
"is a folder, ensure it is not empty and that it contains at",
"directory if os.path.isdir(input_path): all_runs = [file for file in os.listdir(input_path) if file.endswith('.json')] for",
"= [file for file in os.listdir(input_path) if file.endswith('.json')] for json in all_runs: batch_runs[json.replace('.json',",
"ensure it is in json format.') # initialize a dictionary to hold all",
"DockStream execution.') parser.add_argument('-input_path', type=str, required=True, help='The path to either a folder of DockStream",
"json file) if not os.path.isdir(input_path) and not os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path) #",
"DockStream json files or a single json file and returns a dictionary whose",
"batch DockStream execution.') parser.add_argument('-input_path', type=str, required=True, help='The path to either a folder of",
"-> dict: \"\"\"this method takes an input path to either a folder containing",
"neither a folder nor a file :return: dictionary, keys are the DockStream json",
"the names of all runs that did not enforce \"best_per_ligand\" non_bpl_runs = {}",
"non_bpl_runs = {} # loop through all user json files and run DockStream",
"# print the names of the runs which did not enforce \"best_per_ligand\" print(f\"List",
"in all_runs: batch_runs[json.replace('.json', '')] = os.path.join(input_path, json) # at this point, input path",
"must be a file. Check that it is in json format if os.path.isfile(input_path):",
"print the names of the runs which did not enforce \"best_per_ligand\" print(f\"List of",
"or a single json file and returns a dictionary whose keys are the",
"input_path is a folder, ensure it is not empty and that it contains",
"input_path is neither a folder nor a file :return: dictionary, keys are the",
"a file. Check that it is in json format if os.path.isfile(input_path): if not",
"if file.endswith('.json')] for json in all_runs: batch_runs[json.replace('.json', '')] = os.path.join(input_path, json) # at",
"raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path) # if input_path is a folder, ensure it is",
"run.') print(result.stdout) print(result.stderr) if bool(non_bpl_runs): # print the names of the runs which",
"Executor from dockstream.utils import files_paths from dockstream.utils.enums.docking_enum import DockingConfigurationEnum _DC = DockingConfigurationEnum() def",
"format if os.path.isfile(input_path): if not input_path.endswith('.json'): sys.exit(input_path + ' is not a json",
"is not empty and that it contains at least 1 json file if",
"is not a json file. Please ensure it is in json format.') #",
"single json file else: json_name = os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name] = input_path return batch_runs",
"specified in the configuration json try: for docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE]",
"a folder, ensure it is not empty and that it contains at least",
"= argparse.ArgumentParser(description='Facilitates batch DockStream execution.') parser.add_argument('-input_path', type=str, required=True, help='The path to either a",
"is in json format if os.path.isfile(input_path): if not input_path.endswith('.json'): sys.exit(input_path + ' is",
"the current DockStream run has \"best_per_ligand\" enforced with open(json_path, \"r\") as f: parameters",
"'')] = os.path.join(input_path, json) # at this point, input path must be a",
"+ ' contains no json files. Please ensure your DockStream json files are",
"'-debug'], check=False) print(result) # print out error messages (if applicable) for the current",
"the configuration json try: for docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode",
"input_path: path to either a folder of json files or a single json",
"least 1 json file if os.path.isdir(input_path): if not os.listdir(input_path): sys.exit(input_path + ' folder",
"os.path.isdir(input_path): if not os.listdir(input_path): sys.exit(input_path + ' folder is empty. Please ensure your",
"the current DockStream run if result.returncode != 0: print(f'There was an error with",
"file :return: dictionary, keys are the DockStream json names and values are the",
"runs which did not enforce \"best_per_ligand\" print(f\"List of runs which did not have",
"os.path.isdir(input_path) and not os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path) # if input_path is a",
"try: for docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name]",
"be looped later to run DockStream :param input_path: path to either a folder",
"batch_runs[json.replace('.json', '')] = os.path.join(input_path, json) # at this point, input path must be",
"import os import json import errno import sys import argparse from dockstream.utils.execute_external.execute import",
"no json files. Please ensure your DockStream json files are added to the",
"json names and the corresponding values are the paths to the json file.",
"files or a single json file and returns a dictionary whose keys are",
"print(result.stderr) if bool(non_bpl_runs): # print the names of the runs which did not",
"os.path.join(input_path, json) # at this point, input path must be a single json",
"looped later to run DockStream :param input_path: path to either a folder of",
"loop through all user json files and run DockStream for trial_name, json_path in",
"as f: parameters = json.load(f) # in case output mode was not specified",
"did not enforce \"best_per_ligand\" print(f\"List of runs which did not have 'best_per_ligand' specified.",
"argparse from dockstream.utils.execute_external.execute import Executor from dockstream.utils import files_paths from dockstream.utils.enums.docking_enum import DockingConfigurationEnum",
"of json files or a single json file :raises FileNotFoundError: this error is",
"and that it contains at least 1 json file if os.path.isdir(input_path): if not",
"json_name = os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name] = input_path return batch_runs if __name__ == '__main__':",
"json_path, '-debug'], check=False) print(result) # print out error messages (if applicable) for the",
"to either a folder of DockStream json files or a single json file.')",
"output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] = output_mode break except: pass print(f'Running {trial_name}') result =",
"json files or a single json file and returns a dictionary whose keys",
"if input_path is neither a folder nor a file :return: dictionary, keys are",
"names of the runs which did not enforce \"best_per_ligand\" print(f\"List of runs which",
"enforce \"best_per_ligand\" non_bpl_runs = {} # loop through all user json files and",
"import errno import sys import argparse from dockstream.utils.execute_external.execute import Executor from dockstream.utils import",
"input_path is valid (either a folder containing json files or a single json",
"os.path.isdir(input_path): all_runs = [file for file in os.listdir(input_path) if file.endswith('.json')] for json in",
"all user json files and run DockStream for trial_name, json_path in batch_runs.items(): #",
"from dockstream.utils.execute_external.execute import Executor from dockstream.utils import files_paths from dockstream.utils.enums.docking_enum import DockingConfigurationEnum _DC",
"that it contains at least 1 json file if os.path.isdir(input_path): if not os.listdir(input_path):",
"batch_runs = run_script(args.input_path) executor = Executor() # initialize a dictionary to store the",
"json files. Please ensure your DockStream json files are added to the folder.')",
"parser.parse_args() batch_runs = run_script(args.input_path) executor = Executor() # initialize a dictionary to store",
"the corresponding values are the paths to the json file. The dictionary will",
"docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] = output_mode break except: pass print(f'Running {trial_name}')",
"be a single json file else: json_name = os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name] = input_path",
"executor = Executor() # initialize a dictionary to store the names of all",
"os.listdir(input_path): sys.exit(input_path + ' folder is empty. Please ensure your DockStream json files",
"output mode was not specified in the configuration json try: for docking_run in",
"a folder of json files or a single json file :raises FileNotFoundError: this",
"hold all DockStream runs batch_runs = {} # loop through all json files",
"this point, input path must be a single json file else: json_name =",
"_DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] = output_mode break except: pass print(f'Running {trial_name}') result = executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'),",
"(if applicable) for the current DockStream run if result.returncode != 0: print(f'There was",
"to run DockStream :param input_path: path to either a folder of json files",
"out error messages (if applicable) for the current DockStream run if result.returncode !=",
"file and returns a dictionary whose keys are the json names and the",
"at least 1 json file if os.path.isdir(input_path): if not os.listdir(input_path): sys.exit(input_path + '",
"initialize a dictionary to store the names of all runs that did not",
"is in json format.') # initialize a dictionary to hold all DockStream runs",
"argparse.ArgumentParser(description='Facilitates batch DockStream execution.') parser.add_argument('-input_path', type=str, required=True, help='The path to either a folder",
"# at this point, input path must be a single json file else:",
"that did not enforce \"best_per_ligand\" non_bpl_runs = {} # loop through all user",
"in batch_runs.items(): # check if the current DockStream run has \"best_per_ligand\" enforced with",
"containing json files or a single json file) if not os.path.isdir(input_path) and not",
"a folder nor a file :return: dictionary, keys are the DockStream json names",
"to either a folder of json files or a single json file :raises",
"keys are the json names and the corresponding values are the paths to",
"error with {trial_name} DockStream run.') print(result.stdout) print(result.stderr) if bool(non_bpl_runs): # print the names",
"except: pass print(f'Running {trial_name}') result = executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path, '-debug'], check=False) print(result)",
"json files are added to the folder.') # at this point, the path",
"file :raises FileNotFoundError: this error is raised if input_path is neither a folder",
"ensure your DockStream json files are added to the folder.') elif not any(file.endswith('.json')",
"== '__main__': # take user specified input parameters to run the benchmarking script",
"for file in os.listdir(input_path)): sys.exit(input_path + ' contains no json files. Please ensure",
"folder containing json files or a single json file) if not os.path.isdir(input_path) and",
":raises FileNotFoundError: this error is raised if input_path is neither a folder nor",
"json files and update the paths if input_path if a directory if os.path.isdir(input_path):",
"of runs which did not have 'best_per_ligand' specified. These runs cannot be \"",
"def run_script(input_path: str) -> dict: \"\"\"this method takes an input path to either",
"not os.listdir(input_path): sys.exit(input_path + ' folder is empty. Please ensure your DockStream json",
"files or a single json file.') args = parser.parse_args() batch_runs = run_script(args.input_path) executor",
"files and run DockStream for trial_name, json_path in batch_runs.items(): # check if the",
"not enforce \"best_per_ligand\" print(f\"List of runs which did not have 'best_per_ligand' specified. These",
"json files or a single json file) if not os.path.isdir(input_path) and not os.path.isfile(input_path):",
"single json file and returns a dictionary whose keys are the json names",
"result = executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path, '-debug'], check=False) print(result) # print out error",
"os.path.isfile(input_path): if not input_path.endswith('.json'): sys.exit(input_path + ' is not a json file. Please",
"batch_runs[json_name] = input_path return batch_runs if __name__ == '__main__': # take user specified",
"of DockStream json files or a single json file.') args = parser.parse_args() batch_runs",
"if the current DockStream run has \"best_per_ligand\" enforced with open(json_path, \"r\") as f:",
"did not have 'best_per_ligand' specified. These runs cannot be \" f\"passed into the",
"' folder is empty. Please ensure your DockStream json files are added to",
"folder of DockStream json files or a single json file.') args = parser.parse_args()",
"a file :return: dictionary, keys are the DockStream json names and values are",
"corresponding values are the paths to the json file. The dictionary will be",
"= DockingConfigurationEnum() def run_script(input_path: str) -> dict: \"\"\"this method takes an input path",
"run if result.returncode != 0: print(f'There was an error with {trial_name} DockStream run.')",
"a single json file and returns a dictionary whose keys are the json",
"json import errno import sys import argparse from dockstream.utils.execute_external.execute import Executor from dockstream.utils",
"if output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] = output_mode break except: pass print(f'Running {trial_name}') result",
"whose keys are the json names and the corresponding values are the paths",
"the paths to the json file. The dictionary will be looped later to",
"DockStream runs batch_runs = {} # loop through all json files and update",
"dockstream.utils.execute_external.execute import Executor from dockstream.utils import files_paths from dockstream.utils.enums.docking_enum import DockingConfigurationEnum _DC =",
"json file. The dictionary will be looped later to run DockStream :param input_path:",
"= os.path.join(input_path, json) # at this point, input path must be a single",
"and update the paths if input_path if a directory if os.path.isdir(input_path): all_runs =",
"path to either a folder of json files or a single json file",
"a single json file) if not os.path.isdir(input_path) and not os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),",
"with open(json_path, \"r\") as f: parameters = json.load(f) # in case output mode",
"applicable) for the current DockStream run if result.returncode != 0: print(f'There was an",
"this point, the path must be a file. Check that it is in",
"folder nor a file :return: dictionary, keys are the DockStream json names and",
"must be a single json file else: json_name = os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name] =",
"specified input parameters to run the benchmarking script parser = argparse.ArgumentParser(description='Facilitates batch DockStream",
"a dictionary to hold all DockStream runs batch_runs = {} # loop through",
"are added to the folder.') elif not any(file.endswith('.json') for file in os.listdir(input_path)): sys.exit(input_path",
"file in os.listdir(input_path)): sys.exit(input_path + ' contains no json files. Please ensure your",
"script parser = argparse.ArgumentParser(description='Facilitates batch DockStream execution.') parser.add_argument('-input_path', type=str, required=True, help='The path to",
"\"best_per_ligand\" print(f\"List of runs which did not have 'best_per_ligand' specified. These runs cannot",
"The dictionary will be looped later to run DockStream :param input_path: path to",
"path to either a folder containing DockStream json files or a single json",
"the paths to them \"\"\" # first check if input_path is valid (either",
"= json.load(f) # in case output mode was not specified in the configuration",
"sys.exit(input_path + ' folder is empty. Please ensure your DockStream json files are",
"path must be a file. Check that it is in json format if",
"json file.') args = parser.parse_args() batch_runs = run_script(args.input_path) executor = Executor() # initialize",
"a dictionary whose keys are the json names and the corresponding values are",
"if a directory if os.path.isdir(input_path): all_runs = [file for file in os.listdir(input_path) if",
"not input_path.endswith('.json'): sys.exit(input_path + ' is not a json file. Please ensure it",
"# first check if input_path is valid (either a folder containing json files",
"json in all_runs: batch_runs[json.replace('.json', '')] = os.path.join(input_path, json) # at this point, input",
"if os.path.isdir(input_path): if not os.listdir(input_path): sys.exit(input_path + ' folder is empty. Please ensure",
"elif not any(file.endswith('.json') for file in os.listdir(input_path)): sys.exit(input_path + ' contains no json",
"to run the benchmarking script parser = argparse.ArgumentParser(description='Facilitates batch DockStream execution.') parser.add_argument('-input_path', type=str,",
"json files or a single json file :raises FileNotFoundError: this error is raised",
"{trial_name} DockStream run.') print(result.stdout) print(result.stderr) if bool(non_bpl_runs): # print the names of the",
"files and update the paths if input_path if a directory if os.path.isdir(input_path): all_runs",
"first check if input_path is valid (either a folder containing json files or",
"are added to the folder.') # at this point, the path must be",
"dictionary to hold all DockStream runs batch_runs = {} # loop through all",
"messages (if applicable) for the current DockStream run if result.returncode != 0: print(f'There",
"1 json file if os.path.isdir(input_path): if not os.listdir(input_path): sys.exit(input_path + ' folder is",
"os.listdir(input_path) if file.endswith('.json')] for json in all_runs: batch_runs[json.replace('.json', '')] = os.path.join(input_path, json) #",
"contains no json files. Please ensure your DockStream json files are added to",
"files are added to the folder.') # at this point, the path must",
"# loop through all user json files and run DockStream for trial_name, json_path",
"check=False) print(result) # print out error messages (if applicable) for the current DockStream",
"to the folder.') elif not any(file.endswith('.json') for file in os.listdir(input_path)): sys.exit(input_path + '",
"a folder containing DockStream json files or a single json file and returns",
"\"r\") as f: parameters = json.load(f) # in case output mode was not",
"DockStream for trial_name, json_path in batch_runs.items(): # check if the current DockStream run",
"did not enforce \"best_per_ligand\" non_bpl_runs = {} # loop through all user json",
"mode was not specified in the configuration json try: for docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]:",
"not any(file.endswith('.json') for file in os.listdir(input_path)): sys.exit(input_path + ' contains no json files.",
"run DockStream :param input_path: path to either a folder of json files or",
"result.returncode != 0: print(f'There was an error with {trial_name} DockStream run.') print(result.stdout) print(result.stderr)",
"json files or a single json file.') args = parser.parse_args() batch_runs = run_script(args.input_path)",
"= parser.parse_args() batch_runs = run_script(args.input_path) executor = Executor() # initialize a dictionary to",
"# initialize a dictionary to store the names of all runs that did",
":param input_path: path to either a folder of json files or a single",
"json file :raises FileNotFoundError: this error is raised if input_path is neither a",
"at this point, the path must be a file. Check that it is",
"os import json import errno import sys import argparse from dockstream.utils.execute_external.execute import Executor",
"input path must be a single json file else: json_name = os.path.basename(os.path.normpath(input_path)).replace('.json', '')",
"to the folder.') # at this point, the path must be a file.",
"Please ensure it is in json format.') # initialize a dictionary to hold",
"folder is empty. Please ensure your DockStream json files are added to the",
"if result.returncode != 0: print(f'There was an error with {trial_name} DockStream run.') print(result.stdout)",
"store the names of all runs that did not enforce \"best_per_ligand\" non_bpl_runs =",
"run_script(input_path: str) -> dict: \"\"\"this method takes an input path to either a",
"os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path) # if input_path is a folder, ensure it",
"a directory if os.path.isdir(input_path): all_runs = [file for file in os.listdir(input_path) if file.endswith('.json')]",
"print(f'There was an error with {trial_name} DockStream run.') print(result.stdout) print(result.stderr) if bool(non_bpl_runs): #",
"path must be a single json file else: json_name = os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name]",
"a single json file :raises FileNotFoundError: this error is raised if input_path is",
"benchmarking script parser = argparse.ArgumentParser(description='Facilitates batch DockStream execution.') parser.add_argument('-input_path', type=str, required=True, help='The path",
"this error is raised if input_path is neither a folder nor a file",
"json file and returns a dictionary whose keys are the json names and",
"break except: pass print(f'Running {trial_name}') result = executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path, '-debug'], check=False)",
"input path to either a folder containing DockStream json files or a single",
"execution.') parser.add_argument('-input_path', type=str, required=True, help='The path to either a folder of DockStream json",
"empty. Please ensure your DockStream json files are added to the folder.') elif",
"parser.add_argument('-input_path', type=str, required=True, help='The path to either a folder of DockStream json files",
"the names of the runs which did not enforce \"best_per_ligand\" print(f\"List of runs",
"batch_runs if __name__ == '__main__': # take user specified input parameters to run",
"print(result) # print out error messages (if applicable) for the current DockStream run",
"folder.') # at this point, the path must be a file. Check that",
"file.endswith('.json')] for json in all_runs: batch_runs[json.replace('.json', '')] = os.path.join(input_path, json) # at this",
"import Executor from dockstream.utils import files_paths from dockstream.utils.enums.docking_enum import DockingConfigurationEnum _DC = DockingConfigurationEnum()",
"check if the current DockStream run has \"best_per_ligand\" enforced with open(json_path, \"r\") as",
"DockStream json files are added to the folder.') elif not any(file.endswith('.json') for file",
"it contains at least 1 json file if os.path.isdir(input_path): if not os.listdir(input_path): sys.exit(input_path",
"json files and run DockStream for trial_name, json_path in batch_runs.items(): # check if",
":return: dictionary, keys are the DockStream json names and values are the paths",
"all_runs: batch_runs[json.replace('.json', '')] = os.path.join(input_path, json) # at this point, input path must",
"else: json_name = os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name] = input_path return batch_runs if __name__ ==",
"\"\"\"this method takes an input path to either a folder containing DockStream json",
"the json file. The dictionary will be looped later to run DockStream :param",
"the path must be a file. Check that it is in json format",
"path to either a folder of DockStream json files or a single json",
"not specified in the configuration json try: for docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode =",
"Check that it is in json format if os.path.isfile(input_path): if not input_path.endswith('.json'): sys.exit(input_path",
"import files_paths from dockstream.utils.enums.docking_enum import DockingConfigurationEnum _DC = DockingConfigurationEnum() def run_script(input_path: str) ->",
"an error with {trial_name} DockStream run.') print(result.stdout) print(result.stderr) if bool(non_bpl_runs): # print the",
"is empty. Please ensure your DockStream json files are added to the folder.')",
"either a folder of DockStream json files or a single json file.') args",
"with {trial_name} DockStream run.') print(result.stdout) print(result.stderr) if bool(non_bpl_runs): # print the names of",
"are the json names and the corresponding values are the paths to the",
"contains at least 1 json file if os.path.isdir(input_path): if not os.listdir(input_path): sys.exit(input_path +",
"that it is in json format if os.path.isfile(input_path): if not input_path.endswith('.json'): sys.exit(input_path +",
"folder containing DockStream json files or a single json file and returns a",
"are the DockStream json names and values are the paths to them \"\"\"",
"loop through all json files and update the paths if input_path if a",
"= input_path return batch_runs if __name__ == '__main__': # take user specified input",
"in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] = output_mode break",
"json file. Please ensure it is in json format.') # initialize a dictionary",
"at this point, input path must be a single json file else: json_name",
"values are the paths to them \"\"\" # first check if input_path is",
"Please ensure your DockStream json files are added to the folder.') # at",
"'-conf', json_path, '-debug'], check=False) print(result) # print out error messages (if applicable) for",
"through all json files and update the paths if input_path if a directory",
"json names and values are the paths to them \"\"\" # first check",
"ensure your DockStream json files are added to the folder.') # at this",
"current DockStream run has \"best_per_ligand\" enforced with open(json_path, \"r\") as f: parameters =",
"files or a single json file) if not os.path.isdir(input_path) and not os.path.isfile(input_path): raise",
"output_mode break except: pass print(f'Running {trial_name}') result = executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path, '-debug'],",
"json format.') # initialize a dictionary to hold all DockStream runs batch_runs =",
"errno import sys import argparse from dockstream.utils.execute_external.execute import Executor from dockstream.utils import files_paths",
"# print out error messages (if applicable) for the current DockStream run if",
"and values are the paths to them \"\"\" # first check if input_path",
"from dockstream.utils.enums.docking_enum import DockingConfigurationEnum _DC = DockingConfigurationEnum() def run_script(input_path: str) -> dict: \"\"\"this",
"the DockStream json names and values are the paths to them \"\"\" #",
"or a single json file) if not os.path.isdir(input_path) and not os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT,",
"update the paths if input_path if a directory if os.path.isdir(input_path): all_runs = [file",
"(either a folder containing json files or a single json file) if not",
"{} # loop through all user json files and run DockStream for trial_name,",
"DockStream json files or a single json file.') args = parser.parse_args() batch_runs =",
"take user specified input parameters to run the benchmarking script parser = argparse.ArgumentParser(description='Facilitates",
"json) # at this point, input path must be a single json file",
"= Executor() # initialize a dictionary to store the names of all runs",
"through all user json files and run DockStream for trial_name, json_path in batch_runs.items():",
"has \"best_per_ligand\" enforced with open(json_path, \"r\") as f: parameters = json.load(f) # in",
"which did not have 'best_per_ligand' specified. These runs cannot be \" f\"passed into",
"json_path in batch_runs.items(): # check if the current DockStream run has \"best_per_ligand\" enforced",
"json.load(f) # in case output mode was not specified in the configuration json",
"and the corresponding values are the paths to the json file. The dictionary",
"[file for file in os.listdir(input_path) if file.endswith('.json')] for json in all_runs: batch_runs[json.replace('.json', '')]",
"f: parameters = json.load(f) # in case output mode was not specified in",
"non_bpl_runs[trial_name] = output_mode break except: pass print(f'Running {trial_name}') result = executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf',",
"Please ensure your DockStream json files are added to the folder.') elif not",
"for the current DockStream run if result.returncode != 0: print(f'There was an error",
"from dockstream.utils import files_paths from dockstream.utils.enums.docking_enum import DockingConfigurationEnum _DC = DockingConfigurationEnum() def run_script(input_path:",
"parameters to run the benchmarking script parser = argparse.ArgumentParser(description='Facilitates batch DockStream execution.') parser.add_argument('-input_path',",
"enforce \"best_per_ligand\" print(f\"List of runs which did not have 'best_per_ligand' specified. These runs",
"if __name__ == '__main__': # take user specified input parameters to run the",
"!= _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] = output_mode break except: pass print(f'Running {trial_name}') result = executor.execute(command=sys.executable,",
"= {} # loop through all user json files and run DockStream for",
"are the paths to them \"\"\" # first check if input_path is valid",
"dockstream.utils import files_paths from dockstream.utils.enums.docking_enum import DockingConfigurationEnum _DC = DockingConfigurationEnum() def run_script(input_path: str)",
"# check if the current DockStream run has \"best_per_ligand\" enforced with open(json_path, \"r\")",
"in the configuration json try: for docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if",
"file. Check that it is in json format if os.path.isfile(input_path): if not input_path.endswith('.json'):",
"not os.path.isdir(input_path) and not os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path) # if input_path is",
"your DockStream json files are added to the folder.') elif not any(file.endswith('.json') for",
"file.') args = parser.parse_args() batch_runs = run_script(args.input_path) executor = Executor() # initialize a",
"or a single json file.') args = parser.parse_args() batch_runs = run_script(args.input_path) executor =",
"either a folder of json files or a single json file :raises FileNotFoundError:",
"takes an input path to either a folder containing DockStream json files or",
"if input_path is valid (either a folder containing json files or a single",
"' is not a json file. Please ensure it is in json format.')",
"a dictionary to store the names of all runs that did not enforce",
"json format if os.path.isfile(input_path): if not input_path.endswith('.json'): sys.exit(input_path + ' is not a",
"nor a file :return: dictionary, keys are the DockStream json names and values",
"error is raised if input_path is neither a folder nor a file :return:",
"values are the paths to the json file. The dictionary will be looped",
"# loop through all json files and update the paths if input_path if",
"user json files and run DockStream for trial_name, json_path in batch_runs.items(): # check",
"input_path.endswith('.json'): sys.exit(input_path + ' is not a json file. Please ensure it is",
"help='The path to either a folder of DockStream json files or a single",
"to either a folder containing DockStream json files or a single json file",
"folder of json files or a single json file :raises FileNotFoundError: this error",
"run_script(args.input_path) executor = Executor() # initialize a dictionary to store the names of",
"of all runs that did not enforce \"best_per_ligand\" non_bpl_runs = {} # loop",
"if input_path if a directory if os.path.isdir(input_path): all_runs = [file for file in",
"import sys import argparse from dockstream.utils.execute_external.execute import Executor from dockstream.utils import files_paths from",
"= {} # loop through all json files and update the paths if",
"dictionary will be looped later to run DockStream :param input_path: path to either",
"print(result.stdout) print(result.stderr) if bool(non_bpl_runs): # print the names of the runs which did",
"are the paths to the json file. The dictionary will be looped later",
"sys import argparse from dockstream.utils.execute_external.execute import Executor from dockstream.utils import files_paths from dockstream.utils.enums.docking_enum",
"= output_mode break except: pass print(f'Running {trial_name}') result = executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path,",
"if not os.listdir(input_path): sys.exit(input_path + ' folder is empty. Please ensure your DockStream",
"a single json file.') args = parser.parse_args() batch_runs = run_script(args.input_path) executor = Executor()",
"executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path, '-debug'], check=False) print(result) # print out error messages (if",
"args = parser.parse_args() batch_runs = run_script(args.input_path) executor = Executor() # initialize a dictionary",
"files are added to the folder.') elif not any(file.endswith('.json') for file in os.listdir(input_path)):",
"paths to the json file. The dictionary will be looped later to run",
"them \"\"\" # first check if input_path is valid (either a folder containing",
"Executor() # initialize a dictionary to store the names of all runs that",
"input parameters to run the benchmarking script parser = argparse.ArgumentParser(description='Facilitates batch DockStream execution.')",
"added to the folder.') elif not any(file.endswith('.json') for file in os.listdir(input_path)): sys.exit(input_path +",
"was an error with {trial_name} DockStream run.') print(result.stdout) print(result.stderr) if bool(non_bpl_runs): # print",
"of the runs which did not enforce \"best_per_ligand\" print(f\"List of runs which did",
"to store the names of all runs that did not enforce \"best_per_ligand\" non_bpl_runs",
"# at this point, the path must be a file. Check that it",
"os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name] = input_path return batch_runs if __name__ == '__main__': # take",
"import DockingConfigurationEnum _DC = DockingConfigurationEnum() def run_script(input_path: str) -> dict: \"\"\"this method takes",
"runs batch_runs = {} # loop through all json files and update the",
"# in case output mode was not specified in the configuration json try:",
"ensure it is not empty and that it contains at least 1 json",
"and returns a dictionary whose keys are the json names and the corresponding",
"your DockStream json files are added to the folder.') # at this point,",
"run has \"best_per_ligand\" enforced with open(json_path, \"r\") as f: parameters = json.load(f) #",
"be a file. Check that it is in json format if os.path.isfile(input_path): if",
"an input path to either a folder containing DockStream json files or a",
"parser = argparse.ArgumentParser(description='Facilitates batch DockStream execution.') parser.add_argument('-input_path', type=str, required=True, help='The path to either",
"paths if input_path if a directory if os.path.isdir(input_path): all_runs = [file for file",
"files or a single json file :raises FileNotFoundError: this error is raised if",
"point, input path must be a single json file else: json_name = os.path.basename(os.path.normpath(input_path)).replace('.json',",
"dictionary whose keys are the json names and the corresponding values are the",
"in os.listdir(input_path)): sys.exit(input_path + ' contains no json files. Please ensure your DockStream",
"output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] = output_mode break except: pass",
"+ ' is not a json file. Please ensure it is in json",
"file if os.path.isdir(input_path): if not os.listdir(input_path): sys.exit(input_path + ' folder is empty. Please",
"parameters = json.load(f) # in case output mode was not specified in the",
"the paths if input_path if a directory if os.path.isdir(input_path): all_runs = [file for",
"type=str, required=True, help='The path to either a folder of DockStream json files or",
"trial_name, json_path in batch_runs.items(): # check if the current DockStream run has \"best_per_ligand\"",
"in json format if os.path.isfile(input_path): if not input_path.endswith('.json'): sys.exit(input_path + ' is not",
"was not specified in the configuration json try: for docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode",
"return batch_runs if __name__ == '__main__': # take user specified input parameters to",
"DockStream run if result.returncode != 0: print(f'There was an error with {trial_name} DockStream",
"input_path if a directory if os.path.isdir(input_path): all_runs = [file for file in os.listdir(input_path)",
"'') batch_runs[json_name] = input_path return batch_runs if __name__ == '__main__': # take user",
"the json names and the corresponding values are the paths to the json",
"import json import errno import sys import argparse from dockstream.utils.execute_external.execute import Executor from",
"dictionary to store the names of all runs that did not enforce \"best_per_ligand\"",
"'best_per_ligand' specified. These runs cannot be \" f\"passed into the analysis script. {non_bpl_runs}\")",
"will be looped later to run DockStream :param input_path: path to either a",
"dictionary, keys are the DockStream json names and values are the paths to",
"os.listdir(input_path)): sys.exit(input_path + ' contains no json files. Please ensure your DockStream json",
"empty and that it contains at least 1 json file if os.path.isdir(input_path): if",
"later to run DockStream :param input_path: path to either a folder of json",
"json try: for docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND:",
"= docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] = output_mode break except: pass print(f'Running",
"names and the corresponding values are the paths to the json file. The",
"containing DockStream json files or a single json file and returns a dictionary",
"' contains no json files. Please ensure your DockStream json files are added",
"either a folder containing DockStream json files or a single json file and",
"runs that did not enforce \"best_per_ligand\" non_bpl_runs = {} # loop through all",
"import argparse from dockstream.utils.execute_external.execute import Executor from dockstream.utils import files_paths from dockstream.utils.enums.docking_enum import",
"= executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path, '-debug'], check=False) print(result) # print out error messages",
"to the json file. The dictionary will be looped later to run DockStream",
"in os.listdir(input_path) if file.endswith('.json')] for json in all_runs: batch_runs[json.replace('.json', '')] = os.path.join(input_path, json)",
"DockStream run.') print(result.stdout) print(result.stderr) if bool(non_bpl_runs): # print the names of the runs",
"method takes an input path to either a folder containing DockStream json files",
"single json file.') args = parser.parse_args() batch_runs = run_script(args.input_path) executor = Executor() #",
"DockStream run has \"best_per_ligand\" enforced with open(json_path, \"r\") as f: parameters = json.load(f)",
"FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path) # if input_path is a folder, ensure it is not",
"not a json file. Please ensure it is in json format.') # initialize",
"it is in json format.') # initialize a dictionary to hold all DockStream",
"case output mode was not specified in the configuration json try: for docking_run",
"format.') # initialize a dictionary to hold all DockStream runs batch_runs = {}",
"initialize a dictionary to hold all DockStream runs batch_runs = {} # loop",
"to hold all DockStream runs batch_runs = {} # loop through all json",
"in json format.') # initialize a dictionary to hold all DockStream runs batch_runs",
"for trial_name, json_path in batch_runs.items(): # check if the current DockStream run has",
"file. The dictionary will be looped later to run DockStream :param input_path: path",
"FileNotFoundError: this error is raised if input_path is neither a folder nor a",
"all json files and update the paths if input_path if a directory if",
"raised if input_path is neither a folder nor a file :return: dictionary, keys",
"the folder.') elif not any(file.endswith('.json') for file in os.listdir(input_path)): sys.exit(input_path + ' contains",
"if input_path is a folder, ensure it is not empty and that it",
"if os.path.isfile(input_path): if not input_path.endswith('.json'): sys.exit(input_path + ' is not a json file.",
"= os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name] = input_path return batch_runs if __name__ == '__main__': #",
"is raised if input_path is neither a folder nor a file :return: dictionary,",
"if bool(non_bpl_runs): # print the names of the runs which did not enforce",
"runs which did not have 'best_per_ligand' specified. These runs cannot be \" f\"passed",
"DockStream json names and values are the paths to them \"\"\" # first",
"!= 0: print(f'There was an error with {trial_name} DockStream run.') print(result.stdout) print(result.stderr) if",
"user specified input parameters to run the benchmarking script parser = argparse.ArgumentParser(description='Facilitates batch",
"arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path, '-debug'], check=False) print(result) # print out error messages (if applicable)",
"any(file.endswith('.json') for file in os.listdir(input_path)): sys.exit(input_path + ' contains no json files. Please",
"batch_runs.items(): # check if the current DockStream run has \"best_per_ligand\" enforced with open(json_path,",
"names and values are the paths to them \"\"\" # first check if",
"have 'best_per_ligand' specified. These runs cannot be \" f\"passed into the analysis script.",
"{trial_name}') result = executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path, '-debug'], check=False) print(result) # print out",
"# initialize a dictionary to hold all DockStream runs batch_runs = {} #",
"batch_runs = {} # loop through all json files and update the paths",
"print out error messages (if applicable) for the current DockStream run if result.returncode",
"dict: \"\"\"this method takes an input path to either a folder containing DockStream",
"not empty and that it contains at least 1 json file if os.path.isdir(input_path):",
"\"best_per_ligand\" enforced with open(json_path, \"r\") as f: parameters = json.load(f) # in case",
"a folder containing json files or a single json file) if not os.path.isdir(input_path)",
"DockStream :param input_path: path to either a folder of json files or a",
"for docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] =",
"all DockStream runs batch_runs = {} # loop through all json files and",
"DockingConfigurationEnum _DC = DockingConfigurationEnum() def run_script(input_path: str) -> dict: \"\"\"this method takes an",
"if not input_path.endswith('.json'): sys.exit(input_path + ' is not a json file. Please ensure",
"or a single json file :raises FileNotFoundError: this error is raised if input_path",
"keys are the DockStream json names and values are the paths to them",
"if os.path.isdir(input_path): all_runs = [file for file in os.listdir(input_path) if file.endswith('.json')] for json",
"not os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path) # if input_path is a folder, ensure",
"the folder.') # at this point, the path must be a file. Check",
"{} # loop through all json files and update the paths if input_path",
"DockStream json files are added to the folder.') # at this point, the",
"# take user specified input parameters to run the benchmarking script parser =",
"a json file. Please ensure it is in json format.') # initialize a",
"docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] = output_mode",
"open(json_path, \"r\") as f: parameters = json.load(f) # in case output mode was",
"__name__ == '__main__': # take user specified input parameters to run the benchmarking",
"point, the path must be a file. Check that it is in json",
"added to the folder.') # at this point, the path must be a",
"file else: json_name = os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name] = input_path return batch_runs if __name__",
"print(f'Running {trial_name}') result = executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path, '-debug'], check=False) print(result) # print",
"and run DockStream for trial_name, json_path in batch_runs.items(): # check if the current",
"configuration json try: for docking_run in parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode !=",
"sys.exit(input_path + ' contains no json files. Please ensure your DockStream json files",
"sys.exit(input_path + ' is not a json file. Please ensure it is in",
"DockingConfigurationEnum() def run_script(input_path: str) -> dict: \"\"\"this method takes an input path to",
"not have 'best_per_ligand' specified. These runs cannot be \" f\"passed into the analysis",
"which did not enforce \"best_per_ligand\" print(f\"List of runs which did not have 'best_per_ligand'",
"input_path return batch_runs if __name__ == '__main__': # take user specified input parameters",
"dockstream.utils.enums.docking_enum import DockingConfigurationEnum _DC = DockingConfigurationEnum() def run_script(input_path: str) -> dict: \"\"\"this method",
"for file in os.listdir(input_path) if file.endswith('.json')] for json in all_runs: batch_runs[json.replace('.json', '')] =",
"enforced with open(json_path, \"r\") as f: parameters = json.load(f) # in case output",
"\"\"\" # first check if input_path is valid (either a folder containing json",
"str) -> dict: \"\"\"this method takes an input path to either a folder",
"current DockStream run if result.returncode != 0: print(f'There was an error with {trial_name}",
"'__main__': # take user specified input parameters to run the benchmarking script parser",
"is valid (either a folder containing json files or a single json file)",
"parameters[_DC.DOCKING][_DC.DOCKING_RUNS]: output_mode = docking_run[_DC.OUTPUT][_DC.OUTPUT_SCORES][_DC.OUTPUT_MODE] if output_mode != _DC.OUTPUT_MODE_BESTPERLIGAND: non_bpl_runs[trial_name] = output_mode break except:",
"print(f\"List of runs which did not have 'best_per_ligand' specified. These runs cannot be",
"os.strerror(errno.ENOENT), input_path) # if input_path is a folder, ensure it is not empty",
"input_path) # if input_path is a folder, ensure it is not empty and",
"\"best_per_ligand\" non_bpl_runs = {} # loop through all user json files and run",
"file. Please ensure it is in json format.') # initialize a dictionary to",
"files_paths from dockstream.utils.enums.docking_enum import DockingConfigurationEnum _DC = DockingConfigurationEnum() def run_script(input_path: str) -> dict:",
"required=True, help='The path to either a folder of DockStream json files or a",
"it is in json format if os.path.isfile(input_path): if not input_path.endswith('.json'): sys.exit(input_path + '",
"a single json file else: json_name = os.path.basename(os.path.normpath(input_path)).replace('.json', '') batch_runs[json_name] = input_path return",
"run the benchmarking script parser = argparse.ArgumentParser(description='Facilitates batch DockStream execution.') parser.add_argument('-input_path', type=str, required=True,",
"the benchmarking script parser = argparse.ArgumentParser(description='Facilitates batch DockStream execution.') parser.add_argument('-input_path', type=str, required=True, help='The",
"= run_script(args.input_path) executor = Executor() # initialize a dictionary to store the names",
"file) if not os.path.isdir(input_path) and not os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path) # if",
"in case output mode was not specified in the configuration json try: for",
"names of all runs that did not enforce \"best_per_ligand\" non_bpl_runs = {} #",
"the runs which did not enforce \"best_per_ligand\" print(f\"List of runs which did not",
"and not os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path) # if input_path is a folder,",
"check if input_path is valid (either a folder containing json files or a",
"json file if os.path.isdir(input_path): if not os.listdir(input_path): sys.exit(input_path + ' folder is empty.",
"+ ' folder is empty. Please ensure your DockStream json files are added",
"paths to them \"\"\" # first check if input_path is valid (either a",
"pass print(f'Running {trial_name}') result = executor.execute(command=sys.executable, arguments=[files_paths.attach_root_path('docker.py'), '-conf', json_path, '-debug'], check=False) print(result) #",
"folder.') elif not any(file.endswith('.json') for file in os.listdir(input_path)): sys.exit(input_path + ' contains no",
"for json in all_runs: batch_runs[json.replace('.json', '')] = os.path.join(input_path, json) # at this point,",
"returns a dictionary whose keys are the json names and the corresponding values",
"folder, ensure it is not empty and that it contains at least 1",
"_DC = DockingConfigurationEnum() def run_script(input_path: str) -> dict: \"\"\"this method takes an input",
"json files are added to the folder.') elif not any(file.endswith('.json') for file in",
"file in os.listdir(input_path) if file.endswith('.json')] for json in all_runs: batch_runs[json.replace('.json', '')] = os.path.join(input_path,",
"if not os.path.isdir(input_path) and not os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path) # if input_path",
"it is not empty and that it contains at least 1 json file",
"is neither a folder nor a file :return: dictionary, keys are the DockStream",
"# if input_path is a folder, ensure it is not empty and that",
"error messages (if applicable) for the current DockStream run if result.returncode != 0:",
"a folder of DockStream json files or a single json file.') args =",
"files. Please ensure your DockStream json files are added to the folder.') #",
"single json file :raises FileNotFoundError: this error is raised if input_path is neither",
"valid (either a folder containing json files or a single json file) if",
"single json file) if not os.path.isdir(input_path) and not os.path.isfile(input_path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_path)",
"run DockStream for trial_name, json_path in batch_runs.items(): # check if the current DockStream",
"not enforce \"best_per_ligand\" non_bpl_runs = {} # loop through all user json files",
"to them \"\"\" # first check if input_path is valid (either a folder",
"all runs that did not enforce \"best_per_ligand\" non_bpl_runs = {} # loop through",
"bool(non_bpl_runs): # print the names of the runs which did not enforce \"best_per_ligand\"",
"0: print(f'There was an error with {trial_name} DockStream run.') print(result.stdout) print(result.stderr) if bool(non_bpl_runs):"
] |
[
"def test_legal_names(self): products = generate_products() for product in products: first = product.name.split()[0] last",
"= product.name.split()[0] last = product.name.split()[1] self.assertIn(first, ADJECTIVES) self.assertIn(last, NOUNS) if __name__ == '__main__':",
"default product weight being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.weight, 20) def test_methods(self):",
"custom product with changes to defaults ''' self.custom_product = Product('Test Product', price=20, weight=40,",
"def test_default_num_products(self): self.assertEqual(len(generate_products()), 30) def test_legal_names(self): products = generate_products() for product in products:",
"glove.\") class AcmeReportTests(unittest.TestCase): '''Two tests: test_default_num_products() checks if product list received is 30",
"products: first = product.name.split()[0] last = product.name.split()[1] self.assertIn(first, ADJECTIVES) self.assertIn(last, NOUNS) if __name__",
"''' self.custom_product = Product('Test Product', price=20, weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not so stealable...') self.assertEqual(self.custom_product.explode(),",
"with changes to defaults ''' self.custom_product = Product('Test Product', price=20, weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(),",
"price being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): \"\"\"Test default",
"are the tops!\"\"\" def test_default_product_price(self): \"\"\"Test default product price being 10.\"\"\" prod =",
"default product price being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self):",
"test_default_product_weight(self): \"\"\"Test default product weight being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.weight, 20)",
"\"...it's a glove.\") class AcmeReportTests(unittest.TestCase): '''Two tests: test_default_num_products() checks if product list received",
"\"\"\"Test default product price being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.price, 10) def",
"defaults ''' self.custom_product = Product('Test Product', price=20, weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not so stealable...')",
"from acme import Product from acme_report import generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): \"\"\"Making",
"class AcmeProductTests(unittest.TestCase): \"\"\"Making sure Acme products are the tops!\"\"\" def test_default_product_price(self): \"\"\"Test default",
"tops!\"\"\" def test_default_product_price(self): \"\"\"Test default product price being 10.\"\"\" prod = Product('Test Product')",
"price=20, weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not so stealable...') self.assertEqual(self.custom_product.explode(), \"...it's a glove.\") class AcmeReportTests(unittest.TestCase):",
"= generate_products() for product in products: first = product.name.split()[0] last = product.name.split()[1] self.assertIn(first,",
"AcmeReportTests(unittest.TestCase): '''Two tests: test_default_num_products() checks if product list received is 30 test_legal_names() checks",
"Acme products are the tops!\"\"\" def test_default_product_price(self): \"\"\"Test default product price being 10.\"\"\"",
"from ADJECTIVE and NOUN lists ''' def test_default_num_products(self): self.assertEqual(len(generate_products()), 30) def test_legal_names(self): products",
"weight being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.weight, 20) def test_methods(self): '''Test custom",
"ADJECTIVE and NOUN lists ''' def test_default_num_products(self): self.assertEqual(len(generate_products()), 30) def test_legal_names(self): products =",
"a glove.\") class AcmeReportTests(unittest.TestCase): '''Two tests: test_default_num_products() checks if product list received is",
"\"\"\"Test default product weight being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.weight, 20) def",
"Product from acme_report import generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): \"\"\"Making sure Acme products",
"def test_default_product_price(self): \"\"\"Test default product price being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.price,",
"product weight being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.weight, 20) def test_methods(self): '''Test",
"lists ''' def test_default_num_products(self): self.assertEqual(len(generate_products()), 30) def test_legal_names(self): products = generate_products() for product",
"generate_products() for product in products: first = product.name.split()[0] last = product.name.split()[1] self.assertIn(first, ADJECTIVES)",
"product list received is 30 test_legal_names() checks if names generated are valid from",
"Product('Test Product') self.assertEqual(prod.weight, 20) def test_methods(self): '''Test custom product with changes to defaults",
"acme_report import generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): \"\"\"Making sure Acme products are the",
"being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): \"\"\"Test default product",
"= Product('Test Product') self.assertEqual(prod.weight, 20) def test_methods(self): '''Test custom product with changes to",
"so stealable...') self.assertEqual(self.custom_product.explode(), \"...it's a glove.\") class AcmeReportTests(unittest.TestCase): '''Two tests: test_default_num_products() checks if",
"10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): \"\"\"Test default product weight",
"weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not so stealable...') self.assertEqual(self.custom_product.explode(), \"...it's a glove.\") class AcmeReportTests(unittest.TestCase): '''Two",
"for product in products: first = product.name.split()[0] last = product.name.split()[1] self.assertIn(first, ADJECTIVES) self.assertIn(last,",
"Product') self.assertEqual(prod.weight, 20) def test_methods(self): '''Test custom product with changes to defaults '''",
"10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.weight, 20) def test_methods(self): '''Test custom product with",
"AcmeProductTests(unittest.TestCase): \"\"\"Making sure Acme products are the tops!\"\"\" def test_default_product_price(self): \"\"\"Test default product",
"prod = Product('Test Product') self.assertEqual(prod.weight, 20) def test_methods(self): '''Test custom product with changes",
"stealable...') self.assertEqual(self.custom_product.explode(), \"...it's a glove.\") class AcmeReportTests(unittest.TestCase): '''Two tests: test_default_num_products() checks if product",
"self.assertEqual(prod.price, 10) def test_default_product_weight(self): \"\"\"Test default product weight being 10.\"\"\" prod = Product('Test",
"received is 30 test_legal_names() checks if names generated are valid from ADJECTIVE and",
"generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): \"\"\"Making sure Acme products are the tops!\"\"\" def",
"names generated are valid from ADJECTIVE and NOUN lists ''' def test_default_num_products(self): self.assertEqual(len(generate_products()),",
"sure Acme products are the tops!\"\"\" def test_default_product_price(self): \"\"\"Test default product price being",
"flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not so stealable...') self.assertEqual(self.custom_product.explode(), \"...it's a glove.\") class AcmeReportTests(unittest.TestCase): '''Two tests:",
"being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.weight, 20) def test_methods(self): '''Test custom product",
"unittest from acme import Product from acme_report import generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase):",
"test_legal_names(self): products = generate_products() for product in products: first = product.name.split()[0] last =",
"if product list received is 30 test_legal_names() checks if names generated are valid",
"products are the tops!\"\"\" def test_default_product_price(self): \"\"\"Test default product price being 10.\"\"\" prod",
"'Not so stealable...') self.assertEqual(self.custom_product.explode(), \"...it's a glove.\") class AcmeReportTests(unittest.TestCase): '''Two tests: test_default_num_products() checks",
"list received is 30 test_legal_names() checks if names generated are valid from ADJECTIVE",
"test_default_product_price(self): \"\"\"Test default product price being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.price, 10)",
"from acme_report import generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): \"\"\"Making sure Acme products are",
"self.assertEqual(self.custom_product.explode(), \"...it's a glove.\") class AcmeReportTests(unittest.TestCase): '''Two tests: test_default_num_products() checks if product list",
"tests: test_default_num_products() checks if product list received is 30 test_legal_names() checks if names",
"are valid from ADJECTIVE and NOUN lists ''' def test_default_num_products(self): self.assertEqual(len(generate_products()), 30) def",
"= Product('Test Product', price=20, weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not so stealable...') self.assertEqual(self.custom_product.explode(), \"...it's a",
"products = generate_products() for product in products: first = product.name.split()[0] last = product.name.split()[1]",
"checks if names generated are valid from ADJECTIVE and NOUN lists ''' def",
"'''Test custom product with changes to defaults ''' self.custom_product = Product('Test Product', price=20,",
"20) def test_methods(self): '''Test custom product with changes to defaults ''' self.custom_product =",
"'''Two tests: test_default_num_products() checks if product list received is 30 test_legal_names() checks if",
"the tops!\"\"\" def test_default_product_price(self): \"\"\"Test default product price being 10.\"\"\" prod = Product('Test",
"Product('Test Product', price=20, weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not so stealable...') self.assertEqual(self.custom_product.explode(), \"...it's a glove.\")",
"product price being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): \"\"\"Test",
"product.name.split()[0] last = product.name.split()[1] self.assertIn(first, ADJECTIVES) self.assertIn(last, NOUNS) if __name__ == '__main__': unittest.main()",
"test_legal_names() checks if names generated are valid from ADJECTIVE and NOUN lists '''",
"Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): \"\"\"Test default product weight being 10.\"\"\" prod",
"def test_default_product_weight(self): \"\"\"Test default product weight being 10.\"\"\" prod = Product('Test Product') self.assertEqual(prod.weight,",
"NOUN lists ''' def test_default_num_products(self): self.assertEqual(len(generate_products()), 30) def test_legal_names(self): products = generate_products() for",
"test_methods(self): '''Test custom product with changes to defaults ''' self.custom_product = Product('Test Product',",
"import unittest from acme import Product from acme_report import generate_products, ADJECTIVES, NOUNS class",
"10) def test_default_product_weight(self): \"\"\"Test default product weight being 10.\"\"\" prod = Product('Test Product')",
"valid from ADJECTIVE and NOUN lists ''' def test_default_num_products(self): self.assertEqual(len(generate_products()), 30) def test_legal_names(self):",
"prod = Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): \"\"\"Test default product weight being",
"self.assertEqual(len(generate_products()), 30) def test_legal_names(self): products = generate_products() for product in products: first =",
"in products: first = product.name.split()[0] last = product.name.split()[1] self.assertIn(first, ADJECTIVES) self.assertIn(last, NOUNS) if",
"self.custom_product = Product('Test Product', price=20, weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not so stealable...') self.assertEqual(self.custom_product.explode(), \"...it's",
"NOUNS class AcmeProductTests(unittest.TestCase): \"\"\"Making sure Acme products are the tops!\"\"\" def test_default_product_price(self): \"\"\"Test",
"if names generated are valid from ADJECTIVE and NOUN lists ''' def test_default_num_products(self):",
"first = product.name.split()[0] last = product.name.split()[1] self.assertIn(first, ADJECTIVES) self.assertIn(last, NOUNS) if __name__ ==",
"''' def test_default_num_products(self): self.assertEqual(len(generate_products()), 30) def test_legal_names(self): products = generate_products() for product in",
"test_default_num_products(self): self.assertEqual(len(generate_products()), 30) def test_legal_names(self): products = generate_products() for product in products: first",
"\"\"\"Making sure Acme products are the tops!\"\"\" def test_default_product_price(self): \"\"\"Test default product price",
"and NOUN lists ''' def test_default_num_products(self): self.assertEqual(len(generate_products()), 30) def test_legal_names(self): products = generate_products()",
"self.assertEqual(prod.weight, 20) def test_methods(self): '''Test custom product with changes to defaults ''' self.custom_product",
"to defaults ''' self.custom_product = Product('Test Product', price=20, weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not so",
"generated are valid from ADJECTIVE and NOUN lists ''' def test_default_num_products(self): self.assertEqual(len(generate_products()), 30)",
"import generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): \"\"\"Making sure Acme products are the tops!\"\"\"",
"class AcmeReportTests(unittest.TestCase): '''Two tests: test_default_num_products() checks if product list received is 30 test_legal_names()",
"def test_methods(self): '''Test custom product with changes to defaults ''' self.custom_product = Product('Test",
"is 30 test_legal_names() checks if names generated are valid from ADJECTIVE and NOUN",
"30) def test_legal_names(self): products = generate_products() for product in products: first = product.name.split()[0]",
"ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): \"\"\"Making sure Acme products are the tops!\"\"\" def test_default_product_price(self):",
"<reponame>elliotgunn/DS-Unit-3-Sprint-1-Software-Engineering<filename>sc/acme_test.py import unittest from acme import Product from acme_report import generate_products, ADJECTIVES, NOUNS",
"acme import Product from acme_report import generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): \"\"\"Making sure",
"product with changes to defaults ''' self.custom_product = Product('Test Product', price=20, weight=40, flammability=0.5)",
"Product', price=20, weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not so stealable...') self.assertEqual(self.custom_product.explode(), \"...it's a glove.\") class",
"30 test_legal_names() checks if names generated are valid from ADJECTIVE and NOUN lists",
"test_default_num_products() checks if product list received is 30 test_legal_names() checks if names generated",
"import Product from acme_report import generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): \"\"\"Making sure Acme",
"self.assertEqual(self.custom_product.stealability(), 'Not so stealable...') self.assertEqual(self.custom_product.explode(), \"...it's a glove.\") class AcmeReportTests(unittest.TestCase): '''Two tests: test_default_num_products()",
"product in products: first = product.name.split()[0] last = product.name.split()[1] self.assertIn(first, ADJECTIVES) self.assertIn(last, NOUNS)",
"changes to defaults ''' self.custom_product = Product('Test Product', price=20, weight=40, flammability=0.5) self.assertEqual(self.custom_product.stealability(), 'Not",
"= Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): \"\"\"Test default product weight being 10.\"\"\"",
"Product') self.assertEqual(prod.price, 10) def test_default_product_weight(self): \"\"\"Test default product weight being 10.\"\"\" prod =",
"checks if product list received is 30 test_legal_names() checks if names generated are"
] |
[
"from .Flow import get_flow_parameter, flow, Flow, save_parameters, load_parameters from .HelperTasks import Add, Sub,",
"- Simple Orchestration Framework # from .Task import Task, task from .Flow import",
"get_flow_parameter, flow, Flow, save_parameters, load_parameters from .HelperTasks import Add, Sub, Multiplication from .Parameter",
"XYZFlow - Simple Orchestration Framework # from .Task import Task, task from .Flow",
"load_parameters from .HelperTasks import Add, Sub, Multiplication from .Parameter import Parameter from .xyzflow",
"# # XYZFlow - Simple Orchestration Framework # from .Task import Task, task",
"import get_flow_parameter, flow, Flow, save_parameters, load_parameters from .HelperTasks import Add, Sub, Multiplication from",
".Task import Task, task from .Flow import get_flow_parameter, flow, Flow, save_parameters, load_parameters from",
".HelperTasks import Add, Sub, Multiplication from .Parameter import Parameter from .xyzflow import inspect_parameters,",
"from .Task import Task, task from .Flow import get_flow_parameter, flow, Flow, save_parameters, load_parameters",
".Flow import get_flow_parameter, flow, Flow, save_parameters, load_parameters from .HelperTasks import Add, Sub, Multiplication",
"Task, task from .Flow import get_flow_parameter, flow, Flow, save_parameters, load_parameters from .HelperTasks import",
"Framework # from .Task import Task, task from .Flow import get_flow_parameter, flow, Flow,",
"from .HelperTasks import Add, Sub, Multiplication from .Parameter import Parameter from .xyzflow import",
"Simple Orchestration Framework # from .Task import Task, task from .Flow import get_flow_parameter,",
"# XYZFlow - Simple Orchestration Framework # from .Task import Task, task from",
"flow, Flow, save_parameters, load_parameters from .HelperTasks import Add, Sub, Multiplication from .Parameter import",
"Orchestration Framework # from .Task import Task, task from .Flow import get_flow_parameter, flow,",
"save_parameters, load_parameters from .HelperTasks import Add, Sub, Multiplication from .Parameter import Parameter from",
"import Add, Sub, Multiplication from .Parameter import Parameter from .xyzflow import inspect_parameters, main",
"Flow, save_parameters, load_parameters from .HelperTasks import Add, Sub, Multiplication from .Parameter import Parameter",
"import Task, task from .Flow import get_flow_parameter, flow, Flow, save_parameters, load_parameters from .HelperTasks",
"task from .Flow import get_flow_parameter, flow, Flow, save_parameters, load_parameters from .HelperTasks import Add,",
"# from .Task import Task, task from .Flow import get_flow_parameter, flow, Flow, save_parameters,"
] |
[
"& <NAME>\" __version__ = \"1.0.0\" __start_date__ = \"25th July 2020\" __end_date__ = \"3rd",
"self.output_file_path = output_file_path self.video_key = video_key self.kid = kid self.packaged_content_id = packaged_content_id self.url",
"output_file_path self.video_key = video_key self.kid = kid self.packaged_content_id = packaged_content_id self.url = url",
"sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import * from test_database import metadata, db_session class",
"Integer, primary_key=True, autoincrement=True, unique=True), Column('input_content_origin', String(255), ), Column('video_track_number', Integer), Column('status', String(255)), Column('output_file_path', String(255)),",
"\"SQL-Alchemy, MySQL, Flask-SQLAlchemy, database script\" __status__ = \"Production\" __description__ = \"\"\" This is",
"= db_session.query_property() def __init__(self, input_content_id=None, input_content_origin=None, video_track_number=None, status=None, output_file_path=None, video_key=None, kid=None, packaged_content_id=None, url=None):",
"__maintainer__ = \"me\" __email__ = \"<EMAIL>\" __requirements__ = \"SQL-Alchemy, MySQL, Flask-SQLAlchemy, database script\"",
"with our model for this App \"\"\" from sqlalchemy import * from sqlalchemy.ext.declarative",
"July 2020\" __end_date__ = \"3rd August 2020\" __maintainer__ = \"me\" __email__ = \"<EMAIL>\"",
"return '<VideosDB %r>' % (self.input_content_id) test_uploaded_videos = Table('test_uploaded_videos', metadata, Column('input_content_id', Integer, primary_key=True, autoincrement=True,",
"Column('input_content_id', Integer, primary_key=True, autoincrement=True, unique=True), Column('input_content_origin', String(255), ), Column('video_track_number', Integer), Column('status', String(255)), Column('output_file_path',",
"import declarative_base from sqlalchemy.orm import * from test_database import metadata, db_session class test_VideosDB(object):",
"video_track_number self.status = status self.output_file_path = output_file_path self.video_key = video_key self.kid = kid",
"status=None, output_file_path=None, video_key=None, kid=None, packaged_content_id=None, url=None): self.input_content_id = input_content_id self.input_content_origin = input_content_origin self.video_track_number",
"\"<EMAIL>\" __requirements__ = \"SQL-Alchemy, MySQL, Flask-SQLAlchemy, database script\" __status__ = \"Production\" __description__ =",
"* from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import * from test_database import metadata,",
"this App \"\"\" from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm",
"2020\" __maintainer__ = \"me\" __email__ = \"<EMAIL>\" __requirements__ = \"SQL-Alchemy, MySQL, Flask-SQLAlchemy, database",
"This is the Database models script. Very important as it will connect the",
"= \"<NAME> & <NAME>\" __version__ = \"1.0.0\" __start_date__ = \"25th July 2020\" __end_date__",
"= \"<EMAIL>\" __requirements__ = \"SQL-Alchemy, MySQL, Flask-SQLAlchemy, database script\" __status__ = \"Production\" __description__",
"test_database import metadata, db_session class test_VideosDB(object): query = db_session.query_property() def __init__(self, input_content_id=None, input_content_origin=None,",
"sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import * from test_database",
"input_content_origin self.video_track_number = video_track_number self.status = status self.output_file_path = output_file_path self.video_key = video_key",
"the database and map it with our model for this App \"\"\" from",
"primary_key=True, autoincrement=True, unique=True), Column('input_content_origin', String(255), ), Column('video_track_number', Integer), Column('status', String(255)), Column('output_file_path', String(255)), Column('video_key',",
"__description__ = \"\"\" This is the Database models script. Very important as it",
"packaged_content_id self.url = url def __repr__(self): return '<VideosDB %r>' % (self.input_content_id) test_uploaded_videos =",
"Table('test_uploaded_videos', metadata, Column('input_content_id', Integer, primary_key=True, autoincrement=True, unique=True), Column('input_content_origin', String(255), ), Column('video_track_number', Integer), Column('status',",
"will connect the database and map it with our model for this App",
"self.input_content_id = input_content_id self.input_content_origin = input_content_origin self.video_track_number = video_track_number self.status = status self.output_file_path",
"__start_date__ = \"25th July 2020\" __end_date__ = \"3rd August 2020\" __maintainer__ = \"me\"",
"from test_database import metadata, db_session class test_VideosDB(object): query = db_session.query_property() def __init__(self, input_content_id=None,",
"output_file_path=None, video_key=None, kid=None, packaged_content_id=None, url=None): self.input_content_id = input_content_id self.input_content_origin = input_content_origin self.video_track_number =",
"= url def __repr__(self): return '<VideosDB %r>' % (self.input_content_id) test_uploaded_videos = Table('test_uploaded_videos', metadata,",
"our model for this App \"\"\" from sqlalchemy import * from sqlalchemy.ext.declarative import",
"August 2020\" __maintainer__ = \"me\" __email__ = \"<EMAIL>\" __requirements__ = \"SQL-Alchemy, MySQL, Flask-SQLAlchemy,",
"\"me\" __email__ = \"<EMAIL>\" __requirements__ = \"SQL-Alchemy, MySQL, Flask-SQLAlchemy, database script\" __status__ =",
"<gh_stars>1-10 __author__ = \"<NAME> & <NAME>\" __version__ = \"1.0.0\" __start_date__ = \"25th July",
"it will connect the database and map it with our model for this",
"'<VideosDB %r>' % (self.input_content_id) test_uploaded_videos = Table('test_uploaded_videos', metadata, Column('input_content_id', Integer, primary_key=True, autoincrement=True, unique=True),",
"\"\"\" from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import *",
"= \"Production\" __description__ = \"\"\" This is the Database models script. Very important",
"\"<NAME> & <NAME>\" __version__ = \"1.0.0\" __start_date__ = \"25th July 2020\" __end_date__ =",
"\"\"\" This is the Database models script. Very important as it will connect",
"__init__(self, input_content_id=None, input_content_origin=None, video_track_number=None, status=None, output_file_path=None, video_key=None, kid=None, packaged_content_id=None, url=None): self.input_content_id = input_content_id",
"__author__ = \"<NAME> & <NAME>\" __version__ = \"1.0.0\" __start_date__ = \"25th July 2020\"",
"* from test_database import metadata, db_session class test_VideosDB(object): query = db_session.query_property() def __init__(self,",
"(self.input_content_id) test_uploaded_videos = Table('test_uploaded_videos', metadata, Column('input_content_id', Integer, primary_key=True, autoincrement=True, unique=True), Column('input_content_origin', String(255), ),",
"database and map it with our model for this App \"\"\" from sqlalchemy",
"metadata, db_session class test_VideosDB(object): query = db_session.query_property() def __init__(self, input_content_id=None, input_content_origin=None, video_track_number=None, status=None,",
"query = db_session.query_property() def __init__(self, input_content_id=None, input_content_origin=None, video_track_number=None, status=None, output_file_path=None, video_key=None, kid=None, packaged_content_id=None,",
"String(255)), Column('video_key', String(255)), Column('kid', String(255)), Column('packaged_content_id', Integer, unique=True), Column('url', String(255)) ) mapper(test_VideosDB, test_uploaded_videos)",
"declarative_base from sqlalchemy.orm import * from test_database import metadata, db_session class test_VideosDB(object): query",
"video_key=None, kid=None, packaged_content_id=None, url=None): self.input_content_id = input_content_id self.input_content_origin = input_content_origin self.video_track_number = video_track_number",
"= kid self.packaged_content_id = packaged_content_id self.url = url def __repr__(self): return '<VideosDB %r>'",
"connect the database and map it with our model for this App \"\"\"",
"self.url = url def __repr__(self): return '<VideosDB %r>' % (self.input_content_id) test_uploaded_videos = Table('test_uploaded_videos',",
"Column('video_track_number', Integer), Column('status', String(255)), Column('output_file_path', String(255)), Column('video_key', String(255)), Column('kid', String(255)), Column('packaged_content_id', Integer, unique=True),",
"packaged_content_id=None, url=None): self.input_content_id = input_content_id self.input_content_origin = input_content_origin self.video_track_number = video_track_number self.status =",
"__email__ = \"<EMAIL>\" __requirements__ = \"SQL-Alchemy, MySQL, Flask-SQLAlchemy, database script\" __status__ = \"Production\"",
"= \"1.0.0\" __start_date__ = \"25th July 2020\" __end_date__ = \"3rd August 2020\" __maintainer__",
"= \"3rd August 2020\" __maintainer__ = \"me\" __email__ = \"<EMAIL>\" __requirements__ = \"SQL-Alchemy,",
"input_content_id=None, input_content_origin=None, video_track_number=None, status=None, output_file_path=None, video_key=None, kid=None, packaged_content_id=None, url=None): self.input_content_id = input_content_id self.input_content_origin",
"url=None): self.input_content_id = input_content_id self.input_content_origin = input_content_origin self.video_track_number = video_track_number self.status = status",
"import * from test_database import metadata, db_session class test_VideosDB(object): query = db_session.query_property() def",
"kid self.packaged_content_id = packaged_content_id self.url = url def __repr__(self): return '<VideosDB %r>' %",
"= video_key self.kid = kid self.packaged_content_id = packaged_content_id self.url = url def __repr__(self):",
"db_session.query_property() def __init__(self, input_content_id=None, input_content_origin=None, video_track_number=None, status=None, output_file_path=None, video_key=None, kid=None, packaged_content_id=None, url=None): self.input_content_id",
"it with our model for this App \"\"\" from sqlalchemy import * from",
"kid=None, packaged_content_id=None, url=None): self.input_content_id = input_content_id self.input_content_origin = input_content_origin self.video_track_number = video_track_number self.status",
"String(255), ), Column('video_track_number', Integer), Column('status', String(255)), Column('output_file_path', String(255)), Column('video_key', String(255)), Column('kid', String(255)), Column('packaged_content_id',",
"\"1.0.0\" __start_date__ = \"25th July 2020\" __end_date__ = \"3rd August 2020\" __maintainer__ =",
"Database models script. Very important as it will connect the database and map",
"<NAME>\" __version__ = \"1.0.0\" __start_date__ = \"25th July 2020\" __end_date__ = \"3rd August",
"input_content_origin=None, video_track_number=None, status=None, output_file_path=None, video_key=None, kid=None, packaged_content_id=None, url=None): self.input_content_id = input_content_id self.input_content_origin =",
"self.video_key = video_key self.kid = kid self.packaged_content_id = packaged_content_id self.url = url def",
"__version__ = \"1.0.0\" __start_date__ = \"25th July 2020\" __end_date__ = \"3rd August 2020\"",
"String(255)), Column('output_file_path', String(255)), Column('video_key', String(255)), Column('kid', String(255)), Column('packaged_content_id', Integer, unique=True), Column('url', String(255)) )",
"= packaged_content_id self.url = url def __repr__(self): return '<VideosDB %r>' % (self.input_content_id) test_uploaded_videos",
"% (self.input_content_id) test_uploaded_videos = Table('test_uploaded_videos', metadata, Column('input_content_id', Integer, primary_key=True, autoincrement=True, unique=True), Column('input_content_origin', String(255),",
"Column('output_file_path', String(255)), Column('video_key', String(255)), Column('kid', String(255)), Column('packaged_content_id', Integer, unique=True), Column('url', String(255)) ) mapper(test_VideosDB,",
"\"25th July 2020\" __end_date__ = \"3rd August 2020\" __maintainer__ = \"me\" __email__ =",
"= \"\"\" This is the Database models script. Very important as it will",
"Column('status', String(255)), Column('output_file_path', String(255)), Column('video_key', String(255)), Column('kid', String(255)), Column('packaged_content_id', Integer, unique=True), Column('url', String(255))",
"class test_VideosDB(object): query = db_session.query_property() def __init__(self, input_content_id=None, input_content_origin=None, video_track_number=None, status=None, output_file_path=None, video_key=None,",
"video_track_number=None, status=None, output_file_path=None, video_key=None, kid=None, packaged_content_id=None, url=None): self.input_content_id = input_content_id self.input_content_origin = input_content_origin",
"), Column('video_track_number', Integer), Column('status', String(255)), Column('output_file_path', String(255)), Column('video_key', String(255)), Column('kid', String(255)), Column('packaged_content_id', Integer,",
"= output_file_path self.video_key = video_key self.kid = kid self.packaged_content_id = packaged_content_id self.url =",
"= status self.output_file_path = output_file_path self.video_key = video_key self.kid = kid self.packaged_content_id =",
"import metadata, db_session class test_VideosDB(object): query = db_session.query_property() def __init__(self, input_content_id=None, input_content_origin=None, video_track_number=None,",
"self.packaged_content_id = packaged_content_id self.url = url def __repr__(self): return '<VideosDB %r>' % (self.input_content_id)",
"unique=True), Column('input_content_origin', String(255), ), Column('video_track_number', Integer), Column('status', String(255)), Column('output_file_path', String(255)), Column('video_key', String(255)), Column('kid',",
"map it with our model for this App \"\"\" from sqlalchemy import *",
"self.kid = kid self.packaged_content_id = packaged_content_id self.url = url def __repr__(self): return '<VideosDB",
"= \"25th July 2020\" __end_date__ = \"3rd August 2020\" __maintainer__ = \"me\" __email__",
"MySQL, Flask-SQLAlchemy, database script\" __status__ = \"Production\" __description__ = \"\"\" This is the",
"from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import * from",
"Column('input_content_origin', String(255), ), Column('video_track_number', Integer), Column('status', String(255)), Column('output_file_path', String(255)), Column('video_key', String(255)), Column('kid', String(255)),",
"def __repr__(self): return '<VideosDB %r>' % (self.input_content_id) test_uploaded_videos = Table('test_uploaded_videos', metadata, Column('input_content_id', Integer,",
"url def __repr__(self): return '<VideosDB %r>' % (self.input_content_id) test_uploaded_videos = Table('test_uploaded_videos', metadata, Column('input_content_id',",
"script\" __status__ = \"Production\" __description__ = \"\"\" This is the Database models script.",
"self.video_track_number = video_track_number self.status = status self.output_file_path = output_file_path self.video_key = video_key self.kid",
"App \"\"\" from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import",
"\"Production\" __description__ = \"\"\" This is the Database models script. Very important as",
"= input_content_origin self.video_track_number = video_track_number self.status = status self.output_file_path = output_file_path self.video_key =",
"status self.output_file_path = output_file_path self.video_key = video_key self.kid = kid self.packaged_content_id = packaged_content_id",
"self.status = status self.output_file_path = output_file_path self.video_key = video_key self.kid = kid self.packaged_content_id",
"\"3rd August 2020\" __maintainer__ = \"me\" __email__ = \"<EMAIL>\" __requirements__ = \"SQL-Alchemy, MySQL,",
"Flask-SQLAlchemy, database script\" __status__ = \"Production\" __description__ = \"\"\" This is the Database",
"test_uploaded_videos = Table('test_uploaded_videos', metadata, Column('input_content_id', Integer, primary_key=True, autoincrement=True, unique=True), Column('input_content_origin', String(255), ), Column('video_track_number',",
"model for this App \"\"\" from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base",
"the Database models script. Very important as it will connect the database and",
"Very important as it will connect the database and map it with our",
"from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import * from test_database import metadata, db_session",
"db_session class test_VideosDB(object): query = db_session.query_property() def __init__(self, input_content_id=None, input_content_origin=None, video_track_number=None, status=None, output_file_path=None,",
"import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import * from test_database import",
"= \"me\" __email__ = \"<EMAIL>\" __requirements__ = \"SQL-Alchemy, MySQL, Flask-SQLAlchemy, database script\" __status__",
"for this App \"\"\" from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from",
"models script. Very important as it will connect the database and map it",
"video_key self.kid = kid self.packaged_content_id = packaged_content_id self.url = url def __repr__(self): return",
"metadata, Column('input_content_id', Integer, primary_key=True, autoincrement=True, unique=True), Column('input_content_origin', String(255), ), Column('video_track_number', Integer), Column('status', String(255)),",
"test_VideosDB(object): query = db_session.query_property() def __init__(self, input_content_id=None, input_content_origin=None, video_track_number=None, status=None, output_file_path=None, video_key=None, kid=None,",
"as it will connect the database and map it with our model for",
"from sqlalchemy.orm import * from test_database import metadata, db_session class test_VideosDB(object): query =",
"sqlalchemy.orm import * from test_database import metadata, db_session class test_VideosDB(object): query = db_session.query_property()",
"= Table('test_uploaded_videos', metadata, Column('input_content_id', Integer, primary_key=True, autoincrement=True, unique=True), Column('input_content_origin', String(255), ), Column('video_track_number', Integer),",
"is the Database models script. Very important as it will connect the database",
"= input_content_id self.input_content_origin = input_content_origin self.video_track_number = video_track_number self.status = status self.output_file_path =",
"script. Very important as it will connect the database and map it with",
"__requirements__ = \"SQL-Alchemy, MySQL, Flask-SQLAlchemy, database script\" __status__ = \"Production\" __description__ = \"\"\"",
"Integer), Column('status', String(255)), Column('output_file_path', String(255)), Column('video_key', String(255)), Column('kid', String(255)), Column('packaged_content_id', Integer, unique=True), Column('url',",
"__status__ = \"Production\" __description__ = \"\"\" This is the Database models script. Very",
"important as it will connect the database and map it with our model",
"autoincrement=True, unique=True), Column('input_content_origin', String(255), ), Column('video_track_number', Integer), Column('status', String(255)), Column('output_file_path', String(255)), Column('video_key', String(255)),",
"%r>' % (self.input_content_id) test_uploaded_videos = Table('test_uploaded_videos', metadata, Column('input_content_id', Integer, primary_key=True, autoincrement=True, unique=True), Column('input_content_origin',",
"__end_date__ = \"3rd August 2020\" __maintainer__ = \"me\" __email__ = \"<EMAIL>\" __requirements__ =",
"2020\" __end_date__ = \"3rd August 2020\" __maintainer__ = \"me\" __email__ = \"<EMAIL>\" __requirements__",
"and map it with our model for this App \"\"\" from sqlalchemy import",
"database script\" __status__ = \"Production\" __description__ = \"\"\" This is the Database models",
"input_content_id self.input_content_origin = input_content_origin self.video_track_number = video_track_number self.status = status self.output_file_path = output_file_path",
"= \"SQL-Alchemy, MySQL, Flask-SQLAlchemy, database script\" __status__ = \"Production\" __description__ = \"\"\" This",
"def __init__(self, input_content_id=None, input_content_origin=None, video_track_number=None, status=None, output_file_path=None, video_key=None, kid=None, packaged_content_id=None, url=None): self.input_content_id =",
"= video_track_number self.status = status self.output_file_path = output_file_path self.video_key = video_key self.kid =",
"self.input_content_origin = input_content_origin self.video_track_number = video_track_number self.status = status self.output_file_path = output_file_path self.video_key",
"__repr__(self): return '<VideosDB %r>' % (self.input_content_id) test_uploaded_videos = Table('test_uploaded_videos', metadata, Column('input_content_id', Integer, primary_key=True,"
] |
[
"torch.Tensor)-> torch.Tensor: \"\"\"Bayesian Personalized Ranking Loss Parameters ---------- pos : torch.Tensor Ranking logit",
"nn import torch.nn.functional as F def bpr_loss(pos: torch.Tensor, neg: torch.Tensor)-> torch.Tensor: \"\"\"Bayesian Personalized",
"(0..1) neg : torch.Tensor Ranking logit (0..1) Return ------ loss scalar \"\"\" diff",
"torch.nn.functional as F def bpr_loss(pos: torch.Tensor, neg: torch.Tensor)-> torch.Tensor: \"\"\"Bayesian Personalized Ranking Loss",
"import torch.nn as nn import torch.nn.functional as F def bpr_loss(pos: torch.Tensor, neg: torch.Tensor)->",
"---------- pos : torch.Tensor Ranking logit (0..1) neg : torch.Tensor Ranking logit (0..1)",
"bpr_loss(pos: torch.Tensor, neg: torch.Tensor)-> torch.Tensor: \"\"\"Bayesian Personalized Ranking Loss Parameters ---------- pos :",
"import torch.nn.functional as F def bpr_loss(pos: torch.Tensor, neg: torch.Tensor)-> torch.Tensor: \"\"\"Bayesian Personalized Ranking",
"neg: torch.Tensor)-> torch.Tensor: \"\"\"Bayesian Personalized Ranking Loss Parameters ---------- pos : torch.Tensor Ranking",
"import torch import torch.nn as nn import torch.nn.functional as F def bpr_loss(pos: torch.Tensor,",
"\"\"\"Bayesian Personalized Ranking Loss Parameters ---------- pos : torch.Tensor Ranking logit (0..1) neg",
"neg : torch.Tensor Ranking logit (0..1) Return ------ loss scalar \"\"\" diff =",
"Loss Parameters ---------- pos : torch.Tensor Ranking logit (0..1) neg : torch.Tensor Ranking",
"os import numpy as np import torch import torch.nn as nn import torch.nn.functional",
"torch.Tensor, neg: torch.Tensor)-> torch.Tensor: \"\"\"Bayesian Personalized Ranking Loss Parameters ---------- pos : torch.Tensor",
"(0..1) Return ------ loss scalar \"\"\" diff = pos - neg return -F.logsigmoid(diff).mean()",
"torch.Tensor: \"\"\"Bayesian Personalized Ranking Loss Parameters ---------- pos : torch.Tensor Ranking logit (0..1)",
": torch.Tensor Ranking logit (0..1) neg : torch.Tensor Ranking logit (0..1) Return ------",
"torch.Tensor Ranking logit (0..1) Return ------ loss scalar \"\"\" diff = pos -",
"Ranking logit (0..1) Return ------ loss scalar \"\"\" diff = pos - neg",
"torch import torch.nn as nn import torch.nn.functional as F def bpr_loss(pos: torch.Tensor, neg:",
"<reponame>nntrongnghia/learn-recsys<filename>utils.py import os import numpy as np import torch import torch.nn as nn",
"Ranking Loss Parameters ---------- pos : torch.Tensor Ranking logit (0..1) neg : torch.Tensor",
"numpy as np import torch import torch.nn as nn import torch.nn.functional as F",
"torch.nn as nn import torch.nn.functional as F def bpr_loss(pos: torch.Tensor, neg: torch.Tensor)-> torch.Tensor:",
"logit (0..1) neg : torch.Tensor Ranking logit (0..1) Return ------ loss scalar \"\"\"",
"pos : torch.Tensor Ranking logit (0..1) neg : torch.Tensor Ranking logit (0..1) Return",
"Parameters ---------- pos : torch.Tensor Ranking logit (0..1) neg : torch.Tensor Ranking logit",
"torch.Tensor Ranking logit (0..1) neg : torch.Tensor Ranking logit (0..1) Return ------ loss",
"Personalized Ranking Loss Parameters ---------- pos : torch.Tensor Ranking logit (0..1) neg :",
"F def bpr_loss(pos: torch.Tensor, neg: torch.Tensor)-> torch.Tensor: \"\"\"Bayesian Personalized Ranking Loss Parameters ----------",
"def bpr_loss(pos: torch.Tensor, neg: torch.Tensor)-> torch.Tensor: \"\"\"Bayesian Personalized Ranking Loss Parameters ---------- pos",
"as F def bpr_loss(pos: torch.Tensor, neg: torch.Tensor)-> torch.Tensor: \"\"\"Bayesian Personalized Ranking Loss Parameters",
"Ranking logit (0..1) neg : torch.Tensor Ranking logit (0..1) Return ------ loss scalar",
": torch.Tensor Ranking logit (0..1) Return ------ loss scalar \"\"\" diff = pos",
"as nn import torch.nn.functional as F def bpr_loss(pos: torch.Tensor, neg: torch.Tensor)-> torch.Tensor: \"\"\"Bayesian",
"import numpy as np import torch import torch.nn as nn import torch.nn.functional as",
"logit (0..1) Return ------ loss scalar \"\"\" diff = pos - neg return",
"import os import numpy as np import torch import torch.nn as nn import",
"as np import torch import torch.nn as nn import torch.nn.functional as F def",
"np import torch import torch.nn as nn import torch.nn.functional as F def bpr_loss(pos:"
] |
[
"A group of CompareIntegerMaps runs using similar options but different seeds. \"\"\" def",
"in ['TABLE', 'JUDY']: experiment = Experiment(testLauncher, 'MEMORY_%s' % container, 8 if container ==",
"= [(marker, medianAverage(units)) for marker, units in sorted(allGroups.items())] #--------------------------------------------------- # main #--------------------------------------------------- if",
"8 if container == 'JUDY' else 1, 0, maxKeys, granularity, 0, CONTAINER=container, EXPERIMENT='MEMORY')",
"= Experiment(testLauncher, 'LOOKUP_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='LOOKUP',",
"for k, v in mergedDefs.iteritems()]) self.launcher.ignoreCache = IGNORE_CACHE output = self.launcher.run(*args, **fullDefs) return",
"in sys.argv[1:]: IGNORE_CACHE = True results = {} testLauncher = TestLauncher() maxKeys =",
"# without redoing previous experiments. #--------------------------------------------------- import cmake_launcher import math import os import",
"generator=globals().get('GENERATOR')) # It would be cool to get CMake to tell us the",
"18000000 granularity = 200 for container in ['TABLE', 'JUDY']: experiment = Experiment(testLauncher, 'MEMORY_%s'",
"builds & runs CompareIntegerMaps using the specified options. \"\"\" DEFAULT_DEFS = { 'CACHE_STOMPER_ENABLED':",
"1000, 10000]: experiment = Experiment(testLauncher, 'INSERT_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity,",
"**kwargs): self.testLauncher = testLauncher self.name = name self.seeds = seeds self.args = args",
"stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results) experiment = Experiment(testLauncher, 'LOOKUP_%d_%s' %",
"for marker, units in r['results']: allGroups[marker].append(units) def medianAverage(values): if len(values) >= 4: values",
"= dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs = dict([('INTEGER_MAP_' + k, v) for k, v in",
"else 0) if filter.match(experiment.name): experiment.run(results) experiment = Experiment(testLauncher, 'LOOKUP_%d_%s' % (stomp, container), 8,",
"and writes the results to results.txt. # You can filter the experiments by",
"runs CompareIntegerMaps using the specified options. \"\"\" DEFAULT_DEFS = { 'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT':",
"maxKeys = 18000000 granularity = 200 for container in ['TABLE', 'JUDY']: experiment =",
"previous experiments. #--------------------------------------------------- import cmake_launcher import math import os import re import sys",
"+ ['.*'])[1]) if '--nocache' in sys.argv[1:]: IGNORE_CACHE = True results = {} testLauncher",
"= [seed, operationsPerGroup, keyCount, granularity, stompBytes] mergedDefs = dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs = dict([('INTEGER_MAP_'",
"run(self, results): allGroups = defaultdict(list) for seed in xrange(self.seeds): print('Running %s #%d/%d...' %",
"can add new results to results.txt # without redoing previous experiments. #--------------------------------------------------- import",
"operationsPerGroup, keyCount, granularity, stompBytes, **defs): args = [seed, operationsPerGroup, keyCount, granularity, stompBytes] mergedDefs",
"class Experiment: \"\"\" A group of CompareIntegerMaps runs using similar options but different",
"**self.kwargs) for marker, units in r['results']: allGroups[marker].append(units) def medianAverage(values): if len(values) >= 4:",
"experiment = Experiment(testLauncher, 'INSERT_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container,",
"instead. self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def run(self, seed, operationsPerGroup, keyCount, granularity, stompBytes, **defs):",
"if container == 'JUDY' else 1, 0, maxKeys, granularity, 0, CONTAINER=container, EXPERIMENT='MEMORY') if",
"Experiment(testLauncher, 'INSERT_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1",
"run_tests.py LOOKUP_0_.* # Results are also cached in an intermediate directory, temp, so",
"pprint import pprint #GENERATOR = 'Visual Studio 10' IGNORE_CACHE = False #--------------------------------------------------- #",
"> 0 else 0) if filter.match(experiment.name): experiment.run(results) pprint(results, open('results.txt', 'w')) print('Elapsed time: %s'",
"writes the results to results.txt. # You can filter the experiments by name",
"if __name__ == '__main__': from datetime import datetime start = datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter",
"(stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if stomp >",
"#--------------------------------------------------- # Experiment #--------------------------------------------------- class Experiment: \"\"\" A group of CompareIntegerMaps runs using",
"to tell us the path to the executable instead. self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe')",
"options. \"\"\" DEFAULT_DEFS = { 'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT': 'INSERT', 'CONTAINER': 'TABLE', } def",
"#--------------------------------------------------- # main #--------------------------------------------------- if __name__ == '__main__': from datetime import datetime start",
"re.compile((sys.argv + ['.*'])[1]) if '--nocache' in sys.argv[1:]: IGNORE_CACHE = True results = {}",
"seeds self.args = args self.kwargs = kwargs def run(self, results): allGroups = defaultdict(list)",
"\"\"\" def __init__(self, testLauncher, name, seeds, *args, **kwargs): self.testLauncher = testLauncher self.name =",
"datetime start = datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter = re.compile((sys.argv + ['.*'])[1]) if '--nocache' in",
"import defaultdict from pprint import pprint #GENERATOR = 'Visual Studio 10' IGNORE_CACHE =",
"name by passing a regular expression as a script argument. # For example:",
"EXPERIMENT='MEMORY') if filter.match(experiment.name): experiment.run(results) for stomp in [0, 1000, 10000]: experiment = Experiment(testLauncher,",
"0 else 0) if filter.match(experiment.name): experiment.run(results) experiment = Experiment(testLauncher, 'LOOKUP_%d_%s' % (stomp, container),",
"datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter = re.compile((sys.argv + ['.*'])[1]) if '--nocache' in sys.argv[1:]: IGNORE_CACHE =",
"4: values = sorted(values)[1:-1] return sum(values) / len(values) results[self.name] = [(marker, medianAverage(units)) for",
"you can add new results to results.txt # without redoing previous experiments. #---------------------------------------------------",
"& runs CompareIntegerMaps using the specified options. \"\"\" DEFAULT_DEFS = { 'CACHE_STOMPER_ENABLED': 0,",
"\"\"\" A group of CompareIntegerMaps runs using similar options but different seeds. \"\"\"",
"[0, 1000, 10000]: experiment = Experiment(testLauncher, 'INSERT_%d_%s' % (stomp, container), 8, 8000, maxKeys,",
"fullDefs = dict([('INTEGER_MAP_' + k, v) for k, v in mergedDefs.iteritems()]) self.launcher.ignoreCache =",
"== 'JUDY' else 1, 0, maxKeys, granularity, 0, CONTAINER=container, EXPERIMENT='MEMORY') if filter.match(experiment.name): experiment.run(results)",
"%s #%d/%d...' % (self.name, seed + 1, self.seeds)) r = self.testLauncher.run(seed, *self.args, **self.kwargs)",
"k, v in mergedDefs.iteritems()]) self.launcher.ignoreCache = IGNORE_CACHE output = self.launcher.run(*args, **fullDefs) return eval(output)",
"Experiment(testLauncher, 'LOOKUP_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1",
"eval(output) #--------------------------------------------------- # Experiment #--------------------------------------------------- class Experiment: \"\"\" A group of CompareIntegerMaps runs",
"#%d/%d...' % (self.name, seed + 1, self.seeds)) r = self.testLauncher.run(seed, *self.args, **self.kwargs) for",
"seed in xrange(self.seeds): print('Running %s #%d/%d...' % (self.name, seed + 1, self.seeds)) r",
"os.chdir(os.path.split(sys.argv[0])[0]) filter = re.compile((sys.argv + ['.*'])[1]) if '--nocache' in sys.argv[1:]: IGNORE_CACHE = True",
"maxKeys, granularity, 0, CONTAINER=container, EXPERIMENT='MEMORY') if filter.match(experiment.name): experiment.run(results) for stomp in [0, 1000,",
"def __init__(self, testLauncher, name, seeds, *args, **kwargs): self.testLauncher = testLauncher self.name = name",
"== '__main__': from datetime import datetime start = datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter = re.compile((sys.argv",
"'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT': 'INSERT', 'CONTAINER': 'TABLE', } def __init__(self): cmakeBuilder = cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR'))",
"8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if stomp > 0 else",
"'CONTAINER': 'TABLE', } def __init__(self): cmakeBuilder = cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) # It would be",
"without redoing previous experiments. #--------------------------------------------------- import cmake_launcher import math import os import re",
"of experiments using CompareIntegerMaps.exe, and writes the results to results.txt. # You can",
"self.kwargs = kwargs def run(self, results): allGroups = defaultdict(list) for seed in xrange(self.seeds):",
"start = datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter = re.compile((sys.argv + ['.*'])[1]) if '--nocache' in sys.argv[1:]:",
"granularity, stompBytes] mergedDefs = dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs = dict([('INTEGER_MAP_' + k, v) for",
"cmakeBuilder = cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) # It would be cool to get CMake to",
"Experiment #--------------------------------------------------- class Experiment: \"\"\" A group of CompareIntegerMaps runs using similar options",
"__init__(self, testLauncher, name, seeds, *args, **kwargs): self.testLauncher = testLauncher self.name = name self.seeds",
"CMake to tell us the path to the executable instead. self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder,",
"= cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) # It would be cool to get CMake to tell",
"are also cached in an intermediate directory, temp, so you can add new",
"results.txt # without redoing previous experiments. #--------------------------------------------------- import cmake_launcher import math import os",
"= seeds self.args = args self.kwargs = kwargs def run(self, results): allGroups =",
"container, 8 if container == 'JUDY' else 1, 0, maxKeys, granularity, 0, CONTAINER=container,",
"def medianAverage(values): if len(values) >= 4: values = sorted(values)[1:-1] return sum(values) / len(values)",
"'Visual Studio 10' IGNORE_CACHE = False #--------------------------------------------------- # TestLauncher #--------------------------------------------------- class TestLauncher: \"\"\"",
"units in r['results']: allGroups[marker].append(units) def medianAverage(values): if len(values) >= 4: values = sorted(values)[1:-1]",
"def run(self, seed, operationsPerGroup, keyCount, granularity, stompBytes, **defs): args = [seed, operationsPerGroup, keyCount,",
"re import sys from collections import defaultdict from pprint import pprint #GENERATOR =",
"script argument. # For example: run_tests.py LOOKUP_0_.* # Results are also cached in",
"LOOKUP_0_.* # Results are also cached in an intermediate directory, temp, so you",
"TestLauncher() maxKeys = 18000000 granularity = 200 for container in ['TABLE', 'JUDY']: experiment",
"granularity = 200 for container in ['TABLE', 'JUDY']: experiment = Experiment(testLauncher, 'MEMORY_%s' %",
"CompareIntegerMaps runs using similar options but different seeds. \"\"\" def __init__(self, testLauncher, name,",
"argument. # For example: run_tests.py LOOKUP_0_.* # Results are also cached in an",
"using similar options but different seeds. \"\"\" def __init__(self, testLauncher, name, seeds, *args,",
"CompareIntegerMaps using the specified options. \"\"\" DEFAULT_DEFS = { 'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT': 'INSERT',",
"else 0) if filter.match(experiment.name): experiment.run(results) pprint(results, open('results.txt', 'w')) print('Elapsed time: %s' % (datetime.now()",
"using CompareIntegerMaps.exe, and writes the results to results.txt. # You can filter the",
"filter = re.compile((sys.argv + ['.*'])[1]) if '--nocache' in sys.argv[1:]: IGNORE_CACHE = True results",
"directory, temp, so you can add new results to results.txt # without redoing",
"v in mergedDefs.iteritems()]) self.launcher.ignoreCache = IGNORE_CACHE output = self.launcher.run(*args, **fullDefs) return eval(output) #---------------------------------------------------",
"by name by passing a regular expression as a script argument. # For",
"results to results.txt # without redoing previous experiments. #--------------------------------------------------- import cmake_launcher import math",
"a script argument. # For example: run_tests.py LOOKUP_0_.* # Results are also cached",
"'INSERT_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if",
"if stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results) pprint(results, open('results.txt', 'w')) print('Elapsed",
"sorted(allGroups.items())] #--------------------------------------------------- # main #--------------------------------------------------- if __name__ == '__main__': from datetime import datetime",
"% (stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if stomp",
"= datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter = re.compile((sys.argv + ['.*'])[1]) if '--nocache' in sys.argv[1:]: IGNORE_CACHE",
"'JUDY']: experiment = Experiment(testLauncher, 'MEMORY_%s' % container, 8 if container == 'JUDY' else",
"= False #--------------------------------------------------- # TestLauncher #--------------------------------------------------- class TestLauncher: \"\"\" Configures, builds & runs",
"args = [seed, operationsPerGroup, keyCount, granularity, stompBytes] mergedDefs = dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs =",
"> 0 else 0) if filter.match(experiment.name): experiment.run(results) experiment = Experiment(testLauncher, 'LOOKUP_%d_%s' % (stomp,",
"stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results) pprint(results, open('results.txt', 'w')) print('Elapsed time:",
"#GENERATOR = 'Visual Studio 10' IGNORE_CACHE = False #--------------------------------------------------- # TestLauncher #--------------------------------------------------- class",
"= testLauncher self.name = name self.seeds = seeds self.args = args self.kwargs =",
"1, 0, maxKeys, granularity, 0, CONTAINER=container, EXPERIMENT='MEMORY') if filter.match(experiment.name): experiment.run(results) for stomp in",
"'MEMORY_%s' % container, 8 if container == 'JUDY' else 1, 0, maxKeys, granularity,",
"filter.match(experiment.name): experiment.run(results) experiment = Experiment(testLauncher, 'LOOKUP_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity,",
"cached in an intermediate directory, temp, so you can add new results to",
"\"\"\" Configures, builds & runs CompareIntegerMaps using the specified options. \"\"\" DEFAULT_DEFS =",
"main #--------------------------------------------------- if __name__ == '__main__': from datetime import datetime start = datetime.now()",
"8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if stomp > 0 else",
"collections import defaultdict from pprint import pprint #GENERATOR = 'Visual Studio 10' IGNORE_CACHE",
"container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if stomp > 0",
"dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs = dict([('INTEGER_MAP_' + k, v) for k, v in mergedDefs.iteritems()])",
"= 'Visual Studio 10' IGNORE_CACHE = False #--------------------------------------------------- # TestLauncher #--------------------------------------------------- class TestLauncher:",
"container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if stomp > 0",
"in an intermediate directory, temp, so you can add new results to results.txt",
"[(marker, medianAverage(units)) for marker, units in sorted(allGroups.items())] #--------------------------------------------------- # main #--------------------------------------------------- if __name__",
"in xrange(self.seeds): print('Running %s #%d/%d...' % (self.name, seed + 1, self.seeds)) r =",
"200 for container in ['TABLE', 'JUDY']: experiment = Experiment(testLauncher, 'MEMORY_%s' % container, 8",
"a regular expression as a script argument. # For example: run_tests.py LOOKUP_0_.* #",
"[seed, operationsPerGroup, keyCount, granularity, stompBytes] mergedDefs = dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs = dict([('INTEGER_MAP_' +",
"testLauncher = TestLauncher() maxKeys = 18000000 granularity = 200 for container in ['TABLE',",
"= self.launcher.run(*args, **fullDefs) return eval(output) #--------------------------------------------------- # Experiment #--------------------------------------------------- class Experiment: \"\"\" A",
"in r['results']: allGroups[marker].append(units) def medianAverage(values): if len(values) >= 4: values = sorted(values)[1:-1] return",
"def run(self, results): allGroups = defaultdict(list) for seed in xrange(self.seeds): print('Running %s #%d/%d...'",
"/ len(values) results[self.name] = [(marker, medianAverage(units)) for marker, units in sorted(allGroups.items())] #--------------------------------------------------- #",
"IGNORE_CACHE = True results = {} testLauncher = TestLauncher() maxKeys = 18000000 granularity",
"8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0)",
"#--------------------------------------------------- import cmake_launcher import math import os import re import sys from collections",
"values = sorted(values)[1:-1] return sum(values) / len(values) results[self.name] = [(marker, medianAverage(units)) for marker,",
"'EXPERIMENT': 'INSERT', 'CONTAINER': 'TABLE', } def __init__(self): cmakeBuilder = cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) # It",
"= name self.seeds = seeds self.args = args self.kwargs = kwargs def run(self,",
"the executable instead. self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def run(self, seed, operationsPerGroup, keyCount, granularity,",
"print('Running %s #%d/%d...' % (self.name, seed + 1, self.seeds)) r = self.testLauncher.run(seed, *self.args,",
"TestLauncher: \"\"\" Configures, builds & runs CompareIntegerMaps using the specified options. \"\"\" DEFAULT_DEFS",
"import cmake_launcher import math import os import re import sys from collections import",
"container in ['TABLE', 'JUDY']: experiment = Experiment(testLauncher, 'MEMORY_%s' % container, 8 if container",
"= 18000000 granularity = 200 for container in ['TABLE', 'JUDY']: experiment = Experiment(testLauncher,",
"CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results) pprint(results, open('results.txt', 'w'))",
"1, self.seeds)) r = self.testLauncher.run(seed, *self.args, **self.kwargs) for marker, units in r['results']: allGroups[marker].append(units)",
"specified options. \"\"\" DEFAULT_DEFS = { 'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT': 'INSERT', 'CONTAINER': 'TABLE', }",
"regular expression as a script argument. # For example: run_tests.py LOOKUP_0_.* # Results",
"0) if filter.match(experiment.name): experiment.run(results) pprint(results, open('results.txt', 'w')) print('Elapsed time: %s' % (datetime.now() -",
"granularity, stomp, CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if filter.match(experiment.name):",
"def __init__(self): cmakeBuilder = cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) # It would be cool to get",
"= dict([('INTEGER_MAP_' + k, v) for k, v in mergedDefs.iteritems()]) self.launcher.ignoreCache = IGNORE_CACHE",
"in mergedDefs.iteritems()]) self.launcher.ignoreCache = IGNORE_CACHE output = self.launcher.run(*args, **fullDefs) return eval(output) #--------------------------------------------------- #",
"medianAverage(values): if len(values) >= 4: values = sorted(values)[1:-1] return sum(values) / len(values) results[self.name]",
"'LOOKUP_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if",
"stomp in [0, 1000, 10000]: experiment = Experiment(testLauncher, 'INSERT_%d_%s' % (stomp, container), 8,",
"self.args = args self.kwargs = kwargs def run(self, results): allGroups = defaultdict(list) for",
"marker, units in sorted(allGroups.items())] #--------------------------------------------------- # main #--------------------------------------------------- if __name__ == '__main__': from",
"so you can add new results to results.txt # without redoing previous experiments.",
"import re import sys from collections import defaultdict from pprint import pprint #GENERATOR",
"stompBytes] mergedDefs = dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs = dict([('INTEGER_MAP_' + k, v) for k,",
"results): allGroups = defaultdict(list) for seed in xrange(self.seeds): print('Running %s #%d/%d...' % (self.name,",
"'CompareIntegerMaps.exe') def run(self, seed, operationsPerGroup, keyCount, granularity, stompBytes, **defs): args = [seed, operationsPerGroup,",
"for marker, units in sorted(allGroups.items())] #--------------------------------------------------- # main #--------------------------------------------------- if __name__ == '__main__':",
"cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) # It would be cool to get CMake to tell us",
"# Perform a bunch of experiments using CompareIntegerMaps.exe, and writes the results to",
"similar options but different seeds. \"\"\" def __init__(self, testLauncher, name, seeds, *args, **kwargs):",
"**fullDefs) return eval(output) #--------------------------------------------------- # Experiment #--------------------------------------------------- class Experiment: \"\"\" A group of",
"sys.argv[1:]: IGNORE_CACHE = True results = {} testLauncher = TestLauncher() maxKeys = 18000000",
"True results = {} testLauncher = TestLauncher() maxKeys = 18000000 granularity = 200",
"experiment = Experiment(testLauncher, 'MEMORY_%s' % container, 8 if container == 'JUDY' else 1,",
"import sys from collections import defaultdict from pprint import pprint #GENERATOR = 'Visual",
"% container, 8 if container == 'JUDY' else 1, 0, maxKeys, granularity, 0,",
"for container in ['TABLE', 'JUDY']: experiment = Experiment(testLauncher, 'MEMORY_%s' % container, 8 if",
"+ 1, self.seeds)) r = self.testLauncher.run(seed, *self.args, **self.kwargs) for marker, units in r['results']:",
"{} testLauncher = TestLauncher() maxKeys = 18000000 granularity = 200 for container in",
"by passing a regular expression as a script argument. # For example: run_tests.py",
"for seed in xrange(self.seeds): print('Running %s #%d/%d...' % (self.name, seed + 1, self.seeds))",
"['TABLE', 'JUDY']: experiment = Experiment(testLauncher, 'MEMORY_%s' % container, 8 if container == 'JUDY'",
"10' IGNORE_CACHE = False #--------------------------------------------------- # TestLauncher #--------------------------------------------------- class TestLauncher: \"\"\" Configures, builds",
"keyCount, granularity, stompBytes] mergedDefs = dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs = dict([('INTEGER_MAP_' + k, v)",
"'INSERT', 'CONTAINER': 'TABLE', } def __init__(self): cmakeBuilder = cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) # It would",
"\"\"\" DEFAULT_DEFS = { 'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT': 'INSERT', 'CONTAINER': 'TABLE', } def __init__(self):",
"marker, units in r['results']: allGroups[marker].append(units) def medianAverage(values): if len(values) >= 4: values =",
"= { 'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT': 'INSERT', 'CONTAINER': 'TABLE', } def __init__(self): cmakeBuilder =",
"0 else 0) if filter.match(experiment.name): experiment.run(results) pprint(results, open('results.txt', 'w')) print('Elapsed time: %s' %",
"kwargs def run(self, results): allGroups = defaultdict(list) for seed in xrange(self.seeds): print('Running %s",
"name, seeds, *args, **kwargs): self.testLauncher = testLauncher self.name = name self.seeds = seeds",
"experiment.run(results) for stomp in [0, 1000, 10000]: experiment = Experiment(testLauncher, 'INSERT_%d_%s' % (stomp,",
"CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results) pprint(results,",
"} def __init__(self): cmakeBuilder = cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) # It would be cool to",
"run(self, seed, operationsPerGroup, keyCount, granularity, stompBytes, **defs): args = [seed, operationsPerGroup, keyCount, granularity,",
"self.seeds = seeds self.args = args self.kwargs = kwargs def run(self, results): allGroups",
"= True results = {} testLauncher = TestLauncher() maxKeys = 18000000 granularity =",
"r['results']: allGroups[marker].append(units) def medianAverage(values): if len(values) >= 4: values = sorted(values)[1:-1] return sum(values)",
"It would be cool to get CMake to tell us the path to",
"self.testLauncher.run(seed, *self.args, **self.kwargs) for marker, units in r['results']: allGroups[marker].append(units) def medianAverage(values): if len(values)",
"pprint #GENERATOR = 'Visual Studio 10' IGNORE_CACHE = False #--------------------------------------------------- # TestLauncher #---------------------------------------------------",
"= IGNORE_CACHE output = self.launcher.run(*args, **fullDefs) return eval(output) #--------------------------------------------------- # Experiment #--------------------------------------------------- class",
"import os import re import sys from collections import defaultdict from pprint import",
"% (stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if stomp",
"granularity, 0, CONTAINER=container, EXPERIMENT='MEMORY') if filter.match(experiment.name): experiment.run(results) for stomp in [0, 1000, 10000]:",
"__name__ == '__main__': from datetime import datetime start = datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter =",
"'TABLE', } def __init__(self): cmakeBuilder = cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) # It would be cool",
"math import os import re import sys from collections import defaultdict from pprint",
"new results to results.txt # without redoing previous experiments. #--------------------------------------------------- import cmake_launcher import",
"runs using similar options but different seeds. \"\"\" def __init__(self, testLauncher, name, seeds,",
"executable instead. self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def run(self, seed, operationsPerGroup, keyCount, granularity, stompBytes,",
"to the executable instead. self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def run(self, seed, operationsPerGroup, keyCount,",
"Results are also cached in an intermediate directory, temp, so you can add",
"can filter the experiments by name by passing a regular expression as a",
"10000]: experiment = Experiment(testLauncher, 'INSERT_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity, stomp,",
"passing a regular expression as a script argument. # For example: run_tests.py LOOKUP_0_.*",
"IGNORE_CACHE output = self.launcher.run(*args, **fullDefs) return eval(output) #--------------------------------------------------- # Experiment #--------------------------------------------------- class Experiment:",
"% (self.name, seed + 1, self.seeds)) r = self.testLauncher.run(seed, *self.args, **self.kwargs) for marker,",
"to results.txt # without redoing previous experiments. #--------------------------------------------------- import cmake_launcher import math import",
"= self.testLauncher.run(seed, *self.args, **self.kwargs) for marker, units in r['results']: allGroups[marker].append(units) def medianAverage(values): if",
"stomp, CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results)",
"DEFAULT_DEFS = { 'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT': 'INSERT', 'CONTAINER': 'TABLE', } def __init__(self): cmakeBuilder",
"the specified options. \"\"\" DEFAULT_DEFS = { 'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT': 'INSERT', 'CONTAINER': 'TABLE',",
"# Results are also cached in an intermediate directory, temp, so you can",
"CompareIntegerMaps.exe, and writes the results to results.txt. # You can filter the experiments",
"cool to get CMake to tell us the path to the executable instead.",
"medianAverage(units)) for marker, units in sorted(allGroups.items())] #--------------------------------------------------- # main #--------------------------------------------------- if __name__ ==",
"IGNORE_CACHE = False #--------------------------------------------------- # TestLauncher #--------------------------------------------------- class TestLauncher: \"\"\" Configures, builds &",
"8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0)",
"#--------------------------------------------------- # TestLauncher #--------------------------------------------------- class TestLauncher: \"\"\" Configures, builds & runs CompareIntegerMaps using",
"= Experiment(testLauncher, 'MEMORY_%s' % container, 8 if container == 'JUDY' else 1, 0,",
"*self.args, **self.kwargs) for marker, units in r['results']: allGroups[marker].append(units) def medianAverage(values): if len(values) >=",
"granularity, stompBytes, **defs): args = [seed, operationsPerGroup, keyCount, granularity, stompBytes] mergedDefs = dict(self.DEFAULT_DEFS)",
"self.launcher.run(*args, **fullDefs) return eval(output) #--------------------------------------------------- # Experiment #--------------------------------------------------- class Experiment: \"\"\" A group",
"to get CMake to tell us the path to the executable instead. self.launcher",
"in [0, 1000, 10000]: experiment = Experiment(testLauncher, 'INSERT_%d_%s' % (stomp, container), 8, 8000,",
"testLauncher, name, seeds, *args, **kwargs): self.testLauncher = testLauncher self.name = name self.seeds =",
">= 4: values = sorted(values)[1:-1] return sum(values) / len(values) results[self.name] = [(marker, medianAverage(units))",
"allGroups = defaultdict(list) for seed in xrange(self.seeds): print('Running %s #%d/%d...' % (self.name, seed",
"name self.seeds = seeds self.args = args self.kwargs = kwargs def run(self, results):",
"container == 'JUDY' else 1, 0, maxKeys, granularity, 0, CONTAINER=container, EXPERIMENT='MEMORY') if filter.match(experiment.name):",
"v) for k, v in mergedDefs.iteritems()]) self.launcher.ignoreCache = IGNORE_CACHE output = self.launcher.run(*args, **fullDefs)",
"intermediate directory, temp, so you can add new results to results.txt # without",
"False #--------------------------------------------------- # TestLauncher #--------------------------------------------------- class TestLauncher: \"\"\" Configures, builds & runs CompareIntegerMaps",
"from pprint import pprint #GENERATOR = 'Visual Studio 10' IGNORE_CACHE = False #---------------------------------------------------",
"from collections import defaultdict from pprint import pprint #GENERATOR = 'Visual Studio 10'",
"k, v) for k, v in mergedDefs.iteritems()]) self.launcher.ignoreCache = IGNORE_CACHE output = self.launcher.run(*args,",
"EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results) experiment =",
"EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results) pprint(results, open('results.txt',",
"= Experiment(testLauncher, 'INSERT_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='INSERT',",
"seed + 1, self.seeds)) r = self.testLauncher.run(seed, *self.args, **self.kwargs) for marker, units in",
"mergedDefs.iteritems()]) self.launcher.ignoreCache = IGNORE_CACHE output = self.launcher.run(*args, **fullDefs) return eval(output) #--------------------------------------------------- # Experiment",
"the results to results.txt. # You can filter the experiments by name by",
"= cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def run(self, seed, operationsPerGroup, keyCount, granularity, stompBytes, **defs): args =",
"mergedDefs = dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs = dict([('INTEGER_MAP_' + k, v) for k, v",
"sum(values) / len(values) results[self.name] = [(marker, medianAverage(units)) for marker, units in sorted(allGroups.items())] #---------------------------------------------------",
"stompBytes, **defs): args = [seed, operationsPerGroup, keyCount, granularity, stompBytes] mergedDefs = dict(self.DEFAULT_DEFS) mergedDefs.update(defs)",
"seed, operationsPerGroup, keyCount, granularity, stompBytes, **defs): args = [seed, operationsPerGroup, keyCount, granularity, stompBytes]",
"0, 'EXPERIMENT': 'INSERT', 'CONTAINER': 'TABLE', } def __init__(self): cmakeBuilder = cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) #",
"args self.kwargs = kwargs def run(self, results): allGroups = defaultdict(list) for seed in",
"seeds. \"\"\" def __init__(self, testLauncher, name, seeds, *args, **kwargs): self.testLauncher = testLauncher self.name",
"bunch of experiments using CompareIntegerMaps.exe, and writes the results to results.txt. # You",
"import pprint #GENERATOR = 'Visual Studio 10' IGNORE_CACHE = False #--------------------------------------------------- # TestLauncher",
"operationsPerGroup, keyCount, granularity, stompBytes] mergedDefs = dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs = dict([('INTEGER_MAP_' + k,",
"mergedDefs.update(defs) fullDefs = dict([('INTEGER_MAP_' + k, v) for k, v in mergedDefs.iteritems()]) self.launcher.ignoreCache",
"if stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results) experiment = Experiment(testLauncher, 'LOOKUP_%d_%s'",
"self.testLauncher = testLauncher self.name = name self.seeds = seeds self.args = args self.kwargs",
"to results.txt. # You can filter the experiments by name by passing a",
"= re.compile((sys.argv + ['.*'])[1]) if '--nocache' in sys.argv[1:]: IGNORE_CACHE = True results =",
"# For example: run_tests.py LOOKUP_0_.* # Results are also cached in an intermediate",
"example: run_tests.py LOOKUP_0_.* # Results are also cached in an intermediate directory, temp,",
"Studio 10' IGNORE_CACHE = False #--------------------------------------------------- # TestLauncher #--------------------------------------------------- class TestLauncher: \"\"\" Configures,",
"len(values) results[self.name] = [(marker, medianAverage(units)) for marker, units in sorted(allGroups.items())] #--------------------------------------------------- # main",
"the path to the executable instead. self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def run(self, seed,",
"{ 'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT': 'INSERT', 'CONTAINER': 'TABLE', } def __init__(self): cmakeBuilder = cmake_launcher.CMakeBuilder('..',",
"cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def run(self, seed, operationsPerGroup, keyCount, granularity, stompBytes, **defs): args = [seed,",
"*args, **kwargs): self.testLauncher = testLauncher self.name = name self.seeds = seeds self.args =",
"results to results.txt. # You can filter the experiments by name by passing",
"0, maxKeys, granularity, 0, CONTAINER=container, EXPERIMENT='MEMORY') if filter.match(experiment.name): experiment.run(results) for stomp in [0,",
"stomp, CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results)",
"**defs): args = [seed, operationsPerGroup, keyCount, granularity, stompBytes] mergedDefs = dict(self.DEFAULT_DEFS) mergedDefs.update(defs) fullDefs",
"if filter.match(experiment.name): experiment.run(results) for stomp in [0, 1000, 10000]: experiment = Experiment(testLauncher, 'INSERT_%d_%s'",
"if len(values) >= 4: values = sorted(values)[1:-1] return sum(values) / len(values) results[self.name] =",
"maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if",
"redoing previous experiments. #--------------------------------------------------- import cmake_launcher import math import os import re import",
"experiments by name by passing a regular expression as a script argument. #",
"__init__(self): cmakeBuilder = cmake_launcher.CMakeBuilder('..', generator=globals().get('GENERATOR')) # It would be cool to get CMake",
"= {} testLauncher = TestLauncher() maxKeys = 18000000 granularity = 200 for container",
"experiments using CompareIntegerMaps.exe, and writes the results to results.txt. # You can filter",
"cmake_launcher import math import os import re import sys from collections import defaultdict",
"add new results to results.txt # without redoing previous experiments. #--------------------------------------------------- import cmake_launcher",
"results[self.name] = [(marker, medianAverage(units)) for marker, units in sorted(allGroups.items())] #--------------------------------------------------- # main #---------------------------------------------------",
"but different seeds. \"\"\" def __init__(self, testLauncher, name, seeds, *args, **kwargs): self.testLauncher =",
"(stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if stomp >",
"filter the experiments by name by passing a regular expression as a script",
"sys from collections import defaultdict from pprint import pprint #GENERATOR = 'Visual Studio",
"Experiment(testLauncher, 'MEMORY_%s' % container, 8 if container == 'JUDY' else 1, 0, maxKeys,",
"expression as a script argument. # For example: run_tests.py LOOKUP_0_.* # Results are",
"+ k, v) for k, v in mergedDefs.iteritems()]) self.launcher.ignoreCache = IGNORE_CACHE output =",
"(self.name, seed + 1, self.seeds)) r = self.testLauncher.run(seed, *self.args, **self.kwargs) for marker, units",
"r = self.testLauncher.run(seed, *self.args, **self.kwargs) for marker, units in r['results']: allGroups[marker].append(units) def medianAverage(values):",
"group of CompareIntegerMaps runs using similar options but different seeds. \"\"\" def __init__(self,",
"options but different seeds. \"\"\" def __init__(self, testLauncher, name, seeds, *args, **kwargs): self.testLauncher",
"#--------------------------------------------------- class Experiment: \"\"\" A group of CompareIntegerMaps runs using similar options but",
"0, CONTAINER=container, EXPERIMENT='MEMORY') if filter.match(experiment.name): experiment.run(results) for stomp in [0, 1000, 10000]: experiment",
"#--------------------------------------------------- # Perform a bunch of experiments using CompareIntegerMaps.exe, and writes the results",
"#--------------------------------------------------- if __name__ == '__main__': from datetime import datetime start = datetime.now() os.chdir(os.path.split(sys.argv[0])[0])",
"# You can filter the experiments by name by passing a regular expression",
"os import re import sys from collections import defaultdict from pprint import pprint",
"us the path to the executable instead. self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def run(self,",
"['.*'])[1]) if '--nocache' in sys.argv[1:]: IGNORE_CACHE = True results = {} testLauncher =",
"of CompareIntegerMaps runs using similar options but different seeds. \"\"\" def __init__(self, testLauncher,",
"a bunch of experiments using CompareIntegerMaps.exe, and writes the results to results.txt. #",
"# TestLauncher #--------------------------------------------------- class TestLauncher: \"\"\" Configures, builds & runs CompareIntegerMaps using the",
"experiment = Experiment(testLauncher, 'LOOKUP_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity, stomp, CONTAINER=container,",
"len(values) >= 4: values = sorted(values)[1:-1] return sum(values) / len(values) results[self.name] = [(marker,",
"dict([('INTEGER_MAP_' + k, v) for k, v in mergedDefs.iteritems()]) self.launcher.ignoreCache = IGNORE_CACHE output",
"sorted(values)[1:-1] return sum(values) / len(values) results[self.name] = [(marker, medianAverage(units)) for marker, units in",
"units in sorted(allGroups.items())] #--------------------------------------------------- # main #--------------------------------------------------- if __name__ == '__main__': from datetime",
"tell us the path to the executable instead. self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def",
"in sorted(allGroups.items())] #--------------------------------------------------- # main #--------------------------------------------------- if __name__ == '__main__': from datetime import",
"get CMake to tell us the path to the executable instead. self.launcher =",
"maxKeys, granularity, stomp, CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if",
"granularity, stomp, CONTAINER=container, EXPERIMENT='LOOKUP', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if filter.match(experiment.name):",
"also cached in an intermediate directory, temp, so you can add new results",
"'__main__': from datetime import datetime start = datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter = re.compile((sys.argv +",
"Experiment: \"\"\" A group of CompareIntegerMaps runs using similar options but different seeds.",
"seeds, *args, **kwargs): self.testLauncher = testLauncher self.name = name self.seeds = seeds self.args",
"as a script argument. # For example: run_tests.py LOOKUP_0_.* # Results are also",
"would be cool to get CMake to tell us the path to the",
"# Experiment #--------------------------------------------------- class Experiment: \"\"\" A group of CompareIntegerMaps runs using similar",
"= args self.kwargs = kwargs def run(self, results): allGroups = defaultdict(list) for seed",
"else 1, 0, maxKeys, granularity, 0, CONTAINER=container, EXPERIMENT='MEMORY') if filter.match(experiment.name): experiment.run(results) for stomp",
"an intermediate directory, temp, so you can add new results to results.txt #",
"results.txt. # You can filter the experiments by name by passing a regular",
"# main #--------------------------------------------------- if __name__ == '__main__': from datetime import datetime start =",
"= 200 for container in ['TABLE', 'JUDY']: experiment = Experiment(testLauncher, 'MEMORY_%s' % container,",
"CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results) experiment = Experiment(testLauncher,",
"class TestLauncher: \"\"\" Configures, builds & runs CompareIntegerMaps using the specified options. \"\"\"",
"'--nocache' in sys.argv[1:]: IGNORE_CACHE = True results = {} testLauncher = TestLauncher() maxKeys",
"self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def run(self, seed, operationsPerGroup, keyCount, granularity, stompBytes, **defs): args",
"temp, so you can add new results to results.txt # without redoing previous",
"results = {} testLauncher = TestLauncher() maxKeys = 18000000 granularity = 200 for",
"from datetime import datetime start = datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter = re.compile((sys.argv + ['.*'])[1])",
"defaultdict(list) for seed in xrange(self.seeds): print('Running %s #%d/%d...' % (self.name, seed + 1,",
"import math import os import re import sys from collections import defaultdict from",
"path to the executable instead. self.launcher = cmake_launcher.CMakeLauncher(cmakeBuilder, 'CompareIntegerMaps.exe') def run(self, seed, operationsPerGroup,",
"using the specified options. \"\"\" DEFAULT_DEFS = { 'CACHE_STOMPER_ENABLED': 0, 'EXPERIMENT': 'INSERT', 'CONTAINER':",
"self.seeds)) r = self.testLauncher.run(seed, *self.args, **self.kwargs) for marker, units in r['results']: allGroups[marker].append(units) def",
"self.launcher.ignoreCache = IGNORE_CACHE output = self.launcher.run(*args, **fullDefs) return eval(output) #--------------------------------------------------- # Experiment #---------------------------------------------------",
"output = self.launcher.run(*args, **fullDefs) return eval(output) #--------------------------------------------------- # Experiment #--------------------------------------------------- class Experiment: \"\"\"",
"= sorted(values)[1:-1] return sum(values) / len(values) results[self.name] = [(marker, medianAverage(units)) for marker, units",
"different seeds. \"\"\" def __init__(self, testLauncher, name, seeds, *args, **kwargs): self.testLauncher = testLauncher",
"defaultdict from pprint import pprint #GENERATOR = 'Visual Studio 10' IGNORE_CACHE = False",
"= kwargs def run(self, results): allGroups = defaultdict(list) for seed in xrange(self.seeds): print('Running",
"be cool to get CMake to tell us the path to the executable",
"if filter.match(experiment.name): experiment.run(results) experiment = Experiment(testLauncher, 'LOOKUP_%d_%s' % (stomp, container), 8, 8000, maxKeys,",
"For example: run_tests.py LOOKUP_0_.* # Results are also cached in an intermediate directory,",
"filter.match(experiment.name): experiment.run(results) for stomp in [0, 1000, 10000]: experiment = Experiment(testLauncher, 'INSERT_%d_%s' %",
"xrange(self.seeds): print('Running %s #%d/%d...' % (self.name, seed + 1, self.seeds)) r = self.testLauncher.run(seed,",
"= defaultdict(list) for seed in xrange(self.seeds): print('Running %s #%d/%d...' % (self.name, seed +",
"keyCount, granularity, stompBytes, **defs): args = [seed, operationsPerGroup, keyCount, granularity, stompBytes] mergedDefs =",
"CONTAINER=container, EXPERIMENT='MEMORY') if filter.match(experiment.name): experiment.run(results) for stomp in [0, 1000, 10000]: experiment =",
"return sum(values) / len(values) results[self.name] = [(marker, medianAverage(units)) for marker, units in sorted(allGroups.items())]",
"= TestLauncher() maxKeys = 18000000 granularity = 200 for container in ['TABLE', 'JUDY']:",
"allGroups[marker].append(units) def medianAverage(values): if len(values) >= 4: values = sorted(values)[1:-1] return sum(values) /",
"experiment.run(results) experiment = Experiment(testLauncher, 'LOOKUP_%d_%s' % (stomp, container), 8, 8000, maxKeys, granularity, stomp,",
"#--------------------------------------------------- class TestLauncher: \"\"\" Configures, builds & runs CompareIntegerMaps using the specified options.",
"self.name = name self.seeds = seeds self.args = args self.kwargs = kwargs def",
"if filter.match(experiment.name): experiment.run(results) pprint(results, open('results.txt', 'w')) print('Elapsed time: %s' % (datetime.now() - start))",
"the experiments by name by passing a regular expression as a script argument.",
"'JUDY' else 1, 0, maxKeys, granularity, 0, CONTAINER=container, EXPERIMENT='MEMORY') if filter.match(experiment.name): experiment.run(results) for",
"testLauncher self.name = name self.seeds = seeds self.args = args self.kwargs = kwargs",
"experiments. #--------------------------------------------------- import cmake_launcher import math import os import re import sys from",
"import datetime start = datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter = re.compile((sys.argv + ['.*'])[1]) if '--nocache'",
"CONTAINER=container, EXPERIMENT='INSERT', CACHE_STOMPER_ENABLED=1 if stomp > 0 else 0) if filter.match(experiment.name): experiment.run(results) experiment",
"if '--nocache' in sys.argv[1:]: IGNORE_CACHE = True results = {} testLauncher = TestLauncher()",
"TestLauncher #--------------------------------------------------- class TestLauncher: \"\"\" Configures, builds & runs CompareIntegerMaps using the specified",
"0) if filter.match(experiment.name): experiment.run(results) experiment = Experiment(testLauncher, 'LOOKUP_%d_%s' % (stomp, container), 8, 8000,",
"You can filter the experiments by name by passing a regular expression as",
"for stomp in [0, 1000, 10000]: experiment = Experiment(testLauncher, 'INSERT_%d_%s' % (stomp, container),",
"Perform a bunch of experiments using CompareIntegerMaps.exe, and writes the results to results.txt.",
"Configures, builds & runs CompareIntegerMaps using the specified options. \"\"\" DEFAULT_DEFS = {",
"return eval(output) #--------------------------------------------------- # Experiment #--------------------------------------------------- class Experiment: \"\"\" A group of CompareIntegerMaps",
"# It would be cool to get CMake to tell us the path",
"datetime import datetime start = datetime.now() os.chdir(os.path.split(sys.argv[0])[0]) filter = re.compile((sys.argv + ['.*'])[1]) if"
] |
[
"from abc import ABCMeta, abstractmethod class PersistenceFacade(metaclass=ABCMeta): @abstractmethod def save(self, data, *args, **kwargs):",
"abc import ABCMeta, abstractmethod class PersistenceFacade(metaclass=ABCMeta): @abstractmethod def save(self, data, *args, **kwargs): pass"
] |
[
"Callable, Sequence import sympy as sp # sympy symbols for ray-sphere equations x,",
"def ray_sphere_equations(radius: float) -> list[sp.Eq]: \"\"\" generate a simple system of equations for",
"d) sphere_bound_constraint = sp.Eq( ((x - mx) ** 2 + (y - my)",
"Callable]: \"\"\" produce a dict of functions that return solutions for the ray-sphere",
"collections.abc import Callable, Sequence import sympy as sp # sympy symbols for ray-sphere",
"solutions but could also sensibly contain expressions for bodies of different shapes. \"\"\"",
"((x - mx) ** 2 + (y - my) ** 2 + (z",
"direction vector [x, y, z] and a sphere with radius == 'radius' and",
"intersection solutions but could also sensibly contain expressions for bodies of different shapes.",
"which are fairly slow to evaluate; unless you are planning to further manipulate",
"expressions: Sequence[sp.Expr], expression_names: Sequence[str], variables: Sequence[sp.Symbol], ) -> dict[str, Callable]: \"\"\" returns a",
"expression_name in zip(expressions, expression_names) } def make_ray_sphere_lambdas( radius: float, farside=False ) -> dict[str,",
"= sp.Eq( ((x - mx) ** 2 + (y - my) ** 2",
"my) ** 2 + (z - mz) ** 2) ** (1 / 2),",
"of different shapes. \"\"\" from collections.abc import Callable, Sequence import sympy as sp",
") return [x_constraint, y_constraint, z_constraint, sphere_bound_constraint] def get_ray_sphere_solution( radius: float, farside: bool =",
"z, x0, y0, z0, mx, my, mz, d = sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True )",
"sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True ) def ray_sphere_equations(radius: float) -> list[sp.Eq]: \"\"\" generate a simple",
"mx, my, mz, d = sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True ) def ray_sphere_equations(radius: float) ->",
"sympy expressions objects, which are fairly slow to evaluate; unless you are planning",
"produce a solution to the generalized ray-sphere equation for a body of radius",
"in zip(expressions, expression_names) } def make_ray_sphere_lambdas( radius: float, farside=False ) -> dict[str, Callable]:",
"into the expressions in 'expressions'. 'expression_names' serve as the keys of the dict.",
"-> dict[str, Callable]: \"\"\" returns a dict of functions that substitute the symbols",
"a ray with origin at (0, 0, 0) and direction vector [x, y,",
"nearside solution. this produces a tuple of sympy expressions objects, which are fairly",
"z_constraint = sp.Eq(z, z0 * d) sphere_bound_constraint = sp.Eq( ((x - mx) **",
"mz, d = sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True ) def ray_sphere_equations(radius: float) -> list[sp.Eq]: \"\"\"",
"ray-sphere equations x, y, z, x0, y0, z0, mx, my, mz, d =",
"the ray-sphere equation for a sphere of radius `radius`. \"\"\" return lambdify_system( get_ray_sphere_solution(radius,",
"of the dict. \"\"\" return { expression_name: sp.lambdify(variables, expression, \"numpy\") for expression, expression_name",
"if farside: selected_solution = 1 general_solution = sp.solve(ray_sphere_equations(radius), [x, y, z, d])[ selected_solution",
"d) z_constraint = sp.Eq(z, z0 * d) sphere_bound_constraint = sp.Eq( ((x - mx)",
"planning to further manipulate them, you would probably rather call make_ray_sphere_lambdas(). \"\"\" #",
"bodies of different shapes. \"\"\" from collections.abc import Callable, Sequence import sympy as",
"them, you would probably rather call make_ray_sphere_lambdas(). \"\"\" # sp.solve() returns the nearside",
"d])[ selected_solution ] return general_solution def lambdify_system( expressions: Sequence[sp.Expr], expression_names: Sequence[str], variables: Sequence[sp.Symbol],",
"** 2 + (y - my) ** 2 + (z - mz) **",
"and center (mx, my, mz). \"\"\" x_constraint = sp.Eq(x, x0 * d) y_constraint",
"Sequence[sp.Symbol], ) -> dict[str, Callable]: \"\"\" returns a dict of functions that substitute",
"d) y_constraint = sp.Eq(y, y0 * d) z_constraint = sp.Eq(z, z0 * d)",
"the symbols in 'variables' into the expressions in 'expressions'. 'expression_names' serve as the",
"contain expressions for bodies of different shapes. \"\"\" from collections.abc import Callable, Sequence",
"a dict of functions that return solutions for the ray-sphere equation for a",
") -> dict[str, Callable]: \"\"\" returns a dict of functions that substitute the",
"shapes. \"\"\" from collections.abc import Callable, Sequence import sympy as sp # sympy",
"radius `radius`. \"\"\" return lambdify_system( get_ray_sphere_solution(radius, farside), [\"x\", \"y\", \"z\", \"d\"], [x0, y0,",
"sp.solve(ray_sphere_equations(radius), [x, y, z, d])[ selected_solution ] return general_solution def lambdify_system( expressions: Sequence[sp.Expr],",
"\"\"\" from collections.abc import Callable, Sequence import sympy as sp # sympy symbols",
"= sp.Eq(z, z0 * d) sphere_bound_constraint = sp.Eq( ((x - mx) ** 2",
"default, take the nearside solution. this produces a tuple of sympy expressions objects,",
"slow to evaluate; unless you are planning to further manipulate them, you would",
"farside: bool = False ) -> tuple[sp.Expr]: \"\"\" produce a solution to the",
"from collections.abc import Callable, Sequence import sympy as sp # sympy symbols for",
"equation for a body of radius `radius`. by default, take the nearside solution.",
"return [x_constraint, y_constraint, z_constraint, sphere_bound_constraint] def get_ray_sphere_solution( radius: float, farside: bool = False",
"for ray-sphere equations x, y, z, x0, y0, z0, mx, my, mz, d",
"radius `radius`. by default, take the nearside solution. this produces a tuple of",
"return lambdify_system( get_ray_sphere_solution(radius, farside), [\"x\", \"y\", \"z\", \"d\"], [x0, y0, z0, mx, my,",
"between a ray with origin at (0, 0, 0) and direction vector [x,",
"of sympy expressions objects, which are fairly slow to evaluate; unless you are",
"float, farside: bool = False ) -> tuple[sp.Expr]: \"\"\" produce a solution to",
"sphere with radius == 'radius' and center (mx, my, mz). \"\"\" x_constraint =",
"general_solution = sp.solve(ray_sphere_equations(radius), [x, y, z, d])[ selected_solution ] return general_solution def lambdify_system(",
"- mx) ** 2 + (y - my) ** 2 + (z -",
"probably rather call make_ray_sphere_lambdas(). \"\"\" # sp.solve() returns the nearside solution first selected_solution",
"dict of functions that return solutions for the ray-sphere equation for a sphere",
"x0 * d) y_constraint = sp.Eq(y, y0 * d) z_constraint = sp.Eq(z, z0",
"= sp.solve(ray_sphere_equations(radius), [x, y, z, d])[ selected_solution ] return general_solution def lambdify_system( expressions:",
"of functions that return solutions for the ray-sphere equation for a sphere of",
"equations for intersections between a ray with origin at (0, 0, 0) and",
"'expressions'. 'expression_names' serve as the keys of the dict. \"\"\" return { expression_name:",
"selected_solution = 0 if farside: selected_solution = 1 general_solution = sp.solve(ray_sphere_equations(radius), [x, y,",
"further manipulate them, you would probably rather call make_ray_sphere_lambdas(). \"\"\" # sp.solve() returns",
"1 general_solution = sp.solve(ray_sphere_equations(radius), [x, y, z, d])[ selected_solution ] return general_solution def",
"functions that return solutions for the ray-sphere equation for a sphere of radius",
"as the keys of the dict. \"\"\" return { expression_name: sp.lambdify(variables, expression, \"numpy\")",
"for solving body-intersection problems. used by `lhorizon.targeter`. currently contains only ray-sphere intersection solutions",
"`radius`. \"\"\" return lambdify_system( get_ray_sphere_solution(radius, farside), [\"x\", \"y\", \"z\", \"d\"], [x0, y0, z0,",
"\"\"\" produce a solution to the generalized ray-sphere equation for a body of",
"return solutions for the ray-sphere equation for a sphere of radius `radius`. \"\"\"",
"(mx, my, mz). \"\"\" x_constraint = sp.Eq(x, x0 * d) y_constraint = sp.Eq(y,",
"ray-sphere equation for a sphere of radius `radius`. \"\"\" return lambdify_system( get_ray_sphere_solution(radius, farside),",
"generalized ray-sphere equation for a body of radius `radius`. by default, take the",
"would probably rather call make_ray_sphere_lambdas(). \"\"\" # sp.solve() returns the nearside solution first",
"radius ) return [x_constraint, y_constraint, z_constraint, sphere_bound_constraint] def get_ray_sphere_solution( radius: float, farside: bool",
"vector [x, y, z] and a sphere with radius == 'radius' and center",
"== 'radius' and center (mx, my, mz). \"\"\" x_constraint = sp.Eq(x, x0 *",
"radius == 'radius' and center (mx, my, mz). \"\"\" x_constraint = sp.Eq(x, x0",
"mz) ** 2) ** (1 / 2), radius ) return [x_constraint, y_constraint, z_constraint,",
"] return general_solution def lambdify_system( expressions: Sequence[sp.Expr], expression_names: Sequence[str], variables: Sequence[sp.Symbol], ) ->",
"origin at (0, 0, 0) and direction vector [x, y, z] and a",
"generate a simple system of equations for intersections between a ray with origin",
"and direction vector [x, y, z] and a sphere with radius == 'radius'",
"y_constraint = sp.Eq(y, y0 * d) z_constraint = sp.Eq(z, z0 * d) sphere_bound_constraint",
"# sp.solve() returns the nearside solution first selected_solution = 0 if farside: selected_solution",
"used by `lhorizon.targeter`. currently contains only ray-sphere intersection solutions but could also sensibly",
"list[sp.Eq]: \"\"\" generate a simple system of equations for intersections between a ray",
"to the generalized ray-sphere equation for a body of radius `radius`. by default,",
"the expressions in 'expressions'. 'expression_names' serve as the keys of the dict. \"\"\"",
"for bodies of different shapes. \"\"\" from collections.abc import Callable, Sequence import sympy",
"are planning to further manipulate them, you would probably rather call make_ray_sphere_lambdas(). \"\"\"",
"+ (z - mz) ** 2) ** (1 / 2), radius ) return",
"a tuple of sympy expressions objects, which are fairly slow to evaluate; unless",
"for expression, expression_name in zip(expressions, expression_names) } def make_ray_sphere_lambdas( radius: float, farside=False )",
"z_constraint, sphere_bound_constraint] def get_ray_sphere_solution( radius: float, farside: bool = False ) -> tuple[sp.Expr]:",
"[x, y, z, d])[ selected_solution ] return general_solution def lambdify_system( expressions: Sequence[sp.Expr], expression_names:",
"intersections between a ray with origin at (0, 0, 0) and direction vector",
"0 if farside: selected_solution = 1 general_solution = sp.solve(ray_sphere_equations(radius), [x, y, z, d])[",
"of equations for intersections between a ray with origin at (0, 0, 0)",
"* d) z_constraint = sp.Eq(z, z0 * d) sphere_bound_constraint = sp.Eq( ((x -",
"\"\"\" x_constraint = sp.Eq(x, x0 * d) y_constraint = sp.Eq(y, y0 * d)",
"also sensibly contain expressions for bodies of different shapes. \"\"\" from collections.abc import",
"sp.lambdify(variables, expression, \"numpy\") for expression, expression_name in zip(expressions, expression_names) } def make_ray_sphere_lambdas( radius:",
"mx) ** 2 + (y - my) ** 2 + (z - mz)",
"(y - my) ** 2 + (z - mz) ** 2) ** (1",
"sp # sympy symbols for ray-sphere equations x, y, z, x0, y0, z0,",
"tuple of sympy expressions objects, which are fairly slow to evaluate; unless you",
"keys of the dict. \"\"\" return { expression_name: sp.lambdify(variables, expression, \"numpy\") for expression,",
"= False ) -> tuple[sp.Expr]: \"\"\" produce a solution to the generalized ray-sphere",
"you are planning to further manipulate them, you would probably rather call make_ray_sphere_lambdas().",
"take the nearside solution. this produces a tuple of sympy expressions objects, which",
"expressions objects, which are fairly slow to evaluate; unless you are planning to",
"a dict of functions that substitute the symbols in 'variables' into the expressions",
"sp.Eq(y, y0 * d) z_constraint = sp.Eq(z, z0 * d) sphere_bound_constraint = sp.Eq(",
"`radius`. by default, take the nearside solution. this produces a tuple of sympy",
"farside: selected_solution = 1 general_solution = sp.solve(ray_sphere_equations(radius), [x, y, z, d])[ selected_solution ]",
"float, farside=False ) -> dict[str, Callable]: \"\"\" produce a dict of functions that",
"tuple[sp.Expr]: \"\"\" produce a solution to the generalized ray-sphere equation for a body",
"y, z, d])[ selected_solution ] return general_solution def lambdify_system( expressions: Sequence[sp.Expr], expression_names: Sequence[str],",
"simple system of equations for intersections between a ray with origin at (0,",
"-> tuple[sp.Expr]: \"\"\" produce a solution to the generalized ray-sphere equation for a",
"z0 * d) sphere_bound_constraint = sp.Eq( ((x - mx) ** 2 + (y",
"selected_solution ] return general_solution def lambdify_system( expressions: Sequence[sp.Expr], expression_names: Sequence[str], variables: Sequence[sp.Symbol], )",
"general_solution def lambdify_system( expressions: Sequence[sp.Expr], expression_names: Sequence[str], variables: Sequence[sp.Symbol], ) -> dict[str, Callable]:",
"`lhorizon.targeter`. currently contains only ray-sphere intersection solutions but could also sensibly contain expressions",
"z, d])[ selected_solution ] return general_solution def lambdify_system( expressions: Sequence[sp.Expr], expression_names: Sequence[str], variables:",
"Sequence[sp.Expr], expression_names: Sequence[str], variables: Sequence[sp.Symbol], ) -> dict[str, Callable]: \"\"\" returns a dict",
"** 2) ** (1 / 2), radius ) return [x_constraint, y_constraint, z_constraint, sphere_bound_constraint]",
"that substitute the symbols in 'variables' into the expressions in 'expressions'. 'expression_names' serve",
"rather call make_ray_sphere_lambdas(). \"\"\" # sp.solve() returns the nearside solution first selected_solution =",
"solution to the generalized ray-sphere equation for a body of radius `radius`. by",
"x_constraint = sp.Eq(x, x0 * d) y_constraint = sp.Eq(y, y0 * d) z_constraint",
"expressions in 'expressions'. 'expression_names' serve as the keys of the dict. \"\"\" return",
"make_ray_sphere_lambdas( radius: float, farside=False ) -> dict[str, Callable]: \"\"\" produce a dict of",
"+ (y - my) ** 2 + (z - mz) ** 2) **",
"returns a dict of functions that substitute the symbols in 'variables' into the",
"sp.solve() returns the nearside solution first selected_solution = 0 if farside: selected_solution =",
"\"\"\" returns a dict of functions that substitute the symbols in 'variables' into",
"and a sphere with radius == 'radius' and center (mx, my, mz). \"\"\"",
"z] and a sphere with radius == 'radius' and center (mx, my, mz).",
"y, z] and a sphere with radius == 'radius' and center (mx, my,",
"'variables' into the expressions in 'expressions'. 'expression_names' serve as the keys of the",
"sp.Eq(x, x0 * d) y_constraint = sp.Eq(y, y0 * d) z_constraint = sp.Eq(z,",
"sphere_bound_constraint] def get_ray_sphere_solution( radius: float, farside: bool = False ) -> tuple[sp.Expr]: \"\"\"",
"(1 / 2), radius ) return [x_constraint, y_constraint, z_constraint, sphere_bound_constraint] def get_ray_sphere_solution( radius:",
"returns the nearside solution first selected_solution = 0 if farside: selected_solution = 1",
"y0, z0, mx, my, mz, d = sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True ) def ray_sphere_equations(radius:",
"only ray-sphere intersection solutions but could also sensibly contain expressions for bodies of",
"of radius `radius`. \"\"\" return lambdify_system( get_ray_sphere_solution(radius, farside), [\"x\", \"y\", \"z\", \"d\"], [x0,",
"solutions for the ray-sphere equation for a sphere of radius `radius`. \"\"\" return",
"\"\"\" return { expression_name: sp.lambdify(variables, expression, \"numpy\") for expression, expression_name in zip(expressions, expression_names)",
"variables: Sequence[sp.Symbol], ) -> dict[str, Callable]: \"\"\" returns a dict of functions that",
"objects, which are fairly slow to evaluate; unless you are planning to further",
"my, mz). \"\"\" x_constraint = sp.Eq(x, x0 * d) y_constraint = sp.Eq(y, y0",
"a sphere with radius == 'radius' and center (mx, my, mz). \"\"\" x_constraint",
"lambdify_system( expressions: Sequence[sp.Expr], expression_names: Sequence[str], variables: Sequence[sp.Symbol], ) -> dict[str, Callable]: \"\"\" returns",
"in 'expressions'. 'expression_names' serve as the keys of the dict. \"\"\" return {",
"expression_names) } def make_ray_sphere_lambdas( radius: float, farside=False ) -> dict[str, Callable]: \"\"\" produce",
"def get_ray_sphere_solution( radius: float, farside: bool = False ) -> tuple[sp.Expr]: \"\"\" produce",
"the dict. \"\"\" return { expression_name: sp.lambdify(variables, expression, \"numpy\") for expression, expression_name in",
"as sp # sympy symbols for ray-sphere equations x, y, z, x0, y0,",
"\"\"\" # sp.solve() returns the nearside solution first selected_solution = 0 if farside:",
"equation for a sphere of radius `radius`. \"\"\" return lambdify_system( get_ray_sphere_solution(radius, farside), [\"x\",",
"2 + (y - my) ** 2 + (z - mz) ** 2)",
"make_ray_sphere_lambdas(). \"\"\" # sp.solve() returns the nearside solution first selected_solution = 0 if",
"\"\"\" produce a dict of functions that return solutions for the ray-sphere equation",
"unless you are planning to further manipulate them, you would probably rather call",
"Sequence[str], variables: Sequence[sp.Symbol], ) -> dict[str, Callable]: \"\"\" returns a dict of functions",
"** (1 / 2), radius ) return [x_constraint, y_constraint, z_constraint, sphere_bound_constraint] def get_ray_sphere_solution(",
"expression_names: Sequence[str], variables: Sequence[sp.Symbol], ) -> dict[str, Callable]: \"\"\" returns a dict of",
"Sequence import sympy as sp # sympy symbols for ray-sphere equations x, y,",
"that return solutions for the ray-sphere equation for a sphere of radius `radius`.",
"produce a dict of functions that return solutions for the ray-sphere equation for",
"manipulate them, you would probably rather call make_ray_sphere_lambdas(). \"\"\" # sp.solve() returns the",
"first selected_solution = 0 if farside: selected_solution = 1 general_solution = sp.solve(ray_sphere_equations(radius), [x,",
"radius: float, farside=False ) -> dict[str, Callable]: \"\"\" produce a dict of functions",
"return general_solution def lambdify_system( expressions: Sequence[sp.Expr], expression_names: Sequence[str], variables: Sequence[sp.Symbol], ) -> dict[str,",
"radius: float, farside: bool = False ) -> tuple[sp.Expr]: \"\"\" produce a solution",
"= 0 if farside: selected_solution = 1 general_solution = sp.solve(ray_sphere_equations(radius), [x, y, z,",
"{ expression_name: sp.lambdify(variables, expression, \"numpy\") for expression, expression_name in zip(expressions, expression_names) } def",
"different shapes. \"\"\" from collections.abc import Callable, Sequence import sympy as sp #",
"2 + (z - mz) ** 2) ** (1 / 2), radius )",
"} def make_ray_sphere_lambdas( radius: float, farside=False ) -> dict[str, Callable]: \"\"\" produce a",
"'radius' and center (mx, my, mz). \"\"\" x_constraint = sp.Eq(x, x0 * d)",
"of radius `radius`. by default, take the nearside solution. this produces a tuple",
"serve as the keys of the dict. \"\"\" return { expression_name: sp.lambdify(variables, expression,",
"sp.Eq(z, z0 * d) sphere_bound_constraint = sp.Eq( ((x - mx) ** 2 +",
"x0, y0, z0, mx, my, mz, d = sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True ) def",
"** 2 + (z - mz) ** 2) ** (1 / 2), radius",
"for a body of radius `radius`. by default, take the nearside solution. this",
"are fairly slow to evaluate; unless you are planning to further manipulate them,",
"you would probably rather call make_ray_sphere_lambdas(). \"\"\" # sp.solve() returns the nearside solution",
"my, mz, d = sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True ) def ray_sphere_equations(radius: float) -> list[sp.Eq]:",
"contains only ray-sphere intersection solutions but could also sensibly contain expressions for bodies",
"def lambdify_system( expressions: Sequence[sp.Expr], expression_names: Sequence[str], variables: Sequence[sp.Symbol], ) -> dict[str, Callable]: \"\"\"",
"False ) -> tuple[sp.Expr]: \"\"\" produce a solution to the generalized ray-sphere equation",
"farside=False ) -> dict[str, Callable]: \"\"\" produce a dict of functions that return",
"but could also sensibly contain expressions for bodies of different shapes. \"\"\" from",
"for the ray-sphere equation for a sphere of radius `radius`. \"\"\" return lambdify_system(",
"y_constraint, z_constraint, sphere_bound_constraint] def get_ray_sphere_solution( radius: float, farside: bool = False ) ->",
"'expression_names' serve as the keys of the dict. \"\"\" return { expression_name: sp.lambdify(variables,",
") -> dict[str, Callable]: \"\"\" produce a dict of functions that return solutions",
"for intersections between a ray with origin at (0, 0, 0) and direction",
"body of radius `radius`. by default, take the nearside solution. this produces a",
"\"numpy\") for expression, expression_name in zip(expressions, expression_names) } def make_ray_sphere_lambdas( radius: float, farside=False",
") -> tuple[sp.Expr]: \"\"\" produce a solution to the generalized ray-sphere equation for",
"sp.Eq( ((x - mx) ** 2 + (y - my) ** 2 +",
"solution first selected_solution = 0 if farside: selected_solution = 1 general_solution = sp.solve(ray_sphere_equations(radius),",
"= sp.Eq(y, y0 * d) z_constraint = sp.Eq(z, z0 * d) sphere_bound_constraint =",
"[x_constraint, y_constraint, z_constraint, sphere_bound_constraint] def get_ray_sphere_solution( radius: float, farside: bool = False )",
"functionality for solving body-intersection problems. used by `lhorizon.targeter`. currently contains only ray-sphere intersection",
"call make_ray_sphere_lambdas(). \"\"\" # sp.solve() returns the nearside solution first selected_solution = 0",
"real=True ) def ray_sphere_equations(radius: float) -> list[sp.Eq]: \"\"\" generate a simple system of",
"\"\"\" return lambdify_system( get_ray_sphere_solution(radius, farside), [\"x\", \"y\", \"z\", \"d\"], [x0, y0, z0, mx,",
"- mz) ** 2) ** (1 / 2), radius ) return [x_constraint, y_constraint,",
"dict. \"\"\" return { expression_name: sp.lambdify(variables, expression, \"numpy\") for expression, expression_name in zip(expressions,",
"ray-sphere equation for a body of radius `radius`. by default, take the nearside",
"expression, expression_name in zip(expressions, expression_names) } def make_ray_sphere_lambdas( radius: float, farside=False ) ->",
"2) ** (1 / 2), radius ) return [x_constraint, y_constraint, z_constraint, sphere_bound_constraint] def",
"return { expression_name: sp.lambdify(variables, expression, \"numpy\") for expression, expression_name in zip(expressions, expression_names) }",
") def ray_sphere_equations(radius: float) -> list[sp.Eq]: \"\"\" generate a simple system of equations",
"expression, \"numpy\") for expression, expression_name in zip(expressions, expression_names) } def make_ray_sphere_lambdas( radius: float,",
"produces a tuple of sympy expressions objects, which are fairly slow to evaluate;",
"d = sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True ) def ray_sphere_equations(radius: float) -> list[sp.Eq]: \"\"\" generate",
"Callable]: \"\"\" returns a dict of functions that substitute the symbols in 'variables'",
"at (0, 0, 0) and direction vector [x, y, z] and a sphere",
"by default, take the nearside solution. this produces a tuple of sympy expressions",
"# sympy symbols for ray-sphere equations x, y, z, x0, y0, z0, mx,",
"with origin at (0, 0, 0) and direction vector [x, y, z] and",
"currently contains only ray-sphere intersection solutions but could also sensibly contain expressions for",
"ray with origin at (0, 0, 0) and direction vector [x, y, z]",
"import Callable, Sequence import sympy as sp # sympy symbols for ray-sphere equations",
"z0, mx, my, mz, d = sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True ) def ray_sphere_equations(radius: float)",
"-> dict[str, Callable]: \"\"\" produce a dict of functions that return solutions for",
"dict[str, Callable]: \"\"\" produce a dict of functions that return solutions for the",
"the nearside solution. this produces a tuple of sympy expressions objects, which are",
"sphere of radius `radius`. \"\"\" return lambdify_system( get_ray_sphere_solution(radius, farside), [\"x\", \"y\", \"z\", \"d\"],",
"solution. this produces a tuple of sympy expressions objects, which are fairly slow",
"* d) sphere_bound_constraint = sp.Eq( ((x - mx) ** 2 + (y -",
"sphere_bound_constraint = sp.Eq( ((x - mx) ** 2 + (y - my) **",
"2), radius ) return [x_constraint, y_constraint, z_constraint, sphere_bound_constraint] def get_ray_sphere_solution( radius: float, farside:",
"def make_ray_sphere_lambdas( radius: float, farside=False ) -> dict[str, Callable]: \"\"\" produce a dict",
"to further manipulate them, you would probably rather call make_ray_sphere_lambdas(). \"\"\" # sp.solve()",
"- my) ** 2 + (z - mz) ** 2) ** (1 /",
"dict of functions that substitute the symbols in 'variables' into the expressions in",
"expression_name: sp.lambdify(variables, expression, \"numpy\") for expression, expression_name in zip(expressions, expression_names) } def make_ray_sphere_lambdas(",
"solving body-intersection problems. used by `lhorizon.targeter`. currently contains only ray-sphere intersection solutions but",
"float) -> list[sp.Eq]: \"\"\" generate a simple system of equations for intersections between",
"import sympy as sp # sympy symbols for ray-sphere equations x, y, z,",
"nearside solution first selected_solution = 0 if farside: selected_solution = 1 general_solution =",
"(z - mz) ** 2) ** (1 / 2), radius ) return [x_constraint,",
"ray_sphere_equations(radius: float) -> list[sp.Eq]: \"\"\" generate a simple system of equations for intersections",
"get_ray_sphere_solution( radius: float, farside: bool = False ) -> tuple[sp.Expr]: \"\"\" produce a",
"sensibly contain expressions for bodies of different shapes. \"\"\" from collections.abc import Callable,",
"ray-sphere intersection solutions but could also sensibly contain expressions for bodies of different",
"\"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True ) def ray_sphere_equations(radius: float) -> list[sp.Eq]: \"\"\" generate a simple system",
"fairly slow to evaluate; unless you are planning to further manipulate them, you",
"sympy as sp # sympy symbols for ray-sphere equations x, y, z, x0,",
"\"\"\" generate a simple system of equations for intersections between a ray with",
"mz). \"\"\" x_constraint = sp.Eq(x, x0 * d) y_constraint = sp.Eq(y, y0 *",
"functions that substitute the symbols in 'variables' into the expressions in 'expressions'. 'expression_names'",
"body-intersection problems. used by `lhorizon.targeter`. currently contains only ray-sphere intersection solutions but could",
"sympy symbols for ray-sphere equations x, y, z, x0, y0, z0, mx, my,",
"expressions for bodies of different shapes. \"\"\" from collections.abc import Callable, Sequence import",
"problems. used by `lhorizon.targeter`. currently contains only ray-sphere intersection solutions but could also",
"selected_solution = 1 general_solution = sp.solve(ray_sphere_equations(radius), [x, y, z, d])[ selected_solution ] return",
"/ 2), radius ) return [x_constraint, y_constraint, z_constraint, sphere_bound_constraint] def get_ray_sphere_solution( radius: float,",
"-> list[sp.Eq]: \"\"\" generate a simple system of equations for intersections between a",
"symbols in 'variables' into the expressions in 'expressions'. 'expression_names' serve as the keys",
"evaluate; unless you are planning to further manipulate them, you would probably rather",
"* d) y_constraint = sp.Eq(y, y0 * d) z_constraint = sp.Eq(z, z0 *",
"bool = False ) -> tuple[sp.Expr]: \"\"\" produce a solution to the generalized",
"= sp.Eq(x, x0 * d) y_constraint = sp.Eq(y, y0 * d) z_constraint =",
"with radius == 'radius' and center (mx, my, mz). \"\"\" x_constraint = sp.Eq(x,",
"get_ray_sphere_solution(radius, farside), [\"x\", \"y\", \"z\", \"d\"], [x0, y0, z0, mx, my, mz], )",
"0) and direction vector [x, y, z] and a sphere with radius ==",
"symbols for ray-sphere equations x, y, z, x0, y0, z0, mx, my, mz,",
"center (mx, my, mz). \"\"\" x_constraint = sp.Eq(x, x0 * d) y_constraint =",
"= 1 general_solution = sp.solve(ray_sphere_equations(radius), [x, y, z, d])[ selected_solution ] return general_solution",
"a simple system of equations for intersections between a ray with origin at",
"a solution to the generalized ray-sphere equation for a body of radius `radius`.",
"the nearside solution first selected_solution = 0 if farside: selected_solution = 1 general_solution",
"a body of radius `radius`. by default, take the nearside solution. this produces",
"by `lhorizon.targeter`. currently contains only ray-sphere intersection solutions but could also sensibly contain",
"equations x, y, z, x0, y0, z0, mx, my, mz, d = sp.symbols(",
"could also sensibly contain expressions for bodies of different shapes. \"\"\" from collections.abc",
"dict[str, Callable]: \"\"\" returns a dict of functions that substitute the symbols in",
"zip(expressions, expression_names) } def make_ray_sphere_lambdas( radius: float, farside=False ) -> dict[str, Callable]: \"\"\"",
"= sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True ) def ray_sphere_equations(radius: float) -> list[sp.Eq]: \"\"\" generate a",
"of functions that substitute the symbols in 'variables' into the expressions in 'expressions'.",
"[x, y, z] and a sphere with radius == 'radius' and center (mx,",
"substitute the symbols in 'variables' into the expressions in 'expressions'. 'expression_names' serve as",
"y, z, x0, y0, z0, mx, my, mz, d = sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\", real=True",
"the generalized ray-sphere equation for a body of radius `radius`. by default, take",
"\"\"\" functionality for solving body-intersection problems. used by `lhorizon.targeter`. currently contains only ray-sphere",
"in 'variables' into the expressions in 'expressions'. 'expression_names' serve as the keys of",
"a sphere of radius `radius`. \"\"\" return lambdify_system( get_ray_sphere_solution(radius, farside), [\"x\", \"y\", \"z\",",
"x, y, z, x0, y0, z0, mx, my, mz, d = sp.symbols( \"x,y,z,x0,y0,z0,m_x,m_y,m_z,d\",",
"the keys of the dict. \"\"\" return { expression_name: sp.lambdify(variables, expression, \"numpy\") for",
"y0 * d) z_constraint = sp.Eq(z, z0 * d) sphere_bound_constraint = sp.Eq( ((x",
"this produces a tuple of sympy expressions objects, which are fairly slow to",
"system of equations for intersections between a ray with origin at (0, 0,",
"to evaluate; unless you are planning to further manipulate them, you would probably",
"(0, 0, 0) and direction vector [x, y, z] and a sphere with",
"0, 0) and direction vector [x, y, z] and a sphere with radius",
"for a sphere of radius `radius`. \"\"\" return lambdify_system( get_ray_sphere_solution(radius, farside), [\"x\", \"y\",",
"lambdify_system( get_ray_sphere_solution(radius, farside), [\"x\", \"y\", \"z\", \"d\"], [x0, y0, z0, mx, my, mz],"
] |
[
"<reponame>mattwalstra/2019RobotCode<filename>videoFeedStuff/UDPRecieverTest.py import socket import cv2 UDP_IP = \"127.0.0.1\" UDP_PORT = 5005 sock= socket.socket(socket.AF_INET,",
"UDP_PORT = 5005 sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP,UDP_PORT)) while True: data, addr = sock.recvfrom(1024)",
"import socket import cv2 UDP_IP = \"127.0.0.1\" UDP_PORT = 5005 sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)",
"5005 sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP,UDP_PORT)) while True: data, addr = sock.recvfrom(1024) print data",
"\"127.0.0.1\" UDP_PORT = 5005 sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP,UDP_PORT)) while True: data, addr =",
"UDP_IP = \"127.0.0.1\" UDP_PORT = 5005 sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP,UDP_PORT)) while True: data,",
"= \"127.0.0.1\" UDP_PORT = 5005 sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP,UDP_PORT)) while True: data, addr",
"= 5005 sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP,UDP_PORT)) while True: data, addr = sock.recvfrom(1024) print",
"socket import cv2 UDP_IP = \"127.0.0.1\" UDP_PORT = 5005 sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP,UDP_PORT))",
"import cv2 UDP_IP = \"127.0.0.1\" UDP_PORT = 5005 sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP,UDP_PORT)) while",
"cv2 UDP_IP = \"127.0.0.1\" UDP_PORT = 5005 sock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP,UDP_PORT)) while True:"
] |
[
"import db from .user import User from .repository import Repository from .card import",
".base import db from .user import User from .repository import Repository from .card",
"from .user import User from .repository import Repository from .card import Card from",
"from .repository import Repository from .card import Card from .course import Course from",
"import Repository from .card import Card from .course import Course from .course_card_progress import",
"import Card from .course import Course from .course_card_progress import CourseCardProgress def init_app(app): db.init_app(app)",
".repository import Repository from .card import Card from .course import Course from .course_card_progress",
"User from .repository import Repository from .card import Card from .course import Course",
".user import User from .repository import Repository from .card import Card from .course",
"Repository from .card import Card from .course import Course from .course_card_progress import CourseCardProgress",
"db from .user import User from .repository import Repository from .card import Card",
"from .base import db from .user import User from .repository import Repository from",
"import User from .repository import Repository from .card import Card from .course import",
"from .card import Card from .course import Course from .course_card_progress import CourseCardProgress def",
".card import Card from .course import Course from .course_card_progress import CourseCardProgress def init_app(app):"
] |
[
"values are computed once, then re-used. # https://blog.csdn.net/x_r_su/article/details/54730654 class MyList: def __init__(self, init_list=[]):",
"class MyList: def __init__(self, init_list=[]): self.list = init_list print(id(init_list)) def add(self, ele): self.list.append(ele)",
"add(self, ele): self.list.append(ele) def appender(ele): # obj = MyList() obj = MyList(init_list=[]) obj.add(ele)",
"def add(self, ele): self.list.append(ele) def appender(ele): # obj = MyList() obj = MyList(init_list=[])",
"# obj = MyList() obj = MyList(init_list=[]) obj.add(ele) print(obj.list) if __name__ == '__main__':",
"ele): self.list.append(ele) def appender(ele): # obj = MyList() obj = MyList(init_list=[]) obj.add(ele) print(obj.list)",
"# https://blog.csdn.net/x_r_su/article/details/54730654 class MyList: def __init__(self, init_list=[]): self.list = init_list print(id(init_list)) def add(self,",
"def appender(ele): # obj = MyList() obj = MyList(init_list=[]) obj.add(ele) print(obj.list) if __name__",
"obj = MyList(init_list=[]) obj.add(ele) print(obj.list) if __name__ == '__main__': print('start') for i in",
"self.list.append(ele) def appender(ele): # obj = MyList() obj = MyList(init_list=[]) obj.add(ele) print(obj.list) if",
"computed once, then re-used. # https://blog.csdn.net/x_r_su/article/details/54730654 class MyList: def __init__(self, init_list=[]): self.list =",
"= MyList() obj = MyList(init_list=[]) obj.add(ele) print(obj.list) if __name__ == '__main__': print('start') for",
"init_list=[]): self.list = init_list print(id(init_list)) def add(self, ele): self.list.append(ele) def appender(ele): # obj",
"https://blog.csdn.net/x_r_su/article/details/54730654 class MyList: def __init__(self, init_list=[]): self.list = init_list print(id(init_list)) def add(self, ele):",
"init_list print(id(init_list)) def add(self, ele): self.list.append(ele) def appender(ele): # obj = MyList() obj",
"print(id(init_list)) def add(self, ele): self.list.append(ele) def appender(ele): # obj = MyList() obj =",
"Default values are computed once, then re-used. # https://blog.csdn.net/x_r_su/article/details/54730654 class MyList: def __init__(self,",
"appender(ele): # obj = MyList() obj = MyList(init_list=[]) obj.add(ele) print(obj.list) if __name__ ==",
"# Default values are computed once, then re-used. # https://blog.csdn.net/x_r_su/article/details/54730654 class MyList: def",
"def __init__(self, init_list=[]): self.list = init_list print(id(init_list)) def add(self, ele): self.list.append(ele) def appender(ele):",
"__init__(self, init_list=[]): self.list = init_list print(id(init_list)) def add(self, ele): self.list.append(ele) def appender(ele): #",
"then re-used. # https://blog.csdn.net/x_r_su/article/details/54730654 class MyList: def __init__(self, init_list=[]): self.list = init_list print(id(init_list))",
"MyList() obj = MyList(init_list=[]) obj.add(ele) print(obj.list) if __name__ == '__main__': print('start') for i",
"are computed once, then re-used. # https://blog.csdn.net/x_r_su/article/details/54730654 class MyList: def __init__(self, init_list=[]): self.list",
"= init_list print(id(init_list)) def add(self, ele): self.list.append(ele) def appender(ele): # obj = MyList()",
"obj = MyList() obj = MyList(init_list=[]) obj.add(ele) print(obj.list) if __name__ == '__main__': print('start')",
"once, then re-used. # https://blog.csdn.net/x_r_su/article/details/54730654 class MyList: def __init__(self, init_list=[]): self.list = init_list",
"re-used. # https://blog.csdn.net/x_r_su/article/details/54730654 class MyList: def __init__(self, init_list=[]): self.list = init_list print(id(init_list)) def",
"MyList: def __init__(self, init_list=[]): self.list = init_list print(id(init_list)) def add(self, ele): self.list.append(ele) def",
"self.list = init_list print(id(init_list)) def add(self, ele): self.list.append(ele) def appender(ele): # obj =",
"MyList(init_list=[]) obj.add(ele) print(obj.list) if __name__ == '__main__': print('start') for i in range(5): appender(i)",
"= MyList(init_list=[]) obj.add(ele) print(obj.list) if __name__ == '__main__': print('start') for i in range(5):"
] |
[
"code, tutorials ## >MetaKeywords: python functions, function with parameters, function with return value",
"Before passing to function, source_list: ['A', 'B', 'C'] # Input List: ['A', 'B',",
">## Python Global and Local Variables ## >* **Global Variable** is accessable from",
"List: ', in_list) # End of function code: function_pass_by_value print('Before passing by value",
"accessable inside the function as well. ## >* **Local Variable** are variables inside",
"outside function: ', MyVar) ## >``` ## >## Pass by Reference ## >*",
"Pass by Value ## >* The parameter passed in is actually a reference",
"as well. ## >* **Local Variable** are variables inside a function, They are",
"to a variable (but ## > the reference is passed by value) ##",
"', in_list) # Reassigning a local value, [pass by value example] in_list =[1,",
"is reflected outside the call too. ## >``` # Create a source list",
"the \"source_list\" and NOT A COPY of the \"source_list\" function_pass_by_value(source_list_2) print('After passing by",
"parameter ## > value changed inside the function is reflected outside the call",
"to function, source_list: ', source_list_2) # Passing the \"source_list\" and NOT A COPY",
">MetaKeywords: python functions, function with parameters, function with return value example code, tutorials",
"Variable MyVar = 'This is a local variable' print('Value of MyVar inside function:",
"in a function and not outside the function. ## >``` MyVar = 'This",
"'B', 'C'] # changed List: ['A', 'B', 'C', 'D'] # After passing to",
"They are accessable ## > from with in a function and not outside",
"## >Title: python functions ## >MetaDescription: python functions, function with parameters, function with",
"are accessable ## > from with in a function and not outside the",
"inside the function is reflected outside the call too. ## >* The parameter",
"variable (but ## > the reference is passed by value) ## >``` #",
"reference to function, source_list: ', source_list) # Passing the \"source_list\" and NOT A",
"the input by appending a value to in_list in_list.append('D') print('function_pass_by_reference says changed List:",
"= ['A', 'B', 'C'] def function_pass_by_value(in_list): print('function_pass_by_value says Input List: ', in_list) #",
"value to function, source_list: ', source_list_2) # Passing the \"source_list\" and NOT A",
"to function, source_list: ['A', 'B', 'C'] # Input List: ['A', 'B', 'C'] #",
"as well. ## >* Function arguments in python are passed by reference, any",
"the outer variable ## > might be overwritten ! ## >## Python Global",
"After passing to function, source_list: ['A', 'B', 'C', 'D'] ## >``` ## >###",
"value changed inside the function is reflected outside the call too. ## >*",
"## >* Variables defined inside a function have local scope ## >* Variables",
"**Global Variable** is accessable from anywhere in the program, Global ## > Variables",
"ARGUMENTS PASS BY REFERENCE and VALUE, VARIABLE SCOPE ## >* Variables defined inside",
"of function code: function_pass_by_value print('Before passing by value to function, source_list: ', source_list_2)",
"from anywhere in the program, Global ## > Variables outside the function are",
"the function as well. ## >* **Local Variable** are variables inside a function,",
"Hemaxi ## >ContentName: pass-by-reference-value ## >--- ## ># PYTHON FUNCTION ARGUMENTS PASS BY",
"value example] in_list =[1, 2, 3, 4] print('function_pass_by_value says changed List: ', in_list)",
"## >``` ## >### Pass by Value ## >* The parameter passed in",
"variables can be accessed inside functions as well. ## >* Function arguments in",
"print('After passing reference to function, source_list: ', source_list) # OUTPUT # Before passing",
"Passing the \"source_list\" and NOT A COPY of the \"source_list\" function_pass_by_value(source_list_2) print('After passing",
"> the reference is passed by value) ## >* Caution, when changing arguments",
"## >* The parameter passed in is actually a reference to a variable",
"inside function: ', MyVar) # End of function code: myFunction # Make a",
"by value) ## >``` # Create a source list source_list_2 = ['A', 'B',",
"def function_pass_by_reference(in_list): print('function_pass_by_reference says Input List: ', in_list) # Changing the input by",
"in_list) # End of function code: function_pass_by_reference print('Before passing reference to function, source_list:",
">--- ## >YamlDesc: CONTENT-ARTICLE ## >Title: python functions ## >MetaDescription: python functions, function",
"source_list: ', source_list_2) # OUTPUT # Before passing to function, source_list: ['A', 'B',",
"Input List: ', in_list) # Changing the input by appending a value to",
"is a Global Value' def myFunction(): # Local Variable MyVar = 'This is",
"The parameter passed in is actually a reference to a variable (but ##",
"program, Global ## > Variables outside the function are accessable inside the function",
"PASS BY REFERENCE and VALUE, VARIABLE SCOPE ## >* Variables defined inside a",
"Variables defined inside a function have local scope ## >* Variables defined outside",
"to a local variable in the function, or else the outer variable ##",
">``` # Create a source list source_list_2 = ['A', 'B', 'C'] def function_pass_by_value(in_list):",
"## >--- ## >YamlDesc: CONTENT-ARTICLE ## >Title: python functions ## >MetaDescription: python functions,",
"example] in_list =[1, 2, 3, 4] print('function_pass_by_value says changed List: ', in_list) #",
"pass-by-reference-value ## >--- ## ># PYTHON FUNCTION ARGUMENTS PASS BY REFERENCE and VALUE,",
"are accessable inside the function as well. ## >* **Local Variable** are variables",
"'This is a Global Value' def myFunction(): # Local Variable MyVar = 'This",
"['A', 'B', 'C'] def function_pass_by_reference(in_list): print('function_pass_by_reference says Input List: ', in_list) # Changing",
"VARIABLE SCOPE ## >* Variables defined inside a function have local scope ##",
">### Pass by Value ## >* The parameter passed in is actually a",
"> contents to a local variable in the function, or else the outer",
"function_pass_by_value(in_list): print('function_pass_by_value says Input List: ', in_list) # Reassigning a local value, [pass",
"the function are accessable inside the function as well. ## >* **Local Variable**",
"NOT A COPY of the \"source_list\" function_pass_by_value(source_list_2) print('After passing by value to function,",
"3, 4] print('function_pass_by_value says changed List: ', in_list) # End of function code:",
"## >## Pass by Reference ## >* Function arguments in python are passed",
"## >* **Global Variable** is accessable from anywhere in the program, Global ##",
"# Reassigning a local value, [pass by value example] in_list =[1, 2, 3,",
"Pass by Reference ## >* Function arguments in python are passed by reference,",
"print('After passing by value to function, source_list: ', source_list_2) # OUTPUT # Before",
"a local variable' print('Value of MyVar inside function: ', MyVar) # End of",
"accessable ## > from with in a function and not outside the function.",
"# Local Variable MyVar = 'This is a local variable' print('Value of MyVar",
"passing by value to function, source_list: ', source_list_2) # OUTPUT # Before passing",
"# Make a call to myFunction myFunction() print('Value of MyVar outside function: ',",
"passing reference to function, source_list: ', source_list) # Passing the \"source_list\" and NOT",
"'B', 'C'] def function_pass_by_value(in_list): print('function_pass_by_value says Input List: ', in_list) # Reassigning a",
"# After passing to function, source_list: ['A', 'B', 'C', 'D'] ## >``` ##",
"inside the function as well. ## >* **Local Variable** are variables inside a",
"COPY of the \"source_list\" function_pass_by_value(source_list_2) print('After passing by value to function, source_list: ',",
"are variables inside a function, They are accessable ## > from with in",
"to in_list in_list.append('D') print('function_pass_by_reference says changed List: ', in_list) # End of function",
"source_list: ['A', 'B', 'C', 'D'] ## >``` ## >### Pass by Value ##",
"'C'] def function_pass_by_reference(in_list): print('function_pass_by_reference says Input List: ', in_list) # Changing the input",
"parameters, function with return value example code, tutorials ## >Author: Hemaxi ## >ContentName:",
"overwritten ! ## >## Python Global and Local Variables ## >* **Global Variable**",
"source_list: ', source_list) # OUTPUT # Before passing to function, source_list: ['A', 'B',",
"and NOT A COPY of the \"source_list\" function_pass_by_value(source_list_2) print('After passing by value to",
"of MyVar outside function: ', MyVar) ## >``` ## >## Pass by Reference",
"value) ## >``` # Create a source list source_list_2 = ['A', 'B', 'C']",
"source_list: ['A', 'B', 'C'] # Input List: ['A', 'B', 'C'] # changed List:",
"source_list_2 = ['A', 'B', 'C'] def function_pass_by_value(in_list): print('function_pass_by_value says Input List: ', in_list)",
"source_list = ['A', 'B', 'C'] def function_pass_by_reference(in_list): print('function_pass_by_reference says Input List: ', in_list)",
"myFunction myFunction() print('Value of MyVar outside function: ', MyVar) ## >``` ## >##",
"myFunction # Make a call to myFunction myFunction() print('Value of MyVar outside function:",
"any parameter ## > value changed inside the function is reflected outside the",
"and NOT A COPY of the \"source_list\" function_pass_by_reference(source_list) print('After passing reference to function,",
"Variables defined outside a function have global scope. ## >* Global variables can",
"source_list: ', source_list) # Passing the \"source_list\" and NOT A COPY of the",
"A COPY of the \"source_list\" function_pass_by_reference(source_list) print('After passing reference to function, source_list: ',",
"function are accessable inside the function as well. ## >* **Local Variable** are",
"changed List: ', in_list) # End of function code: function_pass_by_value print('Before passing by",
"variable ## > might be overwritten ! ## >## Python Global and Local",
"of MyVar inside function: ', MyVar) # End of function code: myFunction #",
"passed by value) ## >``` # Create a source list source_list_2 = ['A',",
"Global and Local Variables ## >* **Global Variable** is accessable from anywhere in",
"of function code: function_pass_by_reference print('Before passing reference to function, source_list: ', source_list) #",
"inside a function have local scope ## >* Variables defined outside a function",
"passed in is actually a reference to a variable (but ## > the",
"outside the function. ## >``` MyVar = 'This is a Global Value' def",
"(but ## > the reference is passed by value) ## >* Caution, when",
"## >* **Local Variable** are variables inside a function, They are accessable ##",
"'B', 'C', 'D'] ## >``` ## >### Pass by Value ## >* The",
"call too. ## >* The parameter passed in is actually a reference to",
"outside the call too. ## >``` # Create a source list source_list =",
"a function have local scope ## >* Variables defined outside a function have",
"in_list.append('D') print('function_pass_by_reference says changed List: ', in_list) # End of function code: function_pass_by_reference",
"function with return value example code, tutorials ## >Author: Hemaxi ## >ContentName: pass-by-reference-value",
"in the function, or else the outer variable ## > might be overwritten",
">YamlDesc: CONTENT-ARTICLE ## >Title: python functions ## >MetaDescription: python functions, function with parameters,",
"function_pass_by_reference(in_list): print('function_pass_by_reference says Input List: ', in_list) # Changing the input by appending",
"are passed by reference, any parameter ## > value changed inside the function",
"says changed List: ', in_list) # End of function code: function_pass_by_reference print('Before passing",
"function_pass_by_reference(source_list) print('After passing reference to function, source_list: ', source_list) # OUTPUT # Before",
"'C'] # Input List: ['A', 'B', 'C'] # changed List: ['A', 'B', 'C',",
"Value ## >* The parameter passed in is actually a reference to a",
"source_list: ', source_list_2) # Passing the \"source_list\" and NOT A COPY of the",
"Variables ## >* **Global Variable** is accessable from anywhere in the program, Global",
"arguments in python are passed by reference, any parameter ## > value changed",
"and Local Variables ## >* **Global Variable** is accessable from anywhere in the",
"functions, function with parameters, function with return value example code, tutorials ## >Author:",
"with parameters, function with return value example code, tutorials ## >MetaKeywords: python functions,",
">* Global variables can be accessed inside functions as well. ## >* Function",
"the reference is passed by value) ## >* Caution, when changing arguments by",
"CONTENT-ARTICLE ## >Title: python functions ## >MetaDescription: python functions, function with parameters, function",
"myFunction() print('Value of MyVar outside function: ', MyVar) ## >``` ## >## Pass",
"End of function code: function_pass_by_reference print('Before passing reference to function, source_list: ', source_list)",
"arguments by reference make sure to copy the ## > contents to a",
"\"source_list\" function_pass_by_value(source_list_2) print('After passing by value to function, source_list: ', source_list_2) # OUTPUT",
"## >### Pass by Value ## >* The parameter passed in is actually",
"reflected outside the call too. ## >* The parameter passed in is actually",
"code, tutorials ## >Author: Hemaxi ## >ContentName: pass-by-reference-value ## >--- ## ># PYTHON",
"global scope. ## >* Global variables can be accessed inside functions as well.",
"function with parameters, function with return value example code, tutorials ## >MetaKeywords: python",
"## >``` # Create a source list source_list = ['A', 'B', 'C'] def",
"NOT A COPY of the \"source_list\" function_pass_by_reference(source_list) print('After passing reference to function, source_list:",
">--- ## ># PYTHON FUNCTION ARGUMENTS PASS BY REFERENCE and VALUE, VARIABLE SCOPE",
"# Changing the input by appending a value to in_list in_list.append('D') print('function_pass_by_reference says",
"myFunction(): # Local Variable MyVar = 'This is a local variable' print('Value of",
"function is reflected outside the call too. ## >``` # Create a source",
"example code, tutorials ## >Author: Hemaxi ## >ContentName: pass-by-reference-value ## >--- ## >#",
"passed by reference, any parameter ## > value changed inside the function is",
"4] print('function_pass_by_value says changed List: ', in_list) # End of function code: function_pass_by_value",
"defined outside a function have global scope. ## >* Global variables can be",
"parameter passed in is actually a reference to a variable (but ## >",
"with in a function and not outside the function. ## >``` MyVar =",
"might be overwritten ! ## >## Python Global and Local Variables ## >*",
"value example code, tutorials ## >Author: Hemaxi ## >ContentName: pass-by-reference-value ## >--- ##",
"MyVar inside function: ', MyVar) # End of function code: myFunction # Make",
"input by appending a value to in_list in_list.append('D') print('function_pass_by_reference says changed List: ',",
"print('function_pass_by_value says Input List: ', in_list) # Reassigning a local value, [pass by",
"local value, [pass by value example] in_list =[1, 2, 3, 4] print('function_pass_by_value says",
"outside the call too. ## >* The parameter passed in is actually a",
"the program, Global ## > Variables outside the function are accessable inside the",
"Passing the \"source_list\" and NOT A COPY of the \"source_list\" function_pass_by_reference(source_list) print('After passing",
"## >* Global variables can be accessed inside functions as well. ## >*",
"'D'] ## >``` ## >### Pass by Value ## >* The parameter passed",
"source list source_list_2 = ['A', 'B', 'C'] def function_pass_by_value(in_list): print('function_pass_by_value says Input List:",
"# Before passing to function, source_list: ['A', 'B', 'C'] # Input List: ['A',",
"a value to in_list in_list.append('D') print('function_pass_by_reference says changed List: ', in_list) # End",
"# End of function code: myFunction # Make a call to myFunction myFunction()",
"Make a call to myFunction myFunction() print('Value of MyVar outside function: ', MyVar)",
">Title: python functions ## >MetaDescription: python functions, function with parameters, function with return",
"# Create a source list source_list = ['A', 'B', 'C'] def function_pass_by_reference(in_list): print('function_pass_by_reference",
"Reassigning a local value, [pass by value example] in_list =[1, 2, 3, 4]",
"local variable in the function, or else the outer variable ## > might",
"Function arguments in python are passed by reference, any parameter ## > value",
"inside functions as well. ## >* Function arguments in python are passed by",
"to myFunction myFunction() print('Value of MyVar outside function: ', MyVar) ## >``` ##",
"a Global Value' def myFunction(): # Local Variable MyVar = 'This is a",
"function is reflected outside the call too. ## >* The parameter passed in",
">``` ## >## Pass by Reference ## >* Function arguments in python are",
"of the \"source_list\" function_pass_by_value(source_list_2) print('After passing by value to function, source_list: ', source_list_2)",
"not outside the function. ## >``` MyVar = 'This is a Global Value'",
"function, source_list: ', source_list) # Passing the \"source_list\" and NOT A COPY of",
"and not outside the function. ## >``` MyVar = 'This is a Global",
"source_list) # OUTPUT # Before passing to function, source_list: ['A', 'B', 'C'] #",
"python functions, function with parameters, function with return value example code, tutorials ##",
"Input List: ['A', 'B', 'C'] # changed List: ['A', 'B', 'C', 'D'] #",
"outside the function are accessable inside the function as well. ## >* **Local",
">* Variables defined inside a function have local scope ## >* Variables defined",
"by appending a value to in_list in_list.append('D') print('function_pass_by_reference says changed List: ', in_list)",
"## >Author: Hemaxi ## >ContentName: pass-by-reference-value ## >--- ## ># PYTHON FUNCTION ARGUMENTS",
">* Variables defined outside a function have global scope. ## >* Global variables",
"function: ', MyVar) ## >``` ## >## Pass by Reference ## >* Function",
"', source_list_2) # OUTPUT # Before passing to function, source_list: ['A', 'B', 'C']",
"passing to function, source_list: ['A', 'B', 'C'] # Input List: ['A', 'B', 'C']",
"print('function_pass_by_reference says Input List: ', in_list) # Changing the input by appending a",
"= 'This is a Global Value' def myFunction(): # Local Variable MyVar =",
"functions, function with parameters, function with return value example code, tutorials ## >MetaKeywords:",
"to function, source_list: ['A', 'B', 'C', 'D'] ## >``` ## >### Pass by",
"function and not outside the function. ## >``` MyVar = 'This is a",
"Variables outside the function are accessable inside the function as well. ## >*",
"# Input List: ['A', 'B', 'C'] # changed List: ['A', 'B', 'C', 'D']",
"Create a source list source_list_2 = ['A', 'B', 'C'] def function_pass_by_value(in_list): print('function_pass_by_value says",
"outside a function have global scope. ## >* Global variables can be accessed",
"call to myFunction myFunction() print('Value of MyVar outside function: ', MyVar) ## >```",
"the \"source_list\" and NOT A COPY of the \"source_list\" function_pass_by_reference(source_list) print('After passing reference",
"Local Variable MyVar = 'This is a local variable' print('Value of MyVar inside",
"a function, They are accessable ## > from with in a function and",
"## > the reference is passed by value) ## >* Caution, when changing",
"reference is passed by value) ## >* Caution, when changing arguments by reference",
"to function, source_list: ', source_list) # Passing the \"source_list\" and NOT A COPY",
"(but ## > the reference is passed by value) ## >``` # Create",
"## >YamlDesc: CONTENT-ARTICLE ## >Title: python functions ## >MetaDescription: python functions, function with",
"print('Before passing by value to function, source_list: ', source_list_2) # Passing the \"source_list\"",
"## >ContentName: pass-by-reference-value ## >--- ## ># PYTHON FUNCTION ARGUMENTS PASS BY REFERENCE",
"well. ## >* Function arguments in python are passed by reference, any parameter",
"changed inside the function is reflected outside the call too. ## >* The",
"function code: myFunction # Make a call to myFunction myFunction() print('Value of MyVar",
"example code, tutorials ## >MetaKeywords: python functions, function with parameters, function with return",
"'B', 'C'] def function_pass_by_reference(in_list): print('function_pass_by_reference says Input List: ', in_list) # Changing the",
"function, source_list: ['A', 'B', 'C'] # Input List: ['A', 'B', 'C'] # changed",
"'C'] def function_pass_by_value(in_list): print('function_pass_by_value says Input List: ', in_list) # Reassigning a local",
"'C', 'D'] # After passing to function, source_list: ['A', 'B', 'C', 'D'] ##",
"by value to function, source_list: ', source_list_2) # Passing the \"source_list\" and NOT",
"function code: function_pass_by_value print('Before passing by value to function, source_list: ', source_list_2) #",
"SCOPE ## >* Variables defined inside a function have local scope ## >*",
"be accessed inside functions as well. ## >* Function arguments in python are",
"Global variables can be accessed inside functions as well. ## >* Function arguments",
"># PYTHON FUNCTION ARGUMENTS PASS BY REFERENCE and VALUE, VARIABLE SCOPE ## >*",
"defined inside a function have local scope ## >* Variables defined outside a",
"local variable' print('Value of MyVar inside function: ', MyVar) # End of function",
"in_list) # Reassigning a local value, [pass by value example] in_list =[1, 2,",
"source list source_list = ['A', 'B', 'C'] def function_pass_by_reference(in_list): print('function_pass_by_reference says Input List:",
"is reflected outside the call too. ## >* The parameter passed in is",
"List: ['A', 'B', 'C'] # changed List: ['A', 'B', 'C', 'D'] # After",
"of function code: myFunction # Make a call to myFunction myFunction() print('Value of",
"', MyVar) # End of function code: myFunction # Make a call to",
"the call too. ## >* The parameter passed in is actually a reference",
"in python are passed by reference, any parameter ## > value changed inside",
"\"source_list\" and NOT A COPY of the \"source_list\" function_pass_by_reference(source_list) print('After passing reference to",
"variable (but ## > the reference is passed by value) ## >* Caution,",
"function_pass_by_reference print('Before passing reference to function, source_list: ', source_list) # Passing the \"source_list\"",
"inside a function, They are accessable ## > from with in a function",
"or else the outer variable ## > might be overwritten ! ## >##",
"reference, any parameter ## > value changed inside the function is reflected outside",
"', MyVar) ## >``` ## >## Pass by Reference ## >* Function arguments",
"['A', 'B', 'C', 'D'] ## >``` ## >### Pass by Value ## >*",
"List: ', in_list) # Reassigning a local value, [pass by value example] in_list",
"a variable (but ## > the reference is passed by value) ## >```",
"'B', 'C', 'D'] # After passing to function, source_list: ['A', 'B', 'C', 'D']",
"return value example code, tutorials ## >MetaKeywords: python functions, function with parameters, function",
"## >MetaKeywords: python functions, function with parameters, function with return value example code,",
"python functions ## >MetaDescription: python functions, function with parameters, function with return value",
"a function have global scope. ## >* Global variables can be accessed inside",
"Global Value' def myFunction(): # Local Variable MyVar = 'This is a local",
"copy the ## > contents to a local variable in the function, or",
"Python Global and Local Variables ## >* **Global Variable** is accessable from anywhere",
"in_list =[1, 2, 3, 4] print('function_pass_by_value says changed List: ', in_list) # End",
"= 'This is a local variable' print('Value of MyVar inside function: ', MyVar)",
"[pass by value example] in_list =[1, 2, 3, 4] print('function_pass_by_value says changed List:",
"PYTHON FUNCTION ARGUMENTS PASS BY REFERENCE and VALUE, VARIABLE SCOPE ## >* Variables",
"the \"source_list\" function_pass_by_value(source_list_2) print('After passing by value to function, source_list: ', source_list_2) #",
"in_list in_list.append('D') print('function_pass_by_reference says changed List: ', in_list) # End of function code:",
"the ## > contents to a local variable in the function, or else",
"Global ## > Variables outside the function are accessable inside the function as",
"Input List: ', in_list) # Reassigning a local value, [pass by value example]",
"MyVar = 'This is a local variable' print('Value of MyVar inside function: ',",
"> value changed inside the function is reflected outside the call too. ##",
"a variable (but ## > the reference is passed by value) ## >*",
"', source_list) # Passing the \"source_list\" and NOT A COPY of the \"source_list\"",
"List: ', in_list) # End of function code: function_pass_by_reference print('Before passing reference to",
"## > from with in a function and not outside the function. ##",
"COPY of the \"source_list\" function_pass_by_reference(source_list) print('After passing reference to function, source_list: ', source_list)",
"have local scope ## >* Variables defined outside a function have global scope.",
"# End of function code: function_pass_by_value print('Before passing by value to function, source_list:",
"VALUE, VARIABLE SCOPE ## >* Variables defined inside a function have local scope",
"accessable from anywhere in the program, Global ## > Variables outside the function",
"def myFunction(): # Local Variable MyVar = 'This is a local variable' print('Value",
"REFERENCE and VALUE, VARIABLE SCOPE ## >* Variables defined inside a function have",
">MetaDescription: python functions, function with parameters, function with return value example code, tutorials",
"End of function code: myFunction # Make a call to myFunction myFunction() print('Value",
"List: ', in_list) # Changing the input by appending a value to in_list",
"# Passing the \"source_list\" and NOT A COPY of the \"source_list\" function_pass_by_reference(source_list) print('After",
"local scope ## >* Variables defined outside a function have global scope. ##",
"functions as well. ## >* Function arguments in python are passed by reference,",
"with return value example code, tutorials ## >MetaKeywords: python functions, function with parameters,",
"when changing arguments by reference make sure to copy the ## > contents",
"> from with in a function and not outside the function. ## >```",
"def function_pass_by_value(in_list): print('function_pass_by_value says Input List: ', in_list) # Reassigning a local value,",
"to function, source_list: ', source_list_2) # OUTPUT # Before passing to function, source_list:",
"['A', 'B', 'C'] # Input List: ['A', 'B', 'C'] # changed List: ['A',",
"print('function_pass_by_reference says changed List: ', in_list) # End of function code: function_pass_by_reference print('Before",
"make sure to copy the ## > contents to a local variable in",
"changed List: ['A', 'B', 'C', 'D'] # After passing to function, source_list: ['A',",
"value, [pass by value example] in_list =[1, 2, 3, 4] print('function_pass_by_value says changed",
"'D'] # After passing to function, source_list: ['A', 'B', 'C', 'D'] ## >```",
"reference to function, source_list: ', source_list) # OUTPUT # Before passing to function,",
">* **Global Variable** is accessable from anywhere in the program, Global ## >",
"the function is reflected outside the call too. ## >* The parameter passed",
"is actually a reference to a variable (but ## > the reference is",
"says Input List: ', in_list) # Changing the input by appending a value",
"function have global scope. ## >* Global variables can be accessed inside functions",
"changed inside the function is reflected outside the call too. ## >``` #",
"> might be overwritten ! ## >## Python Global and Local Variables ##",
"## >``` MyVar = 'This is a Global Value' def myFunction(): # Local",
"source_list_2) # Passing the \"source_list\" and NOT A COPY of the \"source_list\" function_pass_by_value(source_list_2)",
"and VALUE, VARIABLE SCOPE ## >* Variables defined inside a function have local",
"in is actually a reference to a variable (but ## > the reference",
"appending a value to in_list in_list.append('D') print('function_pass_by_reference says changed List: ', in_list) #",
"call too. ## >``` # Create a source list source_list = ['A', 'B',",
"function, source_list: ', source_list_2) # OUTPUT # Before passing to function, source_list: ['A',",
"passing reference to function, source_list: ', source_list) # OUTPUT # Before passing to",
"FUNCTION ARGUMENTS PASS BY REFERENCE and VALUE, VARIABLE SCOPE ## >* Variables defined",
"', in_list) # End of function code: function_pass_by_value print('Before passing by value to",
"tutorials ## >MetaKeywords: python functions, function with parameters, function with return value example",
"a local value, [pass by value example] in_list =[1, 2, 3, 4] print('function_pass_by_value",
"'B', 'C'] # Input List: ['A', 'B', 'C'] # changed List: ['A', 'B',",
"MyVar = 'This is a Global Value' def myFunction(): # Local Variable MyVar",
"value) ## >* Caution, when changing arguments by reference make sure to copy",
"says changed List: ', in_list) # End of function code: function_pass_by_value print('Before passing",
"a function and not outside the function. ## >``` MyVar = 'This is",
"of the \"source_list\" function_pass_by_reference(source_list) print('After passing reference to function, source_list: ', source_list) #",
"the function, or else the outer variable ## > might be overwritten !",
"sure to copy the ## > contents to a local variable in the",
"function, or else the outer variable ## > might be overwritten ! ##",
"function. ## >``` MyVar = 'This is a Global Value' def myFunction(): #",
"## >``` # Create a source list source_list_2 = ['A', 'B', 'C'] def",
"a source list source_list_2 = ['A', 'B', 'C'] def function_pass_by_value(in_list): print('function_pass_by_value says Input",
"['A', 'B', 'C'] def function_pass_by_value(in_list): print('function_pass_by_value says Input List: ', in_list) # Reassigning",
"is passed by value) ## >* Caution, when changing arguments by reference make",
"**Local Variable** are variables inside a function, They are accessable ## > from",
">* Function arguments in python are passed by reference, any parameter ## >",
"print('Before passing reference to function, source_list: ', source_list) # Passing the \"source_list\" and",
"passing to function, source_list: ['A', 'B', 'C', 'D'] ## >``` ## >### Pass",
"function, source_list: ', source_list) # OUTPUT # Before passing to function, source_list: ['A',",
"well. ## >* **Local Variable** are variables inside a function, They are accessable",
"A COPY of the \"source_list\" function_pass_by_value(source_list_2) print('After passing by value to function, source_list:",
"## > contents to a local variable in the function, or else the",
"passed by value) ## >* Caution, when changing arguments by reference make sure",
"value example code, tutorials ## >MetaKeywords: python functions, function with parameters, function with",
"with return value example code, tutorials ## >Author: Hemaxi ## >ContentName: pass-by-reference-value ##",
"', in_list) # Changing the input by appending a value to in_list in_list.append('D')",
"\"source_list\" and NOT A COPY of the \"source_list\" function_pass_by_value(source_list_2) print('After passing by value",
"else the outer variable ## > might be overwritten ! ## >## Python",
"## >MetaDescription: python functions, function with parameters, function with return value example code,",
"## >``` ## >## Pass by Reference ## >* Function arguments in python",
"OUTPUT # Before passing to function, source_list: ['A', 'B', 'C'] # Input List:",
"can be accessed inside functions as well. ## >* Function arguments in python",
"## > value changed inside the function is reflected outside the call too.",
"function, source_list: ', source_list_2) # Passing the \"source_list\" and NOT A COPY of",
"by Reference ## >* Function arguments in python are passed by reference, any",
"anywhere in the program, Global ## > Variables outside the function are accessable",
"# OUTPUT # Before passing to function, source_list: ['A', 'B', 'C'] # Input",
">* The parameter passed in is actually a reference to a variable (but",
"list source_list_2 = ['A', 'B', 'C'] def function_pass_by_value(in_list): print('function_pass_by_value says Input List: ',",
"Variable** are variables inside a function, They are accessable ## > from with",
"'This is a local variable' print('Value of MyVar inside function: ', MyVar) #",
"reflected outside the call too. ## >``` # Create a source list source_list",
"function with return value example code, tutorials ## >MetaKeywords: python functions, function with",
"function with parameters, function with return value example code, tutorials ## >Author: Hemaxi",
"variable' print('Value of MyVar inside function: ', MyVar) # End of function code:",
">``` # Create a source list source_list = ['A', 'B', 'C'] def function_pass_by_reference(in_list):",
"actually a reference to a variable (but ## > the reference is passed",
"List: ['A', 'B', 'C', 'D'] # After passing to function, source_list: ['A', 'B',",
"print('Value of MyVar outside function: ', MyVar) ## >``` ## >## Pass by",
"reference to a variable (but ## > the reference is passed by value)",
"code: function_pass_by_reference print('Before passing reference to function, source_list: ', source_list) # Passing the",
"too. ## >* The parameter passed in is actually a reference to a",
"accessed inside functions as well. ## >* Function arguments in python are passed",
"# Create a source list source_list_2 = ['A', 'B', 'C'] def function_pass_by_value(in_list): print('function_pass_by_value",
"print('Value of MyVar inside function: ', MyVar) # End of function code: myFunction",
"list source_list = ['A', 'B', 'C'] def function_pass_by_reference(in_list): print('function_pass_by_reference says Input List: ',",
"value to in_list in_list.append('D') print('function_pass_by_reference says changed List: ', in_list) # End of",
"## ># PYTHON FUNCTION ARGUMENTS PASS BY REFERENCE and VALUE, VARIABLE SCOPE ##",
"= ['A', 'B', 'C'] def function_pass_by_reference(in_list): print('function_pass_by_reference says Input List: ', in_list) #",
"outer variable ## > might be overwritten ! ## >## Python Global and",
">* **Local Variable** are variables inside a function, They are accessable ## >",
">ContentName: pass-by-reference-value ## >--- ## ># PYTHON FUNCTION ARGUMENTS PASS BY REFERENCE and",
"function have local scope ## >* Variables defined outside a function have global",
"=[1, 2, 3, 4] print('function_pass_by_value says changed List: ', in_list) # End of",
"## > the reference is passed by value) ## >``` # Create a",
">* Caution, when changing arguments by reference make sure to copy the ##",
"code: myFunction # Make a call to myFunction myFunction() print('Value of MyVar outside",
"scope. ## >* Global variables can be accessed inside functions as well. ##",
"by value example] in_list =[1, 2, 3, 4] print('function_pass_by_value says changed List: ',",
"by reference make sure to copy the ## > contents to a local",
"functions ## >MetaDescription: python functions, function with parameters, function with return value example",
"Changing the input by appending a value to in_list in_list.append('D') print('function_pass_by_reference says changed",
"# Passing the \"source_list\" and NOT A COPY of the \"source_list\" function_pass_by_value(source_list_2) print('After",
"a reference to a variable (but ## > the reference is passed by",
"in_list) # Changing the input by appending a value to in_list in_list.append('D') print('function_pass_by_reference",
"# End of function code: function_pass_by_reference print('Before passing reference to function, source_list: ',",
"inside the function is reflected outside the call too. ## >``` # Create",
">## Pass by Reference ## >* Function arguments in python are passed by",
"', source_list_2) # Passing the \"source_list\" and NOT A COPY of the \"source_list\"",
"is accessable from anywhere in the program, Global ## > Variables outside the",
"with parameters, function with return value example code, tutorials ## >Author: Hemaxi ##",
"# changed List: ['A', 'B', 'C', 'D'] # After passing to function, source_list:",
"reference make sure to copy the ## > contents to a local variable",
"by reference, any parameter ## > value changed inside the function is reflected",
"Reference ## >* Function arguments in python are passed by reference, any parameter",
"value changed inside the function is reflected outside the call too. ## >```",
"## > Variables outside the function are accessable inside the function as well.",
"the \"source_list\" function_pass_by_reference(source_list) print('After passing reference to function, source_list: ', source_list) # OUTPUT",
"> the reference is passed by value) ## >``` # Create a source",
"Value' def myFunction(): # Local Variable MyVar = 'This is a local variable'",
"code: function_pass_by_value print('Before passing by value to function, source_list: ', source_list_2) # Passing",
"by value) ## >* Caution, when changing arguments by reference make sure to",
"'C', 'D'] ## >``` ## >### Pass by Value ## >* The parameter",
"', source_list) # OUTPUT # Before passing to function, source_list: ['A', 'B', 'C']",
"print('function_pass_by_value says changed List: ', in_list) # End of function code: function_pass_by_value print('Before",
"is passed by value) ## >``` # Create a source list source_list_2 =",
"a call to myFunction myFunction() print('Value of MyVar outside function: ', MyVar) ##",
"have global scope. ## >* Global variables can be accessed inside functions as",
"the reference is passed by value) ## >``` # Create a source list",
"MyVar outside function: ', MyVar) ## >``` ## >## Pass by Reference ##",
"python are passed by reference, any parameter ## > value changed inside the",
"Caution, when changing arguments by reference make sure to copy the ## >",
"function: ', MyVar) # End of function code: myFunction # Make a call",
"in_list) # End of function code: function_pass_by_value print('Before passing by value to function,",
"['A', 'B', 'C', 'D'] # After passing to function, source_list: ['A', 'B', 'C',",
"', in_list) # End of function code: function_pass_by_reference print('Before passing reference to function,",
">``` ## >### Pass by Value ## >* The parameter passed in is",
"## >* Variables defined outside a function have global scope. ## >* Global",
"Create a source list source_list = ['A', 'B', 'C'] def function_pass_by_reference(in_list): print('function_pass_by_reference says",
"be overwritten ! ## >## Python Global and Local Variables ## >* **Global",
"variable in the function, or else the outer variable ## > might be",
"the function is reflected outside the call too. ## >``` # Create a",
"the call too. ## >``` # Create a source list source_list = ['A',",
"## >## Python Global and Local Variables ## >* **Global Variable** is accessable",
"function_pass_by_value print('Before passing by value to function, source_list: ', source_list_2) # Passing the",
"BY REFERENCE and VALUE, VARIABLE SCOPE ## >* Variables defined inside a function",
"function code: function_pass_by_reference print('Before passing reference to function, source_list: ', source_list) # Passing",
"source_list_2) # OUTPUT # Before passing to function, source_list: ['A', 'B', 'C'] #",
"> Variables outside the function are accessable inside the function as well. ##",
"return value example code, tutorials ## >Author: Hemaxi ## >ContentName: pass-by-reference-value ## >---",
"source_list) # Passing the \"source_list\" and NOT A COPY of the \"source_list\" function_pass_by_reference(source_list)",
"function, source_list: ['A', 'B', 'C', 'D'] ## >``` ## >### Pass by Value",
"function_pass_by_value(source_list_2) print('After passing by value to function, source_list: ', source_list_2) # OUTPUT #",
"reference is passed by value) ## >``` # Create a source list source_list_2",
"## >--- ## ># PYTHON FUNCTION ARGUMENTS PASS BY REFERENCE and VALUE, VARIABLE",
"tutorials ## >Author: Hemaxi ## >ContentName: pass-by-reference-value ## >--- ## ># PYTHON FUNCTION",
">Author: Hemaxi ## >ContentName: pass-by-reference-value ## >--- ## ># PYTHON FUNCTION ARGUMENTS PASS",
"variables inside a function, They are accessable ## > from with in a",
"in the program, Global ## > Variables outside the function are accessable inside",
"a source list source_list = ['A', 'B', 'C'] def function_pass_by_reference(in_list): print('function_pass_by_reference says Input",
"is a local variable' print('Value of MyVar inside function: ', MyVar) # End",
"to function, source_list: ', source_list) # OUTPUT # Before passing to function, source_list:",
"MyVar) # End of function code: myFunction # Make a call to myFunction",
"by Value ## >* The parameter passed in is actually a reference to",
"## >* Caution, when changing arguments by reference make sure to copy the",
"a local variable in the function, or else the outer variable ## >",
"scope ## >* Variables defined outside a function have global scope. ## >*",
"from with in a function and not outside the function. ## >``` MyVar",
"2, 3, 4] print('function_pass_by_value says changed List: ', in_list) # End of function",
"'C'] # changed List: ['A', 'B', 'C', 'D'] # After passing to function,",
"Local Variables ## >* **Global Variable** is accessable from anywhere in the program,",
"function, They are accessable ## > from with in a function and not",
"## >* Function arguments in python are passed by reference, any parameter ##",
"function as well. ## >* **Local Variable** are variables inside a function, They",
"passing by value to function, source_list: ', source_list_2) # Passing the \"source_list\" and",
"! ## >## Python Global and Local Variables ## >* **Global Variable** is",
"by value to function, source_list: ', source_list_2) # OUTPUT # Before passing to",
"End of function code: function_pass_by_value print('Before passing by value to function, source_list: ',",
"too. ## >``` # Create a source list source_list = ['A', 'B', 'C']",
"## > might be overwritten ! ## >## Python Global and Local Variables",
"to copy the ## > contents to a local variable in the function,",
"contents to a local variable in the function, or else the outer variable",
"['A', 'B', 'C'] # changed List: ['A', 'B', 'C', 'D'] # After passing",
"changing arguments by reference make sure to copy the ## > contents to",
"Variable** is accessable from anywhere in the program, Global ## > Variables outside",
"changed List: ', in_list) # End of function code: function_pass_by_reference print('Before passing reference",
"the function. ## >``` MyVar = 'This is a Global Value' def myFunction():",
">``` MyVar = 'This is a Global Value' def myFunction(): # Local Variable",
"value to function, source_list: ', source_list_2) # OUTPUT # Before passing to function,",
"\"source_list\" function_pass_by_reference(source_list) print('After passing reference to function, source_list: ', source_list) # OUTPUT #",
"parameters, function with return value example code, tutorials ## >MetaKeywords: python functions, function",
"MyVar) ## >``` ## >## Pass by Reference ## >* Function arguments in",
"says Input List: ', in_list) # Reassigning a local value, [pass by value"
] |
[
"start = time.time() evaluation = agent.depth_first_proof_number_search(env=env) end = time.time() print(evaluation) print(\"time to run",
"import SQLiteTranspositionTable env = gym.make('connect_four-v0') env.reset() evaluator = Victor(model=env) hasher = ConnectFourHasher(env=env) tt",
"SQLiteTranspositionTable(database_file=\"connect_four.db\") agent = DFPN(evaluator, hasher, tt) start = time.time() evaluation = agent.depth_first_proof_number_search(env=env) end",
"difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator import Victor from connect_four.hashing import ConnectFourHasher from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable",
"Victor(model=env) hasher = ConnectFourHasher(env=env) tt = SQLiteTranspositionTable(database_file=\"connect_four.db\") agent = DFPN(evaluator, hasher, tt) start",
"time.time() evaluation = agent.depth_first_proof_number_search(env=env) end = time.time() print(evaluation) print(\"time to run = \",",
"import DFPN from connect_four.agents import difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator import Victor from connect_four.hashing import",
"ConnectFourHasher from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable env = gym.make('connect_four-v0') env.reset() evaluator = Victor(model=env) hasher",
"tt = SQLiteTranspositionTable(database_file=\"connect_four.db\") agent = DFPN(evaluator, hasher, tt) start = time.time() evaluation =",
"import difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator import Victor from connect_four.hashing import ConnectFourHasher from connect_four.transposition.sqlite_transposition_table import",
"from connect_four.agents import difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator import Victor from connect_four.hashing import ConnectFourHasher from",
"= SQLiteTranspositionTable(database_file=\"connect_four.db\") agent = DFPN(evaluator, hasher, tt) start = time.time() evaluation = agent.depth_first_proof_number_search(env=env)",
"agent = DFPN(evaluator, hasher, tt) start = time.time() evaluation = agent.depth_first_proof_number_search(env=env) end =",
"from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable env = gym.make('connect_four-v0') env.reset() evaluator = Victor(model=env) hasher =",
"evaluation = agent.depth_first_proof_number_search(env=env) end = time.time() print(evaluation) print(\"time to run = \", end",
"connect_four.agents import DFPN from connect_four.agents import difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator import Victor from connect_four.hashing",
"agent.depth_first_proof_number_search(env=env) end = time.time() print(evaluation) print(\"time to run = \", end - start)",
"end = time.time() print(evaluation) print(\"time to run = \", end - start) tt.close()",
"Victor from connect_four.hashing import ConnectFourHasher from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable env = gym.make('connect_four-v0') env.reset()",
"from connect_four.hashing import ConnectFourHasher from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable env = gym.make('connect_four-v0') env.reset() evaluator",
"evaluator = Victor(model=env) hasher = ConnectFourHasher(env=env) tt = SQLiteTranspositionTable(database_file=\"connect_four.db\") agent = DFPN(evaluator, hasher,",
"hasher, tt) start = time.time() evaluation = agent.depth_first_proof_number_search(env=env) end = time.time() print(evaluation) print(\"time",
"= time.time() evaluation = agent.depth_first_proof_number_search(env=env) end = time.time() print(evaluation) print(\"time to run =",
"tt) start = time.time() evaluation = agent.depth_first_proof_number_search(env=env) end = time.time() print(evaluation) print(\"time to",
"connect_four.evaluation.victor.victor_evaluator import Victor from connect_four.hashing import ConnectFourHasher from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable env =",
"import gym import time from connect_four.agents import DFPN from connect_four.agents import difficult_connect_four_positions from",
"import ConnectFourHasher from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable env = gym.make('connect_four-v0') env.reset() evaluator = Victor(model=env)",
"time from connect_four.agents import DFPN from connect_four.agents import difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator import Victor",
"env = gym.make('connect_four-v0') env.reset() evaluator = Victor(model=env) hasher = ConnectFourHasher(env=env) tt = SQLiteTranspositionTable(database_file=\"connect_four.db\")",
"= agent.depth_first_proof_number_search(env=env) end = time.time() print(evaluation) print(\"time to run = \", end -",
"connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable env = gym.make('connect_four-v0') env.reset() evaluator = Victor(model=env) hasher = ConnectFourHasher(env=env)",
"= DFPN(evaluator, hasher, tt) start = time.time() evaluation = agent.depth_first_proof_number_search(env=env) end = time.time()",
"DFPN(evaluator, hasher, tt) start = time.time() evaluation = agent.depth_first_proof_number_search(env=env) end = time.time() print(evaluation)",
"import Victor from connect_four.hashing import ConnectFourHasher from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable env = gym.make('connect_four-v0')",
"= gym.make('connect_four-v0') env.reset() evaluator = Victor(model=env) hasher = ConnectFourHasher(env=env) tt = SQLiteTranspositionTable(database_file=\"connect_four.db\") agent",
"env.reset() evaluator = Victor(model=env) hasher = ConnectFourHasher(env=env) tt = SQLiteTranspositionTable(database_file=\"connect_four.db\") agent = DFPN(evaluator,",
"DFPN from connect_four.agents import difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator import Victor from connect_four.hashing import ConnectFourHasher",
"import time from connect_four.agents import DFPN from connect_four.agents import difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator import",
"from connect_four.evaluation.victor.victor_evaluator import Victor from connect_four.hashing import ConnectFourHasher from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable env",
"connect_four.agents import difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator import Victor from connect_four.hashing import ConnectFourHasher from connect_four.transposition.sqlite_transposition_table",
"SQLiteTranspositionTable env = gym.make('connect_four-v0') env.reset() evaluator = Victor(model=env) hasher = ConnectFourHasher(env=env) tt =",
"connect_four.hashing import ConnectFourHasher from connect_four.transposition.sqlite_transposition_table import SQLiteTranspositionTable env = gym.make('connect_four-v0') env.reset() evaluator =",
"gym.make('connect_four-v0') env.reset() evaluator = Victor(model=env) hasher = ConnectFourHasher(env=env) tt = SQLiteTranspositionTable(database_file=\"connect_four.db\") agent =",
"ConnectFourHasher(env=env) tt = SQLiteTranspositionTable(database_file=\"connect_four.db\") agent = DFPN(evaluator, hasher, tt) start = time.time() evaluation",
"= ConnectFourHasher(env=env) tt = SQLiteTranspositionTable(database_file=\"connect_four.db\") agent = DFPN(evaluator, hasher, tt) start = time.time()",
"gym import time from connect_four.agents import DFPN from connect_four.agents import difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator",
"hasher = ConnectFourHasher(env=env) tt = SQLiteTranspositionTable(database_file=\"connect_four.db\") agent = DFPN(evaluator, hasher, tt) start =",
"= Victor(model=env) hasher = ConnectFourHasher(env=env) tt = SQLiteTranspositionTable(database_file=\"connect_four.db\") agent = DFPN(evaluator, hasher, tt)",
"from connect_four.agents import DFPN from connect_four.agents import difficult_connect_four_positions from connect_four.evaluation.victor.victor_evaluator import Victor from"
] |
[
"on population...\") if autoencoder: autoencoder_model = joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X = autoencoder_model.get_encode_features(X) if modeltype",
"full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) X, patient_keys = tu.convert_to_temporal_format(full_covariates, timeid_len = timeid_len, predict",
"batch_size = 32) test_pred = [] for test in test_batch: pred_test1 = modelTrained.predict_proba(test)[:,",
"load model print(\"Loading model...\") modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating predictions on population...\") if",
"ready for model has %s features\" %(np.shape(X)[1])) ########################################################################### # uf dense convert if",
"as np from collections import OrderedDict import os import sys import timeit import",
"in population[:, 0]: if p_id not in p_ids_in_cov: tmp_x = np.array([p_id, default_covid, 1,",
"print(\"converting to dense data...\") X=X.toarray() ########################################################################### # load model print(\"Loading model...\") modelTrained =",
"sklearn.feature_selection import SelectFromModel #from sklearn.cross_validation import PredefinedSplit from sklearn.externals.joblib import Memory #from sklearn.datasets",
"%s rows and %s columns\" %(X.shape[0], X.shape[1])) print(\"Data ready for model has %s",
"if test_pred.ndim != 1: test_pred = test_pred[:,1] print(\"Prediction complete: %s rows\" %(np.shape(test_pred)[0])) print(\"Mean:",
"= joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X = autoencoder_model.get_encode_features(X) if modeltype == 'temporal': test_batch = tu.batch(X,",
"#================================================================ import numpy as np from collections import OrderedDict import os import sys",
"= modelTrained.predict_proba(test)[:, 1] test_pred = np.concatenate((test_pred , pred_test1), axis = 0) else: test_pred",
"SelectFromModel #from sklearn.cross_validation import PredefinedSplit from sklearn.externals.joblib import Memory #from sklearn.datasets import load_svmlight_file",
"file print(\"population loaded- %s rows and %s columns\" %(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset has %s",
"rows and %s columns\" %(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset has %s rows and %s columns\"",
"True) return X print(\"Loading Data...\") # load data + train,test indexes + validation",
"tu.convert_to_temporal_format(full_covariates, timeid_len = timeid_len, predict = True) return X print(\"Loading Data...\") # load",
"modeltype == 'temporal': test_batch = tu.batch(X, batch_size = 32) test_pred = [] for",
"cov id, timeid=1 full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) else: tmp_x = covariates[covariates[:, 0]",
"= covariates[0, 1] for p_id in population[:, 0]: if p_id not in p_ids_in_cov:",
"Python Model\") ########################################################################### def get_temproal_data(covariates, population): p_ids_in_cov = set(covariates[:, 0]) timeid_len = len(set(covariates[:,",
"1] for p_id in population[:, 0]: if p_id not in p_ids_in_cov: tmp_x =",
"with prediction for test index - named new_pred #================================================================ import numpy as np",
"of new data # 2) location of model # # OUTPUT: # it",
"#=============================================================== # INPUT: # 1) location of new data # 2) location of",
"location of new data # 2) location of model # # OUTPUT: #",
"test_pred.ndim != 1: test_pred = test_pred[:,1] print(\"Prediction complete: %s rows\" %(np.shape(test_pred)[0])) print(\"Mean: %s",
"else: tmp_x = covariates[covariates[:, 0] == p_id, :] #print tmp_x.shape, X.shape full_covariates =",
"population...\") if autoencoder: autoencoder_model = joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X = autoencoder_model.get_encode_features(X) if modeltype ==",
"has %s rows and %s columns\" %(X.shape[0], X.shape[1])) print(\"Data ready for model has",
"prediction value\" %(np.mean(test_pred))) # merge pred with population test_pred.shape = (population.shape[0], 1) prediction",
"import timeit import math #from sklearn.ensemble import RandomForestClassifier #from sklearn.naive_bayes import GaussianNB from",
"autoencoder_model.get_encode_features(X) if modeltype == 'temporal': test_batch = tu.batch(X, batch_size = 32) test_pred =",
"modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating predictions on population...\") if autoencoder: autoencoder_model = joblib.load(os.path.join(model_loc,",
"test index - named new_pred #================================================================ import numpy as np from collections import",
"indexes merged with prediction for test index - named new_pred #================================================================ import numpy",
"covariates.shape if modeltype == 'temporal': X = plpData.to_dense().numpy() X = X[np.int64(population[:, 0]), :]",
"tmp_x), axis=0) else: tmp_x = covariates[covariates[:, 0] == p_id, :] #print tmp_x.shape, X.shape",
"if autoencoder: autoencoder_model = joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X = autoencoder_model.get_encode_features(X) if modeltype == 'temporal':",
"np.array([]).reshape(0,4) default_covid = covariates[0, 1] for p_id in population[:, 0]: if p_id not",
"scipy.sparse import coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection import SelectFromModel #from sklearn.cross_validation import PredefinedSplit from sklearn.externals.joblib",
"== p_id, :] #print tmp_x.shape, X.shape full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) X, patient_keys",
"%s features\" %(np.shape(X)[1])) ########################################################################### # uf dense convert if dense==1: print(\"converting to dense",
"1] test_pred = np.concatenate((test_pred , pred_test1), axis = 0) else: test_pred = modelTrained.predict_proba(X)[:,",
"import OrderedDict import os import sys import timeit import math #from sklearn.ensemble import",
"predict = True) return X print(\"Loading Data...\") # load data + train,test indexes",
"test_pred = test_pred[:,1] print(\"Prediction complete: %s rows\" %(np.shape(test_pred)[0])) print(\"Mean: %s prediction value\" %(np.mean(test_pred)))",
"test in test_batch: pred_test1 = modelTrained.predict_proba(test)[:, 1] test_pred = np.concatenate((test_pred , pred_test1), axis",
"= plpData.to_dense().numpy() X = X[np.int64(population[:, 0]), :] #X = get_temproal_data(covariates, population) dense =",
"sys import timeit import math #from sklearn.ensemble import RandomForestClassifier #from sklearn.naive_bayes import GaussianNB",
"\"python_dir\" in globals(): sys.path.insert(0, python_dir) import TorchUtils as tu #================================================================ print(\"Applying Python Model\")",
"patient_keys = tu.convert_to_temporal_format(full_covariates, timeid_len = timeid_len, predict = True) return X print(\"Loading Data...\")",
"X[:,included.flatten()] # load index file print(\"population loaded- %s rows and %s columns\" %(np.shape(population)[0],",
"test_pred[:,1] print(\"Prediction complete: %s rows\" %(np.shape(test_pred)[0])) print(\"Mean: %s prediction value\" %(np.mean(test_pred))) # merge",
"0]) timeid_len = len(set(covariates[:, -2])) full_covariates = np.array([]).reshape(0,4) default_covid = covariates[0, 1] for",
"1: test_pred = test_pred[:,1] print(\"Prediction complete: %s rows\" %(np.shape(test_pred)[0])) print(\"Mean: %s prediction value\"",
"tu.batch(X, batch_size = 32) test_pred = [] for test in test_batch: pred_test1 =",
"timeid=1 full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) else: tmp_x = covariates[covariates[:, 0] == p_id,",
"columns\" %(X.shape[0], X.shape[1])) print(\"Data ready for model has %s features\" %(np.shape(X)[1])) ########################################################################### #",
"load index file print(\"population loaded- %s rows and %s columns\" %(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset",
"with indexes merged with prediction for test index - named new_pred #================================================================ import",
"= modelTrained.predict_proba(X)[:, 1] if test_pred.ndim != 1: test_pred = test_pred[:,1] print(\"Prediction complete: %s",
"0]), :] #X = get_temproal_data(covariates, population) dense = 0 else: #print included X",
"sklearn.externals.joblib import Memory #from sklearn.datasets import load_svmlight_file from sklearn.externals import joblib if \"python_dir\"",
"from collections import OrderedDict import os import sys import timeit import math #from",
"np.concatenate((full_covariates, tmp_x), axis=0) X, patient_keys = tu.convert_to_temporal_format(full_covariates, timeid_len = timeid_len, predict = True)",
"test_pred = [] for test in test_batch: pred_test1 = modelTrained.predict_proba(test)[:, 1] test_pred =",
"= get_temproal_data(covariates, population) dense = 0 else: #print included X = plpData[population[:,0],:] X",
"default_covid = covariates[0, 1] for p_id in population[:, 0]: if p_id not in",
"import PredefinedSplit from sklearn.externals.joblib import Memory #from sklearn.datasets import load_svmlight_file from sklearn.externals import",
"# 2) location of model # # OUTPUT: # it returns a file",
"location of model # # OUTPUT: # it returns a file with indexes",
"columns\" %(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset has %s rows and %s columns\" %(X.shape[0], X.shape[1])) print(\"Data",
"full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) else: tmp_x = covariates[covariates[:, 0] == p_id, :]",
"#print tmp_x.shape, X.shape full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) X, patient_keys = tu.convert_to_temporal_format(full_covariates, timeid_len",
"X.shape full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) X, patient_keys = tu.convert_to_temporal_format(full_covariates, timeid_len = timeid_len,",
"model # # OUTPUT: # it returns a file with indexes merged with",
"- named new_pred #================================================================ import numpy as np from collections import OrderedDict import",
"X.shape[1])) print(\"Data ready for model has %s features\" %(np.shape(X)[1])) ########################################################################### # uf dense",
"#from sklearn.cross_validation import PredefinedSplit from sklearn.externals.joblib import Memory #from sklearn.datasets import load_svmlight_file from",
"model print(\"Loading model...\") modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating predictions on population...\") if autoencoder:",
"timeit import math #from sklearn.ensemble import RandomForestClassifier #from sklearn.naive_bayes import GaussianNB from scipy.sparse",
"import load_svmlight_file from sklearn.externals import joblib if \"python_dir\" in globals(): sys.path.insert(0, python_dir) import",
"np.array([p_id, default_covid, 1, 0]).reshape(1,4) #default cov id, timeid=1 full_covariates = np.concatenate((full_covariates, tmp_x), axis=0)",
"X = autoencoder_model.get_encode_features(X) if modeltype == 'temporal': test_batch = tu.batch(X, batch_size = 32)",
"from scipy.sparse import coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection import SelectFromModel #from sklearn.cross_validation import PredefinedSplit from",
"sklearn.cross_validation import PredefinedSplit from sklearn.externals.joblib import Memory #from sklearn.datasets import load_svmlight_file from sklearn.externals",
"p_id in population[:, 0]: if p_id not in p_ids_in_cov: tmp_x = np.array([p_id, default_covid,",
"X[np.int64(population[:, 0]), :] #X = get_temproal_data(covariates, population) dense = 0 else: #print included",
"= X[np.int64(population[:, 0]), :] #X = get_temproal_data(covariates, population) dense = 0 else: #print",
"32) test_pred = [] for test in test_batch: pred_test1 = modelTrained.predict_proba(test)[:, 1] test_pred",
"+ train,test indexes + validation index y=population[:,1] #print covariates.shape if modeltype == 'temporal':",
"= np.concatenate((test_pred , pred_test1), axis = 0) else: test_pred = modelTrained.predict_proba(X)[:, 1] if",
"np.concatenate((test_pred , pred_test1), axis = 0) else: test_pred = modelTrained.predict_proba(X)[:, 1] if test_pred.ndim",
"tmp_x = np.array([p_id, default_covid, 1, 0]).reshape(1,4) #default cov id, timeid=1 full_covariates = np.concatenate((full_covariates,",
"named new_pred #================================================================ import numpy as np from collections import OrderedDict import os",
"X print(\"Loading Data...\") # load data + train,test indexes + validation index y=population[:,1]",
"print(\"Calculating predictions on population...\") if autoencoder: autoencoder_model = joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X = autoencoder_model.get_encode_features(X)",
"= np.concatenate((full_covariates, tmp_x), axis=0) else: tmp_x = covariates[covariates[:, 0] == p_id, :] #print",
"index - named new_pred #================================================================ import numpy as np from collections import OrderedDict",
"# OUTPUT: # it returns a file with indexes merged with prediction for",
"# load index file print(\"population loaded- %s rows and %s columns\" %(np.shape(population)[0], np.shape(population)[1]))",
"if p_id not in p_ids_in_cov: tmp_x = np.array([p_id, default_covid, 1, 0]).reshape(1,4) #default cov",
"print(\"Loading Data...\") # load data + train,test indexes + validation index y=population[:,1] #print",
"if \"python_dir\" in globals(): sys.path.insert(0, python_dir) import TorchUtils as tu #================================================================ print(\"Applying Python",
"timeid_len, predict = True) return X print(\"Loading Data...\") # load data + train,test",
"print(\"Prediction complete: %s rows\" %(np.shape(test_pred)[0])) print(\"Mean: %s prediction value\" %(np.mean(test_pred))) # merge pred",
"collections import OrderedDict import os import sys import timeit import math #from sklearn.ensemble",
"index file print(\"population loaded- %s rows and %s columns\" %(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset has",
"import TorchUtils as tu #================================================================ print(\"Applying Python Model\") ########################################################################### def get_temproal_data(covariates, population): p_ids_in_cov",
"X = X[:,included.flatten()] # load index file print(\"population loaded- %s rows and %s",
"sklearn.ensemble import RandomForestClassifier #from sklearn.naive_bayes import GaussianNB from scipy.sparse import coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection",
"to dense data...\") X=X.toarray() ########################################################################### # load model print(\"Loading model...\") modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\"))",
"PredefinedSplit from sklearn.externals.joblib import Memory #from sklearn.datasets import load_svmlight_file from sklearn.externals import joblib",
"%s columns\" %(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset has %s rows and %s columns\" %(X.shape[0], X.shape[1]))",
"modeltype == 'temporal': X = plpData.to_dense().numpy() X = X[np.int64(population[:, 0]), :] #X =",
"data...\") X=X.toarray() ########################################################################### # load model print(\"Loading model...\") modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating",
"for p_id in population[:, 0]: if p_id not in p_ids_in_cov: tmp_x = np.array([p_id,",
"model...\") modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating predictions on population...\") if autoencoder: autoencoder_model =",
"print(\"Data ready for model has %s features\" %(np.shape(X)[1])) ########################################################################### # uf dense convert",
"print(\"Loading model...\") modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating predictions on population...\") if autoencoder: autoencoder_model",
"!= 1: test_pred = test_pred[:,1] print(\"Prediction complete: %s rows\" %(np.shape(test_pred)[0])) print(\"Mean: %s prediction",
"0] == p_id, :] #print tmp_x.shape, X.shape full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) X,",
"numpy as np from collections import OrderedDict import os import sys import timeit",
"value\" %(np.mean(test_pred))) # merge pred with population test_pred.shape = (population.shape[0], 1) prediction =",
"validation index y=population[:,1] #print covariates.shape if modeltype == 'temporal': X = plpData.to_dense().numpy() X",
"p_id not in p_ids_in_cov: tmp_x = np.array([p_id, default_covid, 1, 0]).reshape(1,4) #default cov id,",
"complete: %s rows\" %(np.shape(test_pred)[0])) print(\"Mean: %s prediction value\" %(np.mean(test_pred))) # merge pred with",
"= 32) test_pred = [] for test in test_batch: pred_test1 = modelTrained.predict_proba(test)[:, 1]",
"default_covid, 1, 0]).reshape(1,4) #default cov id, timeid=1 full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) else:",
"test_batch: pred_test1 = modelTrained.predict_proba(test)[:, 1] test_pred = np.concatenate((test_pred , pred_test1), axis = 0)",
"%s prediction value\" %(np.mean(test_pred))) # merge pred with population test_pred.shape = (population.shape[0], 1)",
"#print covariates.shape if modeltype == 'temporal': X = plpData.to_dense().numpy() X = X[np.int64(population[:, 0]),",
"random forest model on new data #=============================================================== # INPUT: # 1) location of",
"for test in test_batch: pred_test1 = modelTrained.predict_proba(test)[:, 1] test_pred = np.concatenate((test_pred , pred_test1),",
"%(np.shape(test_pred)[0])) print(\"Mean: %s prediction value\" %(np.mean(test_pred))) # merge pred with population test_pred.shape =",
"timeid_len = len(set(covariates[:, -2])) full_covariates = np.array([]).reshape(0,4) default_covid = covariates[0, 1] for p_id",
"# INPUT: # 1) location of new data # 2) location of model",
"prediction for test index - named new_pred #================================================================ import numpy as np from",
"import Memory #from sklearn.datasets import load_svmlight_file from sklearn.externals import joblib if \"python_dir\" in",
"uf dense convert if dense==1: print(\"converting to dense data...\") X=X.toarray() ########################################################################### # load",
"merged with prediction for test index - named new_pred #================================================================ import numpy as",
"in test_batch: pred_test1 = modelTrained.predict_proba(test)[:, 1] test_pred = np.concatenate((test_pred , pred_test1), axis =",
"dense==1: print(\"converting to dense data...\") X=X.toarray() ########################################################################### # load model print(\"Loading model...\") modelTrained",
"from sklearn.externals.joblib import Memory #from sklearn.datasets import load_svmlight_file from sklearn.externals import joblib if",
"# it returns a file with indexes merged with prediction for test index",
"in p_ids_in_cov: tmp_x = np.array([p_id, default_covid, 1, 0]).reshape(1,4) #default cov id, timeid=1 full_covariates",
"new data # 2) location of model # # OUTPUT: # it returns",
"X = X[np.int64(population[:, 0]), :] #X = get_temproal_data(covariates, population) dense = 0 else:",
"for model has %s features\" %(np.shape(X)[1])) ########################################################################### # uf dense convert if dense==1:",
"sklearn.naive_bayes import GaussianNB from scipy.sparse import coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection import SelectFromModel #from sklearn.cross_validation",
"np.concatenate((full_covariates, tmp_x), axis=0) else: tmp_x = covariates[covariates[:, 0] == p_id, :] #print tmp_x.shape,",
"# apply random forest model on new data #=============================================================== # INPUT: # 1)",
"= covariates[covariates[:, 0] == p_id, :] #print tmp_x.shape, X.shape full_covariates = np.concatenate((full_covariates, tmp_x),",
"coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection import SelectFromModel #from sklearn.cross_validation import PredefinedSplit from sklearn.externals.joblib import Memory",
"########################################################################### def get_temproal_data(covariates, population): p_ids_in_cov = set(covariates[:, 0]) timeid_len = len(set(covariates[:, -2])) full_covariates",
"== 'temporal': test_batch = tu.batch(X, batch_size = 32) test_pred = [] for test",
"== 'temporal': X = plpData.to_dense().numpy() X = X[np.int64(population[:, 0]), :] #X = get_temproal_data(covariates,",
"pred_test1), axis = 0) else: test_pred = modelTrained.predict_proba(X)[:, 1] if test_pred.ndim != 1:",
"import SelectFromModel #from sklearn.cross_validation import PredefinedSplit from sklearn.externals.joblib import Memory #from sklearn.datasets import",
", pred_test1), axis = 0) else: test_pred = modelTrained.predict_proba(X)[:, 1] if test_pred.ndim !=",
"import RandomForestClassifier #from sklearn.naive_bayes import GaussianNB from scipy.sparse import coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection import",
"sklearn.datasets import load_svmlight_file from sklearn.externals import joblib if \"python_dir\" in globals(): sys.path.insert(0, python_dir)",
"it returns a file with indexes merged with prediction for test index -",
"'temporal': test_batch = tu.batch(X, batch_size = 32) test_pred = [] for test in",
"for test index - named new_pred #================================================================ import numpy as np from collections",
"np.shape(population)[1])) print(\"Dataset has %s rows and %s columns\" %(X.shape[0], X.shape[1])) print(\"Data ready for",
"modelTrained.predict_proba(X)[:, 1] if test_pred.ndim != 1: test_pred = test_pred[:,1] print(\"Prediction complete: %s rows\"",
"get_temproal_data(covariates, population) dense = 0 else: #print included X = plpData[population[:,0],:] X =",
"%(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset has %s rows and %s columns\" %(X.shape[0], X.shape[1])) print(\"Data ready",
"timeid_len = timeid_len, predict = True) return X print(\"Loading Data...\") # load data",
"X = plpData.to_dense().numpy() X = X[np.int64(population[:, 0]), :] #X = get_temproal_data(covariates, population) dense",
"tmp_x = covariates[covariates[:, 0] == p_id, :] #print tmp_x.shape, X.shape full_covariates = np.concatenate((full_covariates,",
"import numpy as np from collections import OrderedDict import os import sys import",
"#default cov id, timeid=1 full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) else: tmp_x = covariates[covariates[:,",
"joblib if \"python_dir\" in globals(): sys.path.insert(0, python_dir) import TorchUtils as tu #================================================================ print(\"Applying",
"features\" %(np.shape(X)[1])) ########################################################################### # uf dense convert if dense==1: print(\"converting to dense data...\")",
"covariates[0, 1] for p_id in population[:, 0]: if p_id not in p_ids_in_cov: tmp_x",
"of model # # OUTPUT: # it returns a file with indexes merged",
"# load data + train,test indexes + validation index y=population[:,1] #print covariates.shape if",
"2) location of model # # OUTPUT: # it returns a file with",
"dense = 0 else: #print included X = plpData[population[:,0],:] X = X[:,included.flatten()] #",
"python_dir) import TorchUtils as tu #================================================================ print(\"Applying Python Model\") ########################################################################### def get_temproal_data(covariates, population):",
"print(\"Applying Python Model\") ########################################################################### def get_temproal_data(covariates, population): p_ids_in_cov = set(covariates[:, 0]) timeid_len =",
"#from sklearn.datasets import load_svmlight_file from sklearn.externals import joblib if \"python_dir\" in globals(): sys.path.insert(0,",
"import GaussianNB from scipy.sparse import coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection import SelectFromModel #from sklearn.cross_validation import",
"from sklearn.externals import joblib if \"python_dir\" in globals(): sys.path.insert(0, python_dir) import TorchUtils as",
"Memory #from sklearn.datasets import load_svmlight_file from sklearn.externals import joblib if \"python_dir\" in globals():",
"%s columns\" %(X.shape[0], X.shape[1])) print(\"Data ready for model has %s features\" %(np.shape(X)[1])) ###########################################################################",
"np from collections import OrderedDict import os import sys import timeit import math",
"= np.array([]).reshape(0,4) default_covid = covariates[0, 1] for p_id in population[:, 0]: if p_id",
"= X[:,included.flatten()] # load index file print(\"population loaded- %s rows and %s columns\"",
"joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X = autoencoder_model.get_encode_features(X) if modeltype == 'temporal': test_batch = tu.batch(X, batch_size",
"new data #=============================================================== # INPUT: # 1) location of new data # 2)",
"rows and %s columns\" %(X.shape[0], X.shape[1])) print(\"Data ready for model has %s features\"",
"p_ids_in_cov: tmp_x = np.array([p_id, default_covid, 1, 0]).reshape(1,4) #default cov id, timeid=1 full_covariates =",
"= [] for test in test_batch: pred_test1 = modelTrained.predict_proba(test)[:, 1] test_pred = np.concatenate((test_pred",
"[] for test in test_batch: pred_test1 = modelTrained.predict_proba(test)[:, 1] test_pred = np.concatenate((test_pred ,",
"########################################################################### # load model print(\"Loading model...\") modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating predictions on",
"0]: if p_id not in p_ids_in_cov: tmp_x = np.array([p_id, default_covid, 1, 0]).reshape(1,4) #default",
"0 else: #print included X = plpData[population[:,0],:] X = X[:,included.flatten()] # load index",
"= autoencoder_model.get_encode_features(X) if modeltype == 'temporal': test_batch = tu.batch(X, batch_size = 32) test_pred",
"= tu.convert_to_temporal_format(full_covariates, timeid_len = timeid_len, predict = True) return X print(\"Loading Data...\") #",
"OUTPUT: # it returns a file with indexes merged with prediction for test",
"GaussianNB from scipy.sparse import coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection import SelectFromModel #from sklearn.cross_validation import PredefinedSplit",
"tu #================================================================ print(\"Applying Python Model\") ########################################################################### def get_temproal_data(covariates, population): p_ids_in_cov = set(covariates[:, 0])",
"else: #print included X = plpData[population[:,0],:] X = X[:,included.flatten()] # load index file",
"and %s columns\" %(X.shape[0], X.shape[1])) print(\"Data ready for model has %s features\" %(np.shape(X)[1]))",
"'temporal': X = plpData.to_dense().numpy() X = X[np.int64(population[:, 0]), :] #X = get_temproal_data(covariates, population)",
"0]).reshape(1,4) #default cov id, timeid=1 full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) else: tmp_x =",
"population): p_ids_in_cov = set(covariates[:, 0]) timeid_len = len(set(covariates[:, -2])) full_covariates = np.array([]).reshape(0,4) default_covid",
"print(\"Dataset has %s rows and %s columns\" %(X.shape[0], X.shape[1])) print(\"Data ready for model",
"if modeltype == 'temporal': test_batch = tu.batch(X, batch_size = 32) test_pred = []",
"index y=population[:,1] #print covariates.shape if modeltype == 'temporal': X = plpData.to_dense().numpy() X =",
"plpData.to_dense().numpy() X = X[np.int64(population[:, 0]), :] #X = get_temproal_data(covariates, population) dense = 0",
"#print included X = plpData[population[:,0],:] X = X[:,included.flatten()] # load index file print(\"population",
"print(X.shape) print(\"Calculating predictions on population...\") if autoencoder: autoencoder_model = joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X =",
"returns a file with indexes merged with prediction for test index - named",
"= len(set(covariates[:, -2])) full_covariates = np.array([]).reshape(0,4) default_covid = covariates[0, 1] for p_id in",
"data # 2) location of model # # OUTPUT: # it returns a",
"y=population[:,1] #print covariates.shape if modeltype == 'temporal': X = plpData.to_dense().numpy() X = X[np.int64(population[:,",
"Data...\") # load data + train,test indexes + validation index y=population[:,1] #print covariates.shape",
"# 1) location of new data # 2) location of model # #",
"apply random forest model on new data #=============================================================== # INPUT: # 1) location",
"sys.path.insert(0, python_dir) import TorchUtils as tu #================================================================ print(\"Applying Python Model\") ########################################################################### def get_temproal_data(covariates,",
"return X print(\"Loading Data...\") # load data + train,test indexes + validation index",
"a file with indexes merged with prediction for test index - named new_pred",
"# # OUTPUT: # it returns a file with indexes merged with prediction",
"if dense==1: print(\"converting to dense data...\") X=X.toarray() ########################################################################### # load model print(\"Loading model...\")",
"data + train,test indexes + validation index y=population[:,1] #print covariates.shape if modeltype ==",
"loaded- %s rows and %s columns\" %(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset has %s rows and",
"pred_test1 = modelTrained.predict_proba(test)[:, 1] test_pred = np.concatenate((test_pred , pred_test1), axis = 0) else:",
"print(\"population loaded- %s rows and %s columns\" %(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset has %s rows",
"%(np.shape(X)[1])) ########################################################################### # uf dense convert if dense==1: print(\"converting to dense data...\") X=X.toarray()",
"= True) return X print(\"Loading Data...\") # load data + train,test indexes +",
"%s rows\" %(np.shape(test_pred)[0])) print(\"Mean: %s prediction value\" %(np.mean(test_pred))) # merge pred with population",
"RandomForestClassifier #from sklearn.naive_bayes import GaussianNB from scipy.sparse import coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection import SelectFromModel",
"on new data #=============================================================== # INPUT: # 1) location of new data #",
"import coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection import SelectFromModel #from sklearn.cross_validation import PredefinedSplit from sklearn.externals.joblib import",
"dense data...\") X=X.toarray() ########################################################################### # load model print(\"Loading model...\") modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape)",
"def get_temproal_data(covariates, population): p_ids_in_cov = set(covariates[:, 0]) timeid_len = len(set(covariates[:, -2])) full_covariates =",
"p_id, :] #print tmp_x.shape, X.shape full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) X, patient_keys =",
"########################################################################### # uf dense convert if dense==1: print(\"converting to dense data...\") X=X.toarray() ###########################################################################",
"new_pred #================================================================ import numpy as np from collections import OrderedDict import os import",
"convert if dense==1: print(\"converting to dense data...\") X=X.toarray() ########################################################################### # load model print(\"Loading",
"#from sklearn.feature_selection import SelectFromModel #from sklearn.cross_validation import PredefinedSplit from sklearn.externals.joblib import Memory #from",
"train,test indexes + validation index y=population[:,1] #print covariates.shape if modeltype == 'temporal': X",
"len(set(covariates[:, -2])) full_covariates = np.array([]).reshape(0,4) default_covid = covariates[0, 1] for p_id in population[:,",
"indexes + validation index y=population[:,1] #print covariates.shape if modeltype == 'temporal': X =",
"#from sklearn.naive_bayes import GaussianNB from scipy.sparse import coo_matrix,csr_matrix,vstack,hstack #from sklearn.feature_selection import SelectFromModel #from",
"autoencoder: autoencoder_model = joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X = autoencoder_model.get_encode_features(X) if modeltype == 'temporal': test_batch",
"test_batch = tu.batch(X, batch_size = 32) test_pred = [] for test in test_batch:",
"as tu #================================================================ print(\"Applying Python Model\") ########################################################################### def get_temproal_data(covariates, population): p_ids_in_cov = set(covariates[:,",
"'autoencoder_model.pkl')) X = autoencoder_model.get_encode_features(X) if modeltype == 'temporal': test_batch = tu.batch(X, batch_size =",
"INPUT: # 1) location of new data # 2) location of model #",
"#from sklearn.ensemble import RandomForestClassifier #from sklearn.naive_bayes import GaussianNB from scipy.sparse import coo_matrix,csr_matrix,vstack,hstack #from",
"in globals(): sys.path.insert(0, python_dir) import TorchUtils as tu #================================================================ print(\"Applying Python Model\") ###########################################################################",
"Model\") ########################################################################### def get_temproal_data(covariates, population): p_ids_in_cov = set(covariates[:, 0]) timeid_len = len(set(covariates[:, -2]))",
"population) dense = 0 else: #print included X = plpData[population[:,0],:] X = X[:,included.flatten()]",
"= plpData[population[:,0],:] X = X[:,included.flatten()] # load index file print(\"population loaded- %s rows",
"X=X.toarray() ########################################################################### # load model print(\"Loading model...\") modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating predictions",
"included X = plpData[population[:,0],:] X = X[:,included.flatten()] # load index file print(\"population loaded-",
"import os import sys import timeit import math #from sklearn.ensemble import RandomForestClassifier #from",
"covariates[covariates[:, 0] == p_id, :] #print tmp_x.shape, X.shape full_covariates = np.concatenate((full_covariates, tmp_x), axis=0)",
"test_pred = modelTrained.predict_proba(X)[:, 1] if test_pred.ndim != 1: test_pred = test_pred[:,1] print(\"Prediction complete:",
"file with indexes merged with prediction for test index - named new_pred #================================================================",
"= test_pred[:,1] print(\"Prediction complete: %s rows\" %(np.shape(test_pred)[0])) print(\"Mean: %s prediction value\" %(np.mean(test_pred))) #",
"joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating predictions on population...\") if autoencoder: autoencoder_model = joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X",
"forest model on new data #=============================================================== # INPUT: # 1) location of new",
"full_covariates = np.array([]).reshape(0,4) default_covid = covariates[0, 1] for p_id in population[:, 0]: if",
"os import sys import timeit import math #from sklearn.ensemble import RandomForestClassifier #from sklearn.naive_bayes",
"1) location of new data # 2) location of model # # OUTPUT:",
"get_temproal_data(covariates, population): p_ids_in_cov = set(covariates[:, 0]) timeid_len = len(set(covariates[:, -2])) full_covariates = np.array([]).reshape(0,4)",
"# uf dense convert if dense==1: print(\"converting to dense data...\") X=X.toarray() ########################################################################### #",
"import joblib if \"python_dir\" in globals(): sys.path.insert(0, python_dir) import TorchUtils as tu #================================================================",
"has %s features\" %(np.shape(X)[1])) ########################################################################### # uf dense convert if dense==1: print(\"converting to",
"not in p_ids_in_cov: tmp_x = np.array([p_id, default_covid, 1, 0]).reshape(1,4) #default cov id, timeid=1",
"id, timeid=1 full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) else: tmp_x = covariates[covariates[:, 0] ==",
"= joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating predictions on population...\") if autoencoder: autoencoder_model = joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl'))",
"import math #from sklearn.ensemble import RandomForestClassifier #from sklearn.naive_bayes import GaussianNB from scipy.sparse import",
"load_svmlight_file from sklearn.externals import joblib if \"python_dir\" in globals(): sys.path.insert(0, python_dir) import TorchUtils",
"-2])) full_covariates = np.array([]).reshape(0,4) default_covid = covariates[0, 1] for p_id in population[:, 0]:",
"modelTrained.predict_proba(test)[:, 1] test_pred = np.concatenate((test_pred , pred_test1), axis = 0) else: test_pred =",
"# load model print(\"Loading model...\") modelTrained = joblib.load(os.path.join(model_loc,\"model.pkl\")) print(X.shape) print(\"Calculating predictions on population...\")",
"import sys import timeit import math #from sklearn.ensemble import RandomForestClassifier #from sklearn.naive_bayes import",
"= np.concatenate((full_covariates, tmp_x), axis=0) X, patient_keys = tu.convert_to_temporal_format(full_covariates, timeid_len = timeid_len, predict =",
"1, 0]).reshape(1,4) #default cov id, timeid=1 full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) else: tmp_x",
"plpData[population[:,0],:] X = X[:,included.flatten()] # load index file print(\"population loaded- %s rows and",
"X = plpData[population[:,0],:] X = X[:,included.flatten()] # load index file print(\"population loaded- %s",
"%(X.shape[0], X.shape[1])) print(\"Data ready for model has %s features\" %(np.shape(X)[1])) ########################################################################### # uf",
"tmp_x), axis=0) X, patient_keys = tu.convert_to_temporal_format(full_covariates, timeid_len = timeid_len, predict = True) return",
"TorchUtils as tu #================================================================ print(\"Applying Python Model\") ########################################################################### def get_temproal_data(covariates, population): p_ids_in_cov =",
"load data + train,test indexes + validation index y=population[:,1] #print covariates.shape if modeltype",
"# merge pred with population test_pred.shape = (population.shape[0], 1) prediction = np.append(population,test_pred, axis=1)",
"= tu.batch(X, batch_size = 32) test_pred = [] for test in test_batch: pred_test1",
"#X = get_temproal_data(covariates, population) dense = 0 else: #print included X = plpData[population[:,0],:]",
"%(np.mean(test_pred))) # merge pred with population test_pred.shape = (population.shape[0], 1) prediction = np.append(population,test_pred,",
":] #print tmp_x.shape, X.shape full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) X, patient_keys = tu.convert_to_temporal_format(full_covariates,",
"model has %s features\" %(np.shape(X)[1])) ########################################################################### # uf dense convert if dense==1: print(\"converting",
"= set(covariates[:, 0]) timeid_len = len(set(covariates[:, -2])) full_covariates = np.array([]).reshape(0,4) default_covid = covariates[0,",
"0) else: test_pred = modelTrained.predict_proba(X)[:, 1] if test_pred.ndim != 1: test_pred = test_pred[:,1]",
"%s rows and %s columns\" %(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset has %s rows and %s",
"if modeltype == 'temporal': X = plpData.to_dense().numpy() X = X[np.int64(population[:, 0]), :] #X",
"globals(): sys.path.insert(0, python_dir) import TorchUtils as tu #================================================================ print(\"Applying Python Model\") ########################################################################### def",
"X, patient_keys = tu.convert_to_temporal_format(full_covariates, timeid_len = timeid_len, predict = True) return X print(\"Loading",
"axis = 0) else: test_pred = modelTrained.predict_proba(X)[:, 1] if test_pred.ndim != 1: test_pred",
"= 0 else: #print included X = plpData[population[:,0],:] X = X[:,included.flatten()] # load",
"predictions on population...\") if autoencoder: autoencoder_model = joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X = autoencoder_model.get_encode_features(X) if",
"print(\"Mean: %s prediction value\" %(np.mean(test_pred))) # merge pred with population test_pred.shape = (population.shape[0],",
"1] if test_pred.ndim != 1: test_pred = test_pred[:,1] print(\"Prediction complete: %s rows\" %(np.shape(test_pred)[0]))",
"rows\" %(np.shape(test_pred)[0])) print(\"Mean: %s prediction value\" %(np.mean(test_pred))) # merge pred with population test_pred.shape",
"axis=0) X, patient_keys = tu.convert_to_temporal_format(full_covariates, timeid_len = timeid_len, predict = True) return X",
"autoencoder_model = joblib.load(os.path.join(model_loc, 'autoencoder_model.pkl')) X = autoencoder_model.get_encode_features(X) if modeltype == 'temporal': test_batch =",
"sklearn.externals import joblib if \"python_dir\" in globals(): sys.path.insert(0, python_dir) import TorchUtils as tu",
"dense convert if dense==1: print(\"converting to dense data...\") X=X.toarray() ########################################################################### # load model",
"= timeid_len, predict = True) return X print(\"Loading Data...\") # load data +",
"p_ids_in_cov = set(covariates[:, 0]) timeid_len = len(set(covariates[:, -2])) full_covariates = np.array([]).reshape(0,4) default_covid =",
"#================================================================ print(\"Applying Python Model\") ########################################################################### def get_temproal_data(covariates, population): p_ids_in_cov = set(covariates[:, 0]) timeid_len",
"axis=0) else: tmp_x = covariates[covariates[:, 0] == p_id, :] #print tmp_x.shape, X.shape full_covariates",
"math #from sklearn.ensemble import RandomForestClassifier #from sklearn.naive_bayes import GaussianNB from scipy.sparse import coo_matrix,csr_matrix,vstack,hstack",
"= np.array([p_id, default_covid, 1, 0]).reshape(1,4) #default cov id, timeid=1 full_covariates = np.concatenate((full_covariates, tmp_x),",
"set(covariates[:, 0]) timeid_len = len(set(covariates[:, -2])) full_covariates = np.array([]).reshape(0,4) default_covid = covariates[0, 1]",
"= 0) else: test_pred = modelTrained.predict_proba(X)[:, 1] if test_pred.ndim != 1: test_pred =",
"population[:, 0]: if p_id not in p_ids_in_cov: tmp_x = np.array([p_id, default_covid, 1, 0]).reshape(1,4)",
"<reponame>cynthiayang525/PatientLevelPrediction<gh_stars>100-1000 # apply random forest model on new data #=============================================================== # INPUT: #",
"and %s columns\" %(np.shape(population)[0], np.shape(population)[1])) print(\"Dataset has %s rows and %s columns\" %(X.shape[0],",
"model on new data #=============================================================== # INPUT: # 1) location of new data",
"OrderedDict import os import sys import timeit import math #from sklearn.ensemble import RandomForestClassifier",
"test_pred = np.concatenate((test_pred , pred_test1), axis = 0) else: test_pred = modelTrained.predict_proba(X)[:, 1]",
"else: test_pred = modelTrained.predict_proba(X)[:, 1] if test_pred.ndim != 1: test_pred = test_pred[:,1] print(\"Prediction",
"+ validation index y=population[:,1] #print covariates.shape if modeltype == 'temporal': X = plpData.to_dense().numpy()",
":] #X = get_temproal_data(covariates, population) dense = 0 else: #print included X =",
"tmp_x.shape, X.shape full_covariates = np.concatenate((full_covariates, tmp_x), axis=0) X, patient_keys = tu.convert_to_temporal_format(full_covariates, timeid_len =",
"data #=============================================================== # INPUT: # 1) location of new data # 2) location"
] |
[
"a1[0] t2 = a2[0] num_image = anchors[i]['num_image'] delta = (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for ii",
"points[1:])): t1 = a1[0] t2 = a2[0] num_image = anchors[i]['num_image'] delta = (t2-t1).total_seconds()/float(num_image+1)",
"longitude alt: altitude datetime: date time of the anchor (datetime object) num_image: number",
"datetime from lib.geo import interpolate_lat_lon, compute_bearing, offset_bearing from lib.sequence import Sequence import lib.io",
"from lib.exifedit import ExifEdit def interpolate_with_anchors(anchors, angle_offset): ''' Interpolate gps position and compass",
"import interpolate_lat_lon, compute_bearing, offset_bearing from lib.sequence import Sequence import lib.io import os import",
"datetime.timedelta(seconds=(ii+1)*delta) p = interpolate_lat_lon(points, t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) # get angles bearings = [offset_bearing(compute_bearing(ll1[1],",
"lon: longitude alt: altitude datetime: date time of the anchor (datetime object) num_image:",
"} def test_run(image_path): ''' Test run for images ''' s = Sequence(image_path, check_exif=False)",
"offset_bearing from lib.sequence import Sequence import lib.io import os import sys from lib.exifedit",
"p1 = point(0.5, 0.5, 0.2, t1, num_image-2) p2 = point(0.55, 0.55, 0.0, t2,",
"for i, (a1, a2) in enumerate(zip(points[:], points[1:])): t1 = a1[0] t2 = a2[0]",
"run for images ''' s = Sequence(image_path, check_exif=False) file_list = s.get_file_list(image_path) num_image =",
"inter_points def point(lat, lon, alt, datetime, num_image): return { 'lat': lat, 'lon': lon,",
"for a in anchors] inter_points = [] for i, (a1, a2) in enumerate(zip(points[:],",
"inter_points = [ (p[0], p[1], p[2], p[4], bearing) for p, bearing in zip(inter_points,",
"bearing in zip(inter_points, bearings)] return inter_points def point(lat, lon, alt, datetime, num_image): return",
"t1, num_image-2) p2 = point(0.55, 0.55, 0.0, t2, 0) inter_points = interpolate_with_anchors([p1, p2],",
"''' Test run for images ''' s = Sequence(image_path, check_exif=False) file_list = s.get_file_list(image_path)",
"lib.io import os import sys from lib.exifedit import ExifEdit def interpolate_with_anchors(anchors, angle_offset): '''",
"''' Interpolate gps position and compass angle given a list of anchors anchor:",
"compass angle given a list of anchors anchor: lat: latitude lon: longitude alt:",
"num_image: number of images in between two anchors ''' points = [ (a['datetime'],",
"0.2, t1, num_image-2) p2 = point(0.55, 0.55, 0.0, t2, 0) inter_points = interpolate_with_anchors([p1,",
"from lib.geo import interpolate_lat_lon, compute_bearing, offset_bearing from lib.sequence import Sequence import lib.io import",
"test_run(image_path): ''' Test run for images ''' s = Sequence(image_path, check_exif=False) file_list =",
"p2], angle_offset=-90.0) save_path = os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for f, p in zip(file_list,",
"num_image = len(file_list) t1 = datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2 = datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1 =",
"= a1[0] t2 = a2[0] num_image = anchors[i]['num_image'] delta = (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for",
"Interpolate gps position and compass angle given a list of anchors anchor: lat:",
"os import sys from lib.exifedit import ExifEdit def interpolate_with_anchors(anchors, angle_offset): ''' Interpolate gps",
"for p, bearing in zip(inter_points, bearings)] return inter_points def point(lat, lon, alt, datetime,",
"latitude lon: longitude alt: altitude datetime: date time of the anchor (datetime object)",
"a['lon'], a.get('alt', 0)) for a in anchors] inter_points = [] for i, (a1,",
"[offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1], ll2[2]), angle_offset) for ll1, ll2 in zip(inter_points, inter_points[1:])] bearings.append(bearings[-1]) inter_points",
"point(0.5, 0.5, 0.2, t1, num_image-2) p2 = point(0.55, 0.55, 0.0, t2, 0) inter_points",
"s.get_file_list(image_path) num_image = len(file_list) t1 = datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2 = datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1",
"get angles bearings = [offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1], ll2[2]), angle_offset) for ll1, ll2 in",
"a list of anchors anchor: lat: latitude lon: longitude alt: altitude datetime: date",
"given a list of anchors anchor: lat: latitude lon: longitude alt: altitude datetime:",
"point(lat, lon, alt, datetime, num_image): return { 'lat': lat, 'lon': lon, 'alt': alt,",
"the anchor (datetime object) num_image: number of images in between two anchors '''",
"inter_points[1:])] bearings.append(bearings[-1]) inter_points = [ (p[0], p[1], p[2], p[4], bearing) for p, bearing",
"0.55, 0.0, t2, 0) inter_points = interpolate_with_anchors([p1, p2], angle_offset=-90.0) save_path = os.path.join(image_path, 'processed')",
"[ (p[0], p[1], p[2], p[4], bearing) for p, bearing in zip(inter_points, bearings)] return",
"two anchors ''' points = [ (a['datetime'], a['lat'], a['lon'], a.get('alt', 0)) for a",
"i, (a1, a2) in enumerate(zip(points[:], points[1:])): t1 = a1[0] t2 = a2[0] num_image",
"p = interpolate_lat_lon(points, t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) # get angles bearings = [offset_bearing(compute_bearing(ll1[1], ll1[2],",
"p in zip(file_list, inter_points): meta = ExifEdit(f) meta.add_lat_lon(p[1], p[2]) meta.add_altitude(p[3]) meta.add_date_time_original(p[0]) meta.add_orientation(1) meta.add_direction(p[4])",
"# get angles bearings = [offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1], ll2[2]), angle_offset) for ll1, ll2",
"len(file_list) t1 = datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2 = datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1 = point(0.5, 0.5,",
"points = [ (a['datetime'], a['lat'], a['lon'], a.get('alt', 0)) for a in anchors] inter_points",
"= Sequence(image_path, check_exif=False) file_list = s.get_file_list(image_path) num_image = len(file_list) t1 = datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S')",
"sys from lib.exifedit import ExifEdit def interpolate_with_anchors(anchors, angle_offset): ''' Interpolate gps position and",
"angle given a list of anchors anchor: lat: latitude lon: longitude alt: altitude",
"inter_points.append(points[-1]+(0,0,)) # get angles bearings = [offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1], ll2[2]), angle_offset) for ll1,",
"xrange(num_image): t = t1 + datetime.timedelta(seconds=(ii+1)*delta) p = interpolate_lat_lon(points, t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) #",
"[] for i, (a1, a2) in enumerate(zip(points[:], points[1:])): t1 = a1[0] t2 =",
"Test run for images ''' s = Sequence(image_path, check_exif=False) file_list = s.get_file_list(image_path) num_image",
"''' s = Sequence(image_path, check_exif=False) file_list = s.get_file_list(image_path) num_image = len(file_list) t1 =",
"anchors anchor: lat: latitude lon: longitude alt: altitude datetime: date time of the",
"anchor (datetime object) num_image: number of images in between two anchors ''' points",
"0)) for a in anchors] inter_points = [] for i, (a1, a2) in",
"def point(lat, lon, alt, datetime, num_image): return { 'lat': lat, 'lon': lon, 'alt':",
"def test_run(image_path): ''' Test run for images ''' s = Sequence(image_path, check_exif=False) file_list",
"from lib.sequence import Sequence import lib.io import os import sys from lib.exifedit import",
"enumerate(zip(points[:], points[1:])): t1 = a1[0] t2 = a2[0] num_image = anchors[i]['num_image'] delta =",
"lon, 'alt': alt, 'datetime': datetime, 'num_image': num_image } def test_run(image_path): ''' Test run",
"inter_points = [] for i, (a1, a2) in enumerate(zip(points[:], points[1:])): t1 = a1[0]",
"= interpolate_with_anchors([p1, p2], angle_offset=-90.0) save_path = os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for f, p",
"(a['datetime'], a['lat'], a['lon'], a.get('alt', 0)) for a in anchors] inter_points = [] for",
"in anchors] inter_points = [] for i, (a1, a2) in enumerate(zip(points[:], points[1:])): t1",
"t1 = datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2 = datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1 = point(0.5, 0.5, 0.2,",
"= len(file_list) t1 = datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2 = datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1 = point(0.5,",
"= datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1 = point(0.5, 0.5, 0.2, t1, num_image-2) p2 = point(0.55,",
"inter_points = interpolate_with_anchors([p1, p2], angle_offset=-90.0) save_path = os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for f,",
"= os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for f, p in zip(file_list, inter_points): meta =",
"datetime, 'num_image': num_image } def test_run(image_path): ''' Test run for images ''' s",
"os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for f, p in zip(file_list, inter_points): meta = ExifEdit(f)",
"anchors] inter_points = [] for i, (a1, a2) in enumerate(zip(points[:], points[1:])): t1 =",
"{ 'lat': lat, 'lon': lon, 'alt': alt, 'datetime': datetime, 'num_image': num_image } def",
"for ii in xrange(num_image): t = t1 + datetime.timedelta(seconds=(ii+1)*delta) p = interpolate_lat_lon(points, t)",
"0.0, t2, 0) inter_points = interpolate_with_anchors([p1, p2], angle_offset=-90.0) save_path = os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path)",
"in xrange(num_image): t = t1 + datetime.timedelta(seconds=(ii+1)*delta) p = interpolate_lat_lon(points, t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,))",
"(datetime object) num_image: number of images in between two anchors ''' points =",
"datetime, num_image): return { 'lat': lat, 'lon': lon, 'alt': alt, 'datetime': datetime, 'num_image':",
"num_image-2) p2 = point(0.55, 0.55, 0.0, t2, 0) inter_points = interpolate_with_anchors([p1, p2], angle_offset=-90.0)",
"t2, 0) inter_points = interpolate_with_anchors([p1, p2], angle_offset=-90.0) save_path = os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list))",
"return inter_points def point(lat, lon, alt, datetime, num_image): return { 'lat': lat, 'lon':",
"altitude datetime: date time of the anchor (datetime object) num_image: number of images",
"datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1 = point(0.5, 0.5, 0.2, t1, num_image-2) p2 = point(0.55, 0.55,",
"'%Y_%m_%d_%H_%M_%S') p1 = point(0.5, 0.5, 0.2, t1, num_image-2) p2 = point(0.55, 0.55, 0.0,",
"bearings.append(bearings[-1]) inter_points = [ (p[0], p[1], p[2], p[4], bearing) for p, bearing in",
"position and compass angle given a list of anchors anchor: lat: latitude lon:",
"(t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for ii in xrange(num_image): t = t1 + datetime.timedelta(seconds=(ii+1)*delta) p =",
"'datetime': datetime, 'num_image': num_image } def test_run(image_path): ''' Test run for images '''",
"check_exif=False) file_list = s.get_file_list(image_path) num_image = len(file_list) t1 = datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2 =",
"datetime: date time of the anchor (datetime object) num_image: number of images in",
"list of anchors anchor: lat: latitude lon: longitude alt: altitude datetime: date time",
"between two anchors ''' points = [ (a['datetime'], a['lat'], a['lon'], a.get('alt', 0)) for",
"bearing) for p, bearing in zip(inter_points, bearings)] return inter_points def point(lat, lon, alt,",
"s = Sequence(image_path, check_exif=False) file_list = s.get_file_list(image_path) num_image = len(file_list) t1 = datetime.datetime.strptime('2000_09_03_12_00_00',",
"= datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2 = datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1 = point(0.5, 0.5, 0.2, t1,",
"import os import sys from lib.exifedit import ExifEdit def interpolate_with_anchors(anchors, angle_offset): ''' Interpolate",
"of the anchor (datetime object) num_image: number of images in between two anchors",
"interpolate_with_anchors([p1, p2], angle_offset=-90.0) save_path = os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for f, p in",
"ll1, ll2 in zip(inter_points, inter_points[1:])] bearings.append(bearings[-1]) inter_points = [ (p[0], p[1], p[2], p[4],",
"datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2 = datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1 = point(0.5, 0.5, 0.2, t1, num_image-2)",
"0.5, 0.2, t1, num_image-2) p2 = point(0.55, 0.55, 0.0, t2, 0) inter_points =",
"inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) # get angles bearings = [offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1], ll2[2]), angle_offset) for",
"interpolate_lat_lon, compute_bearing, offset_bearing from lib.sequence import Sequence import lib.io import os import sys",
"zip(inter_points, bearings)] return inter_points def point(lat, lon, alt, datetime, num_image): return { 'lat':",
"'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for f, p in zip(file_list, inter_points): meta = ExifEdit(f) meta.add_lat_lon(p[1],",
"in zip(inter_points, bearings)] return inter_points def point(lat, lon, alt, datetime, num_image): return {",
"Sequence import lib.io import os import sys from lib.exifedit import ExifEdit def interpolate_with_anchors(anchors,",
"delta = (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for ii in xrange(num_image): t = t1 + datetime.timedelta(seconds=(ii+1)*delta)",
"(a1, a2) in enumerate(zip(points[:], points[1:])): t1 = a1[0] t2 = a2[0] num_image =",
"bearings = [offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1], ll2[2]), angle_offset) for ll1, ll2 in zip(inter_points, inter_points[1:])]",
"in between two anchors ''' points = [ (a['datetime'], a['lat'], a['lon'], a.get('alt', 0))",
"lon, alt, datetime, num_image): return { 'lat': lat, 'lon': lon, 'alt': alt, 'datetime':",
"lib.sequence import Sequence import lib.io import os import sys from lib.exifedit import ExifEdit",
"in zip(inter_points, inter_points[1:])] bearings.append(bearings[-1]) inter_points = [ (p[0], p[1], p[2], p[4], bearing) for",
"p[4], bearing) for p, bearing in zip(inter_points, bearings)] return inter_points def point(lat, lon,",
"lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for f, p in zip(file_list, inter_points): meta = ExifEdit(f) meta.add_lat_lon(p[1], p[2])",
"assert(len(inter_points)==len(file_list)) for f, p in zip(file_list, inter_points): meta = ExifEdit(f) meta.add_lat_lon(p[1], p[2]) meta.add_altitude(p[3])",
"lib.exifedit import ExifEdit def interpolate_with_anchors(anchors, angle_offset): ''' Interpolate gps position and compass angle",
"ll2[2]), angle_offset) for ll1, ll2 in zip(inter_points, inter_points[1:])] bearings.append(bearings[-1]) inter_points = [ (p[0],",
"a2[0] num_image = anchors[i]['num_image'] delta = (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for ii in xrange(num_image): t",
"Sequence(image_path, check_exif=False) file_list = s.get_file_list(image_path) num_image = len(file_list) t1 = datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2",
"p, bearing in zip(inter_points, bearings)] return inter_points def point(lat, lon, alt, datetime, num_image):",
"alt, 'datetime': datetime, 'num_image': num_image } def test_run(image_path): ''' Test run for images",
"images in between two anchors ''' points = [ (a['datetime'], a['lat'], a['lon'], a.get('alt',",
"= [] for i, (a1, a2) in enumerate(zip(points[:], points[1:])): t1 = a1[0] t2",
"lib.geo import interpolate_lat_lon, compute_bearing, offset_bearing from lib.sequence import Sequence import lib.io import os",
"'num_image': num_image } def test_run(image_path): ''' Test run for images ''' s =",
"ll2[1], ll2[2]), angle_offset) for ll1, ll2 in zip(inter_points, inter_points[1:])] bearings.append(bearings[-1]) inter_points = [",
"= [offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1], ll2[2]), angle_offset) for ll1, ll2 in zip(inter_points, inter_points[1:])] bearings.append(bearings[-1])",
"f, p in zip(file_list, inter_points): meta = ExifEdit(f) meta.add_lat_lon(p[1], p[2]) meta.add_altitude(p[3]) meta.add_date_time_original(p[0]) meta.add_orientation(1)",
"= [ (p[0], p[1], p[2], p[4], bearing) for p, bearing in zip(inter_points, bearings)]",
"a.get('alt', 0)) for a in anchors] inter_points = [] for i, (a1, a2)",
"zip(inter_points, inter_points[1:])] bearings.append(bearings[-1]) inter_points = [ (p[0], p[1], p[2], p[4], bearing) for p,",
"file_list = s.get_file_list(image_path) num_image = len(file_list) t1 = datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2 = datetime.datetime.strptime('2000_09_03_12_30_00',",
"#!/usr/bin/env python import datetime from lib.geo import interpolate_lat_lon, compute_bearing, offset_bearing from lib.sequence import",
"= point(0.5, 0.5, 0.2, t1, num_image-2) p2 = point(0.55, 0.55, 0.0, t2, 0)",
"inter_points.append(points[i]+(0.0,)) for ii in xrange(num_image): t = t1 + datetime.timedelta(seconds=(ii+1)*delta) p = interpolate_lat_lon(points,",
"0) inter_points = interpolate_with_anchors([p1, p2], angle_offset=-90.0) save_path = os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for",
"= interpolate_lat_lon(points, t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) # get angles bearings = [offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1],",
"= t1 + datetime.timedelta(seconds=(ii+1)*delta) p = interpolate_lat_lon(points, t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) # get angles",
"t = t1 + datetime.timedelta(seconds=(ii+1)*delta) p = interpolate_lat_lon(points, t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) # get",
"num_image = anchors[i]['num_image'] delta = (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for ii in xrange(num_image): t =",
"number of images in between two anchors ''' points = [ (a['datetime'], a['lat'],",
"ll1[2], ll2[1], ll2[2]), angle_offset) for ll1, ll2 in zip(inter_points, inter_points[1:])] bearings.append(bearings[-1]) inter_points =",
"import lib.io import os import sys from lib.exifedit import ExifEdit def interpolate_with_anchors(anchors, angle_offset):",
"object) num_image: number of images in between two anchors ''' points = [",
"t1 = a1[0] t2 = a2[0] num_image = anchors[i]['num_image'] delta = (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,))",
"'lon': lon, 'alt': alt, 'datetime': datetime, 'num_image': num_image } def test_run(image_path): ''' Test",
"in zip(file_list, inter_points): meta = ExifEdit(f) meta.add_lat_lon(p[1], p[2]) meta.add_altitude(p[3]) meta.add_date_time_original(p[0]) meta.add_orientation(1) meta.add_direction(p[4]) meta.write()",
"date time of the anchor (datetime object) num_image: number of images in between",
"a2) in enumerate(zip(points[:], points[1:])): t1 = a1[0] t2 = a2[0] num_image = anchors[i]['num_image']",
"for f, p in zip(file_list, inter_points): meta = ExifEdit(f) meta.add_lat_lon(p[1], p[2]) meta.add_altitude(p[3]) meta.add_date_time_original(p[0])",
"= (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for ii in xrange(num_image): t = t1 + datetime.timedelta(seconds=(ii+1)*delta) p",
"+ datetime.timedelta(seconds=(ii+1)*delta) p = interpolate_lat_lon(points, t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) # get angles bearings =",
"'%Y_%m_%d_%H_%M_%S') t2 = datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1 = point(0.5, 0.5, 0.2, t1, num_image-2) p2",
"p[2], p[4], bearing) for p, bearing in zip(inter_points, bearings)] return inter_points def point(lat,",
"'lat': lat, 'lon': lon, 'alt': alt, 'datetime': datetime, 'num_image': num_image } def test_run(image_path):",
"and compass angle given a list of anchors anchor: lat: latitude lon: longitude",
"= anchors[i]['num_image'] delta = (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for ii in xrange(num_image): t = t1",
"= a2[0] num_image = anchors[i]['num_image'] delta = (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for ii in xrange(num_image):",
"save_path = os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for f, p in zip(file_list, inter_points): meta",
"import ExifEdit def interpolate_with_anchors(anchors, angle_offset): ''' Interpolate gps position and compass angle given",
"anchors[i]['num_image'] delta = (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for ii in xrange(num_image): t = t1 +",
"a in anchors] inter_points = [] for i, (a1, a2) in enumerate(zip(points[:], points[1:])):",
"angle_offset) for ll1, ll2 in zip(inter_points, inter_points[1:])] bearings.append(bearings[-1]) inter_points = [ (p[0], p[1],",
"t1 + datetime.timedelta(seconds=(ii+1)*delta) p = interpolate_lat_lon(points, t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) # get angles bearings",
"p[1], p[2], p[4], bearing) for p, bearing in zip(inter_points, bearings)] return inter_points def",
"alt: altitude datetime: date time of the anchor (datetime object) num_image: number of",
"t2 = datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S') p1 = point(0.5, 0.5, 0.2, t1, num_image-2) p2 =",
"anchor: lat: latitude lon: longitude alt: altitude datetime: date time of the anchor",
"(p[0], p[1], p[2], p[4], bearing) for p, bearing in zip(inter_points, bearings)] return inter_points",
"def interpolate_with_anchors(anchors, angle_offset): ''' Interpolate gps position and compass angle given a list",
"for images ''' s = Sequence(image_path, check_exif=False) file_list = s.get_file_list(image_path) num_image = len(file_list)",
"anchors ''' points = [ (a['datetime'], a['lat'], a['lon'], a.get('alt', 0)) for a in",
"ii in xrange(num_image): t = t1 + datetime.timedelta(seconds=(ii+1)*delta) p = interpolate_lat_lon(points, t) inter_points.append((t,)+p)",
"angles bearings = [offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1], ll2[2]), angle_offset) for ll1, ll2 in zip(inter_points,",
"images ''' s = Sequence(image_path, check_exif=False) file_list = s.get_file_list(image_path) num_image = len(file_list) t1",
"in enumerate(zip(points[:], points[1:])): t1 = a1[0] t2 = a2[0] num_image = anchors[i]['num_image'] delta",
"'alt': alt, 'datetime': datetime, 'num_image': num_image } def test_run(image_path): ''' Test run for",
"''' points = [ (a['datetime'], a['lat'], a['lon'], a.get('alt', 0)) for a in anchors]",
"num_image): return { 'lat': lat, 'lon': lon, 'alt': alt, 'datetime': datetime, 'num_image': num_image",
"t2 = a2[0] num_image = anchors[i]['num_image'] delta = (t2-t1).total_seconds()/float(num_image+1) inter_points.append(points[i]+(0.0,)) for ii in",
"t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) # get angles bearings = [offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1], ll2[2]), angle_offset)",
"for ll1, ll2 in zip(inter_points, inter_points[1:])] bearings.append(bearings[-1]) inter_points = [ (p[0], p[1], p[2],",
"ExifEdit def interpolate_with_anchors(anchors, angle_offset): ''' Interpolate gps position and compass angle given a",
"python import datetime from lib.geo import interpolate_lat_lon, compute_bearing, offset_bearing from lib.sequence import Sequence",
"lat: latitude lon: longitude alt: altitude datetime: date time of the anchor (datetime",
"p2 = point(0.55, 0.55, 0.0, t2, 0) inter_points = interpolate_with_anchors([p1, p2], angle_offset=-90.0) save_path",
"gps position and compass angle given a list of anchors anchor: lat: latitude",
"= s.get_file_list(image_path) num_image = len(file_list) t1 = datetime.datetime.strptime('2000_09_03_12_00_00', '%Y_%m_%d_%H_%M_%S') t2 = datetime.datetime.strptime('2000_09_03_12_30_00', '%Y_%m_%d_%H_%M_%S')",
"a['lat'], a['lon'], a.get('alt', 0)) for a in anchors] inter_points = [] for i,",
"= point(0.55, 0.55, 0.0, t2, 0) inter_points = interpolate_with_anchors([p1, p2], angle_offset=-90.0) save_path =",
"bearings)] return inter_points def point(lat, lon, alt, datetime, num_image): return { 'lat': lat,",
"interpolate_lat_lon(points, t) inter_points.append((t,)+p) inter_points.append(points[-1]+(0,0,)) # get angles bearings = [offset_bearing(compute_bearing(ll1[1], ll1[2], ll2[1], ll2[2]),",
"return { 'lat': lat, 'lon': lon, 'alt': alt, 'datetime': datetime, 'num_image': num_image }",
"import sys from lib.exifedit import ExifEdit def interpolate_with_anchors(anchors, angle_offset): ''' Interpolate gps position",
"ll2 in zip(inter_points, inter_points[1:])] bearings.append(bearings[-1]) inter_points = [ (p[0], p[1], p[2], p[4], bearing)",
"time of the anchor (datetime object) num_image: number of images in between two",
"import Sequence import lib.io import os import sys from lib.exifedit import ExifEdit def",
"alt, datetime, num_image): return { 'lat': lat, 'lon': lon, 'alt': alt, 'datetime': datetime,",
"of anchors anchor: lat: latitude lon: longitude alt: altitude datetime: date time of",
"lat, 'lon': lon, 'alt': alt, 'datetime': datetime, 'num_image': num_image } def test_run(image_path): '''",
"[ (a['datetime'], a['lat'], a['lon'], a.get('alt', 0)) for a in anchors] inter_points = []",
"= [ (a['datetime'], a['lat'], a['lon'], a.get('alt', 0)) for a in anchors] inter_points =",
"of images in between two anchors ''' points = [ (a['datetime'], a['lat'], a['lon'],",
"angle_offset): ''' Interpolate gps position and compass angle given a list of anchors",
"num_image } def test_run(image_path): ''' Test run for images ''' s = Sequence(image_path,",
"point(0.55, 0.55, 0.0, t2, 0) inter_points = interpolate_with_anchors([p1, p2], angle_offset=-90.0) save_path = os.path.join(image_path,",
"angle_offset=-90.0) save_path = os.path.join(image_path, 'processed') lib.io.mkdir_p(save_path) assert(len(inter_points)==len(file_list)) for f, p in zip(file_list, inter_points):",
"interpolate_with_anchors(anchors, angle_offset): ''' Interpolate gps position and compass angle given a list of",
"import datetime from lib.geo import interpolate_lat_lon, compute_bearing, offset_bearing from lib.sequence import Sequence import",
"compute_bearing, offset_bearing from lib.sequence import Sequence import lib.io import os import sys from"
] |
[
"we've hit the end of the list if n + 1 == len(self.items):",
"line += text self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) continue # If the",
"# Add the new entry to the SRT list self.srt.append(srt.Subtitle(index=len(self.srt) + 1, start=start,",
"timedelta(seconds=0) self.outfile = outfile f = open(infile, 'r') self.data = json.loads(f.read()) self.items =",
"# Maximum characters per screen (37 * 2) MAX_LINE_LEN = 37 # Maximum",
"74) characters. Break lines on punctuation, line length, and intervals between words. '''",
"the next word, end it. if text == '.' and len(line) + len(self.get_text(self.items[n",
"No space before punctuation line += text else: line += ' {}'.format(text) else:",
"f_time, _redux, _total)) self.srt[-1].end = f_time # So fix it if len(text) >",
"elif len(tout) + len(t) <= MAX_LINE_LEN: tout += ' {}'.format(t) else: tout +=",
"open(filename, 'w') f.write(srt.compose(self.srt)) f.flush() f.close() if __name__ == \"__main__\": infile = sys.argv[1] outfile",
"length of self.items, we've hit the end of the list if n +",
"punctuation line += text else: line += ' {}'.format(text) else: # Line is",
"(f_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"End timestamp reduced to {} ({}ms, {}ms total",
"behavior. See http://bbc.github.io/subtitle-guidelines/ for recommended practices. ''' MAX_LEN = 74 # Maximum characters",
"{}'.format(text) else: # Line is long enough. Commit it. self._add_line(line, start, self.get_last( i)",
"and '\\n' not in text: # Break the line if not already split",
"f_time = start - timedelta(milliseconds=33) _redux = (f_time - self.srt[-1].end).total_seconds() * 1000 _total",
"the new entry to the SRT list self.srt.append(srt.Subtitle(index=len(self.srt) + 1, start=start, end=end, content=text))",
"and update the pointer to this one if possible.''' old_last = self.last if",
"if 'start_time' in i: start = self.to_delta(i['start_time']) else: start = self.get_last(i) self.get_last(i) def",
"+ timedelta(milliseconds=INTERVAL)) continue # If the text is a period and the line",
"start < self.srt[-1].start + delta: # Is it within the time window? #",
"Seconds any line should persist on-screen class TranscribeToSRT(): def __init__(self, infile, outfile): self.srt",
"within the time window? # Combine self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine: {}\".format(self.srt[-1])) else:",
"{}'.format(t) else: tout += '\\n{}'.format(' '.join(tlist[i:])) break log.debug(\"Split line longer than {} characters:\\n{}==>\\n{}\".format(",
"logging from datetime import timedelta import srt import webvtt log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler())",
"combining window in ms MAX_TIME = 8 # Seconds any line should persist",
"def parse(self): line = '' start = None for n, i in enumerate(self.items):",
"import timedelta import srt import webvtt log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") '''",
"self.data['results']['items'] log.debug(\"{} items found.\".format(len(self.items))) def to_delta(self, str_seconds, int_offset_secs=0): ''' Transform a string representing",
"line. if (self.get_start(i) - self.get_last(i)).total_seconds() > INTERVAL / 1000: log.debug(\"Interval exceeded\") self._add_line(line, start,",
"tout # This could be assigned above, but is done here for the",
"= (_e_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"Length set to {} (removed {}ms, {}ms",
"0: # First line self.srt.append(srt.Subtitle(index=1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) return # Line-combining",
"[] self.subtitles = [] self.last = timedelta(seconds=0) self.outfile = outfile f = open(infile,",
"i) + timedelta(milliseconds=INTERVAL)) line = text if 'start_time' in i: start = self.to_delta(i['start_time'])",
"0: # New line. Start subtitle timestamp. start = self.get_start(i) # If n-1",
"word, end it. if text == '.' and len(line) + len(self.get_text(self.items[n + 1]))",
"items found.\".format(len(self.items))) def to_delta(self, str_seconds, int_offset_secs=0): ''' Transform a string representing seconds in",
"self.srt.append(srt.Subtitle(index=1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) return # Line-combining threshold delta = timedelta(milliseconds=CC_TIME_WINDOW)",
"'' continue # If the time elapsed since the last word is >",
"/ 1000: log.debug(\"Interval exceeded\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text",
"not already split tlist = str.split(text) tout = '' for i, t in",
"f.flush() f.close() if __name__ == \"__main__\": infile = sys.argv[1] outfile = sys.argv[2] t",
"to_delta(self, str_seconds, int_offset_secs=0): ''' Transform a string representing seconds in float (e.g. ss.mmm)",
"int_s) * 1000.0) return timedelta(seconds=int_s + int_offset_secs, milliseconds=int_ms) def get_last(self, i): ''' Return",
"len(self.srt) == 0: # First line self.srt.append(srt.Subtitle(index=1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) return",
"screen (37 * 2) MAX_LINE_LEN = 37 # Maximum characters per line INTERVAL",
"one SRT entry. Subsequent entries should end the previous entry if it comes",
"len(t) <= MAX_LINE_LEN: tout += ' {}'.format(t) else: tout += '\\n{}'.format(' '.join(tlist[i:])) break",
"self.srt[-1].end = _e_time # So fix it if self.srt[-1].end > start: # Previous",
"log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters to control subtitle behavior. See http://bbc.github.io/subtitle-guidelines/ for recommended",
"self.get_last(i) except: log.exception('{}'.format(i)) def get_text(self, i): return i['alternatives'][0]['content'] ''' SRT lines are up",
"import srt import webvtt log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters to",
"74 # Maximum characters per screen (37 * 2) MAX_LINE_LEN = 37 #",
"elapsed since the last word is > INTERVAL ms, go to a new",
"between lines CC_TIME_WINDOW = 500 # Line combining window in ms MAX_TIME =",
"at end of line.\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = ''",
"* 1000.0) return timedelta(seconds=int_s + int_offset_secs, milliseconds=int_ms) def get_last(self, i): ''' Return the",
"self.get_text(i) if len(line) == 0: # New line. Start subtitle timestamp. start =",
"# If the time elapsed since the last word is > INTERVAL ms,",
"# So fix it if self.srt[-1].end > start: # Previous entry ends past",
"self.srt[-1].start + timedelta(seconds=MAX_TIME): _e_time = self.srt[-1].start + timedelta(seconds=MAX_TIME) _redux = (self.srt[-1].end - _e_time).total_seconds()",
"ms MAX_TIME = 8 # Seconds any line should persist on-screen class TranscribeToSRT():",
"= [] self.last = timedelta(seconds=0) self.outfile = outfile f = open(infile, 'r') self.data",
"except: log.exception('{}'.format(i)) def get_text(self, i): return i['alternatives'][0]['content'] ''' SRT lines are up to",
"len(text) < MAX_LEN: # Add it to the line if i['type'] == 'punctuation':",
"self.get_last(i) self.get_last(i) def _add_line(self, text, start, end): ''' As each line comes in,",
"start, end): ''' As each line comes in, set and/or correct the timing.",
"window? # Combine self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine: {}\".format(self.srt[-1])) else: # It is",
"line self.srt.append(srt.Subtitle(index=1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) return # Line-combining threshold delta =",
"# Line-combining threshold delta = timedelta(milliseconds=CC_TIME_WINDOW) if start < self.srt[-1].start + delta: #",
"end): ''' As each line comes in, set and/or correct the timing. Algorithmically,",
"SRT entry. Subsequent entries should end the previous entry if it comes less",
"f.close() if __name__ == \"__main__\": infile = sys.argv[1] outfile = sys.argv[2] t =",
"timedelta(milliseconds=INTERVAL)) line = '' continue # If the time elapsed since the last",
"word and update the pointer to this one if possible.''' old_last = self.last",
"line should persist on-screen class TranscribeToSRT(): def __init__(self, infile, outfile): self.srt = []",
"'.' and len(line) + len(self.get_text(self.items[n + 1])) > MAX_LEN: line += text log.debug(\"Hit",
"{}\".format(self.srt[-1])) else: # It is outside the time window # Previous entry is",
"MAX_LEN: # Add it to the line if i['type'] == 'punctuation': # No",
"on the screen no more than 2 at a time, and for up",
"next entry for the start time and set the end 1 frame (~33ms)",
"i: start = self.to_delta(i['start_time']) else: start = self.get_last(i) self.get_last(i) def _add_line(self, text, start,",
"log.debug(\"Add: {}\".format(self.srt[-1])) #if len(self.srt) > 10: # quit() def write(self, filename=None): if not",
"(usually 74) characters. Break lines on punctuation, line length, and intervals between words.",
"self.outfile = outfile f = open(infile, 'r') self.data = json.loads(f.read()) self.items = self.data['results']['items']",
"fix it if self.srt[-1].end > start: # Previous entry ends past what we're",
"{}ms total display time)\".format( _e_time, _redux, _total)) self.srt[-1].end = _e_time # So fix",
"new entry to the SRT list self.srt.append(srt.Subtitle(index=len(self.srt) + 1, start=start, end=end, content=text)) log.debug(\"Add:",
"list if n + 1 == len(self.items): line += text self._add_line(line, start, self.get_last(",
"transcribed word and update the pointer to this one if possible.''' old_last =",
"= timedelta(seconds=0) self.outfile = outfile f = open(infile, 'r') self.data = json.loads(f.read()) self.items",
"a timedelta) of the last transcribed word and update the pointer to this",
"return self.get_last(i) except: log.exception('{}'.format(i)) def get_text(self, i): return i['alternatives'][0]['content'] ''' SRT lines are",
"characters. Break lines on punctuation, line length, and intervals between words. ''' def",
"''' Parameters to control subtitle behavior. See http://bbc.github.io/subtitle-guidelines/ for recommended practices. ''' MAX_LEN",
"== len(self.items): line += text self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) continue #",
"of the last transcribed word and update the pointer to this one if",
"timedelta(milliseconds=INTERVAL)) line = text start = self.get_start(i) continue if len(line) + len(text) <",
"text: # Break the line if not already split tlist = str.split(text) tout",
"log.exception('{}'.format(i)) def get_text(self, i): return i['alternatives'][0]['content'] ''' SRT lines are up to MAX_LEN",
"ss.mmm) to a timedelta object''' flt_s = float(str_seconds) int_s = int(flt_s) int_ms =",
"be on the screen no more than 2 at a time, and for",
"1000: log.debug(\"Interval exceeded\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text start",
"length, and intervals between words. ''' def parse(self): line = '' start =",
"up to MAX_LEN (usually 74) characters. Break lines on punctuation, line length, and",
"self.outfile f = open(filename, 'w') f.write(srt.compose(self.srt)) f.flush() f.close() if __name__ == \"__main__\": infile",
"infile, outfile): self.srt = [] self.subtitles = [] self.last = timedelta(seconds=0) self.outfile =",
"is > INTERVAL ms, go to a new line. if (self.get_start(i) - self.get_last(i)).total_seconds()",
"the last word is > INTERVAL ms, go to a new line. if",
"log.debug(\"Split line longer than {} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text, tout)) text = tout #",
"in i: return self.to_delta(i['start_time']) else: return self.get_last(i) except: log.exception('{}'.format(i)) def get_text(self, i): return",
"if (self.get_start(i) - self.get_last(i)).total_seconds() > INTERVAL / 1000: log.debug(\"Interval exceeded\") self._add_line(line, start, self.get_last(",
"= t elif len(tout) + len(t) <= MAX_LINE_LEN: tout += ' {}'.format(t) else:",
"self.last = timedelta(seconds=0) self.outfile = outfile f = open(infile, 'r') self.data = json.loads(f.read())",
"else: # Line is long enough. Commit it. self._add_line(line, start, self.get_last( i) +",
"timedelta import srt import webvtt log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters",
"end of the list if n + 1 == len(self.items): line += text",
"t elif len(tout) + len(t) <= MAX_LINE_LEN: tout += ' {}'.format(t) else: tout",
"parse(self): line = '' start = None for n, i in enumerate(self.items): text",
"(self.get_start(i) - self.get_last(i)).total_seconds() > INTERVAL / 1000: log.debug(\"Interval exceeded\") self._add_line(line, start, self.get_last( i)",
"end the previous entry if it comes less than 5 seconds after it.",
"_e_time = self.srt[-1].start + timedelta(seconds=MAX_TIME) _redux = (self.srt[-1].end - _e_time).total_seconds() * 1000 _total",
"_total = (_e_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"Length set to {} (removed {}ms,",
"in enumerate(tlist): if i == 0: # First word tout = t elif",
"log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters to control subtitle behavior. See",
"a period and the line will be over MAX_LEN with the next word,",
"Break the line if not already split tlist = str.split(text) tout = ''",
"last word is > INTERVAL ms, go to a new line. if (self.get_start(i)",
"As each line comes in, set and/or correct the timing. Algorithmically, subtitles are",
"- self.srt[-1].end).total_seconds() * 1000 _total = (f_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"End timestamp",
"past what we're adding f_time = start - timedelta(milliseconds=33) _redux = (f_time -",
"should persist on-screen class TranscribeToSRT(): def __init__(self, infile, outfile): self.srt = [] self.subtitles",
"already split tlist = str.split(text) tout = '' for i, t in enumerate(tlist):",
"logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters to control subtitle behavior. See http://bbc.github.io/subtitle-guidelines/ for",
"exceeded\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text start = self.get_start(i)",
"the next entry for the start time and set the end 1 frame",
"self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) continue # If the text is a",
"INTERVAL / 1000: log.debug(\"Interval exceeded\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line =",
"of a second should be consolidated into one SRT entry. Subsequent entries should",
"re import sys import json import logging from datetime import timedelta import srt",
"return timedelta(seconds=int_s + int_offset_secs, milliseconds=int_ms) def get_last(self, i): ''' Return the timestamp (as",
"and the line will be over MAX_LEN with the next word, end it.",
"seconds. Since each line comes individually from the VBI parser, any lines that",
"end it. if text == '.' and len(line) + len(self.get_text(self.items[n + 1])) >",
"a new line. if (self.get_start(i) - self.get_last(i)).total_seconds() > INTERVAL / 1000: log.debug(\"Interval exceeded\")",
"- int_s) * 1000.0) return timedelta(seconds=int_s + int_offset_secs, milliseconds=int_ms) def get_last(self, i): '''",
"self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text start = self.get_start(i) continue if len(line)",
"= self.get_last(i) self.get_last(i) def _add_line(self, text, start, end): ''' As each line comes",
"i): try: if 'start_time' in i: return self.to_delta(i['start_time']) else: return self.get_last(i) except: log.exception('{}'.format(i))",
"= self.get_start(i) # If n-1 is the length of self.items, we've hit the",
"old_last def get_start(self, i): try: if 'start_time' in i: return self.to_delta(i['start_time']) else: return",
"* 2) MAX_LINE_LEN = 37 # Maximum characters per line INTERVAL = 2000",
"line INTERVAL = 2000 # Minimum time in ms between lines CC_TIME_WINDOW =",
"if it comes less than 5 seconds after it. Check that the next",
"infile = sys.argv[1] outfile = sys.argv[2] t = TranscribeToSRT(infile, outfile) t.parse() t.write() webvtt.from_srt(outfile).save()",
"self.srt[-1].start).total_seconds() * 1000 log.debug(\"Length set to {} (removed {}ms, {}ms total display time)\".format(",
"to MAX_LEN (usually 74) characters. Break lines on punctuation, line length, and intervals",
"previous entry if it comes less than 5 seconds after it. Check that",
"in ms MAX_TIME = 8 # Seconds any line should persist on-screen class",
"enumerate(self.items): text = self.get_text(i) if len(line) == 0: # New line. Start subtitle",
"5 seconds after it. Check that the next entry for the start time",
"the SRT list self.srt.append(srt.Subtitle(index=len(self.srt) + 1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) #if len(self.srt)",
"and set the end 1 frame (~33ms) before it. ''' if len(self.srt) ==",
"1000 log.debug(\"End timestamp reduced to {} ({}ms, {}ms total display time)\".format( f_time, _redux,",
"log.debug(\"{} items found.\".format(len(self.items))) def to_delta(self, str_seconds, int_offset_secs=0): ''' Transform a string representing seconds",
"+ len(self.get_text(self.items[n + 1])) > MAX_LEN: line += text log.debug(\"Hit period at end",
"= '{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine: {}\".format(self.srt[-1])) else: # It is outside the time window",
"MAX_LEN with the next word, end it. if text == '.' and len(line)",
"delta: # Is it within the time window? # Combine self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content,",
"start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) return # Line-combining threshold delta = timedelta(milliseconds=CC_TIME_WINDOW) if",
"to the SRT list self.srt.append(srt.Subtitle(index=len(self.srt) + 1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) #if",
"Return the timestamp (as a timedelta) of the last transcribed word and update",
"outside the time window # Previous entry is too long if self.srt[-1].end >",
"should end the previous entry if it comes less than 5 seconds after",
"8 # Seconds any line should persist on-screen class TranscribeToSRT(): def __init__(self, infile,",
"of the list if n + 1 == len(self.items): line += text self._add_line(line,",
"If the text is a period and the line will be over MAX_LEN",
"to the line if i['type'] == 'punctuation': # No space before punctuation line",
"be assigned above, but is done here for the debug line above #",
"line longer than {} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text, tout)) text = tout # This",
"text if 'start_time' in i: start = self.to_delta(i['start_time']) else: start = self.get_last(i) self.get_last(i)",
"def to_delta(self, str_seconds, int_offset_secs=0): ''' Transform a string representing seconds in float (e.g.",
"self.to_delta(i['start_time']) else: return self.get_last(i) except: log.exception('{}'.format(i)) def get_text(self, i): return i['alternatives'][0]['content'] ''' SRT",
"above, but is done here for the debug line above # Add the",
"each line comes in, set and/or correct the timing. Algorithmically, subtitles are to",
"get_text(self, i): return i['alternatives'][0]['content'] ''' SRT lines are up to MAX_LEN (usually 74)",
"outfile f = open(infile, 'r') self.data = json.loads(f.read()) self.items = self.data['results']['items'] log.debug(\"{} items",
"+ timedelta(seconds=MAX_TIME): _e_time = self.srt[-1].start + timedelta(seconds=MAX_TIME) _redux = (self.srt[-1].end - _e_time).total_seconds() *",
"''' def parse(self): line = '' start = None for n, i in",
"that arrive within half of a second should be consolidated into one SRT",
"= 74 # Maximum characters per screen (37 * 2) MAX_LINE_LEN = 37",
"If the time elapsed since the last word is > INTERVAL ms, go",
"line comes individually from the VBI parser, any lines that arrive within half",
"to be on the screen no more than 2 at a time, and",
"individually from the VBI parser, any lines that arrive within half of a",
"> MAX_LEN: line += text log.debug(\"Hit period at end of line.\") self._add_line(line, start,",
"that the next entry for the start time and set the end 1",
"timedelta object''' flt_s = float(str_seconds) int_s = int(flt_s) int_ms = int((flt_s - int_s)",
"self.srt[-1].start).total_seconds() * 1000 log.debug(\"End timestamp reduced to {} ({}ms, {}ms total display time)\".format(",
"<reponame>asulibraries/AwsTranscribe<gh_stars>0 import re import sys import json import logging from datetime import timedelta",
"go to a new line. if (self.get_start(i) - self.get_last(i)).total_seconds() > INTERVAL / 1000:",
"is long enough. Commit it. self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line =",
"class TranscribeToSRT(): def __init__(self, infile, outfile): self.srt = [] self.subtitles = [] self.last",
"Break lines on punctuation, line length, and intervals between words. ''' def parse(self):",
"+= ' {}'.format(text) else: # Line is long enough. Commit it. self._add_line(line, start,",
"self.srt[-1].start + delta: # Is it within the time window? # Combine self.srt[-1].content",
"end 1 frame (~33ms) before it. ''' if len(self.srt) == 0: # First",
"split tlist = str.split(text) tout = '' for i, t in enumerate(tlist): if",
"== \"__main__\": infile = sys.argv[1] outfile = sys.argv[2] t = TranscribeToSRT(infile, outfile) t.parse()",
"= '' continue # If the time elapsed since the last word is",
"log.debug(\"Interval exceeded\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text start =",
"enough. Commit it. self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text if",
"#if len(self.srt) > 10: # quit() def write(self, filename=None): if not filename: filename",
"self.get_last(i) def _add_line(self, text, start, end): ''' As each line comes in, set",
"Maximum characters per screen (37 * 2) MAX_LINE_LEN = 37 # Maximum characters",
"window # Previous entry is too long if self.srt[-1].end > self.srt[-1].start + timedelta(seconds=MAX_TIME):",
"and/or correct the timing. Algorithmically, subtitles are to be on the screen no",
"correct the timing. Algorithmically, subtitles are to be on the screen no more",
"text = tout # This could be assigned above, but is done here",
"the debug line above # Add the new entry to the SRT list",
"1000 _total = (f_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"End timestamp reduced to {}",
"_e_time).total_seconds() * 1000 _total = (_e_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"Length set to",
"assigned above, but is done here for the debug line above # Add",
"'{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine: {}\".format(self.srt[-1])) else: # It is outside the time window #",
"the end of the list if n + 1 == len(self.items): line +=",
"i) + timedelta(milliseconds=INTERVAL)) line = text start = self.get_start(i) continue if len(line) +",
"i) + timedelta(milliseconds=INTERVAL)) continue # If the text is a period and the",
"_total)) self.srt[-1].end = f_time # So fix it if len(text) > MAX_LINE_LEN and",
"if possible.''' old_last = self.last if 'start_time' in i: self.last = self.to_delta(i['start_time']) return",
"# Break the line if not already split tlist = str.split(text) tout =",
"int_offset_secs=0): ''' Transform a string representing seconds in float (e.g. ss.mmm) to a",
"' {}'.format(t) else: tout += '\\n{}'.format(' '.join(tlist[i:])) break log.debug(\"Split line longer than {}",
"= (f_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"End timestamp reduced to {} ({}ms, {}ms",
"i['type'] == 'punctuation': # No space before punctuation line += text else: line",
"# First word tout = t elif len(tout) + len(t) <= MAX_LINE_LEN: tout",
"of line.\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = '' continue #",
"timedelta(milliseconds=INTERVAL)) continue # If the text is a period and the line will",
"[] self.last = timedelta(seconds=0) self.outfile = outfile f = open(infile, 'r') self.data =",
"(37 * 2) MAX_LINE_LEN = 37 # Maximum characters per line INTERVAL =",
"= self.srt[-1].start + timedelta(seconds=MAX_TIME) _redux = (self.srt[-1].end - _e_time).total_seconds() * 1000 _total =",
"= 8 # Seconds any line should persist on-screen class TranscribeToSRT(): def __init__(self,",
"Is it within the time window? # Combine self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine:",
"float(str_seconds) int_s = int(flt_s) int_ms = int((flt_s - int_s) * 1000.0) return timedelta(seconds=int_s",
"it if len(text) > MAX_LINE_LEN and '\\n' not in text: # Break the",
"before it. ''' if len(self.srt) == 0: # First line self.srt.append(srt.Subtitle(index=1, start=start, end=end,",
"up to MAX_TIME seconds. Since each line comes individually from the VBI parser,",
"# First line self.srt.append(srt.Subtitle(index=1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) return # Line-combining threshold",
"on punctuation, line length, and intervals between words. ''' def parse(self): line =",
"1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) #if len(self.srt) > 10: # quit() def",
"try: if 'start_time' in i: return self.to_delta(i['start_time']) else: return self.get_last(i) except: log.exception('{}'.format(i)) def",
"else: tout += '\\n{}'.format(' '.join(tlist[i:])) break log.debug(\"Split line longer than {} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN,",
"= timedelta(milliseconds=CC_TIME_WINDOW) if start < self.srt[-1].start + delta: # Is it within the",
"text, start, end): ''' As each line comes in, set and/or correct the",
"= self.to_delta(i['start_time']) return old_last def get_start(self, i): try: if 'start_time' in i: return",
"'r') self.data = json.loads(f.read()) self.items = self.data['results']['items'] log.debug(\"{} items found.\".format(len(self.items))) def to_delta(self, str_seconds,",
"# So fix it if len(text) > MAX_LINE_LEN and '\\n' not in text:",
"open(infile, 'r') self.data = json.loads(f.read()) self.items = self.data['results']['items'] log.debug(\"{} items found.\".format(len(self.items))) def to_delta(self,",
"for n, i in enumerate(self.items): text = self.get_text(i) if len(line) == 0: #",
"the time window # Previous entry is too long if self.srt[-1].end > self.srt[-1].start",
"text) log.debug(\"Combine: {}\".format(self.srt[-1])) else: # It is outside the time window # Previous",
"delta = timedelta(milliseconds=CC_TIME_WINDOW) if start < self.srt[-1].start + delta: # Is it within",
"line = text start = self.get_start(i) continue if len(line) + len(text) < MAX_LEN:",
"for i, t in enumerate(tlist): if i == 0: # First word tout",
"n-1 is the length of self.items, we've hit the end of the list",
"subtitle timestamp. start = self.get_start(i) # If n-1 is the length of self.items,",
"start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) continue # If the text is a period",
"MAX_LINE_LEN: tout += ' {}'.format(t) else: tout += '\\n{}'.format(' '.join(tlist[i:])) break log.debug(\"Split line",
"hit the end of the list if n + 1 == len(self.items): line",
"# Seconds any line should persist on-screen class TranscribeToSRT(): def __init__(self, infile, outfile):",
"time elapsed since the last word is > INTERVAL ms, go to a",
"word is > INTERVAL ms, go to a new line. if (self.get_start(i) -",
"import json import logging from datetime import timedelta import srt import webvtt log",
"in ms between lines CC_TIME_WINDOW = 500 # Line combining window in ms",
"Maximum characters per line INTERVAL = 2000 # Minimum time in ms between",
"total display time)\".format( f_time, _redux, _total)) self.srt[-1].end = f_time # So fix it",
"= int(flt_s) int_ms = int((flt_s - int_s) * 1000.0) return timedelta(seconds=int_s + int_offset_secs,",
"in float (e.g. ss.mmm) to a timedelta object''' flt_s = float(str_seconds) int_s =",
"be consolidated into one SRT entry. Subsequent entries should end the previous entry",
"(_e_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"Length set to {} (removed {}ms, {}ms total",
"but is done here for the debug line above # Add the new",
"First line self.srt.append(srt.Subtitle(index=1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) return # Line-combining threshold delta",
"content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) #if len(self.srt) > 10: # quit() def write(self, filename=None): if",
"long enough. Commit it. self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text",
"word tout = t elif len(tout) + len(t) <= MAX_LINE_LEN: tout += '",
"from the VBI parser, any lines that arrive within half of a second",
"timedelta) of the last transcribed word and update the pointer to this one",
"- _e_time).total_seconds() * 1000 _total = (_e_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"Length set",
"else: start = self.get_last(i) self.get_last(i) def _add_line(self, text, start, end): ''' As each",
"any line should persist on-screen class TranscribeToSRT(): def __init__(self, infile, outfile): self.srt =",
"'\\n' not in text: # Break the line if not already split tlist",
"the line if i['type'] == 'punctuation': # No space before punctuation line +=",
"(as a timedelta) of the last transcribed word and update the pointer to",
"- self.srt[-1].start).total_seconds() * 1000 log.debug(\"End timestamp reduced to {} ({}ms, {}ms total display",
"continue # If the time elapsed since the last word is > INTERVAL",
"comes individually from the VBI parser, any lines that arrive within half of",
"reduced to {} ({}ms, {}ms total display time)\".format( f_time, _redux, _total)) self.srt[-1].end =",
"== 0: # First line self.srt.append(srt.Subtitle(index=1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) return #",
"timedelta(milliseconds=33) _redux = (f_time - self.srt[-1].end).total_seconds() * 1000 _total = (f_time - self.srt[-1].start).total_seconds()",
"= '' for i, t in enumerate(tlist): if i == 0: # First",
"entry ends past what we're adding f_time = start - timedelta(milliseconds=33) _redux =",
"+ 1])) > MAX_LEN: line += text log.debug(\"Hit period at end of line.\")",
"webvtt log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters to control subtitle behavior.",
"if n + 1 == len(self.items): line += text self._add_line(line, start, self.get_last( i)",
"VBI parser, any lines that arrive within half of a second should be",
"lines on punctuation, line length, and intervals between words. ''' def parse(self): line",
"time in ms between lines CC_TIME_WINDOW = 500 # Line combining window in",
"tout += '\\n{}'.format(' '.join(tlist[i:])) break log.debug(\"Split line longer than {} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text,",
"to control subtitle behavior. See http://bbc.github.io/subtitle-guidelines/ for recommended practices. ''' MAX_LEN = 74",
"timedelta(seconds=MAX_TIME): _e_time = self.srt[-1].start + timedelta(seconds=MAX_TIME) _redux = (self.srt[-1].end - _e_time).total_seconds() * 1000",
"- self.get_last(i)).total_seconds() > INTERVAL / 1000: log.debug(\"Interval exceeded\") self._add_line(line, start, self.get_last( i) +",
"= start - timedelta(milliseconds=33) _redux = (f_time - self.srt[-1].end).total_seconds() * 1000 _total =",
"ms between lines CC_TIME_WINDOW = 500 # Line combining window in ms MAX_TIME",
"with the next word, end it. if text == '.' and len(line) +",
"to a new line. if (self.get_start(i) - self.get_last(i)).total_seconds() > INTERVAL / 1000: log.debug(\"Interval",
"not in text: # Break the line if not already split tlist =",
"if 'start_time' in i: return self.to_delta(i['start_time']) else: return self.get_last(i) except: log.exception('{}'.format(i)) def get_text(self,",
"def get_last(self, i): ''' Return the timestamp (as a timedelta) of the last",
"SRT lines are up to MAX_LEN (usually 74) characters. Break lines on punctuation,",
"after it. Check that the next entry for the start time and set",
"MAX_TIME seconds. Since each line comes individually from the VBI parser, any lines",
"it comes less than 5 seconds after it. Check that the next entry",
"- timedelta(milliseconds=33) _redux = (f_time - self.srt[-1].end).total_seconds() * 1000 _total = (f_time -",
"persist on-screen class TranscribeToSRT(): def __init__(self, infile, outfile): self.srt = [] self.subtitles =",
"self.last if 'start_time' in i: self.last = self.to_delta(i['start_time']) return old_last def get_start(self, i):",
"= outfile f = open(infile, 'r') self.data = json.loads(f.read()) self.items = self.data['results']['items'] log.debug(\"{}",
"this one if possible.''' old_last = self.last if 'start_time' in i: self.last =",
"start = self.to_delta(i['start_time']) else: start = self.get_last(i) self.get_last(i) def _add_line(self, text, start, end):",
"self.items, we've hit the end of the list if n + 1 ==",
"len(line) == 0: # New line. Start subtitle timestamp. start = self.get_start(i) #",
"# Previous entry is too long if self.srt[-1].end > self.srt[-1].start + timedelta(seconds=MAX_TIME): _e_time",
"0: # First word tout = t elif len(tout) + len(t) <= MAX_LINE_LEN:",
"the previous entry if it comes less than 5 seconds after it. Check",
"on-screen class TranscribeToSRT(): def __init__(self, infile, outfile): self.srt = [] self.subtitles = []",
"text start = self.get_start(i) continue if len(line) + len(text) < MAX_LEN: # Add",
"text self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) continue # If the text is",
"def _add_line(self, text, start, end): ''' As each line comes in, set and/or",
"filename = self.outfile f = open(filename, 'w') f.write(srt.compose(self.srt)) f.flush() f.close() if __name__ ==",
"new line. if (self.get_start(i) - self.get_last(i)).total_seconds() > INTERVAL / 1000: log.debug(\"Interval exceeded\") self._add_line(line,",
"37 # Maximum characters per line INTERVAL = 2000 # Minimum time in",
"and len(line) + len(self.get_text(self.items[n + 1])) > MAX_LEN: line += text log.debug(\"Hit period",
"timestamp (as a timedelta) of the last transcribed word and update the pointer",
"self.get_last( i) + timedelta(milliseconds=INTERVAL)) continue # If the text is a period and",
"it. ''' if len(self.srt) == 0: # First line self.srt.append(srt.Subtitle(index=1, start=start, end=end, content=text))",
"line length, and intervals between words. ''' def parse(self): line = '' start",
"{}\".format(self.srt[-1])) return # Line-combining threshold delta = timedelta(milliseconds=CC_TIME_WINDOW) if start < self.srt[-1].start +",
"> MAX_LINE_LEN and '\\n' not in text: # Break the line if not",
"+ 1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) #if len(self.srt) > 10: # quit()",
"= [] self.subtitles = [] self.last = timedelta(seconds=0) self.outfile = outfile f =",
"in i: self.last = self.to_delta(i['start_time']) return old_last def get_start(self, i): try: if 'start_time'",
"= self.get_start(i) continue if len(line) + len(text) < MAX_LEN: # Add it to",
"get_start(self, i): try: if 'start_time' in i: return self.to_delta(i['start_time']) else: return self.get_last(i) except:",
"_e_time # So fix it if self.srt[-1].end > start: # Previous entry ends",
"start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = '' continue # If the time",
"line.\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = '' continue # If",
"import re import sys import json import logging from datetime import timedelta import",
"longer than {} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text, tout)) text = tout # This could",
"== 0: # First word tout = t elif len(tout) + len(t) <=",
"+ len(text) < MAX_LEN: # Add it to the line if i['type'] ==",
"time window? # Combine self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine: {}\".format(self.srt[-1])) else: # It",
"i, t in enumerate(tlist): if i == 0: # First word tout =",
"1 == len(self.items): line += text self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) continue",
"self.srt[-1].end = f_time # So fix it if len(text) > MAX_LINE_LEN and '\\n'",
"'start_time' in i: start = self.to_delta(i['start_time']) else: start = self.get_last(i) self.get_last(i) def _add_line(self,",
"timedelta(milliseconds=INTERVAL)) line = text if 'start_time' in i: start = self.to_delta(i['start_time']) else: start",
"= 500 # Line combining window in ms MAX_TIME = 8 # Seconds",
"_redux = (self.srt[-1].end - _e_time).total_seconds() * 1000 _total = (_e_time - self.srt[-1].start).total_seconds() *",
"half of a second should be consolidated into one SRT entry. Subsequent entries",
"Parameters to control subtitle behavior. See http://bbc.github.io/subtitle-guidelines/ for recommended practices. ''' MAX_LEN =",
"srt import webvtt log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters to control",
"int_ms = int((flt_s - int_s) * 1000.0) return timedelta(seconds=int_s + int_offset_secs, milliseconds=int_ms) def",
"= f_time # So fix it if len(text) > MAX_LINE_LEN and '\\n' not",
"timedelta(milliseconds=CC_TIME_WINDOW) if start < self.srt[-1].start + delta: # Is it within the time",
"1])) > MAX_LEN: line += text log.debug(\"Hit period at end of line.\") self._add_line(line,",
"+ timedelta(milliseconds=INTERVAL)) line = '' continue # If the time elapsed since the",
"in text: # Break the line if not already split tlist = str.split(text)",
"__name__ == \"__main__\": infile = sys.argv[1] outfile = sys.argv[2] t = TranscribeToSRT(infile, outfile)",
"MAX_LINE_LEN, text, tout)) text = tout # This could be assigned above, but",
"timestamp reduced to {} ({}ms, {}ms total display time)\".format( f_time, _redux, _total)) self.srt[-1].end",
"Commit it. self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text if 'start_time'",
"practices. ''' MAX_LEN = 74 # Maximum characters per screen (37 * 2)",
"set and/or correct the timing. Algorithmically, subtitles are to be on the screen",
"tlist = str.split(text) tout = '' for i, t in enumerate(tlist): if i",
"characters per screen (37 * 2) MAX_LINE_LEN = 37 # Maximum characters per",
"entry. Subsequent entries should end the previous entry if it comes less than",
"2000 # Minimum time in ms between lines CC_TIME_WINDOW = 500 # Line",
"self.last = self.to_delta(i['start_time']) return old_last def get_start(self, i): try: if 'start_time' in i:",
"total display time)\".format( _e_time, _redux, _total)) self.srt[-1].end = _e_time # So fix it",
"Previous entry is too long if self.srt[-1].end > self.srt[-1].start + timedelta(seconds=MAX_TIME): _e_time =",
"'w') f.write(srt.compose(self.srt)) f.flush() f.close() if __name__ == \"__main__\": infile = sys.argv[1] outfile =",
"SRT list self.srt.append(srt.Subtitle(index=len(self.srt) + 1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) #if len(self.srt) >",
"start = self.get_start(i) continue if len(line) + len(text) < MAX_LEN: # Add it",
"# Combine self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine: {}\".format(self.srt[-1])) else: # It is outside",
"= open(infile, 'r') self.data = json.loads(f.read()) self.items = self.data['results']['items'] log.debug(\"{} items found.\".format(len(self.items))) def",
"= self.get_text(i) if len(line) == 0: # New line. Start subtitle timestamp. start",
"len(self.srt) > 10: # quit() def write(self, filename=None): if not filename: filename =",
"if __name__ == \"__main__\": infile = sys.argv[1] outfile = sys.argv[2] t = TranscribeToSRT(infile,",
"# If n-1 is the length of self.items, we've hit the end of",
"= 37 # Maximum characters per line INTERVAL = 2000 # Minimum time",
"self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = '' continue # If the",
"sys import json import logging from datetime import timedelta import srt import webvtt",
"INTERVAL ms, go to a new line. if (self.get_start(i) - self.get_last(i)).total_seconds() > INTERVAL",
"be over MAX_LEN with the next word, end it. if text == '.'",
"self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text if 'start_time' in i:",
"datetime import timedelta import srt import webvtt log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\")",
"* 1000 _total = (f_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"End timestamp reduced to",
"else: return self.get_last(i) except: log.exception('{}'.format(i)) def get_text(self, i): return i['alternatives'][0]['content'] ''' SRT lines",
"# Maximum characters per line INTERVAL = 2000 # Minimum time in ms",
"f.write(srt.compose(self.srt)) f.flush() f.close() if __name__ == \"__main__\": infile = sys.argv[1] outfile = sys.argv[2]",
"if not already split tlist = str.split(text) tout = '' for i, t",
"(~33ms) before it. ''' if len(self.srt) == 0: # First line self.srt.append(srt.Subtitle(index=1, start=start,",
"what we're adding f_time = start - timedelta(milliseconds=33) _redux = (f_time - self.srt[-1].end).total_seconds()",
"self.get_start(i) continue if len(line) + len(text) < MAX_LEN: # Add it to the",
"int_offset_secs, milliseconds=int_ms) def get_last(self, i): ''' Return the timestamp (as a timedelta) of",
"over MAX_LEN with the next word, end it. if text == '.' and",
"flt_s = float(str_seconds) int_s = int(flt_s) int_ms = int((flt_s - int_s) * 1000.0)",
"<= MAX_LINE_LEN: tout += ' {}'.format(t) else: tout += '\\n{}'.format(' '.join(tlist[i:])) break log.debug(\"Split",
"line += ' {}'.format(text) else: # Line is long enough. Commit it. self._add_line(line,",
"== 'punctuation': # No space before punctuation line += text else: line +=",
"Line-combining threshold delta = timedelta(milliseconds=CC_TIME_WINDOW) if start < self.srt[-1].start + delta: # Is",
"entry is too long if self.srt[-1].end > self.srt[-1].start + timedelta(seconds=MAX_TIME): _e_time = self.srt[-1].start",
"= logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters to control subtitle behavior. See http://bbc.github.io/subtitle-guidelines/",
"in i: start = self.to_delta(i['start_time']) else: start = self.get_last(i) self.get_last(i) def _add_line(self, text,",
"the list if n + 1 == len(self.items): line += text self._add_line(line, start,",
"log.debug(\"Length set to {} (removed {}ms, {}ms total display time)\".format( _e_time, _redux, _total))",
"+ delta: # Is it within the time window? # Combine self.srt[-1].content =",
"> INTERVAL / 1000: log.debug(\"Interval exceeded\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line",
"the last transcribed word and update the pointer to this one if possible.'''",
"= float(str_seconds) int_s = int(flt_s) int_ms = int((flt_s - int_s) * 1000.0) return",
"representing seconds in float (e.g. ss.mmm) to a timedelta object''' flt_s = float(str_seconds)",
"= (f_time - self.srt[-1].end).total_seconds() * 1000 _total = (f_time - self.srt[-1].start).total_seconds() * 1000",
"time)\".format( f_time, _redux, _total)) self.srt[-1].end = f_time # So fix it if len(text)",
"second should be consolidated into one SRT entry. Subsequent entries should end the",
"str_seconds, int_offset_secs=0): ''' Transform a string representing seconds in float (e.g. ss.mmm) to",
"self.srt[-1].end > start: # Previous entry ends past what we're adding f_time =",
"end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) #if len(self.srt) > 10: # quit() def write(self, filename=None):",
"Add the new entry to the SRT list self.srt.append(srt.Subtitle(index=len(self.srt) + 1, start=start, end=end,",
"line = text if 'start_time' in i: start = self.to_delta(i['start_time']) else: start =",
"''' Return the timestamp (as a timedelta) of the last transcribed word and",
"here for the debug line above # Add the new entry to the",
"end of line.\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = '' continue",
"write(self, filename=None): if not filename: filename = self.outfile f = open(filename, 'w') f.write(srt.compose(self.srt))",
"(self.srt[-1].end - _e_time).total_seconds() * 1000 _total = (_e_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"Length",
"None for n, i in enumerate(self.items): text = self.get_text(i) if len(line) == 0:",
"i) + timedelta(milliseconds=INTERVAL)) line = '' continue # If the time elapsed since",
"i['alternatives'][0]['content'] ''' SRT lines are up to MAX_LEN (usually 74) characters. Break lines",
"are up to MAX_LEN (usually 74) characters. Break lines on punctuation, line length,",
"# If the text is a period and the line will be over",
"log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters to control subtitle behavior. See http://bbc.github.io/subtitle-guidelines/ for recommended practices.",
"== '.' and len(line) + len(self.get_text(self.items[n + 1])) > MAX_LEN: line += text",
"screen no more than 2 at a time, and for up to MAX_TIME",
"fix it if len(text) > MAX_LINE_LEN and '\\n' not in text: # Break",
"it. self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text if 'start_time' in",
"(f_time - self.srt[-1].end).total_seconds() * 1000 _total = (f_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"End",
"it if self.srt[-1].end > start: # Previous entry ends past what we're adding",
"display time)\".format( f_time, _redux, _total)) self.srt[-1].end = f_time # So fix it if",
"window in ms MAX_TIME = 8 # Seconds any line should persist on-screen",
"set the end 1 frame (~33ms) before it. ''' if len(self.srt) == 0:",
"import webvtt log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters to control subtitle",
"= self.outfile f = open(filename, 'w') f.write(srt.compose(self.srt)) f.flush() f.close() if __name__ == \"__main__\":",
"continue if len(line) + len(text) < MAX_LEN: # Add it to the line",
"arrive within half of a second should be consolidated into one SRT entry.",
"to a timedelta object''' flt_s = float(str_seconds) int_s = int(flt_s) int_ms = int((flt_s",
"+= ' {}'.format(t) else: tout += '\\n{}'.format(' '.join(tlist[i:])) break log.debug(\"Split line longer than",
"characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text, tout)) text = tout # This could be assigned above,",
"timedelta(seconds=int_s + int_offset_secs, milliseconds=int_ms) def get_last(self, i): ''' Return the timestamp (as a",
"MAX_TIME = 8 # Seconds any line should persist on-screen class TranscribeToSRT(): def",
"self.srt[-1].end > self.srt[-1].start + timedelta(seconds=MAX_TIME): _e_time = self.srt[-1].start + timedelta(seconds=MAX_TIME) _redux = (self.srt[-1].end",
"should be consolidated into one SRT entry. Subsequent entries should end the previous",
"in enumerate(self.items): text = self.get_text(i) if len(line) == 0: # New line. Start",
"timing. Algorithmically, subtitles are to be on the screen no more than 2",
"if len(line) + len(text) < MAX_LEN: # Add it to the line if",
"not filename: filename = self.outfile f = open(filename, 'w') f.write(srt.compose(self.srt)) f.flush() f.close() if",
"if len(self.srt) == 0: # First line self.srt.append(srt.Subtitle(index=1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1]))",
"Minimum time in ms between lines CC_TIME_WINDOW = 500 # Line combining window",
"and intervals between words. ''' def parse(self): line = '' start = None",
"({}ms, {}ms total display time)\".format( f_time, _redux, _total)) self.srt[-1].end = f_time # So",
"for the debug line above # Add the new entry to the SRT",
"the time window? # Combine self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine: {}\".format(self.srt[-1])) else: #",
"to this one if possible.''' old_last = self.last if 'start_time' in i: self.last",
"recommended practices. ''' MAX_LEN = 74 # Maximum characters per screen (37 *",
"are to be on the screen no more than 2 at a time,",
"http://bbc.github.io/subtitle-guidelines/ for recommended practices. ''' MAX_LEN = 74 # Maximum characters per screen",
"> 10: # quit() def write(self, filename=None): if not filename: filename = self.outfile",
"any lines that arrive within half of a second should be consolidated into",
"It is outside the time window # Previous entry is too long if",
"= self.data['results']['items'] log.debug(\"{} items found.\".format(len(self.items))) def to_delta(self, str_seconds, int_offset_secs=0): ''' Transform a string",
"list self.srt.append(srt.Subtitle(index=len(self.srt) + 1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) #if len(self.srt) > 10:",
"f = open(infile, 'r') self.data = json.loads(f.read()) self.items = self.data['results']['items'] log.debug(\"{} items found.\".format(len(self.items)))",
"= str.split(text) tout = '' for i, t in enumerate(tlist): if i ==",
"str.split(text) tout = '' for i, t in enumerate(tlist): if i == 0:",
"# quit() def write(self, filename=None): if not filename: filename = self.outfile f =",
"self.get_start(i) # If n-1 is the length of self.items, we've hit the end",
"the end 1 frame (~33ms) before it. ''' if len(self.srt) == 0: #",
"than {} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text, tout)) text = tout # This could be",
"i): return i['alternatives'][0]['content'] ''' SRT lines are up to MAX_LEN (usually 74) characters.",
"> start: # Previous entry ends past what we're adding f_time = start",
"len(line) + len(text) < MAX_LEN: # Add it to the line if i['type']",
"entry to the SRT list self.srt.append(srt.Subtitle(index=len(self.srt) + 1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1]))",
"{}\".format(self.srt[-1])) #if len(self.srt) > 10: # quit() def write(self, filename=None): if not filename:",
"log.debug(\"Add: {}\".format(self.srt[-1])) return # Line-combining threshold delta = timedelta(milliseconds=CC_TIME_WINDOW) if start < self.srt[-1].start",
"# Line combining window in ms MAX_TIME = 8 # Seconds any line",
"'start_time' in i: self.last = self.to_delta(i['start_time']) return old_last def get_start(self, i): try: if",
"self.data = json.loads(f.read()) self.items = self.data['results']['items'] log.debug(\"{} items found.\".format(len(self.items))) def to_delta(self, str_seconds, int_offset_secs=0):",
"1 frame (~33ms) before it. ''' if len(self.srt) == 0: # First line",
"tout)) text = tout # This could be assigned above, but is done",
"line comes in, set and/or correct the timing. Algorithmically, subtitles are to be",
"done here for the debug line above # Add the new entry to",
"update the pointer to this one if possible.''' old_last = self.last if 'start_time'",
"+ timedelta(milliseconds=INTERVAL)) line = text start = self.get_start(i) continue if len(line) + len(text)",
"filename=None): if not filename: filename = self.outfile f = open(filename, 'w') f.write(srt.compose(self.srt)) f.flush()",
"self.srt = [] self.subtitles = [] self.last = timedelta(seconds=0) self.outfile = outfile f",
"Line is long enough. Commit it. self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line",
"Start subtitle timestamp. start = self.get_start(i) # If n-1 is the length of",
"ends past what we're adding f_time = start - timedelta(milliseconds=33) _redux = (f_time",
"next word, end it. if text == '.' and len(line) + len(self.get_text(self.items[n +",
"(removed {}ms, {}ms total display time)\".format( _e_time, _redux, _total)) self.srt[-1].end = _e_time #",
"get_last(self, i): ''' Return the timestamp (as a timedelta) of the last transcribed",
"text == '.' and len(line) + len(self.get_text(self.items[n + 1])) > MAX_LEN: line +=",
"subtitles are to be on the screen no more than 2 at a",
"= (self.srt[-1].end - _e_time).total_seconds() * 1000 _total = (_e_time - self.srt[-1].start).total_seconds() * 1000",
"2) MAX_LINE_LEN = 37 # Maximum characters per line INTERVAL = 2000 #",
"string representing seconds in float (e.g. ss.mmm) to a timedelta object''' flt_s =",
"{} ({}ms, {}ms total display time)\".format( f_time, _redux, _total)) self.srt[-1].end = f_time #",
"+= '\\n{}'.format(' '.join(tlist[i:])) break log.debug(\"Split line longer than {} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text, tout))",
"self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text start = self.get_start(i) continue",
"start = None for n, i in enumerate(self.items): text = self.get_text(i) if len(line)",
"len(self.items): line += text self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) continue # If",
"enumerate(tlist): if i == 0: # First word tout = t elif len(tout)",
"+ int_offset_secs, milliseconds=int_ms) def get_last(self, i): ''' Return the timestamp (as a timedelta)",
"return self.to_delta(i['start_time']) else: return self.get_last(i) except: log.exception('{}'.format(i)) def get_text(self, i): return i['alternatives'][0]['content'] '''",
"we're adding f_time = start - timedelta(milliseconds=33) _redux = (f_time - self.srt[-1].end).total_seconds() *",
"pointer to this one if possible.''' old_last = self.last if 'start_time' in i:",
"self.srt.append(srt.Subtitle(index=len(self.srt) + 1, start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) #if len(self.srt) > 10: #",
"MAX_LEN = 74 # Maximum characters per screen (37 * 2) MAX_LINE_LEN =",
"time, and for up to MAX_TIME seconds. Since each line comes individually from",
"'' for i, t in enumerate(tlist): if i == 0: # First word",
"Add it to the line if i['type'] == 'punctuation': # No space before",
"n, i in enumerate(self.items): text = self.get_text(i) if len(line) == 0: # New",
"start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text if 'start_time' in i: start",
"to MAX_TIME seconds. Since each line comes individually from the VBI parser, any",
"text, tout)) text = tout # This could be assigned above, but is",
"comes in, set and/or correct the timing. Algorithmically, subtitles are to be on",
"the pointer to this one if possible.''' old_last = self.last if 'start_time' in",
"self.subtitles = [] self.last = timedelta(seconds=0) self.outfile = outfile f = open(infile, 'r')",
"line += text else: line += ' {}'.format(text) else: # Line is long",
"{} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text, tout)) text = tout # This could be assigned",
"ms, go to a new line. if (self.get_start(i) - self.get_last(i)).total_seconds() > INTERVAL /",
"i == 0: # First word tout = t elif len(tout) + len(t)",
"Check that the next entry for the start time and set the end",
"10: # quit() def write(self, filename=None): if not filename: filename = self.outfile f",
"json import logging from datetime import timedelta import srt import webvtt log =",
"First word tout = t elif len(tout) + len(t) <= MAX_LINE_LEN: tout +=",
"could be assigned above, but is done here for the debug line above",
"= None for n, i in enumerate(self.items): text = self.get_text(i) if len(line) ==",
"1000 _total = (_e_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"Length set to {} (removed",
"period and the line will be over MAX_LEN with the next word, end",
"_add_line(self, text, start, end): ''' As each line comes in, set and/or correct",
"i in enumerate(self.items): text = self.get_text(i) if len(line) == 0: # New line.",
"since the last word is > INTERVAL ms, go to a new line.",
"entry if it comes less than 5 seconds after it. Check that the",
"self.to_delta(i['start_time']) return old_last def get_start(self, i): try: if 'start_time' in i: return self.to_delta(i['start_time'])",
"= 2000 # Minimum time in ms between lines CC_TIME_WINDOW = 500 #",
"If n-1 is the length of self.items, we've hit the end of the",
"a second should be consolidated into one SRT entry. Subsequent entries should end",
"* 1000 _total = (_e_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"Length set to {}",
"if not filename: filename = self.outfile f = open(filename, 'w') f.write(srt.compose(self.srt)) f.flush() f.close()",
"possible.''' old_last = self.last if 'start_time' in i: self.last = self.to_delta(i['start_time']) return old_last",
"characters per line INTERVAL = 2000 # Minimum time in ms between lines",
"= tout # This could be assigned above, but is done here for",
"line += text log.debug(\"Hit period at end of line.\") self._add_line(line, start, self.get_last( i)",
"intervals between words. ''' def parse(self): line = '' start = None for",
"end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) return # Line-combining threshold delta = timedelta(milliseconds=CC_TIME_WINDOW) if start",
"else: line += ' {}'.format(text) else: # Line is long enough. Commit it.",
"each line comes individually from the VBI parser, any lines that arrive within",
"= '' start = None for n, i in enumerate(self.items): text = self.get_text(i)",
"subtitle behavior. See http://bbc.github.io/subtitle-guidelines/ for recommended practices. ''' MAX_LEN = 74 # Maximum",
"TranscribeToSRT(): def __init__(self, infile, outfile): self.srt = [] self.subtitles = [] self.last =",
"the line will be over MAX_LEN with the next word, end it. if",
"the timestamp (as a timedelta) of the last transcribed word and update the",
"New line. Start subtitle timestamp. start = self.get_start(i) # If n-1 is the",
"= json.loads(f.read()) self.items = self.data['results']['items'] log.debug(\"{} items found.\".format(len(self.items))) def to_delta(self, str_seconds, int_offset_secs=0): '''",
"text is a period and the line will be over MAX_LEN with the",
"= self.last if 'start_time' in i: self.last = self.to_delta(i['start_time']) return old_last def get_start(self,",
"is too long if self.srt[-1].end > self.srt[-1].start + timedelta(seconds=MAX_TIME): _e_time = self.srt[-1].start +",
"than 2 at a time, and for up to MAX_TIME seconds. Since each",
"{}ms, {}ms total display time)\".format( _e_time, _redux, _total)) self.srt[-1].end = _e_time # So",
"= text if 'start_time' in i: start = self.to_delta(i['start_time']) else: start = self.get_last(i)",
"object''' flt_s = float(str_seconds) int_s = int(flt_s) int_ms = int((flt_s - int_s) *",
"(e.g. ss.mmm) to a timedelta object''' flt_s = float(str_seconds) int_s = int(flt_s) int_ms",
"+ timedelta(seconds=MAX_TIME) _redux = (self.srt[-1].end - _e_time).total_seconds() * 1000 _total = (_e_time -",
"\"__main__\": infile = sys.argv[1] outfile = sys.argv[2] t = TranscribeToSRT(infile, outfile) t.parse() t.write()",
"content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) return # Line-combining threshold delta = timedelta(milliseconds=CC_TIME_WINDOW) if start <",
"len(tout) + len(t) <= MAX_LINE_LEN: tout += ' {}'.format(t) else: tout += '\\n{}'.format('",
"log.debug(\"Hit period at end of line.\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line",
"MAX_LEN: line += text log.debug(\"Hit period at end of line.\") self._add_line(line, start, self.get_last(",
"self.srt[-1].end).total_seconds() * 1000 _total = (f_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"End timestamp reduced",
"= self.to_delta(i['start_time']) else: start = self.get_last(i) self.get_last(i) def _add_line(self, text, start, end): '''",
"self.get_last(i)).total_seconds() > INTERVAL / 1000: log.debug(\"Interval exceeded\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL))",
"'\\n{}'.format(' '.join(tlist[i:])) break log.debug(\"Split line longer than {} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text, tout)) text",
"int((flt_s - int_s) * 1000.0) return timedelta(seconds=int_s + int_offset_secs, milliseconds=int_ms) def get_last(self, i):",
"# No space before punctuation line += text else: line += ' {}'.format(text)",
"it. Check that the next entry for the start time and set the",
"''' Transform a string representing seconds in float (e.g. ss.mmm) to a timedelta",
"start=start, end=end, content=text)) log.debug(\"Add: {}\".format(self.srt[-1])) #if len(self.srt) > 10: # quit() def write(self,",
"seconds in float (e.g. ss.mmm) to a timedelta object''' flt_s = float(str_seconds) int_s",
"found.\".format(len(self.items))) def to_delta(self, str_seconds, int_offset_secs=0): ''' Transform a string representing seconds in float",
"Since each line comes individually from the VBI parser, any lines that arrive",
"the timing. Algorithmically, subtitles are to be on the screen no more than",
"entry for the start time and set the end 1 frame (~33ms) before",
"within half of a second should be consolidated into one SRT entry. Subsequent",
"a string representing seconds in float (e.g. ss.mmm) to a timedelta object''' flt_s",
"to {} (removed {}ms, {}ms total display time)\".format( _e_time, _redux, _total)) self.srt[-1].end =",
"So fix it if self.srt[-1].end > start: # Previous entry ends past what",
"< MAX_LEN: # Add it to the line if i['type'] == 'punctuation': #",
"consolidated into one SRT entry. Subsequent entries should end the previous entry if",
"- self.srt[-1].start).total_seconds() * 1000 log.debug(\"Length set to {} (removed {}ms, {}ms total display",
"_total)) self.srt[-1].end = _e_time # So fix it if self.srt[-1].end > start: #",
"MAX_LEN (usually 74) characters. Break lines on punctuation, line length, and intervals between",
"line = '' start = None for n, i in enumerate(self.items): text =",
"will be over MAX_LEN with the next word, end it. if text ==",
"log.debug(\"End timestamp reduced to {} ({}ms, {}ms total display time)\".format( f_time, _redux, _total))",
"''' SRT lines are up to MAX_LEN (usually 74) characters. Break lines on",
"a time, and for up to MAX_TIME seconds. Since each line comes individually",
"punctuation, line length, and intervals between words. ''' def parse(self): line = ''",
"_redux = (f_time - self.srt[-1].end).total_seconds() * 1000 _total = (f_time - self.srt[-1].start).total_seconds() *",
"''' MAX_LEN = 74 # Maximum characters per screen (37 * 2) MAX_LINE_LEN",
"i: return self.to_delta(i['start_time']) else: return self.get_last(i) except: log.exception('{}'.format(i)) def get_text(self, i): return i['alternatives'][0]['content']",
"start = self.get_start(i) # If n-1 is the length of self.items, we've hit",
"tout = '' for i, t in enumerate(tlist): if i == 0: #",
"less than 5 seconds after it. Check that the next entry for the",
"self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = '' continue # If the time elapsed",
"''' if len(self.srt) == 0: # First line self.srt.append(srt.Subtitle(index=1, start=start, end=end, content=text)) log.debug(\"Add:",
"no more than 2 at a time, and for up to MAX_TIME seconds.",
"+= text log.debug(\"Hit period at end of line.\") self._add_line(line, start, self.get_last( i) +",
"return i['alternatives'][0]['content'] ''' SRT lines are up to MAX_LEN (usually 74) characters. Break",
"_redux, _total)) self.srt[-1].end = _e_time # So fix it if self.srt[-1].end > start:",
"> INTERVAL ms, go to a new line. if (self.get_start(i) - self.get_last(i)).total_seconds() >",
"self.srt[-1].start + timedelta(seconds=MAX_TIME) _redux = (self.srt[-1].end - _e_time).total_seconds() * 1000 _total = (_e_time",
"to {} ({}ms, {}ms total display time)\".format( f_time, _redux, _total)) self.srt[-1].end = f_time",
"one if possible.''' old_last = self.last if 'start_time' in i: self.last = self.to_delta(i['start_time'])",
"CC_TIME_WINDOW = 500 # Line combining window in ms MAX_TIME = 8 #",
"# Minimum time in ms between lines CC_TIME_WINDOW = 500 # Line combining",
"= text start = self.get_start(i) continue if len(line) + len(text) < MAX_LEN: #",
"2 at a time, and for up to MAX_TIME seconds. Since each line",
"text log.debug(\"Hit period at end of line.\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL))",
"and for up to MAX_TIME seconds. Since each line comes individually from the",
"for up to MAX_TIME seconds. Since each line comes individually from the VBI",
"line will be over MAX_LEN with the next word, end it. if text",
"if text == '.' and len(line) + len(self.get_text(self.items[n + 1])) > MAX_LEN: line",
"at a time, and for up to MAX_TIME seconds. Since each line comes",
"+ len(t) <= MAX_LINE_LEN: tout += ' {}'.format(t) else: tout += '\\n{}'.format(' '.join(tlist[i:]))",
"# It is outside the time window # Previous entry is too long",
"the VBI parser, any lines that arrive within half of a second should",
"__init__(self, infile, outfile): self.srt = [] self.subtitles = [] self.last = timedelta(seconds=0) self.outfile",
"than 5 seconds after it. Check that the next entry for the start",
"control subtitle behavior. See http://bbc.github.io/subtitle-guidelines/ for recommended practices. ''' MAX_LEN = 74 #",
"_e_time, _redux, _total)) self.srt[-1].end = _e_time # So fix it if self.srt[-1].end >",
"{}ms total display time)\".format( f_time, _redux, _total)) self.srt[-1].end = f_time # So fix",
"self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine: {}\".format(self.srt[-1])) else: # It is outside the time",
"+= text else: line += ' {}'.format(text) else: # Line is long enough.",
"last transcribed word and update the pointer to this one if possible.''' old_last",
"# Add it to the line if i['type'] == 'punctuation': # No space",
"text = self.get_text(i) if len(line) == 0: # New line. Start subtitle timestamp.",
"is done here for the debug line above # Add the new entry",
"== 0: # New line. Start subtitle timestamp. start = self.get_start(i) # If",
"set to {} (removed {}ms, {}ms total display time)\".format( _e_time, _redux, _total)) self.srt[-1].end",
"Subsequent entries should end the previous entry if it comes less than 5",
"if i['type'] == 'punctuation': # No space before punctuation line += text else:",
"between words. ''' def parse(self): line = '' start = None for n,",
"len(line) + len(self.get_text(self.items[n + 1])) > MAX_LEN: line += text log.debug(\"Hit period at",
"it. if text == '.' and len(line) + len(self.get_text(self.items[n + 1])) > MAX_LEN:",
"tout += ' {}'.format(t) else: tout += '\\n{}'.format(' '.join(tlist[i:])) break log.debug(\"Split line longer",
"space before punctuation line += text else: line += ' {}'.format(text) else: #",
"long if self.srt[-1].end > self.srt[-1].start + timedelta(seconds=MAX_TIME): _e_time = self.srt[-1].start + timedelta(seconds=MAX_TIME) _redux",
"Algorithmically, subtitles are to be on the screen no more than 2 at",
"len(text) > MAX_LINE_LEN and '\\n' not in text: # Break the line if",
"line if not already split tlist = str.split(text) tout = '' for i,",
"* 1000 log.debug(\"End timestamp reduced to {} ({}ms, {}ms total display time)\".format( f_time,",
"+= text self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) continue # If the text",
"int_s = int(flt_s) int_ms = int((flt_s - int_s) * 1000.0) return timedelta(seconds=int_s +",
"'.join(tlist[i:])) break log.debug(\"Split line longer than {} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text, tout)) text =",
"def write(self, filename=None): if not filename: filename = self.outfile f = open(filename, 'w')",
"float (e.g. ss.mmm) to a timedelta object''' flt_s = float(str_seconds) int_s = int(flt_s)",
"t in enumerate(tlist): if i == 0: # First word tout = t",
"start - timedelta(milliseconds=33) _redux = (f_time - self.srt[-1].end).total_seconds() * 1000 _total = (f_time",
"quit() def write(self, filename=None): if not filename: filename = self.outfile f = open(filename,",
"import logging from datetime import timedelta import srt import webvtt log = logging.getLogger(__name__)",
"is outside the time window # Previous entry is too long if self.srt[-1].end",
"return old_last def get_start(self, i): try: if 'start_time' in i: return self.to_delta(i['start_time']) else:",
"_redux, _total)) self.srt[-1].end = f_time # So fix it if len(text) > MAX_LINE_LEN",
"line = '' continue # If the time elapsed since the last word",
"Previous entry ends past what we're adding f_time = start - timedelta(milliseconds=33) _redux",
"Transform a string representing seconds in float (e.g. ss.mmm) to a timedelta object'''",
"< self.srt[-1].start + delta: # Is it within the time window? # Combine",
"per line INTERVAL = 2000 # Minimum time in ms between lines CC_TIME_WINDOW",
"start = self.get_last(i) self.get_last(i) def _add_line(self, text, start, end): ''' As each line",
"1000 log.debug(\"Length set to {} (removed {}ms, {}ms total display time)\".format( _e_time, _redux,",
"{} (removed {}ms, {}ms total display time)\".format( _e_time, _redux, _total)) self.srt[-1].end = _e_time",
"time)\".format( _e_time, _redux, _total)) self.srt[-1].end = _e_time # So fix it if self.srt[-1].end",
"def get_start(self, i): try: if 'start_time' in i: return self.to_delta(i['start_time']) else: return self.get_last(i)",
"Line combining window in ms MAX_TIME = 8 # Seconds any line should",
"+ timedelta(milliseconds=INTERVAL)) line = text if 'start_time' in i: start = self.to_delta(i['start_time']) else:",
"entries should end the previous entry if it comes less than 5 seconds",
"start time and set the end 1 frame (~33ms) before it. ''' if",
"# Is it within the time window? # Combine self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content, text)",
"log.debug(\"Combine: {}\".format(self.srt[-1])) else: # It is outside the time window # Previous entry",
"if 'start_time' in i: self.last = self.to_delta(i['start_time']) return old_last def get_start(self, i): try:",
"the length of self.items, we've hit the end of the list if n",
"for the start time and set the end 1 frame (~33ms) before it.",
"f = open(filename, 'w') f.write(srt.compose(self.srt)) f.flush() f.close() if __name__ == \"__main__\": infile =",
"f_time # So fix it if len(text) > MAX_LINE_LEN and '\\n' not in",
"is the length of self.items, we've hit the end of the list if",
"if self.srt[-1].end > self.srt[-1].start + timedelta(seconds=MAX_TIME): _e_time = self.srt[-1].start + timedelta(seconds=MAX_TIME) _redux =",
"milliseconds=int_ms) def get_last(self, i): ''' Return the timestamp (as a timedelta) of the",
"break log.debug(\"Split line longer than {} characters:\\n{}==>\\n{}\".format( MAX_LINE_LEN, text, tout)) text = tout",
"into one SRT entry. Subsequent entries should end the previous entry if it",
"if len(line) == 0: # New line. Start subtitle timestamp. start = self.get_start(i)",
"# Line is long enough. Commit it. self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL))",
"' {}'.format(text) else: # Line is long enough. Commit it. self._add_line(line, start, self.get_last(",
"it to the line if i['type'] == 'punctuation': # No space before punctuation",
"= open(filename, 'w') f.write(srt.compose(self.srt)) f.flush() f.close() if __name__ == \"__main__\": infile = sys.argv[1]",
"the line if not already split tlist = str.split(text) tout = '' for",
"int(flt_s) int_ms = int((flt_s - int_s) * 1000.0) return timedelta(seconds=int_s + int_offset_secs, milliseconds=int_ms)",
"def __init__(self, infile, outfile): self.srt = [] self.subtitles = [] self.last = timedelta(seconds=0)",
"the screen no more than 2 at a time, and for up to",
"if self.srt[-1].end > start: # Previous entry ends past what we're adding f_time",
"is a period and the line will be over MAX_LEN with the next",
"adding f_time = start - timedelta(milliseconds=33) _redux = (f_time - self.srt[-1].end).total_seconds() * 1000",
"filename: filename = self.outfile f = open(filename, 'w') f.write(srt.compose(self.srt)) f.flush() f.close() if __name__",
"def get_text(self, i): return i['alternatives'][0]['content'] ''' SRT lines are up to MAX_LEN (usually",
"timestamp. start = self.get_start(i) # If n-1 is the length of self.items, we've",
"Combine self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine: {}\".format(self.srt[-1])) else: # It is outside the",
"json.loads(f.read()) self.items = self.data['results']['items'] log.debug(\"{} items found.\".format(len(self.items))) def to_delta(self, str_seconds, int_offset_secs=0): ''' Transform",
"+ 1 == len(self.items): line += text self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL))",
"''' As each line comes in, set and/or correct the timing. Algorithmically, subtitles",
"So fix it if len(text) > MAX_LINE_LEN and '\\n' not in text: #",
"before punctuation line += text else: line += ' {}'.format(text) else: # Line",
"start: # Previous entry ends past what we're adding f_time = start -",
"'punctuation': # No space before punctuation line += text else: line += '",
"lines that arrive within half of a second should be consolidated into one",
"See http://bbc.github.io/subtitle-guidelines/ for recommended practices. ''' MAX_LEN = 74 # Maximum characters per",
"continue # If the text is a period and the line will be",
"= int((flt_s - int_s) * 1000.0) return timedelta(seconds=int_s + int_offset_secs, milliseconds=int_ms) def get_last(self,",
"outfile): self.srt = [] self.subtitles = [] self.last = timedelta(seconds=0) self.outfile = outfile",
"the time elapsed since the last word is > INTERVAL ms, go to",
"it within the time window? # Combine self.srt[-1].content = '{}\\n{}'.format(self.srt[-1].content, text) log.debug(\"Combine: {}\".format(self.srt[-1]))",
"for recommended practices. ''' MAX_LEN = 74 # Maximum characters per screen (37",
"timedelta(seconds=MAX_TIME) _redux = (self.srt[-1].end - _e_time).total_seconds() * 1000 _total = (_e_time - self.srt[-1].start).total_seconds()",
"return # Line-combining threshold delta = timedelta(milliseconds=CC_TIME_WINDOW) if start < self.srt[-1].start + delta:",
"too long if self.srt[-1].end > self.srt[-1].start + timedelta(seconds=MAX_TIME): _e_time = self.srt[-1].start + timedelta(seconds=MAX_TIME)",
"of self.items, we've hit the end of the list if n + 1",
"start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text start = self.get_start(i) continue if",
"if i == 0: # First word tout = t elif len(tout) +",
"text else: line += ' {}'.format(text) else: # Line is long enough. Commit",
"from datetime import timedelta import srt import webvtt log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG)",
"* 1000 log.debug(\"Length set to {} (removed {}ms, {}ms total display time)\".format( _e_time,",
"MAX_LINE_LEN and '\\n' not in text: # Break the line if not already",
"period at end of line.\") self._add_line(line, start, self.get_last( i) + timedelta(milliseconds=INTERVAL)) line =",
"self.to_delta(i['start_time']) else: start = self.get_last(i) self.get_last(i) def _add_line(self, text, start, end): ''' As",
"if start < self.srt[-1].start + delta: # Is it within the time window?",
"# New line. Start subtitle timestamp. start = self.get_start(i) # If n-1 is",
"time and set the end 1 frame (~33ms) before it. ''' if len(self.srt)",
"time window # Previous entry is too long if self.srt[-1].end > self.srt[-1].start +",
"= _e_time # So fix it if self.srt[-1].end > start: # Previous entry",
"# This could be assigned above, but is done here for the debug",
"words. ''' def parse(self): line = '' start = None for n, i",
"line above # Add the new entry to the SRT list self.srt.append(srt.Subtitle(index=len(self.srt) +",
"threshold delta = timedelta(milliseconds=CC_TIME_WINDOW) if start < self.srt[-1].start + delta: # Is it",
"debug line above # Add the new entry to the SRT list self.srt.append(srt.Subtitle(index=len(self.srt)",
"MAX_LINE_LEN = 37 # Maximum characters per line INTERVAL = 2000 # Minimum",
"self.get_last( i) + timedelta(milliseconds=INTERVAL)) line = text if 'start_time' in i: start =",
"more than 2 at a time, and for up to MAX_TIME seconds. Since",
"the start time and set the end 1 frame (~33ms) before it. '''",
"if len(text) > MAX_LINE_LEN and '\\n' not in text: # Break the line",
"len(self.get_text(self.items[n + 1])) > MAX_LEN: line += text log.debug(\"Hit period at end of",
"tout = t elif len(tout) + len(t) <= MAX_LINE_LEN: tout += ' {}'.format(t)",
"above # Add the new entry to the SRT list self.srt.append(srt.Subtitle(index=len(self.srt) + 1,",
"self.items = self.data['results']['items'] log.debug(\"{} items found.\".format(len(self.items))) def to_delta(self, str_seconds, int_offset_secs=0): ''' Transform a",
"'start_time' in i: return self.to_delta(i['start_time']) else: return self.get_last(i) except: log.exception('{}'.format(i)) def get_text(self, i):",
"_total = (f_time - self.srt[-1].start).total_seconds() * 1000 log.debug(\"End timestamp reduced to {} ({}ms,",
"500 # Line combining window in ms MAX_TIME = 8 # Seconds any",
"sys.path.append(\"/home/ubuntu/.local/lib/python3.6/site-packages\") ''' Parameters to control subtitle behavior. See http://bbc.github.io/subtitle-guidelines/ for recommended practices. '''",
"> self.srt[-1].start + timedelta(seconds=MAX_TIME): _e_time = self.srt[-1].start + timedelta(seconds=MAX_TIME) _redux = (self.srt[-1].end -",
"in, set and/or correct the timing. Algorithmically, subtitles are to be on the",
"seconds after it. Check that the next entry for the start time and",
"lines CC_TIME_WINDOW = 500 # Line combining window in ms MAX_TIME = 8",
"else: # It is outside the time window # Previous entry is too",
"the text is a period and the line will be over MAX_LEN with",
"line if i['type'] == 'punctuation': # No space before punctuation line += text",
"n + 1 == len(self.items): line += text self._add_line(line, start, self.get_last( i) +",
"frame (~33ms) before it. ''' if len(self.srt) == 0: # First line self.srt.append(srt.Subtitle(index=1,",
"a timedelta object''' flt_s = float(str_seconds) int_s = int(flt_s) int_ms = int((flt_s -",
"# Previous entry ends past what we're adding f_time = start - timedelta(milliseconds=33)",
"INTERVAL = 2000 # Minimum time in ms between lines CC_TIME_WINDOW = 500",
"1000.0) return timedelta(seconds=int_s + int_offset_secs, milliseconds=int_ms) def get_last(self, i): ''' Return the timestamp",
"'' start = None for n, i in enumerate(self.items): text = self.get_text(i) if",
"old_last = self.last if 'start_time' in i: self.last = self.to_delta(i['start_time']) return old_last def",
"lines are up to MAX_LEN (usually 74) characters. Break lines on punctuation, line",
"i): ''' Return the timestamp (as a timedelta) of the last transcribed word",
"display time)\".format( _e_time, _redux, _total)) self.srt[-1].end = _e_time # So fix it if",
"i: self.last = self.to_delta(i['start_time']) return old_last def get_start(self, i): try: if 'start_time' in",
"per screen (37 * 2) MAX_LINE_LEN = 37 # Maximum characters per line",
"line. Start subtitle timestamp. start = self.get_start(i) # If n-1 is the length",
"parser, any lines that arrive within half of a second should be consolidated",
"comes less than 5 seconds after it. Check that the next entry for",
"This could be assigned above, but is done here for the debug line",
"import sys import json import logging from datetime import timedelta import srt import"
] |
[
"MockServerJsonContentMismatchException ] = [ e1 for e1 in e.exceptions if isinstance(e1, MockServerJsonContentMismatchException) ]",
"from mockserver_client.mockserver_client import MockServerFriendlyClient from mockserver_client.mockserver_verify_exception import MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch() -> None: expectations_dir:",
"\"test_mock_server\" mock_server_url = \"http://mock-server:1080\" mock_client: MockServerFriendlyClient = MockServerFriendlyClient( base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests(",
"glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) ) for file_path in files: with open(file_path, \"r\") as file: content:",
"for the expectation not triggered assert len(e.exceptions) == 2 json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException ]",
"Any, Dict import pytest import requests import json from requests import Response from",
"\"/foo/1/merge\", json=[content], ) assert response.ok with pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException as e:",
"requests.Session() file_path: str files: List[str] = sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) ) for file_path in",
"str files: List[str] = sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) ) for file_path in files: with",
"and one for the expectation not triggered assert len(e.exceptions) == 2 json_content_mismatch_exceptions: List[",
"= \"http://mock-server:1080\" mock_client: MockServerFriendlyClient = MockServerFriendlyClient( base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\",",
"\"http://mock-server:1080\" mock_client: MockServerFriendlyClient = MockServerFriendlyClient( base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={}",
"\"r\") as file: content: Dict[str, Any] = json.loads(file.read()) response: Response = http.post( mock_server_url",
"# One for the content not matching and one for the expectation not",
"( MockServerExpectationNotFoundException, ) from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import ( MockServerJsonContentMismatchException, ) from mockserver_client.mockserver_client import MockServerFriendlyClient",
"json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException ] = [ e1 for e1 in e.exceptions if isinstance(e1,",
"glob from pathlib import Path from typing import List, Any, Dict import pytest",
"MockServerFriendlyClient( base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={} ) mock_client.expect_default() http =",
"file: content: Dict[str, Any] = json.loads(file.read()) response: Response = http.post( mock_server_url + \"/\"",
"json=[content], ) assert response.ok with pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException as e: #",
"try: mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException as e: # there should be two expectations. #",
"the expectation not triggered assert len(e.exceptions) == 2 json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException ] =",
"MockServerExpectationNotFoundException, ) from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import ( MockServerJsonContentMismatchException, ) from mockserver_client.mockserver_client import MockServerFriendlyClient from",
"assert len(e.exceptions) == 2 json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException ] = [ e1 for e1",
"Path = Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path = Path(__file__).parent.joinpath(\"./requests\") test_name = \"test_mock_server\" mock_server_url = \"http://mock-server:1080\"",
"import MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch() -> None: expectations_dir: Path = Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path =",
") from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import ( MockServerJsonContentMismatchException, ) from mockserver_client.mockserver_client import MockServerFriendlyClient from mockserver_client.mockserver_verify_exception",
"should be two expectations. # One for the content not matching and one",
"e.exceptions if isinstance(e1, MockServerJsonContentMismatchException) ] assert len(json_content_mismatch_exceptions) == 1 expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException ]",
"from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import ( MockServerJsonContentMismatchException, ) from mockserver_client.mockserver_client import MockServerFriendlyClient from mockserver_client.mockserver_verify_exception import",
"triggered assert len(e.exceptions) == 2 json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException ] = [ e1 for",
") assert response.ok with pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException as e: # there",
"as e: # there should be two expectations. # One for the content",
"= Path(__file__).parent.joinpath(\"./requests\") test_name = \"test_mock_server\" mock_server_url = \"http://mock-server:1080\" mock_client: MockServerFriendlyClient = MockServerFriendlyClient( base_url=mock_server_url",
"= [ e1 for e1 in e.exceptions if isinstance(e1, MockServerExpectationNotFoundException) ] assert len(expectation_not_found_exceptions)",
"import Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception import ( MockServerExpectationNotFoundException, ) from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import ( MockServerJsonContentMismatchException,",
"content: Dict[str, Any] = json.loads(file.read()) response: Response = http.post( mock_server_url + \"/\" +",
"path=f\"/{test_name}/foo/1/merge\", json_response_body={} ) mock_client.expect_default() http = requests.Session() file_path: str files: List[str] = sorted(",
"List[ MockServerJsonContentMismatchException ] = [ e1 for e1 in e.exceptions if isinstance(e1, MockServerJsonContentMismatchException)",
"expectation not triggered assert len(e.exceptions) == 2 json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException ] = [",
"from requests import Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception import ( MockServerExpectationNotFoundException, ) from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import",
"MockServerVerifyException as e: # there should be two expectations. # One for the",
"1 expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException ] = [ e1 for e1 in e.exceptions if",
"= sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) ) for file_path in files: with open(file_path, \"r\") as",
"mockserver_client.exceptions.mock_server_json_content_mismatch_exception import ( MockServerJsonContentMismatchException, ) from mockserver_client.mockserver_client import MockServerFriendlyClient from mockserver_client.mockserver_verify_exception import MockServerVerifyException",
"test_name = \"test_mock_server\" mock_server_url = \"http://mock-server:1080\" mock_client: MockServerFriendlyClient = MockServerFriendlyClient( base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\")",
"] = [ e1 for e1 in e.exceptions if isinstance(e1, MockServerExpectationNotFoundException) ] assert",
"e1 in e.exceptions if isinstance(e1, MockServerJsonContentMismatchException) ] assert len(json_content_mismatch_exceptions) == 1 expectation_not_found_exceptions: List[",
"requests_dir: Path = Path(__file__).parent.joinpath(\"./requests\") test_name = \"test_mock_server\" mock_server_url = \"http://mock-server:1080\" mock_client: MockServerFriendlyClient =",
"not triggered assert len(e.exceptions) == 2 json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException ] = [ e1",
"mockserver_client.exceptions.mock_server_expectation_not_found_exception import ( MockServerExpectationNotFoundException, ) from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import ( MockServerJsonContentMismatchException, ) from mockserver_client.mockserver_client",
"for e1 in e.exceptions if isinstance(e1, MockServerJsonContentMismatchException) ] assert len(json_content_mismatch_exceptions) == 1 expectation_not_found_exceptions:",
"if isinstance(e1, MockServerJsonContentMismatchException) ] assert len(json_content_mismatch_exceptions) == 1 expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException ] =",
"import Path from typing import List, Any, Dict import pytest import requests import",
"for file_path in files: with open(file_path, \"r\") as file: content: Dict[str, Any] =",
"# there should be two expectations. # One for the content not matching",
"in e.exceptions if isinstance(e1, MockServerExpectationNotFoundException) ] assert len(expectation_not_found_exceptions) == 1 print(str(e)) raise e",
"import json from requests import Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception import ( MockServerExpectationNotFoundException, ) from",
") mock_client.expect_default() http = requests.Session() file_path: str files: List[str] = sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True)",
"from pathlib import Path from typing import List, Any, Dict import pytest import",
"expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={} ) mock_client.expect_default() http = requests.Session() file_path: str files: List[str] =",
"] assert len(json_content_mismatch_exceptions) == 1 expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException ] = [ e1 for",
"] = [ e1 for e1 in e.exceptions if isinstance(e1, MockServerJsonContentMismatchException) ] assert",
"e1 for e1 in e.exceptions if isinstance(e1, MockServerExpectationNotFoundException) ] assert len(expectation_not_found_exceptions) == 1",
"sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) ) for file_path in files: with open(file_path, \"r\") as file:",
"= http.post( mock_server_url + \"/\" + test_name + \"/foo/1/merge\", json=[content], ) assert response.ok",
"requests import json from requests import Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception import ( MockServerExpectationNotFoundException, )",
"from mockserver_client.exceptions.mock_server_expectation_not_found_exception import ( MockServerExpectationNotFoundException, ) from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import ( MockServerJsonContentMismatchException, ) from",
"mock_server_url = \"http://mock-server:1080\" mock_client: MockServerFriendlyClient = MockServerFriendlyClient( base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir,",
"= Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path = Path(__file__).parent.joinpath(\"./requests\") test_name = \"test_mock_server\" mock_server_url = \"http://mock-server:1080\" mock_client:",
"== 1 expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException ] = [ e1 for e1 in e.exceptions",
"test_name + \"/foo/1/merge\", json=[content], ) assert response.ok with pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException",
"mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={} ) mock_client.expect_default() http = requests.Session() file_path: str files: List[str]",
"\"/\" + test_name + \"/foo/1/merge\", json=[content], ) assert response.ok with pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name)",
"isinstance(e1, MockServerJsonContentMismatchException) ] assert len(json_content_mismatch_exceptions) == 1 expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException ] = [",
"Any] = json.loads(file.read()) response: Response = http.post( mock_server_url + \"/\" + test_name +",
"pathlib import Path from typing import List, Any, Dict import pytest import requests",
"mock_server_url + \"/\" + test_name + \"/foo/1/merge\", json=[content], ) assert response.ok with pytest.raises(MockServerVerifyException):",
"List, Any, Dict import pytest import requests import json from requests import Response",
"List[ MockServerExpectationNotFoundException ] = [ e1 for e1 in e.exceptions if isinstance(e1, MockServerExpectationNotFoundException)",
"import List, Any, Dict import pytest import requests import json from requests import",
"def test_mock_server_from_file_multiple_calls_mismatch() -> None: expectations_dir: Path = Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path = Path(__file__).parent.joinpath(\"./requests\") test_name",
"json.loads(file.read()) response: Response = http.post( mock_server_url + \"/\" + test_name + \"/foo/1/merge\", json=[content],",
"http = requests.Session() file_path: str files: List[str] = sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) ) for",
"in files: with open(file_path, \"r\") as file: content: Dict[str, Any] = json.loads(file.read()) response:",
"mock_client.expect_default() http = requests.Session() file_path: str files: List[str] = sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) )",
"expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException ] = [ e1 for e1 in e.exceptions if isinstance(e1,",
"e: # there should be two expectations. # One for the content not",
"assert len(json_content_mismatch_exceptions) == 1 expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException ] = [ e1 for e1",
"with open(file_path, \"r\") as file: content: Dict[str, Any] = json.loads(file.read()) response: Response =",
"expectations_dir: Path = Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path = Path(__file__).parent.joinpath(\"./requests\") test_name = \"test_mock_server\" mock_server_url =",
"test_mock_server_from_file_multiple_calls_mismatch() -> None: expectations_dir: Path = Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path = Path(__file__).parent.joinpath(\"./requests\") test_name =",
"json from requests import Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception import ( MockServerExpectationNotFoundException, ) from mockserver_client.exceptions.mock_server_json_content_mismatch_exception",
"pytest import requests import json from requests import Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception import (",
"requests import Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception import ( MockServerExpectationNotFoundException, ) from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import (",
"MockServerExpectationNotFoundException ] = [ e1 for e1 in e.exceptions if isinstance(e1, MockServerExpectationNotFoundException) ]",
"MockServerFriendlyClient = MockServerFriendlyClient( base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={} ) mock_client.expect_default()",
"response: Response = http.post( mock_server_url + \"/\" + test_name + \"/foo/1/merge\", json=[content], )",
"2 json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException ] = [ e1 for e1 in e.exceptions if",
"+ test_name + \"/foo/1/merge\", json=[content], ) assert response.ok with pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name) except",
"import MockServerFriendlyClient from mockserver_client.mockserver_verify_exception import MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch() -> None: expectations_dir: Path =",
"import requests import json from requests import Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception import ( MockServerExpectationNotFoundException,",
") mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={} ) mock_client.expect_default() http = requests.Session() file_path:",
"json_response_body={} ) mock_client.expect_default() http = requests.Session() file_path: str files: List[str] = sorted( glob(str(requests_dir.joinpath(\"**/*.json\")),",
"response.ok with pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException as e: # there should be",
"the content not matching and one for the expectation not triggered assert len(e.exceptions)",
"as file: content: Dict[str, Any] = json.loads(file.read()) response: Response = http.post( mock_server_url +",
"from glob import glob from pathlib import Path from typing import List, Any,",
"open(file_path, \"r\") as file: content: Dict[str, Any] = json.loads(file.read()) response: Response = http.post(",
"glob import glob from pathlib import Path from typing import List, Any, Dict",
"base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={} ) mock_client.expect_default() http = requests.Session()",
"import glob from pathlib import Path from typing import List, Any, Dict import",
"http.post( mock_server_url + \"/\" + test_name + \"/foo/1/merge\", json=[content], ) assert response.ok with",
"e1 for e1 in e.exceptions if isinstance(e1, MockServerJsonContentMismatchException) ] assert len(json_content_mismatch_exceptions) == 1",
"MockServerJsonContentMismatchException, ) from mockserver_client.mockserver_client import MockServerFriendlyClient from mockserver_client.mockserver_verify_exception import MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch() ->",
"mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={} ) mock_client.expect_default() http = requests.Session() file_path: str",
"mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException as e: # there should be two expectations. # One",
"pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException as e: # there should be two expectations.",
"= \"test_mock_server\" mock_server_url = \"http://mock-server:1080\" mock_client: MockServerFriendlyClient = MockServerFriendlyClient( base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\") mock_client.reset()",
"len(json_content_mismatch_exceptions) == 1 expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException ] = [ e1 for e1 in",
"mock_client: MockServerFriendlyClient = MockServerFriendlyClient( base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={} )",
"( MockServerJsonContentMismatchException, ) from mockserver_client.mockserver_client import MockServerFriendlyClient from mockserver_client.mockserver_verify_exception import MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch()",
"matching and one for the expectation not triggered assert len(e.exceptions) == 2 json_content_mismatch_exceptions:",
"[ e1 for e1 in e.exceptions if isinstance(e1, MockServerJsonContentMismatchException) ] assert len(json_content_mismatch_exceptions) ==",
"from typing import List, Any, Dict import pytest import requests import json from",
"in e.exceptions if isinstance(e1, MockServerJsonContentMismatchException) ] assert len(json_content_mismatch_exceptions) == 1 expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException",
"mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={} ) mock_client.expect_default() http = requests.Session() file_path: str files:",
"import ( MockServerExpectationNotFoundException, ) from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import ( MockServerJsonContentMismatchException, ) from mockserver_client.mockserver_client import",
"List[str] = sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) ) for file_path in files: with open(file_path, \"r\")",
"= MockServerFriendlyClient( base_url=mock_server_url ) mock_client.clear(f\"/{test_name}/*\") mock_client.reset() mock_client.expect_files_as_json_requests( expectations_dir, path=f\"/{test_name}/foo/1/merge\", json_response_body={} ) mock_client.expect_default() http",
"= [ e1 for e1 in e.exceptions if isinstance(e1, MockServerJsonContentMismatchException) ] assert len(json_content_mismatch_exceptions)",
"MockServerFriendlyClient from mockserver_client.mockserver_verify_exception import MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch() -> None: expectations_dir: Path = Path(__file__).parent.joinpath(\"./expectations\")",
"Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception import ( MockServerExpectationNotFoundException, ) from mockserver_client.exceptions.mock_server_json_content_mismatch_exception import ( MockServerJsonContentMismatchException, )",
"Path from typing import List, Any, Dict import pytest import requests import json",
"one for the expectation not triggered assert len(e.exceptions) == 2 json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException",
"MockServerJsonContentMismatchException) ] assert len(json_content_mismatch_exceptions) == 1 expectation_not_found_exceptions: List[ MockServerExpectationNotFoundException ] = [ e1",
"Path = Path(__file__).parent.joinpath(\"./requests\") test_name = \"test_mock_server\" mock_server_url = \"http://mock-server:1080\" mock_client: MockServerFriendlyClient = MockServerFriendlyClient(",
"[ e1 for e1 in e.exceptions if isinstance(e1, MockServerExpectationNotFoundException) ] assert len(expectation_not_found_exceptions) ==",
") for file_path in files: with open(file_path, \"r\") as file: content: Dict[str, Any]",
"file_path in files: with open(file_path, \"r\") as file: content: Dict[str, Any] = json.loads(file.read())",
"One for the content not matching and one for the expectation not triggered",
"mockserver_client.mockserver_client import MockServerFriendlyClient from mockserver_client.mockserver_verify_exception import MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch() -> None: expectations_dir: Path",
"be two expectations. # One for the content not matching and one for",
"recursive=True) ) for file_path in files: with open(file_path, \"r\") as file: content: Dict[str,",
"Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path = Path(__file__).parent.joinpath(\"./requests\") test_name = \"test_mock_server\" mock_server_url = \"http://mock-server:1080\" mock_client: MockServerFriendlyClient",
"Dict[str, Any] = json.loads(file.read()) response: Response = http.post( mock_server_url + \"/\" + test_name",
"+ \"/foo/1/merge\", json=[content], ) assert response.ok with pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException as",
"from mockserver_client.mockserver_verify_exception import MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch() -> None: expectations_dir: Path = Path(__file__).parent.joinpath(\"./expectations\") requests_dir:",
") from mockserver_client.mockserver_client import MockServerFriendlyClient from mockserver_client.mockserver_verify_exception import MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch() -> None:",
"two expectations. # One for the content not matching and one for the",
"len(e.exceptions) == 2 json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException ] = [ e1 for e1 in",
"MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch() -> None: expectations_dir: Path = Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path = Path(__file__).parent.joinpath(\"./requests\")",
"typing import List, Any, Dict import pytest import requests import json from requests",
"assert response.ok with pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException as e: # there should",
"== 2 json_content_mismatch_exceptions: List[ MockServerJsonContentMismatchException ] = [ e1 for e1 in e.exceptions",
"e1 in e.exceptions if isinstance(e1, MockServerExpectationNotFoundException) ] assert len(expectation_not_found_exceptions) == 1 print(str(e)) raise",
"+ \"/\" + test_name + \"/foo/1/merge\", json=[content], ) assert response.ok with pytest.raises(MockServerVerifyException): try:",
"expectations. # One for the content not matching and one for the expectation",
"content not matching and one for the expectation not triggered assert len(e.exceptions) ==",
"import pytest import requests import json from requests import Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception import",
"= json.loads(file.read()) response: Response = http.post( mock_server_url + \"/\" + test_name + \"/foo/1/merge\",",
"file_path: str files: List[str] = sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) ) for file_path in files:",
"files: List[str] = sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) ) for file_path in files: with open(file_path,",
"except MockServerVerifyException as e: # there should be two expectations. # One for",
"Dict import pytest import requests import json from requests import Response from mockserver_client.exceptions.mock_server_expectation_not_found_exception",
"not matching and one for the expectation not triggered assert len(e.exceptions) == 2",
"files: with open(file_path, \"r\") as file: content: Dict[str, Any] = json.loads(file.read()) response: Response",
"-> None: expectations_dir: Path = Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path = Path(__file__).parent.joinpath(\"./requests\") test_name = \"test_mock_server\"",
"mockserver_client.mockserver_verify_exception import MockServerVerifyException def test_mock_server_from_file_multiple_calls_mismatch() -> None: expectations_dir: Path = Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path",
"Response = http.post( mock_server_url + \"/\" + test_name + \"/foo/1/merge\", json=[content], ) assert",
"import ( MockServerJsonContentMismatchException, ) from mockserver_client.mockserver_client import MockServerFriendlyClient from mockserver_client.mockserver_verify_exception import MockServerVerifyException def",
"Path(__file__).parent.joinpath(\"./requests\") test_name = \"test_mock_server\" mock_server_url = \"http://mock-server:1080\" mock_client: MockServerFriendlyClient = MockServerFriendlyClient( base_url=mock_server_url )",
"there should be two expectations. # One for the content not matching and",
"= requests.Session() file_path: str files: List[str] = sorted( glob(str(requests_dir.joinpath(\"**/*.json\")), recursive=True) ) for file_path",
"with pytest.raises(MockServerVerifyException): try: mock_client.verify_expectations(test_name=test_name) except MockServerVerifyException as e: # there should be two",
"for the content not matching and one for the expectation not triggered assert",
"for e1 in e.exceptions if isinstance(e1, MockServerExpectationNotFoundException) ] assert len(expectation_not_found_exceptions) == 1 print(str(e))",
"None: expectations_dir: Path = Path(__file__).parent.joinpath(\"./expectations\") requests_dir: Path = Path(__file__).parent.joinpath(\"./requests\") test_name = \"test_mock_server\" mock_server_url"
] |
[
"and the following disclaimer in the documentation # and/or other materials provided with",
"# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #",
"name of ytranslate nor the names of its # contributors may be used",
"EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES",
"def OnText(self, text=\"\"): \"\"\"The text of the indicator changes.\"\"\" pass def OnForceDestroy(self): \"\"\"Ask",
"AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL",
"lang = DEFAULT_LANGUAGE # Translation init(root_dir=\"translations\") select(lang) # Classes class DummyUpdater(wx.Frame): \"\"\"Dummy updater,",
"e): \"\"\"The user clicks on 'cancel'.\"\"\" value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO | wx.NO_DEFAULT",
"configobj import ConfigObj from ytranslate import init, select, t import wx from wx.lib.pubsub",
"OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE",
"without # modification, are permitted provided that the following conditions are met: #",
"in binary form must reproduce the above copyright notice, # this list of",
"import AutoUpdate from version import BUILD # Determines the user's language AVAILABLE_LANGUAGES =",
"UpdateGauge(self, value): \"\"\"Change the level indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\", value=value) def UpdateText(self, text): \"\"\"Change",
"# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE",
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT",
"ConfigObj(path) try: lang = config[\"general\"][\"language\"] assert lang in AVAILABLE_LANGUAGES except (KeyError, AssertionError): lang",
"PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS",
"ResponseUpdate(self, build): \"\"\"The check for updates has responded. Note: the build parameter may",
"build=None): \"\"\"The check for updates is complete.\"\"\" pass def UpdateGauge(self, value): \"\"\"Change the",
"or a number (updates are available). \"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build) class Updater(DummyUpdater): \"\"\"Graphical",
"path = os.path.join(\"settings\", \"options.conf\") config = ConfigObj(path) try: lang = config[\"general\"][\"language\"] assert lang",
"\"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build) class Updater(DummyUpdater): \"\"\"Graphical updater with a gauge.\"\"\" def __init__(self,",
"check for updates is complete.\"\"\" pass def UpdateGauge(self, value): \"\"\"Change the level indicator.\"\"\"",
"the text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\", text=text) def AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\") def ResponseUpdate(self, build): \"\"\"The",
"materials provided with the distribution. # * Neither the name of ytranslate nor",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #",
"lang = config[\"general\"][\"language\"] assert lang in AVAILABLE_LANGUAGES except (KeyError, AssertionError): lang = DEFAULT_LANGUAGE",
"config[\"general\"][\"language\"] assert lang in AVAILABLE_LANGUAGES except (KeyError, AssertionError): lang = DEFAULT_LANGUAGE # Translation",
"sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text = wx.TextCtrl(panel, value=self.default_text, size=(600, 100), style=wx.TE_MULTILINE | wx.TE_READONLY)",
"= 0 # Event binding pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\")",
"are permitted provided that the following conditions are met: # * Redistributions of",
"# Translation init(root_dir=\"translations\") select(lang) # Classes class DummyUpdater(wx.Frame): \"\"\"Dummy updater, to which updaters",
"text=text) def AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\") def ResponseUpdate(self, build): \"\"\"The check for updates has",
"All rights reserved. # Redistribution and use in source and binary forms, with",
"\"en\" path = os.path.join(\"settings\", \"options.conf\") config = ConfigObj(path) try: lang = config[\"general\"][\"language\"] assert",
"OF SUCH DAMAGE. \"\"\"Auto-updater of the CocoMUD client.\"\"\" import os from configobj import",
"# and/or other materials provided with the distribution. # * Neither the name",
"try: lang = config[\"general\"][\"language\"] assert lang in AVAILABLE_LANGUAGES except (KeyError, AssertionError): lang =",
"code must retain the above copyright notice, this # list of conditions and",
"select(lang) # Classes class DummyUpdater(wx.Frame): \"\"\"Dummy updater, to which updaters should inherit.\"\"\" def",
"pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def create_updater(self, just_checking=False): \"\"\"Create a new autoupdater instance.\"\"\" self.autoupdate = AutoUpdate(BUILD,",
"(no update is available) or a number (updates are available). \"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\",",
"class Updater(DummyUpdater): \"\"\"Graphical updater with a gauge.\"\"\" def __init__(self, parent, just_checking=False): DummyUpdater.__init__(self, parent)",
"of conditions and the following disclaimer. # * Redistributions in binary form must",
"init(root_dir=\"translations\") select(lang) # Classes class DummyUpdater(wx.Frame): \"\"\"Dummy updater, to which updaters should inherit.\"\"\"",
"build parameter may be None (no update is available) or a number (updates",
"self.gauge.SetValue(value) text = self.default_text text += \" ({}%)\".format(value) self.text.SetValue(text) def OnText(self, text): self.default_text",
"wx.ID_CANCEL) # Window design sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel) # Event binding self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel)",
"text of the indicator changes.\"\"\" pass def OnForceDestroy(self): \"\"\"Ask for the window's destruction.\"\"\"",
"self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center() def InitUI(self): panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer)",
"def __init__(self, parent, just_checking=False): DummyUpdater.__init__(self, parent) self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center() def InitUI(self):",
"the CocoMUD client.\"\"\" import os from configobj import ConfigObj from ytranslate import init,",
"\"\"\"Auto-updater of the CocoMUD client.\"\"\" import os from configobj import ConfigObj from ytranslate",
"\"gauge\", value=value) def UpdateText(self, text): \"\"\"Change the text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\", text=text) def AskDestroy(self):",
"100), style=wx.TE_MULTILINE | wx.TE_READONLY) self.gauge = wx.Gauge(panel, range=100, size=(250, 25)) self.cancel = wx.Button(panel,",
"| wx.ICON_QUESTION) if value == wx.YES: self.Destroy() # AppMainLoop if __name__ == \"__main__\":",
"just_checking=just_checking) self.autoupdate.start() def OnGauge(self, value=0): \"\"\"The progress indicator changes.\"\"\" pass def OnText(self, text=\"\"):",
"# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING,",
"LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR",
"= t(\"ui.message.update.loading\") self.progress = 0 # Event binding pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy,",
"* Redistributions in binary form must reproduce the above copyright notice, # this",
"CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT",
"def OnResponseUpdate(self, build=None): \"\"\"The check for updates is complete.\"\"\" pass def UpdateGauge(self, value):",
"the following conditions are met: # * Redistributions of source code must retain",
"wx.Button(panel, wx.ID_CANCEL) # Window design sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel) # Event binding self.Bind(wx.EVT_BUTTON, self.OnCancel,",
"with or without # modification, are permitted provided that the following conditions are",
"THE POSSIBILITY OF SUCH DAMAGE. \"\"\"Auto-updater of the CocoMUD client.\"\"\" import os from",
"conditions and the following disclaimer. # * Redistributions in binary form must reproduce",
"| wx.TE_READONLY) self.gauge = wx.Gauge(panel, range=100, size=(250, 25)) self.cancel = wx.Button(panel, wx.ID_CANCEL) #",
"wx.CallAfter(pub.sendMessage, \"text\", text=text) def AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\") def ResponseUpdate(self, build): \"\"\"The check for",
"software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE",
"self.text.SetValue(text) def OnText(self, text): self.default_text = t(text) self.text.SetValue(self.default_text) def OnForceDestroy(self): self.Destroy() def OnCancel(self,",
"range=100, size=(250, 25)) self.cancel = wx.Button(panel, wx.ID_CANCEL) # Window design sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel)",
"following disclaimer. # * Redistributions in binary form must reproduce the above copyright",
"specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS",
"endorse or promote products derived from # this software without specific prior written",
"# list of conditions and the following disclaimer. # * Redistributions in binary",
"# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF",
"LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND",
"(KeyError, AssertionError): lang = DEFAULT_LANGUAGE # Translation init(root_dir=\"translations\") select(lang) # Classes class DummyUpdater(wx.Frame):",
"# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,",
"Redistributions of source code must retain the above copyright notice, this # list",
"= wx.TextCtrl(panel, value=self.default_text, size=(600, 100), style=wx.TE_MULTILINE | wx.TE_READONLY) self.gauge = wx.Gauge(panel, range=100, size=(250,",
"USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY",
"\"options.conf\") config = ConfigObj(path) try: lang = config[\"general\"][\"language\"] assert lang in AVAILABLE_LANGUAGES except",
"self.autoupdate.start() def OnGauge(self, value=0): \"\"\"The progress indicator changes.\"\"\" pass def OnText(self, text=\"\"): \"\"\"The",
"NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
"config = ConfigObj(path) try: lang = config[\"general\"][\"language\"] assert lang in AVAILABLE_LANGUAGES except (KeyError,",
"WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF",
"notice, this # list of conditions and the following disclaimer. # * Redistributions",
"# this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED",
"list of conditions and the following disclaimer. # * Redistributions in binary form",
"indicator changes.\"\"\" pass def OnForceDestroy(self): \"\"\"Ask for the window's destruction.\"\"\" pass def OnResponseUpdate(self,",
"text): \"\"\"Change the text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\", text=text) def AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\") def ResponseUpdate(self,",
"value): \"\"\"Change the level indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\", value=value) def UpdateText(self, text): \"\"\"Change the",
"responded. Note: the build parameter may be None (no update is available) or",
"self.Center() def InitUI(self): panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text = wx.TextCtrl(panel,",
"update is available) or a number (updates are available). \"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build)",
"(c) 2016-2020, <NAME> # All rights reserved. # Redistribution and use in source",
"+= \" ({}%)\".format(value) self.text.SetValue(text) def OnText(self, text): self.default_text = t(text) self.text.SetValue(self.default_text) def OnForceDestroy(self):",
"permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS",
"OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE,",
"self.OnCancel, self.cancel) def OnGauge(self, value=0): self.gauge.SetValue(value) text = self.default_text text += \" ({}%)\".format(value)",
"THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF",
"reproduce the above copyright notice, # this list of conditions and the following",
"the documentation # and/or other materials provided with the distribution. # * Neither",
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\"Auto-updater",
"gauge.\"\"\" def __init__(self, parent, just_checking=False): DummyUpdater.__init__(self, parent) self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center() def",
"HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,",
"binding self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel) def OnGauge(self, value=0): self.gauge.SetValue(value) text = self.default_text text +=",
"GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)",
"Note: the build parameter may be None (no update is available) or a",
"TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE",
"reserved. # Redistribution and use in source and binary forms, with or without",
"parameter may be None (no update is available) or a number (updates are",
"instance.\"\"\" self.autoupdate = AutoUpdate(BUILD, self, just_checking=just_checking) self.autoupdate.start() def OnGauge(self, value=0): \"\"\"The progress indicator",
"for updates has responded. Note: the build parameter may be None (no update",
"of the CocoMUD client.\"\"\" import os from configobj import ConfigObj from ytranslate import",
"IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY",
"Determines the user's language AVAILABLE_LANGUAGES = (\"en\", \"fr\") DEFAULT_LANGUAGE = \"en\" path =",
"or without # modification, are permitted provided that the following conditions are met:",
"has responded. Note: the build parameter may be None (no update is available)",
"CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY",
"wx from wx.lib.pubsub import pub from autoupdate import AutoUpdate from version import BUILD",
"conditions are met: # * Redistributions of source code must retain the above",
"documentation # and/or other materials provided with the distribution. # * Neither the",
"DEFAULT_LANGUAGE = \"en\" path = os.path.join(\"settings\", \"options.conf\") config = ConfigObj(path) try: lang =",
"available) or a number (updates are available). \"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build) class Updater(DummyUpdater):",
"a gauge.\"\"\" def __init__(self, parent, just_checking=False): DummyUpdater.__init__(self, parent) self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center()",
"ytranslate import init, select, t import wx from wx.lib.pubsub import pub from autoupdate",
"Event binding self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel) def OnGauge(self, value=0): self.gauge.SetValue(value) text = self.default_text text",
"copyright notice, # this list of conditions and the following disclaimer in the",
"25)) self.cancel = wx.Button(panel, wx.ID_CANCEL) # Window design sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel) # Event",
"# modification, are permitted provided that the following conditions are met: # *",
"BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL #",
"THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
"from # this software without specific prior written permission. # THIS SOFTWARE IS",
"import ConfigObj from ytranslate import init, select, t import wx from wx.lib.pubsub import",
"self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center() def InitUI(self): panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL)",
"OnCancel(self, e): \"\"\"The user clicks on 'cancel'.\"\"\" value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO |",
"if value == wx.YES: self.Destroy() # AppMainLoop if __name__ == \"__main__\": app =",
"prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND",
"INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,",
"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS",
"= AutoUpdate(BUILD, self, just_checking=just_checking) self.autoupdate.start() def OnGauge(self, value=0): \"\"\"The progress indicator changes.\"\"\" pass",
"pass def OnText(self, text=\"\"): \"\"\"The text of the indicator changes.\"\"\" pass def OnForceDestroy(self):",
"this list of conditions and the following disclaimer in the documentation # and/or",
"of conditions and the following disclaimer in the documentation # and/or other materials",
"without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT",
"self.text = wx.TextCtrl(panel, value=self.default_text, size=(600, 100), style=wx.TE_MULTILINE | wx.TE_READONLY) self.gauge = wx.Gauge(panel, range=100,",
"autoupdater instance.\"\"\" self.autoupdate = AutoUpdate(BUILD, self, just_checking=just_checking) self.autoupdate.start() def OnGauge(self, value=0): \"\"\"The progress",
"Translation init(root_dir=\"translations\") select(lang) # Classes class DummyUpdater(wx.Frame): \"\"\"Dummy updater, to which updaters should",
"list of conditions and the following disclaimer in the documentation # and/or other",
"to which updaters should inherit.\"\"\" def __init__(self, parent): wx.Frame.__init__(self, parent) self.autoupdater = None",
"binding pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def create_updater(self, just_checking=False): \"\"\"Create",
"OnForceDestroy(self): self.Destroy() def OnCancel(self, e): \"\"\"The user clicks on 'cancel'.\"\"\" value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"),",
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF",
"the distribution. # * Neither the name of ytranslate nor the names of",
"NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF",
"and use in source and binary forms, with or without # modification, are",
"FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
"# this list of conditions and the following disclaimer in the documentation #",
"class DummyUpdater(wx.Frame): \"\"\"Dummy updater, to which updaters should inherit.\"\"\" def __init__(self, parent): wx.Frame.__init__(self,",
"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED",
"OnGauge(self, value=0): \"\"\"The progress indicator changes.\"\"\" pass def OnText(self, text=\"\"): \"\"\"The text of",
"OnGauge(self, value=0): self.gauge.SetValue(value) text = self.default_text text += \" ({}%)\".format(value) self.text.SetValue(text) def OnText(self,",
"# Copyright (c) 2016-2020, <NAME> # All rights reserved. # Redistribution and use",
"rights reserved. # Redistribution and use in source and binary forms, with or",
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE #",
"SUCH DAMAGE. \"\"\"Auto-updater of the CocoMUD client.\"\"\" import os from configobj import ConfigObj",
"os from configobj import ConfigObj from ytranslate import init, select, t import wx",
"= \"en\" path = os.path.join(\"settings\", \"options.conf\") config = ConfigObj(path) try: lang = config[\"general\"][\"language\"]",
"OnText(self, text=\"\"): \"\"\"The text of the indicator changes.\"\"\" pass def OnForceDestroy(self): \"\"\"Ask for",
"self.text.SetValue(self.default_text) def OnForceDestroy(self): self.Destroy() def OnCancel(self, e): \"\"\"The user clicks on 'cancel'.\"\"\" value",
"\"\"\"Change the text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\", text=text) def AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\") def ResponseUpdate(self, build):",
"# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE",
"wx.Frame.__init__(self, parent) self.autoupdater = None self.default_text = t(\"ui.message.update.loading\") self.progress = 0 # Event",
"ConfigObj from ytranslate import init, select, t import wx from wx.lib.pubsub import pub",
"wx.ICON_QUESTION) if value == wx.YES: self.Destroy() # AppMainLoop if __name__ == \"__main__\": app",
"of its # contributors may be used to endorse or promote products derived",
"its # contributors may be used to endorse or promote products derived from",
"Classes class DummyUpdater(wx.Frame): \"\"\"Dummy updater, to which updaters should inherit.\"\"\" def __init__(self, parent):",
"design sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel) # Event binding self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel) def OnGauge(self, value=0):",
"wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if value == wx.YES: self.Destroy() # AppMainLoop if",
"AutoUpdate(BUILD, self, just_checking=just_checking) self.autoupdate.start() def OnGauge(self, value=0): \"\"\"The progress indicator changes.\"\"\" pass def",
"pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def create_updater(self, just_checking=False): \"\"\"Create a",
"OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER",
"WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING",
"value=self.default_text, size=(600, 100), style=wx.TE_MULTILINE | wx.TE_READONLY) self.gauge = wx.Gauge(panel, range=100, size=(250, 25)) self.cancel",
"OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE",
"check for updates has responded. Note: the build parameter may be None (no",
"the level indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\", value=value) def UpdateText(self, text): \"\"\"Change the text.\"\"\" wx.CallAfter(pub.sendMessage,",
"0 # Event binding pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def",
"OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS",
"IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR",
"def AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\") def ResponseUpdate(self, build): \"\"\"The check for updates has responded.",
"Copyright (c) 2016-2020, <NAME> # All rights reserved. # Redistribution and use in",
"from autoupdate import AutoUpdate from version import BUILD # Determines the user's language",
"def OnCancel(self, e): \"\"\"The user clicks on 'cancel'.\"\"\" value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO",
"contributors may be used to endorse or promote products derived from # this",
"value=value) def UpdateText(self, text): \"\"\"Change the text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\", text=text) def AskDestroy(self): wx.CallAfter(pub.sendMessage,",
"== wx.YES: self.Destroy() # AppMainLoop if __name__ == \"__main__\": app = wx.App() frame",
"from wx.lib.pubsub import pub from autoupdate import AutoUpdate from version import BUILD #",
"NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY",
"AVAILABLE_LANGUAGES except (KeyError, AssertionError): lang = DEFAULT_LANGUAGE # Translation init(root_dir=\"translations\") select(lang) # Classes",
"user's language AVAILABLE_LANGUAGES = (\"en\", \"fr\") DEFAULT_LANGUAGE = \"en\" path = os.path.join(\"settings\", \"options.conf\")",
"| wx.NO_DEFAULT | wx.ICON_QUESTION) if value == wx.YES: self.Destroy() # AppMainLoop if __name__",
"Redistribution and use in source and binary forms, with or without # modification,",
"\"responseUpdate\") def create_updater(self, just_checking=False): \"\"\"Create a new autoupdater instance.\"\"\" self.autoupdate = AutoUpdate(BUILD, self,",
"OnForceDestroy(self): \"\"\"Ask for the window's destruction.\"\"\" pass def OnResponseUpdate(self, build=None): \"\"\"The check for",
"pass def OnForceDestroy(self): \"\"\"Ask for the window's destruction.\"\"\" pass def OnResponseUpdate(self, build=None): \"\"\"The",
"source and binary forms, with or without # modification, are permitted provided that",
"BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR",
"destruction.\"\"\" pass def OnResponseUpdate(self, build=None): \"\"\"The check for updates is complete.\"\"\" pass def",
"FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE",
"updates has responded. Note: the build parameter may be None (no update is",
"CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, #",
"def ResponseUpdate(self, build): \"\"\"The check for updates has responded. Note: the build parameter",
"text=\"\"): \"\"\"The text of the indicator changes.\"\"\" pass def OnForceDestroy(self): \"\"\"Ask for the",
"def OnGauge(self, value=0): self.gauge.SetValue(value) text = self.default_text text += \" ({}%)\".format(value) self.text.SetValue(text) def",
"wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text = wx.TextCtrl(panel, value=self.default_text, size=(600, 100), style=wx.TE_MULTILINE | wx.TE_READONLY) self.gauge =",
"above copyright notice, this # list of conditions and the following disclaimer. #",
"self.gauge = wx.Gauge(panel, range=100, size=(250, 25)) self.cancel = wx.Button(panel, wx.ID_CANCEL) # Window design",
"\"\"\"Graphical updater with a gauge.\"\"\" def __init__(self, parent, just_checking=False): DummyUpdater.__init__(self, parent) self.create_updater(just_checking) self.InitUI()",
"ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\"Auto-updater of the CocoMUD client.\"\"\" import",
"panel.SetSizer(sizer) self.text = wx.TextCtrl(panel, value=self.default_text, size=(600, 100), style=wx.TE_MULTILINE | wx.TE_READONLY) self.gauge = wx.Gauge(panel,",
"wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text = wx.TextCtrl(panel, value=self.default_text, size=(600, 100), style=wx.TE_MULTILINE |",
"HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT",
"provided that the following conditions are met: # * Redistributions of source code",
"the window's destruction.\"\"\" pass def OnResponseUpdate(self, build=None): \"\"\"The check for updates is complete.\"\"\"",
"products derived from # this software without specific prior written permission. # THIS",
"version import BUILD # Determines the user's language AVAILABLE_LANGUAGES = (\"en\", \"fr\") DEFAULT_LANGUAGE",
"pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def create_updater(self, just_checking=False): \"\"\"Create a new autoupdater instance.\"\"\" self.autoupdate",
"ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING",
"are met: # * Redistributions of source code must retain the above copyright",
"t(\"ui.dialog.confirm\"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if value == wx.YES: self.Destroy() # AppMainLoop",
"\"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def create_updater(self, just_checking=False): \"\"\"Create a new autoupdater instance.\"\"\" self.autoupdate =",
"self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center() def InitUI(self): panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text",
"# contributors may be used to endorse or promote products derived from #",
"lang in AVAILABLE_LANGUAGES except (KeyError, AssertionError): lang = DEFAULT_LANGUAGE # Translation init(root_dir=\"translations\") select(lang)",
"DummyUpdater.__init__(self, parent) self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center() def InitUI(self): panel = wx.Panel(self) sizer",
"of ytranslate nor the names of its # contributors may be used to",
"HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,",
"the build parameter may be None (no update is available) or a number",
"COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES,",
"# Classes class DummyUpdater(wx.Frame): \"\"\"Dummy updater, to which updaters should inherit.\"\"\" def __init__(self,",
"language AVAILABLE_LANGUAGES = (\"en\", \"fr\") DEFAULT_LANGUAGE = \"en\" path = os.path.join(\"settings\", \"options.conf\") config",
"= ConfigObj(path) try: lang = config[\"general\"][\"language\"] assert lang in AVAILABLE_LANGUAGES except (KeyError, AssertionError):",
"BUILD # Determines the user's language AVAILABLE_LANGUAGES = (\"en\", \"fr\") DEFAULT_LANGUAGE = \"en\"",
"__init__(self, parent): wx.Frame.__init__(self, parent) self.autoupdater = None self.default_text = t(\"ui.message.update.loading\") self.progress = 0",
"t(\"ui.message.update.loading\") self.progress = 0 # Event binding pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\")",
"def create_updater(self, just_checking=False): \"\"\"Create a new autoupdater instance.\"\"\" self.autoupdate = AutoUpdate(BUILD, self, just_checking=just_checking)",
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO",
"should inherit.\"\"\" def __init__(self, parent): wx.Frame.__init__(self, parent) self.autoupdater = None self.default_text = t(\"ui.message.update.loading\")",
"forms, with or without # modification, are permitted provided that the following conditions",
"self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel) def OnGauge(self, value=0): self.gauge.SetValue(value) text = self.default_text text += \"",
"changes.\"\"\" pass def OnForceDestroy(self): \"\"\"Ask for the window's destruction.\"\"\" pass def OnResponseUpdate(self, build=None):",
"above copyright notice, # this list of conditions and the following disclaimer in",
"def OnText(self, text): self.default_text = t(text) self.text.SetValue(self.default_text) def OnForceDestroy(self): self.Destroy() def OnCancel(self, e):",
"Updater(DummyUpdater): \"\"\"Graphical updater with a gauge.\"\"\" def __init__(self, parent, just_checking=False): DummyUpdater.__init__(self, parent) self.create_updater(just_checking)",
"DEFAULT_LANGUAGE # Translation init(root_dir=\"translations\") select(lang) # Classes class DummyUpdater(wx.Frame): \"\"\"Dummy updater, to which",
"the indicator changes.\"\"\" pass def OnForceDestroy(self): \"\"\"Ask for the window's destruction.\"\"\" pass def",
"parent) self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center() def InitUI(self): panel = wx.Panel(self) sizer =",
"'cancel'.\"\"\" value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if value ==",
"sizer.Add(self.cancel) # Event binding self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel) def OnGauge(self, value=0): self.gauge.SetValue(value) text =",
"in source and binary forms, with or without # modification, are permitted provided",
"def UpdateGauge(self, value): \"\"\"Change the level indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\", value=value) def UpdateText(self, text):",
"IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF",
"the following disclaimer in the documentation # and/or other materials provided with the",
"PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY,",
"\"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def create_updater(self, just_checking=False): \"\"\"Create a new autoupdater instance.\"\"\"",
"AVAILABLE_LANGUAGES = (\"en\", \"fr\") DEFAULT_LANGUAGE = \"en\" path = os.path.join(\"settings\", \"options.conf\") config =",
"import BUILD # Determines the user's language AVAILABLE_LANGUAGES = (\"en\", \"fr\") DEFAULT_LANGUAGE =",
"\"text\", text=text) def AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\") def ResponseUpdate(self, build): \"\"\"The check for updates",
"this # list of conditions and the following disclaimer. # * Redistributions in",
"from ytranslate import init, select, t import wx from wx.lib.pubsub import pub from",
"value=0): \"\"\"The progress indicator changes.\"\"\" pass def OnText(self, text=\"\"): \"\"\"The text of the",
"AssertionError): lang = DEFAULT_LANGUAGE # Translation init(root_dir=\"translations\") select(lang) # Classes class DummyUpdater(wx.Frame): \"\"\"Dummy",
"the above copyright notice, this # list of conditions and the following disclaimer.",
"pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def create_updater(self, just_checking=False): \"\"\"Create a new autoupdater",
"TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE",
"text): self.default_text = t(text) self.text.SetValue(self.default_text) def OnForceDestroy(self): self.Destroy() def OnCancel(self, e): \"\"\"The user",
"used to endorse or promote products derived from # this software without specific",
"\"forceDestroy\") def ResponseUpdate(self, build): \"\"\"The check for updates has responded. Note: the build",
"\"\"\"The check for updates is complete.\"\"\" pass def UpdateGauge(self, value): \"\"\"Change the level",
"promote products derived from # this software without specific prior written permission. #",
"= wx.Button(panel, wx.ID_CANCEL) # Window design sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel) # Event binding self.Bind(wx.EVT_BUTTON,",
"wx.lib.pubsub import pub from autoupdate import AutoUpdate from version import BUILD # Determines",
"in AVAILABLE_LANGUAGES except (KeyError, AssertionError): lang = DEFAULT_LANGUAGE # Translation init(root_dir=\"translations\") select(lang) #",
"updates is complete.\"\"\" pass def UpdateGauge(self, value): \"\"\"Change the level indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\",",
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #",
"wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build) class Updater(DummyUpdater): \"\"\"Graphical updater with a gauge.\"\"\" def __init__(self, parent,",
"build=build) class Updater(DummyUpdater): \"\"\"Graphical updater with a gauge.\"\"\" def __init__(self, parent, just_checking=False): DummyUpdater.__init__(self,",
"def OnForceDestroy(self): self.Destroy() def OnCancel(self, e): \"\"\"The user clicks on 'cancel'.\"\"\" value =",
"OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\"Auto-updater of the CocoMUD client.\"\"\" import os",
"other materials provided with the distribution. # * Neither the name of ytranslate",
"OnResponseUpdate(self, build=None): \"\"\"The check for updates is complete.\"\"\" pass def UpdateGauge(self, value): \"\"\"Change",
"= config[\"general\"][\"language\"] assert lang in AVAILABLE_LANGUAGES except (KeyError, AssertionError): lang = DEFAULT_LANGUAGE #",
"wx.TextCtrl(panel, value=self.default_text, size=(600, 100), style=wx.TE_MULTILINE | wx.TE_READONLY) self.gauge = wx.Gauge(panel, range=100, size=(250, 25))",
"use in source and binary forms, with or without # modification, are permitted",
"# Event binding self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel) def OnGauge(self, value=0): self.gauge.SetValue(value) text = self.default_text",
"clicks on 'cancel'.\"\"\" value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if",
"\"\"\"Create a new autoupdater instance.\"\"\" self.autoupdate = AutoUpdate(BUILD, self, just_checking=just_checking) self.autoupdate.start() def OnGauge(self,",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED.",
"self, just_checking=just_checking) self.autoupdate.start() def OnGauge(self, value=0): \"\"\"The progress indicator changes.\"\"\" pass def OnText(self,",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" #",
"import os from configobj import ConfigObj from ytranslate import init, select, t import",
"wx.NO_DEFAULT | wx.ICON_QUESTION) if value == wx.YES: self.Destroy() # AppMainLoop if __name__ ==",
"the name of ytranslate nor the names of its # contributors may be",
"OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR",
"must reproduce the above copyright notice, # this list of conditions and the",
"parent) self.autoupdater = None self.default_text = t(\"ui.message.update.loading\") self.progress = 0 # Event binding",
"style=wx.TE_MULTILINE | wx.TE_READONLY) self.gauge = wx.Gauge(panel, range=100, size=(250, 25)) self.cancel = wx.Button(panel, wx.ID_CANCEL)",
"size=(250, 25)) self.cancel = wx.Button(panel, wx.ID_CANCEL) # Window design sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel) #",
"# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #",
"disclaimer in the documentation # and/or other materials provided with the distribution. #",
"self.cancel = wx.Button(panel, wx.ID_CANCEL) # Window design sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel) # Event binding",
"to endorse or promote products derived from # this software without specific prior",
"IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\"Auto-updater of the CocoMUD client.\"\"\"",
"# * Neither the name of ytranslate nor the names of its #",
"pub from autoupdate import AutoUpdate from version import BUILD # Determines the user's",
"assert lang in AVAILABLE_LANGUAGES except (KeyError, AssertionError): lang = DEFAULT_LANGUAGE # Translation init(root_dir=\"translations\")",
"self.autoupdate = AutoUpdate(BUILD, self, just_checking=just_checking) self.autoupdate.start() def OnGauge(self, value=0): \"\"\"The progress indicator changes.\"\"\"",
"UpdateText(self, text): \"\"\"Change the text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\", text=text) def AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\") def",
"OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER",
"value == wx.YES: self.Destroy() # AppMainLoop if __name__ == \"__main__\": app = wx.App()",
"for updates is complete.\"\"\" pass def UpdateGauge(self, value): \"\"\"Change the level indicator.\"\"\" wx.CallAfter(pub.sendMessage,",
"for the window's destruction.\"\"\" pass def OnResponseUpdate(self, build=None): \"\"\"The check for updates is",
"INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO,",
"POSSIBILITY OF SUCH DAMAGE. \"\"\"Auto-updater of the CocoMUD client.\"\"\" import os from configobj",
"wx.YES: self.Destroy() # AppMainLoop if __name__ == \"__main__\": app = wx.App() frame =",
"= None self.default_text = t(\"ui.message.update.loading\") self.progress = 0 # Event binding pub.subscribe(self.OnGauge, \"gauge\")",
"# Window design sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel) # Event binding self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel) def",
"available). \"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build) class Updater(DummyUpdater): \"\"\"Graphical updater with a gauge.\"\"\" def",
"from version import BUILD # Determines the user's language AVAILABLE_LANGUAGES = (\"en\", \"fr\")",
"EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT,",
"indicator changes.\"\"\" pass def OnText(self, text=\"\"): \"\"\"The text of the indicator changes.\"\"\" pass",
"= self.default_text text += \" ({}%)\".format(value) self.text.SetValue(text) def OnText(self, text): self.default_text = t(text)",
"LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)",
"wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if value == wx.YES: self.Destroy() #",
"value=0): self.gauge.SetValue(value) text = self.default_text text += \" ({}%)\".format(value) self.text.SetValue(text) def OnText(self, text):",
"def UpdateText(self, text): \"\"\"Change the text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\", text=text) def AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\")",
"client.\"\"\" import os from configobj import ConfigObj from ytranslate import init, select, t",
"TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR",
"and/or other materials provided with the distribution. # * Neither the name of",
"disclaimer. # * Redistributions in binary form must reproduce the above copyright notice,",
"which updaters should inherit.\"\"\" def __init__(self, parent): wx.Frame.__init__(self, parent) self.autoupdater = None self.default_text",
"AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT",
"SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS",
"autoupdate import AutoUpdate from version import BUILD # Determines the user's language AVAILABLE_LANGUAGES",
"and the following disclaimer. # * Redistributions in binary form must reproduce the",
"self.Destroy() # AppMainLoop if __name__ == \"__main__\": app = wx.App() frame = Updater(None)",
"the above copyright notice, # this list of conditions and the following disclaimer",
"= wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text = wx.TextCtrl(panel, value=self.default_text, size=(600, 100), style=wx.TE_MULTILINE",
"\"\"\"The text of the indicator changes.\"\"\" pass def OnForceDestroy(self): \"\"\"Ask for the window's",
"create_updater(self, just_checking=False): \"\"\"Create a new autoupdater instance.\"\"\" self.autoupdate = AutoUpdate(BUILD, self, just_checking=just_checking) self.autoupdate.start()",
"DAMAGE. \"\"\"Auto-updater of the CocoMUD client.\"\"\" import os from configobj import ConfigObj from",
"DummyUpdater(wx.Frame): \"\"\"Dummy updater, to which updaters should inherit.\"\"\" def __init__(self, parent): wx.Frame.__init__(self, parent)",
"be used to endorse or promote products derived from # this software without",
"OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF",
"IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,",
"text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\", text=text) def AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\") def ResponseUpdate(self, build): \"\"\"The check",
"Window design sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel) # Event binding self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel) def OnGauge(self,",
"({}%)\".format(value) self.text.SetValue(text) def OnText(self, text): self.default_text = t(text) self.text.SetValue(self.default_text) def OnForceDestroy(self): self.Destroy() def",
"OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON",
"= wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if value == wx.YES: self.Destroy()",
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY",
"BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN",
"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT",
"USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH",
"Event binding pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def create_updater(self, just_checking=False):",
"EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE",
"self.default_text = t(\"ui.message.update.loading\") self.progress = 0 # Event binding pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText, \"text\")",
"PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR",
"number (updates are available). \"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build) class Updater(DummyUpdater): \"\"\"Graphical updater with",
"are available). \"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build) class Updater(DummyUpdater): \"\"\"Graphical updater with a gauge.\"\"\"",
"self.Show() self.Center() def InitUI(self): panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text =",
"IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN",
"and binary forms, with or without # modification, are permitted provided that the",
"conditions and the following disclaimer in the documentation # and/or other materials provided",
"\"\"\"Dummy updater, to which updaters should inherit.\"\"\" def __init__(self, parent): wx.Frame.__init__(self, parent) self.autoupdater",
"names of its # contributors may be used to endorse or promote products",
"derived from # this software without specific prior written permission. # THIS SOFTWARE",
"SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND",
"modification, are permitted provided that the following conditions are met: # * Redistributions",
"OnText(self, text): self.default_text = t(text) self.text.SetValue(self.default_text) def OnForceDestroy(self): self.Destroy() def OnCancel(self, e): \"\"\"The",
"of the indicator changes.\"\"\" pass def OnForceDestroy(self): \"\"\"Ask for the window's destruction.\"\"\" pass",
"def __init__(self, parent): wx.Frame.__init__(self, parent) self.autoupdater = None self.default_text = t(\"ui.message.update.loading\") self.progress =",
"None (no update is available) or a number (updates are available). \"\"\" wx.CallAfter(pub.sendMessage,",
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED",
"\"\"\"Ask for the window's destruction.\"\"\" pass def OnResponseUpdate(self, build=None): \"\"\"The check for updates",
"parent, just_checking=False): DummyUpdater.__init__(self, parent) self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center() def InitUI(self): panel =",
"= wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text = wx.TextCtrl(panel, value=self.default_text, size=(600, 100), style=wx.TE_MULTILINE | wx.TE_READONLY) self.gauge",
"# Event binding pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def create_updater(self,",
"WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND",
"(updates are available). \"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build) class Updater(DummyUpdater): \"\"\"Graphical updater with a",
"self.default_text = t(text) self.text.SetValue(self.default_text) def OnForceDestroy(self): self.Destroy() def OnCancel(self, e): \"\"\"The user clicks",
"os.path.join(\"settings\", \"options.conf\") config = ConfigObj(path) try: lang = config[\"general\"][\"language\"] assert lang in AVAILABLE_LANGUAGES",
"A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER",
"import init, select, t import wx from wx.lib.pubsub import pub from autoupdate import",
"must retain the above copyright notice, this # list of conditions and the",
"import pub from autoupdate import AutoUpdate from version import BUILD # Determines the",
"written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS",
"CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR",
"provided with the distribution. # * Neither the name of ytranslate nor the",
"= DEFAULT_LANGUAGE # Translation init(root_dir=\"translations\") select(lang) # Classes class DummyUpdater(wx.Frame): \"\"\"Dummy updater, to",
"\" ({}%)\".format(value) self.text.SetValue(text) def OnText(self, text): self.default_text = t(text) self.text.SetValue(self.default_text) def OnForceDestroy(self): self.Destroy()",
"OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS",
"wx.CallAfter(pub.sendMessage, \"forceDestroy\") def ResponseUpdate(self, build): \"\"\"The check for updates has responded. Note: the",
"window's destruction.\"\"\" pass def OnResponseUpdate(self, build=None): \"\"\"The check for updates is complete.\"\"\" pass",
"is complete.\"\"\" pass def UpdateGauge(self, value): \"\"\"Change the level indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\", value=value)",
"EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\"Auto-updater of the CocoMUD",
"InitUI(self): panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text = wx.TextCtrl(panel, value=self.default_text, size=(600,",
"ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED",
"self.cancel) def OnGauge(self, value=0): self.gauge.SetValue(value) text = self.default_text text += \" ({}%)\".format(value) self.text.SetValue(text)",
"ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN",
"is available) or a number (updates are available). \"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build) class",
"self.Destroy() def OnCancel(self, e): \"\"\"The user clicks on 'cancel'.\"\"\" value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"),",
"sizer.Add(self.gauge) sizer.Add(self.cancel) # Event binding self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel) def OnGauge(self, value=0): self.gauge.SetValue(value) text",
"self.progress = 0 # Event binding pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate,",
"PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS;",
"COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,",
"SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT,",
"progress indicator changes.\"\"\" pass def OnText(self, text=\"\"): \"\"\"The text of the indicator changes.\"\"\"",
"# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #",
"this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY",
"<NAME> # All rights reserved. # Redistribution and use in source and binary",
"t import wx from wx.lib.pubsub import pub from autoupdate import AutoUpdate from version",
"AutoUpdate from version import BUILD # Determines the user's language AVAILABLE_LANGUAGES = (\"en\",",
"with the distribution. # * Neither the name of ytranslate nor the names",
"\"\"\"The progress indicator changes.\"\"\" pass def OnText(self, text=\"\"): \"\"\"The text of the indicator",
"with a gauge.\"\"\" def __init__(self, parent, just_checking=False): DummyUpdater.__init__(self, parent) self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show()",
"\"\"\"Change the level indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\", value=value) def UpdateText(self, text): \"\"\"Change the text.\"\"\"",
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY",
"\"fr\") DEFAULT_LANGUAGE = \"en\" path = os.path.join(\"settings\", \"options.conf\") config = ConfigObj(path) try: lang",
"\"gauge\") pub.subscribe(self.OnText, \"text\") pub.subscribe(self.OnForceDestroy, \"forceDestroy\") pub.subscribe(self.OnResponseUpdate, \"responseUpdate\") def create_updater(self, just_checking=False): \"\"\"Create a new",
"a number (updates are available). \"\"\" wx.CallAfter(pub.sendMessage, \"responseUpdate\", build=build) class Updater(DummyUpdater): \"\"\"Graphical updater",
"parent): wx.Frame.__init__(self, parent) self.autoupdater = None self.default_text = t(\"ui.message.update.loading\") self.progress = 0 #",
"Redistributions in binary form must reproduce the above copyright notice, # this list",
"ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE",
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT",
"None self.default_text = t(\"ui.message.update.loading\") self.progress = 0 # Event binding pub.subscribe(self.OnGauge, \"gauge\") pub.subscribe(self.OnText,",
"size=(600, 100), style=wx.TE_MULTILINE | wx.TE_READONLY) self.gauge = wx.Gauge(panel, range=100, size=(250, 25)) self.cancel =",
"CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL",
"just_checking=False): DummyUpdater.__init__(self, parent) self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center() def InitUI(self): panel = wx.Panel(self)",
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA,",
"t(text) self.text.SetValue(self.default_text) def OnForceDestroy(self): self.Destroy() def OnCancel(self, e): \"\"\"The user clicks on 'cancel'.\"\"\"",
"wx.CallAfter(pub.sendMessage, \"gauge\", value=value) def UpdateText(self, text): \"\"\"Change the text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\", text=text) def",
"LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT",
"inherit.\"\"\" def __init__(self, parent): wx.Frame.__init__(self, parent) self.autoupdater = None self.default_text = t(\"ui.message.update.loading\") self.progress",
"__init__(self, parent, just_checking=False): DummyUpdater.__init__(self, parent) self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\")) self.Show() self.Center() def InitUI(self): panel",
"Neither the name of ytranslate nor the names of its # contributors may",
"\"responseUpdate\", build=build) class Updater(DummyUpdater): \"\"\"Graphical updater with a gauge.\"\"\" def __init__(self, parent, just_checking=False):",
"# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"",
"of source code must retain the above copyright notice, this # list of",
"ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT",
"wx.TE_READONLY) self.gauge = wx.Gauge(panel, range=100, size=(250, 25)) self.cancel = wx.Button(panel, wx.ID_CANCEL) # Window",
"value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if value == wx.YES:",
"the following disclaimer. # * Redistributions in binary form must reproduce the above",
"from configobj import ConfigObj from ytranslate import init, select, t import wx from",
"= os.path.join(\"settings\", \"options.conf\") config = ConfigObj(path) try: lang = config[\"general\"][\"language\"] assert lang in",
"init, select, t import wx from wx.lib.pubsub import pub from autoupdate import AutoUpdate",
"complete.\"\"\" pass def UpdateGauge(self, value): \"\"\"Change the level indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\", value=value) def",
"notice, # this list of conditions and the following disclaimer in the documentation",
"(\"en\", \"fr\") DEFAULT_LANGUAGE = \"en\" path = os.path.join(\"settings\", \"options.conf\") config = ConfigObj(path) try:",
"may be None (no update is available) or a number (updates are available).",
"# Determines the user's language AVAILABLE_LANGUAGES = (\"en\", \"fr\") DEFAULT_LANGUAGE = \"en\" path",
"THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE",
"MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT",
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\"Auto-updater of",
"THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED",
"pass def OnResponseUpdate(self, build=None): \"\"\"The check for updates is complete.\"\"\" pass def UpdateGauge(self,",
"CocoMUD client.\"\"\" import os from configobj import ConfigObj from ytranslate import init, select,",
"user clicks on 'cancel'.\"\"\" value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)",
"the names of its # contributors may be used to endorse or promote",
"following conditions are met: # * Redistributions of source code must retain the",
"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES;",
"met: # * Redistributions of source code must retain the above copyright notice,",
"\"\"\"The check for updates has responded. Note: the build parameter may be None",
"= wx.Gauge(panel, range=100, size=(250, 25)) self.cancel = wx.Button(panel, wx.ID_CANCEL) # Window design sizer.Add(self.text)",
"2016-2020, <NAME> # All rights reserved. # Redistribution and use in source and",
"just_checking=False): \"\"\"Create a new autoupdater instance.\"\"\" self.autoupdate = AutoUpdate(BUILD, self, just_checking=just_checking) self.autoupdate.start() def",
"level indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\", value=value) def UpdateText(self, text): \"\"\"Change the text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\",",
"\"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED",
"indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\", value=value) def UpdateText(self, text): \"\"\"Change the text.\"\"\" wx.CallAfter(pub.sendMessage, \"text\", text=text)",
"# Redistribution and use in source and binary forms, with or without #",
"INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS",
"\"\"\"The user clicks on 'cancel'.\"\"\" value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO | wx.NO_DEFAULT |",
"# AppMainLoop if __name__ == \"__main__\": app = wx.App() frame = Updater(None) app.MainLoop()",
"* Neither the name of ytranslate nor the names of its # contributors",
"the user's language AVAILABLE_LANGUAGES = (\"en\", \"fr\") DEFAULT_LANGUAGE = \"en\" path = os.path.join(\"settings\",",
"wx.Gauge(panel, range=100, size=(250, 25)) self.cancel = wx.Button(panel, wx.ID_CANCEL) # Window design sizer.Add(self.text) sizer.Add(self.gauge)",
"nor the names of its # contributors may be used to endorse or",
"self.default_text text += \" ({}%)\".format(value) self.text.SetValue(text) def OnText(self, text): self.default_text = t(text) self.text.SetValue(self.default_text)",
"source code must retain the above copyright notice, this # list of conditions",
"retain the above copyright notice, this # list of conditions and the following",
"BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR",
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \"\"\"Auto-updater of the",
"updater, to which updaters should inherit.\"\"\" def __init__(self, parent): wx.Frame.__init__(self, parent) self.autoupdater =",
"BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF",
"new autoupdater instance.\"\"\" self.autoupdate = AutoUpdate(BUILD, self, just_checking=just_checking) self.autoupdate.start() def OnGauge(self, value=0): \"\"\"The",
"text += \" ({}%)\".format(value) self.text.SetValue(text) def OnText(self, text): self.default_text = t(text) self.text.SetValue(self.default_text) def",
"copyright notice, this # list of conditions and the following disclaimer. # *",
"import wx from wx.lib.pubsub import pub from autoupdate import AutoUpdate from version import",
"STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY",
"binary forms, with or without # modification, are permitted provided that the following",
"panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text = wx.TextCtrl(panel, value=self.default_text, size=(600, 100),",
"be None (no update is available) or a number (updates are available). \"\"\"",
"updater with a gauge.\"\"\" def __init__(self, parent, just_checking=False): DummyUpdater.__init__(self, parent) self.create_updater(just_checking) self.InitUI() self.SetTitle(t(\"ui.message.update.updating\"))",
"def InitUI(self): panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) self.text = wx.TextCtrl(panel, value=self.default_text,",
"self.autoupdater = None self.default_text = t(\"ui.message.update.loading\") self.progress = 0 # Event binding pub.subscribe(self.OnGauge,",
"may be used to endorse or promote products derived from # this software",
"except (KeyError, AssertionError): lang = DEFAULT_LANGUAGE # Translation init(root_dir=\"translations\") select(lang) # Classes class",
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE",
"changes.\"\"\" pass def OnText(self, text=\"\"): \"\"\"The text of the indicator changes.\"\"\" pass def",
"binary form must reproduce the above copyright notice, # this list of conditions",
"pass def UpdateGauge(self, value): \"\"\"Change the level indicator.\"\"\" wx.CallAfter(pub.sendMessage, \"gauge\", value=value) def UpdateText(self,",
"following disclaimer in the documentation # and/or other materials provided with the distribution.",
"sizer.Add(self.text) sizer.Add(self.gauge) sizer.Add(self.cancel) # Event binding self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancel) def OnGauge(self, value=0): self.gauge.SetValue(value)",
"in the documentation # and/or other materials provided with the distribution. # *",
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE,",
"form must reproduce the above copyright notice, # this list of conditions and",
"def OnGauge(self, value=0): \"\"\"The progress indicator changes.\"\"\" pass def OnText(self, text=\"\"): \"\"\"The text",
"LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES",
"build): \"\"\"The check for updates has responded. Note: the build parameter may be",
"text = self.default_text text += \" ({}%)\".format(value) self.text.SetValue(text) def OnText(self, text): self.default_text =",
"PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS",
"OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY",
"def OnForceDestroy(self): \"\"\"Ask for the window's destruction.\"\"\" pass def OnResponseUpdate(self, build=None): \"\"\"The check",
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN",
"# All rights reserved. # Redistribution and use in source and binary forms,",
"distribution. # * Neither the name of ytranslate nor the names of its",
"updaters should inherit.\"\"\" def __init__(self, parent): wx.Frame.__init__(self, parent) self.autoupdater = None self.default_text =",
"ytranslate nor the names of its # contributors may be used to endorse",
"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED",
"OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR",
"a new autoupdater instance.\"\"\" self.autoupdate = AutoUpdate(BUILD, self, just_checking=just_checking) self.autoupdate.start() def OnGauge(self, value=0):",
"OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR",
"# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
"select, t import wx from wx.lib.pubsub import pub from autoupdate import AutoUpdate from",
"on 'cancel'.\"\"\" value = wx.MessageBox(t(\"ui.message.update.confirm_cancel\"), t(\"ui.dialog.confirm\"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if value",
"permitted provided that the following conditions are met: # * Redistributions of source",
"# * Redistributions of source code must retain the above copyright notice, this",
"# * Redistributions in binary form must reproduce the above copyright notice, #",
"AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR",
"= (\"en\", \"fr\") DEFAULT_LANGUAGE = \"en\" path = os.path.join(\"settings\", \"options.conf\") config = ConfigObj(path)",
"that the following conditions are met: # * Redistributions of source code must",
"OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF",
"or promote products derived from # this software without specific prior written permission.",
"AskDestroy(self): wx.CallAfter(pub.sendMessage, \"forceDestroy\") def ResponseUpdate(self, build): \"\"\"The check for updates has responded. Note:",
"* Redistributions of source code must retain the above copyright notice, this #",
"= t(text) self.text.SetValue(self.default_text) def OnForceDestroy(self): self.Destroy() def OnCancel(self, e): \"\"\"The user clicks on"
] |
[
"import AbstractDevice class PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector for show port utilization table command \"\"\"",
"PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector for show port utilization table command \"\"\" def __init__(self, template_dir:",
"table command \"\"\" def __init__(self, template_dir: str, device: AbstractDevice, registry=REGISTRY): super().__init__( template_dir +",
"= [ GaugeMetricFamily(\"epc_port_rx_current\", \"epc port rx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu tx current.\",",
"from collector.abstract_command_collector import AbstractCommandCollector from device import AbstractDevice class PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector for",
"npu tx 15m.\", labels=[\"port\"]) ] for row in rows: for field_index in range(6):",
"labels=[\"port\"]) ] for row in rows: for field_index in range(6): metrics[field_index].add_metric(labels=[row[0]], value=row[field_index +",
"\"epc npu tx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\", \"epc port rx 15m.\", labels=[\"port\"]), GaugeMetricFamily(",
"npu tx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\", \"epc port rx 15m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\",",
"\"epc_port_rx_15m\", \"epc port rx 15m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\", \"epc npu tx 15m.\", labels=[\"port\"])",
"template_dir + \"/show_port_utilization_table.template\", device, registry) def collect(self): \"\"\" collect method collects the command",
"device and return the metrics \"\"\" output = self._device.exec(\"show port utilization table\") rows",
"device: AbstractDevice, registry=REGISTRY): super().__init__( template_dir + \"/show_port_utilization_table.template\", device, registry) def collect(self): \"\"\" collect",
"[ GaugeMetricFamily(\"epc_port_rx_current\", \"epc port rx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu tx current.\", labels=[\"port\"]),",
"\"\"\" Collector for show port utilization table command \"\"\" def __init__(self, template_dir: str,",
"\"epc npu tx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port rx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\",",
"GaugeMetricFamily( \"epc_port_tx_15m\", \"epc npu tx 15m.\", labels=[\"port\"]) ] for row in rows: for",
"labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\", \"epc npu tx 15m.\", labels=[\"port\"]) ] for row in rows:",
"current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu tx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port rx 5m.\",",
"AbstractDevice, registry=REGISTRY): super().__init__( template_dir + \"/show_port_utilization_table.template\", device, registry) def collect(self): \"\"\" collect method",
"command and parses it \"\"\" from prometheus_client import REGISTRY from prometheus_client.metrics_core import GaugeMetricFamily",
"port rx 15m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\", \"epc npu tx 15m.\", labels=[\"port\"]) ] for",
"the metrics \"\"\" output = self._device.exec(\"show port utilization table\") rows = self._parser.ParseText(output) metrics",
"\"\"\" from prometheus_client import REGISTRY from prometheus_client.metrics_core import GaugeMetricFamily from collector.abstract_command_collector import AbstractCommandCollector",
"collect method collects the command output from device and return the metrics \"\"\"",
"and parses it \"\"\" from prometheus_client import REGISTRY from prometheus_client.metrics_core import GaugeMetricFamily from",
"output from device and return the metrics \"\"\" output = self._device.exec(\"show port utilization",
"collects the command output from device and return the metrics \"\"\" output =",
"rx 15m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\", \"epc npu tx 15m.\", labels=[\"port\"]) ] for row",
"<reponame>cisco-cx/epc_exporter \"\"\" Collects show port utilization table command and parses it \"\"\" from",
"port utilization table command and parses it \"\"\" from prometheus_client import REGISTRY from",
"\"/show_port_utilization_table.template\", device, registry) def collect(self): \"\"\" collect method collects the command output from",
"\"epc_port_tx_5m\", \"epc npu tx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\", \"epc port rx 15m.\", labels=[\"port\"]),",
"command \"\"\" def __init__(self, template_dir: str, device: AbstractDevice, registry=REGISTRY): super().__init__( template_dir + \"/show_port_utilization_table.template\",",
"show port utilization table command \"\"\" def __init__(self, template_dir: str, device: AbstractDevice, registry=REGISTRY):",
"port utilization table command \"\"\" def __init__(self, template_dir: str, device: AbstractDevice, registry=REGISTRY): super().__init__(",
"5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\", \"epc npu tx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\", \"epc port",
"GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu tx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port rx 5m.\", labels=[\"port\"]), GaugeMetricFamily(",
"= self._parser.ParseText(output) metrics = [ GaugeMetricFamily(\"epc_port_rx_current\", \"epc port rx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc",
"] for row in rows: for field_index in range(6): metrics[field_index].add_metric(labels=[row[0]], value=row[field_index + 1])",
"method collects the command output from device and return the metrics \"\"\" output",
"parses it \"\"\" from prometheus_client import REGISTRY from prometheus_client.metrics_core import GaugeMetricFamily from collector.abstract_command_collector",
"from prometheus_client import REGISTRY from prometheus_client.metrics_core import GaugeMetricFamily from collector.abstract_command_collector import AbstractCommandCollector from",
"prometheus_client.metrics_core import GaugeMetricFamily from collector.abstract_command_collector import AbstractCommandCollector from device import AbstractDevice class PortUtilizationCollector(AbstractCommandCollector):",
"return the metrics \"\"\" output = self._device.exec(\"show port utilization table\") rows = self._parser.ParseText(output)",
"from prometheus_client.metrics_core import GaugeMetricFamily from collector.abstract_command_collector import AbstractCommandCollector from device import AbstractDevice class",
"REGISTRY from prometheus_client.metrics_core import GaugeMetricFamily from collector.abstract_command_collector import AbstractCommandCollector from device import AbstractDevice",
"\"\"\" def __init__(self, template_dir: str, device: AbstractDevice, registry=REGISTRY): super().__init__( template_dir + \"/show_port_utilization_table.template\", device,",
"str, device: AbstractDevice, registry=REGISTRY): super().__init__( template_dir + \"/show_port_utilization_table.template\", device, registry) def collect(self): \"\"\"",
"metrics = [ GaugeMetricFamily(\"epc_port_rx_current\", \"epc port rx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu tx",
"import AbstractCommandCollector from device import AbstractDevice class PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector for show port",
"for show port utilization table command \"\"\" def __init__(self, template_dir: str, device: AbstractDevice,",
"device, registry) def collect(self): \"\"\" collect method collects the command output from device",
"command output from device and return the metrics \"\"\" output = self._device.exec(\"show port",
"labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu tx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port rx 5m.\", labels=[\"port\"]),",
"labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port rx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\", \"epc npu tx 5m.\",",
"tx 15m.\", labels=[\"port\"]) ] for row in rows: for field_index in range(6): metrics[field_index].add_metric(labels=[row[0]],",
"__init__(self, template_dir: str, device: AbstractDevice, registry=REGISTRY): super().__init__( template_dir + \"/show_port_utilization_table.template\", device, registry) def",
"device import AbstractDevice class PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector for show port utilization table command",
"= self._device.exec(\"show port utilization table\") rows = self._parser.ParseText(output) metrics = [ GaugeMetricFamily(\"epc_port_rx_current\", \"epc",
"\"epc npu tx 15m.\", labels=[\"port\"]) ] for row in rows: for field_index in",
"GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port rx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\", \"epc npu tx 5m.\", labels=[\"port\"]),",
"\"\"\" Collects show port utilization table command and parses it \"\"\" from prometheus_client",
"import REGISTRY from prometheus_client.metrics_core import GaugeMetricFamily from collector.abstract_command_collector import AbstractCommandCollector from device import",
"15m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\", \"epc npu tx 15m.\", labels=[\"port\"]) ] for row in",
"from device import AbstractDevice class PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector for show port utilization table",
"+ \"/show_port_utilization_table.template\", device, registry) def collect(self): \"\"\" collect method collects the command output",
"GaugeMetricFamily( \"epc_port_tx_5m\", \"epc npu tx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\", \"epc port rx 15m.\",",
"\"epc port rx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\", \"epc npu tx 5m.\", labels=[\"port\"]), GaugeMetricFamily(",
"super().__init__( template_dir + \"/show_port_utilization_table.template\", device, registry) def collect(self): \"\"\" collect method collects the",
"\"\"\" output = self._device.exec(\"show port utilization table\") rows = self._parser.ParseText(output) metrics = [",
"\"epc port rx 15m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\", \"epc npu tx 15m.\", labels=[\"port\"]) ]",
"tx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port rx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\", \"epc npu",
"self._parser.ParseText(output) metrics = [ GaugeMetricFamily(\"epc_port_rx_current\", \"epc port rx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu",
"rx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\", \"epc npu tx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\", \"epc",
"template_dir: str, device: AbstractDevice, registry=REGISTRY): super().__init__( template_dir + \"/show_port_utilization_table.template\", device, registry) def collect(self):",
"utilization table\") rows = self._parser.ParseText(output) metrics = [ GaugeMetricFamily(\"epc_port_rx_current\", \"epc port rx current.\",",
"GaugeMetricFamily( \"epc_port_rx_15m\", \"epc port rx 15m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\", \"epc npu tx 15m.\",",
"import GaugeMetricFamily from collector.abstract_command_collector import AbstractCommandCollector from device import AbstractDevice class PortUtilizationCollector(AbstractCommandCollector): \"\"\"",
"current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port rx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\", \"epc npu tx",
"registry=REGISTRY): super().__init__( template_dir + \"/show_port_utilization_table.template\", device, registry) def collect(self): \"\"\" collect method collects",
"the command output from device and return the metrics \"\"\" output = self._device.exec(\"show",
"\"epc_port_tx_15m\", \"epc npu tx 15m.\", labels=[\"port\"]) ] for row in rows: for field_index",
"collector.abstract_command_collector import AbstractCommandCollector from device import AbstractDevice class PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector for show",
"registry) def collect(self): \"\"\" collect method collects the command output from device and",
"port utilization table\") rows = self._parser.ParseText(output) metrics = [ GaugeMetricFamily(\"epc_port_rx_current\", \"epc port rx",
"utilization table command \"\"\" def __init__(self, template_dir: str, device: AbstractDevice, registry=REGISTRY): super().__init__( template_dir",
"metrics \"\"\" output = self._device.exec(\"show port utilization table\") rows = self._parser.ParseText(output) metrics =",
"npu tx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port rx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\", \"epc",
"row in rows: for field_index in range(6): metrics[field_index].add_metric(labels=[row[0]], value=row[field_index + 1]) return metrics",
"prometheus_client import REGISTRY from prometheus_client.metrics_core import GaugeMetricFamily from collector.abstract_command_collector import AbstractCommandCollector from device",
"AbstractCommandCollector from device import AbstractDevice class PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector for show port utilization",
"show port utilization table command and parses it \"\"\" from prometheus_client import REGISTRY",
"port rx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu tx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port",
"def __init__(self, template_dir: str, device: AbstractDevice, registry=REGISTRY): super().__init__( template_dir + \"/show_port_utilization_table.template\", device, registry)",
"tx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\", \"epc port rx 15m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\", \"epc",
"utilization table command and parses it \"\"\" from prometheus_client import REGISTRY from prometheus_client.metrics_core",
"it \"\"\" from prometheus_client import REGISTRY from prometheus_client.metrics_core import GaugeMetricFamily from collector.abstract_command_collector import",
"5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\", \"epc port rx 15m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\", \"epc npu",
"collect(self): \"\"\" collect method collects the command output from device and return the",
"GaugeMetricFamily from collector.abstract_command_collector import AbstractCommandCollector from device import AbstractDevice class PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector",
"rows = self._parser.ParseText(output) metrics = [ GaugeMetricFamily(\"epc_port_rx_current\", \"epc port rx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\",",
"AbstractDevice class PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector for show port utilization table command \"\"\" def",
"GaugeMetricFamily(\"epc_port_rx_current\", \"epc port rx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu tx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\",",
"labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\", \"epc port rx 15m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_15m\", \"epc npu tx",
"table\") rows = self._parser.ParseText(output) metrics = [ GaugeMetricFamily(\"epc_port_rx_current\", \"epc port rx current.\", labels=[\"port\"]),",
"15m.\", labels=[\"port\"]) ] for row in rows: for field_index in range(6): metrics[field_index].add_metric(labels=[row[0]], value=row[field_index",
"port rx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\", \"epc npu tx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\",",
"table command and parses it \"\"\" from prometheus_client import REGISTRY from prometheus_client.metrics_core import",
"Collects show port utilization table command and parses it \"\"\" from prometheus_client import",
"from device and return the metrics \"\"\" output = self._device.exec(\"show port utilization table\")",
"output = self._device.exec(\"show port utilization table\") rows = self._parser.ParseText(output) metrics = [ GaugeMetricFamily(\"epc_port_rx_current\",",
"rx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu tx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc port rx",
"\"\"\" collect method collects the command output from device and return the metrics",
"and return the metrics \"\"\" output = self._device.exec(\"show port utilization table\") rows =",
"for row in rows: for field_index in range(6): metrics[field_index].add_metric(labels=[row[0]], value=row[field_index + 1]) return",
"self._device.exec(\"show port utilization table\") rows = self._parser.ParseText(output) metrics = [ GaugeMetricFamily(\"epc_port_rx_current\", \"epc port",
"def collect(self): \"\"\" collect method collects the command output from device and return",
"class PortUtilizationCollector(AbstractCommandCollector): \"\"\" Collector for show port utilization table command \"\"\" def __init__(self,",
"Collector for show port utilization table command \"\"\" def __init__(self, template_dir: str, device:",
"labels=[\"port\"]), GaugeMetricFamily( \"epc_port_tx_5m\", \"epc npu tx 5m.\", labels=[\"port\"]), GaugeMetricFamily( \"epc_port_rx_15m\", \"epc port rx",
"\"epc port rx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_tx_current\", \"epc npu tx current.\", labels=[\"port\"]), GaugeMetricFamily(\"epc_port_rx_5m\", \"epc"
] |
[] |
[
"self.mat = scipy.io.loadmat(self.file_in, squeeze_me=False) def test_get_time_series_quantiles(self): met_names, rxn_names = get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline =",
"conc, conc_interp, flux, flux_interp = gather_sim_data(self.mat, met_names, rxn_names, n_models, time_points_spline, save_concs=False, save_fluxes=False) data_type",
"scipy.io.loadmat(self.file_in, squeeze_me=False) def test_get_time_series_quantiles(self): met_names, rxn_names = get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline = [10**-9, 10",
"n_models, time_points_spline, save_concs=False, save_fluxes=False) data_type = 'rxn' flux_interp_quantiles = get_time_series_quantiles(flux_interp, time_points_spline, data_type, rxn_names)",
"TestProcessSimulations(unittest.TestCase): def setUp(self): this_dir, this_filename = os.path.split(__file__) self.data_dir = os.path.join(this_dir, '..', '..', 'data',",
"** -1, 1] # , 10, 100] n_models = 10 conc, conc_interp, flux,",
"10, 100] n_models = 10 conc, conc_interp, flux, flux_interp = gather_sim_data(self.mat, met_names, rxn_names,",
"100] n_models = 10 conc, conc_interp, flux, flux_interp = gather_sim_data(self.mat, met_names, rxn_names, n_models,",
"10 ** -3, 10 ** -2, 10 ** -1, 1] # , 10,",
"this_dir, this_filename = os.path.split(__file__) self.data_dir = os.path.join(this_dir, '..', '..', 'data', 'raw') self.model_name =",
"-4, 10 ** -3, 10 ** -2, 10 ** -1, 1] # ,",
"unittest import scipy.io from src.data.process_simulations import get_time_series_quantiles from src.data.import_simulations import gather_sim_data, get_met_rxn_names class",
"[10**-9, 10 ** -4, 10 ** -3, 10 ** -2, 10 ** -1,",
"= [10**-9, 10 ** -4, 10 ** -3, 10 ** -2, 10 **",
"'putida_v2_3_all_fixed_flux') time_points_spline = [10**-9, 10 ** -4, 10 ** -3, 10 ** -2,",
"get_met_rxn_names class TestProcessSimulations(unittest.TestCase): def setUp(self): this_dir, this_filename = os.path.split(__file__) self.data_dir = os.path.join(this_dir, '..',",
"'..', '..', 'data', 'raw') self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in = os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat =",
"gather_sim_data(self.mat, met_names, rxn_names, n_models, time_points_spline, save_concs=False, save_fluxes=False) data_type = 'rxn' flux_interp_quantiles = get_time_series_quantiles(flux_interp,",
"self.file_in = os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat = scipy.io.loadmat(self.file_in, squeeze_me=False) def test_get_time_series_quantiles(self): met_names, rxn_names =",
"import os import unittest import scipy.io from src.data.process_simulations import get_time_series_quantiles from src.data.import_simulations import",
"os.path.split(__file__) self.data_dir = os.path.join(this_dir, '..', '..', 'data', 'raw') self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in =",
"= scipy.io.loadmat(self.file_in, squeeze_me=False) def test_get_time_series_quantiles(self): met_names, rxn_names = get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline = [10**-9,",
"met_names, rxn_names, n_models, time_points_spline, save_concs=False, save_fluxes=False) data_type = 'rxn' flux_interp_quantiles = get_time_series_quantiles(flux_interp, time_points_spline,",
"# , 10, 100] n_models = 10 conc, conc_interp, flux, flux_interp = gather_sim_data(self.mat,",
"'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in = os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat = scipy.io.loadmat(self.file_in, squeeze_me=False) def test_get_time_series_quantiles(self): met_names, rxn_names",
"n_models = 10 conc, conc_interp, flux, flux_interp = gather_sim_data(self.mat, met_names, rxn_names, n_models, time_points_spline,",
"this_filename = os.path.split(__file__) self.data_dir = os.path.join(this_dir, '..', '..', 'data', 'raw') self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4'",
"def test_get_time_series_quantiles(self): met_names, rxn_names = get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline = [10**-9, 10 ** -4,",
"-3, 10 ** -2, 10 ** -1, 1] # , 10, 100] n_models",
"gather_sim_data, get_met_rxn_names class TestProcessSimulations(unittest.TestCase): def setUp(self): this_dir, this_filename = os.path.split(__file__) self.data_dir = os.path.join(this_dir,",
"def setUp(self): this_dir, this_filename = os.path.split(__file__) self.data_dir = os.path.join(this_dir, '..', '..', 'data', 'raw')",
"10 ** -4, 10 ** -3, 10 ** -2, 10 ** -1, 1]",
"= os.path.split(__file__) self.data_dir = os.path.join(this_dir, '..', '..', 'data', 'raw') self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in",
"rxn_names = get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline = [10**-9, 10 ** -4, 10 ** -3,",
"-2, 10 ** -1, 1] # , 10, 100] n_models = 10 conc,",
"'raw') self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in = os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat = scipy.io.loadmat(self.file_in, squeeze_me=False) def",
"= 10 conc, conc_interp, flux, flux_interp = gather_sim_data(self.mat, met_names, rxn_names, n_models, time_points_spline, save_concs=False,",
"src.data.import_simulations import gather_sim_data, get_met_rxn_names class TestProcessSimulations(unittest.TestCase): def setUp(self): this_dir, this_filename = os.path.split(__file__) self.data_dir",
"'..', 'data', 'raw') self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in = os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat = scipy.io.loadmat(self.file_in,",
"scipy.io from src.data.process_simulations import get_time_series_quantiles from src.data.import_simulations import gather_sim_data, get_met_rxn_names class TestProcessSimulations(unittest.TestCase): def",
"test_get_time_series_quantiles(self): met_names, rxn_names = get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline = [10**-9, 10 ** -4, 10",
"= 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in = os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat = scipy.io.loadmat(self.file_in, squeeze_me=False) def test_get_time_series_quantiles(self): met_names,",
"import scipy.io from src.data.process_simulations import get_time_series_quantiles from src.data.import_simulations import gather_sim_data, get_met_rxn_names class TestProcessSimulations(unittest.TestCase):",
"met_names, rxn_names = get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline = [10**-9, 10 ** -4, 10 **",
"= get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline = [10**-9, 10 ** -4, 10 ** -3, 10",
"= os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat = scipy.io.loadmat(self.file_in, squeeze_me=False) def test_get_time_series_quantiles(self): met_names, rxn_names = get_met_rxn_names(self.data_dir,",
"10 conc, conc_interp, flux, flux_interp = gather_sim_data(self.mat, met_names, rxn_names, n_models, time_points_spline, save_concs=False, save_fluxes=False)",
"= gather_sim_data(self.mat, met_names, rxn_names, n_models, time_points_spline, save_concs=False, save_fluxes=False) data_type = 'rxn' flux_interp_quantiles =",
"f'simulation_{self.model_name}.mat') self.mat = scipy.io.loadmat(self.file_in, squeeze_me=False) def test_get_time_series_quantiles(self): met_names, rxn_names = get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline",
"get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline = [10**-9, 10 ** -4, 10 ** -3, 10 **",
"rxn_names, n_models, time_points_spline, save_concs=False, save_fluxes=False) data_type = 'rxn' flux_interp_quantiles = get_time_series_quantiles(flux_interp, time_points_spline, data_type,",
"setUp(self): this_dir, this_filename = os.path.split(__file__) self.data_dir = os.path.join(this_dir, '..', '..', 'data', 'raw') self.model_name",
"from src.data.process_simulations import get_time_series_quantiles from src.data.import_simulations import gather_sim_data, get_met_rxn_names class TestProcessSimulations(unittest.TestCase): def setUp(self):",
"<reponame>svevol/accoa_project_data_analysis<filename>kinetic_model_construction_and_analysis/src/tests/test_process_simulations.py<gh_stars>0 import os import unittest import scipy.io from src.data.process_simulations import get_time_series_quantiles from src.data.import_simulations",
"from src.data.import_simulations import gather_sim_data, get_met_rxn_names class TestProcessSimulations(unittest.TestCase): def setUp(self): this_dir, this_filename = os.path.split(__file__)",
"'data', 'raw') self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in = os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat = scipy.io.loadmat(self.file_in, squeeze_me=False)",
"self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in = os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat = scipy.io.loadmat(self.file_in, squeeze_me=False) def test_get_time_series_quantiles(self):",
"** -4, 10 ** -3, 10 ** -2, 10 ** -1, 1] #",
"src.data.process_simulations import get_time_series_quantiles from src.data.import_simulations import gather_sim_data, get_met_rxn_names class TestProcessSimulations(unittest.TestCase): def setUp(self): this_dir,",
"10 ** -2, 10 ** -1, 1] # , 10, 100] n_models =",
"= os.path.join(this_dir, '..', '..', 'data', 'raw') self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in = os.path.join(self.data_dir, f'simulation_{self.model_name}.mat')",
"conc_interp, flux, flux_interp = gather_sim_data(self.mat, met_names, rxn_names, n_models, time_points_spline, save_concs=False, save_fluxes=False) data_type =",
"1] # , 10, 100] n_models = 10 conc, conc_interp, flux, flux_interp =",
"-1, 1] # , 10, 100] n_models = 10 conc, conc_interp, flux, flux_interp",
"os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat = scipy.io.loadmat(self.file_in, squeeze_me=False) def test_get_time_series_quantiles(self): met_names, rxn_names = get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux')",
", 10, 100] n_models = 10 conc, conc_interp, flux, flux_interp = gather_sim_data(self.mat, met_names,",
"import gather_sim_data, get_met_rxn_names class TestProcessSimulations(unittest.TestCase): def setUp(self): this_dir, this_filename = os.path.split(__file__) self.data_dir =",
"self.data_dir = os.path.join(this_dir, '..', '..', 'data', 'raw') self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in = os.path.join(self.data_dir,",
"flux, flux_interp = gather_sim_data(self.mat, met_names, rxn_names, n_models, time_points_spline, save_concs=False, save_fluxes=False) data_type = 'rxn'",
"os.path.join(this_dir, '..', '..', 'data', 'raw') self.model_name = 'putida_v2_3_all_fixed_flux_2000_abs10_-4' self.file_in = os.path.join(self.data_dir, f'simulation_{self.model_name}.mat') self.mat",
"import unittest import scipy.io from src.data.process_simulations import get_time_series_quantiles from src.data.import_simulations import gather_sim_data, get_met_rxn_names",
"flux_interp = gather_sim_data(self.mat, met_names, rxn_names, n_models, time_points_spline, save_concs=False, save_fluxes=False) data_type = 'rxn' flux_interp_quantiles",
"import get_time_series_quantiles from src.data.import_simulations import gather_sim_data, get_met_rxn_names class TestProcessSimulations(unittest.TestCase): def setUp(self): this_dir, this_filename",
"squeeze_me=False) def test_get_time_series_quantiles(self): met_names, rxn_names = get_met_rxn_names(self.data_dir, 'putida_v2_3_all_fixed_flux') time_points_spline = [10**-9, 10 **",
"time_points_spline = [10**-9, 10 ** -4, 10 ** -3, 10 ** -2, 10",
"class TestProcessSimulations(unittest.TestCase): def setUp(self): this_dir, this_filename = os.path.split(__file__) self.data_dir = os.path.join(this_dir, '..', '..',",
"** -2, 10 ** -1, 1] # , 10, 100] n_models = 10",
"os import unittest import scipy.io from src.data.process_simulations import get_time_series_quantiles from src.data.import_simulations import gather_sim_data,",
"get_time_series_quantiles from src.data.import_simulations import gather_sim_data, get_met_rxn_names class TestProcessSimulations(unittest.TestCase): def setUp(self): this_dir, this_filename =",
"10 ** -1, 1] # , 10, 100] n_models = 10 conc, conc_interp,",
"** -3, 10 ** -2, 10 ** -1, 1] # , 10, 100]"
] |
[
"by hand self.assertEqual(charmander.hp, charmander.maxhp-76) def test_acrobatics_noitem(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander',",
"0)) b.do_turn() charmander = b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage calcs were done by",
"were done by hand self.assertEqual(charmander.hp, charmander.maxhp-76) def test_acrobatics_noitem(self): b = Battle(debug=False, rng=False) b.join(0,",
"hand self.assertEqual(charmander.hp, charmander.maxhp-76) def test_acrobatics_noitem(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves':",
"data import dex class TestAcrobatics(unittest.TestCase): def test_acrobatics(self): b = Battle(debug=False, rng=False) b.join(0, [{'species':",
"import unittest from sim.battle import Battle from data import dex class TestAcrobatics(unittest.TestCase): def",
"Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'moves': ['acrobatics']}]) b.choose(0,",
"b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'moves':",
"= b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-76)",
"'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'item': 'pokeball','moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move',",
"'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'item': 'pokeball','moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1,",
"test_acrobatics_noitem(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey',",
"b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander = b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0]",
"done by hand self.assertEqual(charmander.hp, charmander.maxhp-76) def test_acrobatics_noitem(self): b = Battle(debug=False, rng=False) b.join(0, [{'species':",
"TestAcrobatics(unittest.TestCase): def test_acrobatics(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1,",
"pidgey = b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-39) def runTest(self):",
"dex class TestAcrobatics(unittest.TestCase): def test_acrobatics(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves':",
"= b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-76) def test_acrobatics_noitem(self): b",
"[{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1,",
"rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'moves': ['acrobatics']}]) b.choose(0, dex.Decision('move',",
"test_acrobatics(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey',",
"b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-39) def",
"b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-39) def runTest(self): self.test_acrobatics() self.test_acrobatics_noitem()",
"import Battle from data import dex class TestAcrobatics(unittest.TestCase): def test_acrobatics(self): b = Battle(debug=False,",
"sim.battle import Battle from data import dex class TestAcrobatics(unittest.TestCase): def test_acrobatics(self): b =",
"unittest from sim.battle import Battle from data import dex class TestAcrobatics(unittest.TestCase): def test_acrobatics(self):",
"= Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'item': 'pokeball','moves':",
"from sim.battle import Battle from data import dex class TestAcrobatics(unittest.TestCase): def test_acrobatics(self): b",
"class TestAcrobatics(unittest.TestCase): def test_acrobatics(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}])",
"rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'item': 'pokeball','moves': ['acrobatics']}]) b.choose(0,",
"'item': 'pokeball','moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander = b.sides[0].pokemon[0]",
"'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move',",
"b.join(1, [{'species': 'pidgey', 'moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander",
"charmander = b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp,",
"pidgey = b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-76) def test_acrobatics_noitem(self):",
"['tackle']}]) b.join(1, [{'species': 'pidgey', 'item': 'pokeball','moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0))",
"['tackle']}]) b.join(1, [{'species': 'pidgey', 'moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn()",
"'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0))",
"['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander = b.sides[0].pokemon[0] pidgey =",
"b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander = b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage calcs were",
"b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0))",
"self.assertEqual(charmander.hp, charmander.maxhp-76) def test_acrobatics_noitem(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}])",
"Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'item': 'pokeball','moves': ['acrobatics']}])",
"= b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-39) def runTest(self): self.test_acrobatics()",
"b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-76) def test_acrobatics_noitem(self): b =",
"'moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander = b.sides[0].pokemon[0] pidgey",
"#damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-76) def test_acrobatics_noitem(self): b = Battle(debug=False,",
"import dex class TestAcrobatics(unittest.TestCase): def test_acrobatics(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander',",
"[{'species': 'pidgey', 'moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander =",
"b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-76) def",
"calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-76) def test_acrobatics_noitem(self): b = Battle(debug=False, rng=False)",
"b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'item': 'pokeball','moves': ['acrobatics']}]) b.choose(0, dex.Decision('move',",
"def test_acrobatics_noitem(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species':",
"'pidgey', 'item': 'pokeball','moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander =",
"def test_acrobatics(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species':",
"0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander = b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage calcs",
"= Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'moves': ['acrobatics']}])",
"dex.Decision('move', 0)) b.do_turn() charmander = b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage calcs were done",
"[{'species': 'pidgey', 'item': 'pokeball','moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander",
"dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander = b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage",
"'pidgey', 'moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander = b.sides[0].pokemon[0]",
"b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'item':",
"Battle from data import dex class TestAcrobatics(unittest.TestCase): def test_acrobatics(self): b = Battle(debug=False, rng=False)",
"charmander.maxhp-76) def test_acrobatics_noitem(self): b = Battle(debug=False, rng=False) b.join(0, [{'species': 'charmander', 'moves': ['tackle']}]) b.join(1,",
"[{'species': 'charmander', 'moves': ['tackle']}]) b.join(1, [{'species': 'pidgey', 'item': 'pokeball','moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0))",
"b.join(1, [{'species': 'pidgey', 'item': 'pokeball','moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn()",
"'pokeball','moves': ['acrobatics']}]) b.choose(0, dex.Decision('move', 0)) b.choose(1, dex.Decision('move', 0)) b.do_turn() charmander = b.sides[0].pokemon[0] pidgey",
"from data import dex class TestAcrobatics(unittest.TestCase): def test_acrobatics(self): b = Battle(debug=False, rng=False) b.join(0,",
"b.do_turn() charmander = b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage calcs were done by hand",
"= b.sides[0].pokemon[0] pidgey = b.sides[1].pokemon[0] #damage calcs were done by hand self.assertEqual(charmander.hp, charmander.maxhp-39)"
] |
[
"values should be True where a replicate belongs to a condition and False",
"<gh_stars>0 import numpy as np import scipy.stats as stats from hic3defdr.util.scaled_nb import logpmf,",
"= np.dot(mu_hat_alt, design.T) null_ll = np.sum(logpmf(raw, mu_hat_null[:, None] * f, disp), axis=1) alt_ll",
"* f, disp), axis=1) llr = null_ll - alt_ll pvalues = stats.chi2(design.shape[1] -",
"mu_hat_alt = np.array( [fit_mu_hat(raw[:, design[:, c]], f[:, design[:, c]], disp[:, design[:, c]]) for",
"/ f[:, design[:, c]], axis=1) for c in range(design.shape[1])]).T mu_hat_alt_wide = np.dot(mu_hat_alt, design.T)",
"be True where a replicate belongs to a condition and False otherwise. Returns",
"disp : np.ndarray Matrices of raw values, combined scaling factors, and dispersions, respectively.",
"per pixel. \"\"\" if refit_mu: mu_hat_null = fit_mu_hat(raw, f, disp) mu_hat_alt = np.array(",
"Returns ------- pvalues : np.ndarray The LRT p-values per pixel. llr : np.ndarray",
"* f, disp), axis=1) alt_ll = np.sum(logpmf(raw, mu_hat_alt_wide * f, disp), axis=1) llr",
"scaling factors ``f`` and dispersion ``disp``. Parameters ---------- raw, f, disp : np.ndarray",
"mu_hat_null = np.mean(raw / f, axis=1) mu_hat_alt = np.array( [np.mean(raw[:, design[:, c]] /",
"pixels, columns correspond to replicates. design : np.ndarray Describes the grouping of replicates",
"f, disp), axis=1) llr = null_ll - alt_ll pvalues = stats.chi2(design.shape[1] - 1).sf(-2",
"------- pvalues : np.ndarray The LRT p-values per pixel. llr : np.ndarray The",
"None] * f, disp), axis=1) alt_ll = np.sum(logpmf(raw, mu_hat_alt_wide * f, disp), axis=1)",
"respectively. Rows correspond to pixels, columns correspond to replicates. design : np.ndarray Describes",
"to pixels, columns correspond to replicates. design : np.ndarray Describes the grouping of",
"f, disp : np.ndarray Matrices of raw values, combined scaling factors, and dispersions,",
"\"\"\" Performs a likelihood ratio test on raw data ``raw`` given scaling factors",
"combined scaling factors, and dispersions, respectively. Rows correspond to pixels, columns correspond to",
": np.ndarray Matrices of raw values, combined scaling factors, and dispersions, respectively. Rows",
"raw, f, disp : np.ndarray Matrices of raw values, combined scaling factors, and",
"factors, and dispersions, respectively. Rows correspond to pixels, columns correspond to replicates. design",
"where a replicate belongs to a condition and False otherwise. Returns ------- pvalues",
"a condition and False otherwise. Returns ------- pvalues : np.ndarray The LRT p-values",
"into conditions. Rows correspond to replicates, columns correspond to conditions, and values should",
"def lrt(raw, f, disp, design, refit_mu=True): \"\"\" Performs a likelihood ratio test on",
"condition and False otherwise. Returns ------- pvalues : np.ndarray The LRT p-values per",
"scipy.stats as stats from hic3defdr.util.scaled_nb import logpmf, fit_mu_hat def lrt(raw, f, disp, design,",
": np.ndarray The log likelihood ratio per pixel. mu_hat_null, mu_hat_alt : np.ndarray The",
"disp) mu_hat_alt = np.array( [fit_mu_hat(raw[:, design[:, c]], f[:, design[:, c]], disp[:, design[:, c]])",
"replicates, columns correspond to conditions, and values should be True where a replicate",
"Performs a likelihood ratio test on raw data ``raw`` given scaling factors ``f``",
"fitted mean parameters under the null and alt models, respectively, per pixel. \"\"\"",
"c in range(design.shape[1])]).T else: mu_hat_null = np.mean(raw / f, axis=1) mu_hat_alt = np.array(",
"axis=1) llr = null_ll - alt_ll pvalues = stats.chi2(design.shape[1] - 1).sf(-2 * llr)",
"\"\"\" if refit_mu: mu_hat_null = fit_mu_hat(raw, f, disp) mu_hat_alt = np.array( [fit_mu_hat(raw[:, design[:,",
": np.ndarray Describes the grouping of replicates into conditions. Rows correspond to replicates,",
"np.ndarray Matrices of raw values, combined scaling factors, and dispersions, respectively. Rows correspond",
"disp), axis=1) llr = null_ll - alt_ll pvalues = stats.chi2(design.shape[1] - 1).sf(-2 *",
"mu_hat_null[:, None] * f, disp), axis=1) alt_ll = np.sum(logpmf(raw, mu_hat_alt_wide * f, disp),",
"to conditions, and values should be True where a replicate belongs to a",
"``f`` and dispersion ``disp``. Parameters ---------- raw, f, disp : np.ndarray Matrices of",
"np.ndarray The LRT p-values per pixel. llr : np.ndarray The log likelihood ratio",
"axis=1) for c in range(design.shape[1])]).T mu_hat_alt_wide = np.dot(mu_hat_alt, design.T) null_ll = np.sum(logpmf(raw, mu_hat_null[:,",
"False otherwise. Returns ------- pvalues : np.ndarray The LRT p-values per pixel. llr",
"to replicates. design : np.ndarray Describes the grouping of replicates into conditions. Rows",
": np.ndarray The fitted mean parameters under the null and alt models, respectively,",
"pixel. mu_hat_null, mu_hat_alt : np.ndarray The fitted mean parameters under the null and",
"lrt(raw, f, disp, design, refit_mu=True): \"\"\" Performs a likelihood ratio test on raw",
"and values should be True where a replicate belongs to a condition and",
"design : np.ndarray Describes the grouping of replicates into conditions. Rows correspond to",
"True where a replicate belongs to a condition and False otherwise. Returns -------",
"design[:, c]], f[:, design[:, c]], disp[:, design[:, c]]) for c in range(design.shape[1])]).T else:",
"and dispersions, respectively. Rows correspond to pixels, columns correspond to replicates. design :",
"to replicates, columns correspond to conditions, and values should be True where a",
"alt_ll pvalues = stats.chi2(design.shape[1] - 1).sf(-2 * llr) return pvalues, llr, mu_hat_null, mu_hat_alt",
": np.ndarray The LRT p-values per pixel. llr : np.ndarray The log likelihood",
"c]], axis=1) for c in range(design.shape[1])]).T mu_hat_alt_wide = np.dot(mu_hat_alt, design.T) null_ll = np.sum(logpmf(raw,",
"logpmf, fit_mu_hat def lrt(raw, f, disp, design, refit_mu=True): \"\"\" Performs a likelihood ratio",
"import numpy as np import scipy.stats as stats from hic3defdr.util.scaled_nb import logpmf, fit_mu_hat",
"null_ll - alt_ll pvalues = stats.chi2(design.shape[1] - 1).sf(-2 * llr) return pvalues, llr,",
"Parameters ---------- raw, f, disp : np.ndarray Matrices of raw values, combined scaling",
"dispersion ``disp``. Parameters ---------- raw, f, disp : np.ndarray Matrices of raw values,",
"under the null and alt models, respectively, per pixel. \"\"\" if refit_mu: mu_hat_null",
"Rows correspond to replicates, columns correspond to conditions, and values should be True",
"mu_hat_alt_wide * f, disp), axis=1) llr = null_ll - alt_ll pvalues = stats.chi2(design.shape[1]",
"replicates. design : np.ndarray Describes the grouping of replicates into conditions. Rows correspond",
"belongs to a condition and False otherwise. Returns ------- pvalues : np.ndarray The",
"null_ll = np.sum(logpmf(raw, mu_hat_null[:, None] * f, disp), axis=1) alt_ll = np.sum(logpmf(raw, mu_hat_alt_wide",
"mu_hat_alt_wide = np.dot(mu_hat_alt, design.T) null_ll = np.sum(logpmf(raw, mu_hat_null[:, None] * f, disp), axis=1)",
"scaling factors, and dispersions, respectively. Rows correspond to pixels, columns correspond to replicates.",
"f[:, design[:, c]], axis=1) for c in range(design.shape[1])]).T mu_hat_alt_wide = np.dot(mu_hat_alt, design.T) null_ll",
"np.array( [np.mean(raw[:, design[:, c]] / f[:, design[:, c]], axis=1) for c in range(design.shape[1])]).T",
"np.ndarray The fitted mean parameters under the null and alt models, respectively, per",
"raw values, combined scaling factors, and dispersions, respectively. Rows correspond to pixels, columns",
"The fitted mean parameters under the null and alt models, respectively, per pixel.",
"correspond to pixels, columns correspond to replicates. design : np.ndarray Describes the grouping",
"log likelihood ratio per pixel. mu_hat_null, mu_hat_alt : np.ndarray The fitted mean parameters",
"np.array( [fit_mu_hat(raw[:, design[:, c]], f[:, design[:, c]], disp[:, design[:, c]]) for c in",
"design, refit_mu=True): \"\"\" Performs a likelihood ratio test on raw data ``raw`` given",
"np.ndarray Describes the grouping of replicates into conditions. Rows correspond to replicates, columns",
"= null_ll - alt_ll pvalues = stats.chi2(design.shape[1] - 1).sf(-2 * llr) return pvalues,",
"mean parameters under the null and alt models, respectively, per pixel. \"\"\" if",
"conditions. Rows correspond to replicates, columns correspond to conditions, and values should be",
"raw data ``raw`` given scaling factors ``f`` and dispersion ``disp``. Parameters ---------- raw,",
"and dispersion ``disp``. Parameters ---------- raw, f, disp : np.ndarray Matrices of raw",
"design[:, c]]) for c in range(design.shape[1])]).T else: mu_hat_null = np.mean(raw / f, axis=1)",
"stats from hic3defdr.util.scaled_nb import logpmf, fit_mu_hat def lrt(raw, f, disp, design, refit_mu=True): \"\"\"",
"and False otherwise. Returns ------- pvalues : np.ndarray The LRT p-values per pixel.",
"for c in range(design.shape[1])]).T else: mu_hat_null = np.mean(raw / f, axis=1) mu_hat_alt =",
"llr : np.ndarray The log likelihood ratio per pixel. mu_hat_null, mu_hat_alt : np.ndarray",
"np.mean(raw / f, axis=1) mu_hat_alt = np.array( [np.mean(raw[:, design[:, c]] / f[:, design[:,",
"for c in range(design.shape[1])]).T mu_hat_alt_wide = np.dot(mu_hat_alt, design.T) null_ll = np.sum(logpmf(raw, mu_hat_null[:, None]",
"of raw values, combined scaling factors, and dispersions, respectively. Rows correspond to pixels,",
"grouping of replicates into conditions. Rows correspond to replicates, columns correspond to conditions,",
"design[:, c]] / f[:, design[:, c]], axis=1) for c in range(design.shape[1])]).T mu_hat_alt_wide =",
"design.T) null_ll = np.sum(logpmf(raw, mu_hat_null[:, None] * f, disp), axis=1) alt_ll = np.sum(logpmf(raw,",
"ratio per pixel. mu_hat_null, mu_hat_alt : np.ndarray The fitted mean parameters under the",
"correspond to replicates, columns correspond to conditions, and values should be True where",
"mu_hat_alt = np.array( [np.mean(raw[:, design[:, c]] / f[:, design[:, c]], axis=1) for c",
"per pixel. llr : np.ndarray The log likelihood ratio per pixel. mu_hat_null, mu_hat_alt",
"Describes the grouping of replicates into conditions. Rows correspond to replicates, columns correspond",
"= np.mean(raw / f, axis=1) mu_hat_alt = np.array( [np.mean(raw[:, design[:, c]] / f[:,",
"per pixel. mu_hat_null, mu_hat_alt : np.ndarray The fitted mean parameters under the null",
"likelihood ratio per pixel. mu_hat_null, mu_hat_alt : np.ndarray The fitted mean parameters under",
"np.sum(logpmf(raw, mu_hat_null[:, None] * f, disp), axis=1) alt_ll = np.sum(logpmf(raw, mu_hat_alt_wide * f,",
"f, disp, design, refit_mu=True): \"\"\" Performs a likelihood ratio test on raw data",
"a likelihood ratio test on raw data ``raw`` given scaling factors ``f`` and",
"disp, design, refit_mu=True): \"\"\" Performs a likelihood ratio test on raw data ``raw``",
"np.ndarray The log likelihood ratio per pixel. mu_hat_null, mu_hat_alt : np.ndarray The fitted",
"test on raw data ``raw`` given scaling factors ``f`` and dispersion ``disp``. Parameters",
"---------- raw, f, disp : np.ndarray Matrices of raw values, combined scaling factors,",
"The LRT p-values per pixel. llr : np.ndarray The log likelihood ratio per",
"to a condition and False otherwise. Returns ------- pvalues : np.ndarray The LRT",
"numpy as np import scipy.stats as stats from hic3defdr.util.scaled_nb import logpmf, fit_mu_hat def",
"design[:, c]], disp[:, design[:, c]]) for c in range(design.shape[1])]).T else: mu_hat_null = np.mean(raw",
"alt models, respectively, per pixel. \"\"\" if refit_mu: mu_hat_null = fit_mu_hat(raw, f, disp)",
"from hic3defdr.util.scaled_nb import logpmf, fit_mu_hat def lrt(raw, f, disp, design, refit_mu=True): \"\"\" Performs",
"np.dot(mu_hat_alt, design.T) null_ll = np.sum(logpmf(raw, mu_hat_null[:, None] * f, disp), axis=1) alt_ll =",
"ratio test on raw data ``raw`` given scaling factors ``f`` and dispersion ``disp``.",
"hic3defdr.util.scaled_nb import logpmf, fit_mu_hat def lrt(raw, f, disp, design, refit_mu=True): \"\"\" Performs a",
"axis=1) mu_hat_alt = np.array( [np.mean(raw[:, design[:, c]] / f[:, design[:, c]], axis=1) for",
"models, respectively, per pixel. \"\"\" if refit_mu: mu_hat_null = fit_mu_hat(raw, f, disp) mu_hat_alt",
"replicate belongs to a condition and False otherwise. Returns ------- pvalues : np.ndarray",
"replicates into conditions. Rows correspond to replicates, columns correspond to conditions, and values",
"disp), axis=1) alt_ll = np.sum(logpmf(raw, mu_hat_alt_wide * f, disp), axis=1) llr = null_ll",
"llr = null_ll - alt_ll pvalues = stats.chi2(design.shape[1] - 1).sf(-2 * llr) return",
"and alt models, respectively, per pixel. \"\"\" if refit_mu: mu_hat_null = fit_mu_hat(raw, f,",
"c]], f[:, design[:, c]], disp[:, design[:, c]]) for c in range(design.shape[1])]).T else: mu_hat_null",
"import scipy.stats as stats from hic3defdr.util.scaled_nb import logpmf, fit_mu_hat def lrt(raw, f, disp,",
"``raw`` given scaling factors ``f`` and dispersion ``disp``. Parameters ---------- raw, f, disp",
"The log likelihood ratio per pixel. mu_hat_null, mu_hat_alt : np.ndarray The fitted mean",
"refit_mu=True): \"\"\" Performs a likelihood ratio test on raw data ``raw`` given scaling",
"parameters under the null and alt models, respectively, per pixel. \"\"\" if refit_mu:",
"range(design.shape[1])]).T else: mu_hat_null = np.mean(raw / f, axis=1) mu_hat_alt = np.array( [np.mean(raw[:, design[:,",
"columns correspond to replicates. design : np.ndarray Describes the grouping of replicates into",
"alt_ll = np.sum(logpmf(raw, mu_hat_alt_wide * f, disp), axis=1) llr = null_ll - alt_ll",
"f[:, design[:, c]], disp[:, design[:, c]]) for c in range(design.shape[1])]).T else: mu_hat_null =",
"= np.array( [np.mean(raw[:, design[:, c]] / f[:, design[:, c]], axis=1) for c in",
"of replicates into conditions. Rows correspond to replicates, columns correspond to conditions, and",
"p-values per pixel. llr : np.ndarray The log likelihood ratio per pixel. mu_hat_null,",
"axis=1) alt_ll = np.sum(logpmf(raw, mu_hat_alt_wide * f, disp), axis=1) llr = null_ll -",
"mu_hat_null, mu_hat_alt : np.ndarray The fitted mean parameters under the null and alt",
"design[:, c]], axis=1) for c in range(design.shape[1])]).T mu_hat_alt_wide = np.dot(mu_hat_alt, design.T) null_ll =",
"given scaling factors ``f`` and dispersion ``disp``. Parameters ---------- raw, f, disp :",
"range(design.shape[1])]).T mu_hat_alt_wide = np.dot(mu_hat_alt, design.T) null_ll = np.sum(logpmf(raw, mu_hat_null[:, None] * f, disp),",
"as stats from hic3defdr.util.scaled_nb import logpmf, fit_mu_hat def lrt(raw, f, disp, design, refit_mu=True):",
"c in range(design.shape[1])]).T mu_hat_alt_wide = np.dot(mu_hat_alt, design.T) null_ll = np.sum(logpmf(raw, mu_hat_null[:, None] *",
"fit_mu_hat def lrt(raw, f, disp, design, refit_mu=True): \"\"\" Performs a likelihood ratio test",
"pvalues : np.ndarray The LRT p-values per pixel. llr : np.ndarray The log",
"null and alt models, respectively, per pixel. \"\"\" if refit_mu: mu_hat_null = fit_mu_hat(raw,",
"a replicate belongs to a condition and False otherwise. Returns ------- pvalues :",
"respectively, per pixel. \"\"\" if refit_mu: mu_hat_null = fit_mu_hat(raw, f, disp) mu_hat_alt =",
"correspond to replicates. design : np.ndarray Describes the grouping of replicates into conditions.",
"f, disp) mu_hat_alt = np.array( [fit_mu_hat(raw[:, design[:, c]], f[:, design[:, c]], disp[:, design[:,",
"f, axis=1) mu_hat_alt = np.array( [np.mean(raw[:, design[:, c]] / f[:, design[:, c]], axis=1)",
"- alt_ll pvalues = stats.chi2(design.shape[1] - 1).sf(-2 * llr) return pvalues, llr, mu_hat_null,",
"the grouping of replicates into conditions. Rows correspond to replicates, columns correspond to",
"f, disp), axis=1) alt_ll = np.sum(logpmf(raw, mu_hat_alt_wide * f, disp), axis=1) llr =",
"np import scipy.stats as stats from hic3defdr.util.scaled_nb import logpmf, fit_mu_hat def lrt(raw, f,",
"``disp``. Parameters ---------- raw, f, disp : np.ndarray Matrices of raw values, combined",
"columns correspond to conditions, and values should be True where a replicate belongs",
"if refit_mu: mu_hat_null = fit_mu_hat(raw, f, disp) mu_hat_alt = np.array( [fit_mu_hat(raw[:, design[:, c]],",
"/ f, axis=1) mu_hat_alt = np.array( [np.mean(raw[:, design[:, c]] / f[:, design[:, c]],",
"mu_hat_null = fit_mu_hat(raw, f, disp) mu_hat_alt = np.array( [fit_mu_hat(raw[:, design[:, c]], f[:, design[:,",
"else: mu_hat_null = np.mean(raw / f, axis=1) mu_hat_alt = np.array( [np.mean(raw[:, design[:, c]]",
"likelihood ratio test on raw data ``raw`` given scaling factors ``f`` and dispersion",
"the null and alt models, respectively, per pixel. \"\"\" if refit_mu: mu_hat_null =",
"fit_mu_hat(raw, f, disp) mu_hat_alt = np.array( [fit_mu_hat(raw[:, design[:, c]], f[:, design[:, c]], disp[:,",
"c]], disp[:, design[:, c]]) for c in range(design.shape[1])]).T else: mu_hat_null = np.mean(raw /",
"should be True where a replicate belongs to a condition and False otherwise.",
"data ``raw`` given scaling factors ``f`` and dispersion ``disp``. Parameters ---------- raw, f,",
"values, combined scaling factors, and dispersions, respectively. Rows correspond to pixels, columns correspond",
"in range(design.shape[1])]).T mu_hat_alt_wide = np.dot(mu_hat_alt, design.T) null_ll = np.sum(logpmf(raw, mu_hat_null[:, None] * f,",
"conditions, and values should be True where a replicate belongs to a condition",
"pixel. \"\"\" if refit_mu: mu_hat_null = fit_mu_hat(raw, f, disp) mu_hat_alt = np.array( [fit_mu_hat(raw[:,",
"otherwise. Returns ------- pvalues : np.ndarray The LRT p-values per pixel. llr :",
"= np.sum(logpmf(raw, mu_hat_null[:, None] * f, disp), axis=1) alt_ll = np.sum(logpmf(raw, mu_hat_alt_wide *",
"on raw data ``raw`` given scaling factors ``f`` and dispersion ``disp``. Parameters ----------",
"= np.sum(logpmf(raw, mu_hat_alt_wide * f, disp), axis=1) llr = null_ll - alt_ll pvalues",
"c]] / f[:, design[:, c]], axis=1) for c in range(design.shape[1])]).T mu_hat_alt_wide = np.dot(mu_hat_alt,",
"= np.array( [fit_mu_hat(raw[:, design[:, c]], f[:, design[:, c]], disp[:, design[:, c]]) for c",
"[fit_mu_hat(raw[:, design[:, c]], f[:, design[:, c]], disp[:, design[:, c]]) for c in range(design.shape[1])]).T",
"c]]) for c in range(design.shape[1])]).T else: mu_hat_null = np.mean(raw / f, axis=1) mu_hat_alt",
"Rows correspond to pixels, columns correspond to replicates. design : np.ndarray Describes the",
"dispersions, respectively. Rows correspond to pixels, columns correspond to replicates. design : np.ndarray",
"disp[:, design[:, c]]) for c in range(design.shape[1])]).T else: mu_hat_null = np.mean(raw / f,",
"[np.mean(raw[:, design[:, c]] / f[:, design[:, c]], axis=1) for c in range(design.shape[1])]).T mu_hat_alt_wide",
"import logpmf, fit_mu_hat def lrt(raw, f, disp, design, refit_mu=True): \"\"\" Performs a likelihood",
"pixel. llr : np.ndarray The log likelihood ratio per pixel. mu_hat_null, mu_hat_alt :",
"correspond to conditions, and values should be True where a replicate belongs to",
"factors ``f`` and dispersion ``disp``. Parameters ---------- raw, f, disp : np.ndarray Matrices",
"refit_mu: mu_hat_null = fit_mu_hat(raw, f, disp) mu_hat_alt = np.array( [fit_mu_hat(raw[:, design[:, c]], f[:,",
"np.sum(logpmf(raw, mu_hat_alt_wide * f, disp), axis=1) llr = null_ll - alt_ll pvalues =",
"as np import scipy.stats as stats from hic3defdr.util.scaled_nb import logpmf, fit_mu_hat def lrt(raw,",
"LRT p-values per pixel. llr : np.ndarray The log likelihood ratio per pixel.",
"Matrices of raw values, combined scaling factors, and dispersions, respectively. Rows correspond to",
"mu_hat_alt : np.ndarray The fitted mean parameters under the null and alt models,",
"in range(design.shape[1])]).T else: mu_hat_null = np.mean(raw / f, axis=1) mu_hat_alt = np.array( [np.mean(raw[:,",
"= fit_mu_hat(raw, f, disp) mu_hat_alt = np.array( [fit_mu_hat(raw[:, design[:, c]], f[:, design[:, c]],"
] |
[
"== \"kpoint_focal\": loss = KpointFocalLoss(**params) elif loss_name == \"masked_focal\": loss = MaskedFocal() elif",
"RegrLoss, MaskedFocal def get_loss(loss): loss_name = loss[\"name\"] params = loss[\"params\"] if loss_name ==",
"loss = RegrLoss(**params) else: raise ValueError(\"Loss [%s] not recognized.\" % loss_name) return loss",
".keypoint_losses import KpointFocalLoss from .aux_losses import RegrLoss, MaskedFocal def get_loss(loss): loss_name = loss[\"name\"]",
"KpointFocalLoss from .aux_losses import RegrLoss, MaskedFocal def get_loss(loss): loss_name = loss[\"name\"] params =",
"loss = KpointFocalLoss(**params) elif loss_name == \"masked_focal\": loss = MaskedFocal() elif loss_name ==",
"from .keypoint_losses import KpointFocalLoss from .aux_losses import RegrLoss, MaskedFocal def get_loss(loss): loss_name =",
"loss = MaskedFocal() elif loss_name == \"regr_loss\": loss = RegrLoss(**params) else: raise ValueError(\"Loss",
"elif loss_name == \"masked_focal\": loss = MaskedFocal() elif loss_name == \"regr_loss\": loss =",
"MaskedFocal() elif loss_name == \"regr_loss\": loss = RegrLoss(**params) else: raise ValueError(\"Loss [%s] not",
"if loss_name == \"kpoint_focal\": loss = KpointFocalLoss(**params) elif loss_name == \"masked_focal\": loss =",
"loss_name == \"regr_loss\": loss = RegrLoss(**params) else: raise ValueError(\"Loss [%s] not recognized.\" %",
"import KpointFocalLoss from .aux_losses import RegrLoss, MaskedFocal def get_loss(loss): loss_name = loss[\"name\"] params",
"= loss[\"name\"] params = loss[\"params\"] if loss_name == \"kpoint_focal\": loss = KpointFocalLoss(**params) elif",
"loss_name = loss[\"name\"] params = loss[\"params\"] if loss_name == \"kpoint_focal\": loss = KpointFocalLoss(**params)",
"loss_name == \"masked_focal\": loss = MaskedFocal() elif loss_name == \"regr_loss\": loss = RegrLoss(**params)",
"MaskedFocal def get_loss(loss): loss_name = loss[\"name\"] params = loss[\"params\"] if loss_name == \"kpoint_focal\":",
"elif loss_name == \"regr_loss\": loss = RegrLoss(**params) else: raise ValueError(\"Loss [%s] not recognized.\"",
"loss[\"params\"] if loss_name == \"kpoint_focal\": loss = KpointFocalLoss(**params) elif loss_name == \"masked_focal\": loss",
"def get_loss(loss): loss_name = loss[\"name\"] params = loss[\"params\"] if loss_name == \"kpoint_focal\": loss",
"loss_name == \"kpoint_focal\": loss = KpointFocalLoss(**params) elif loss_name == \"masked_focal\": loss = MaskedFocal()",
"\"masked_focal\": loss = MaskedFocal() elif loss_name == \"regr_loss\": loss = RegrLoss(**params) else: raise",
"\"kpoint_focal\": loss = KpointFocalLoss(**params) elif loss_name == \"masked_focal\": loss = MaskedFocal() elif loss_name",
"get_loss(loss): loss_name = loss[\"name\"] params = loss[\"params\"] if loss_name == \"kpoint_focal\": loss =",
"== \"regr_loss\": loss = RegrLoss(**params) else: raise ValueError(\"Loss [%s] not recognized.\" % loss_name)",
"params = loss[\"params\"] if loss_name == \"kpoint_focal\": loss = KpointFocalLoss(**params) elif loss_name ==",
"== \"masked_focal\": loss = MaskedFocal() elif loss_name == \"regr_loss\": loss = RegrLoss(**params) else:",
"= KpointFocalLoss(**params) elif loss_name == \"masked_focal\": loss = MaskedFocal() elif loss_name == \"regr_loss\":",
".aux_losses import RegrLoss, MaskedFocal def get_loss(loss): loss_name = loss[\"name\"] params = loss[\"params\"] if",
"from .aux_losses import RegrLoss, MaskedFocal def get_loss(loss): loss_name = loss[\"name\"] params = loss[\"params\"]",
"KpointFocalLoss(**params) elif loss_name == \"masked_focal\": loss = MaskedFocal() elif loss_name == \"regr_loss\": loss",
"= MaskedFocal() elif loss_name == \"regr_loss\": loss = RegrLoss(**params) else: raise ValueError(\"Loss [%s]",
"= loss[\"params\"] if loss_name == \"kpoint_focal\": loss = KpointFocalLoss(**params) elif loss_name == \"masked_focal\":",
"loss[\"name\"] params = loss[\"params\"] if loss_name == \"kpoint_focal\": loss = KpointFocalLoss(**params) elif loss_name",
"import RegrLoss, MaskedFocal def get_loss(loss): loss_name = loss[\"name\"] params = loss[\"params\"] if loss_name",
"\"regr_loss\": loss = RegrLoss(**params) else: raise ValueError(\"Loss [%s] not recognized.\" % loss_name) return"
] |
[
") urlpatterns = [ path('contributor', Contributor.as_view()), path('maintainer', Maintainer.as_view()), path('healthcheck', HealthCheck.as_view()), path('team', Team.as_view()), path('contact-us',",
"path from .open_views import ( Contributor, Maintainer, HealthCheck, Team, ContactUs ) urlpatterns =",
"from .open_views import ( Contributor, Maintainer, HealthCheck, Team, ContactUs ) urlpatterns = [",
".open_views import ( Contributor, Maintainer, HealthCheck, Team, ContactUs ) urlpatterns = [ path('contributor',",
"( Contributor, Maintainer, HealthCheck, Team, ContactUs ) urlpatterns = [ path('contributor', Contributor.as_view()), path('maintainer',",
"Team, ContactUs ) urlpatterns = [ path('contributor', Contributor.as_view()), path('maintainer', Maintainer.as_view()), path('healthcheck', HealthCheck.as_view()), path('team',",
"import path from .open_views import ( Contributor, Maintainer, HealthCheck, Team, ContactUs ) urlpatterns",
"django.urls import path from .open_views import ( Contributor, Maintainer, HealthCheck, Team, ContactUs )",
"Contributor, Maintainer, HealthCheck, Team, ContactUs ) urlpatterns = [ path('contributor', Contributor.as_view()), path('maintainer', Maintainer.as_view()),",
"Maintainer, HealthCheck, Team, ContactUs ) urlpatterns = [ path('contributor', Contributor.as_view()), path('maintainer', Maintainer.as_view()), path('healthcheck',",
"ContactUs ) urlpatterns = [ path('contributor', Contributor.as_view()), path('maintainer', Maintainer.as_view()), path('healthcheck', HealthCheck.as_view()), path('team', Team.as_view()),",
"= [ path('contributor', Contributor.as_view()), path('maintainer', Maintainer.as_view()), path('healthcheck', HealthCheck.as_view()), path('team', Team.as_view()), path('contact-us', ContactUs.as_view()), ]",
"HealthCheck, Team, ContactUs ) urlpatterns = [ path('contributor', Contributor.as_view()), path('maintainer', Maintainer.as_view()), path('healthcheck', HealthCheck.as_view()),",
"urlpatterns = [ path('contributor', Contributor.as_view()), path('maintainer', Maintainer.as_view()), path('healthcheck', HealthCheck.as_view()), path('team', Team.as_view()), path('contact-us', ContactUs.as_view()),",
"from django.urls import path from .open_views import ( Contributor, Maintainer, HealthCheck, Team, ContactUs",
"import ( Contributor, Maintainer, HealthCheck, Team, ContactUs ) urlpatterns = [ path('contributor', Contributor.as_view()),"
] |
[
"str :param controller: swagger controller :type controller: str :return: file \"\"\" # prepare",
"+ server_error) elif status_code != 200 and status_code != 204: error = response.text",
"files is None: if data is None: raise Pdf4meClientException(\"Please provide at least one",
"server_error) elif status_code != 200 and status_code != 204: error = response.text raise",
"for error messages self.__check_docLogs_for_error_messages(res) # read content from response json_response = self.json_converter.load(res.text) return",
"self.token = token self.json_converter = JsonConverter() self.url = \"https://api.pdf4me.com/\" if apiurl is not",
"= self.json_converter.load(res.text) return json_response def post_wrapper(self, octet_streams, values, controller): \"\"\"Builds a post requests",
"!= 0: data = {key: value for (key, value) in values} else: data",
"value, value: content of value) pairs :type values: list :param controller: swagger controller",
"= \"https://api.pdf4me.com/\" if apiurl is not None and len(apiurl) != 0: self.url =",
"of an error a Pdf4meBackendException is thrown. :param response: post response :type response:",
"def __init__(self, token, apiurl): self.token = token self.json_converter = JsonConverter() self.url = \"https://api.pdf4me.com/\"",
"\" : trace_id \" + trace_id + \" : \" + server_error) elif",
"and status_code != 204: error = response.text raise Pdf4meBackendException('HTTP ' + str(status_code) +",
"json_response def get_wrapper(self, query_strings, controller): \"\"\"Sends a get request to the specified controller",
"values if len(values) != 0: data = {key: value for (key, value) in",
"open(fileName, 'rb'))) pairs :type octet_streams: list :param values: (key: identifier of value, value:",
"= None # send request if files is None: if data is None:",
"value for (key, value) in values} else: data = None # send request",
"for (key, value) in values} else: data = None # send request if",
"0: self.url = apiurl self.userAgent = \"pdf4me-python/0.8.24\" def post_universal_object(self, universal_object, controller): \"\"\"Sends a",
"identifier of value, value: content of value) pairs :type values: list :param controller:",
"self.__check_docLogs_for_error_messages(res) return res.content def get_object(self, query_strings, controller): \"\"\"Sends a get request to the",
"post requests from the given parameters. :param octet_streams: (key: file identifier, value: open(fileName,",
"octet-stream.\") else: res = requests.post(request_url, data=data, headers=header) else: if data is None: res",
"'Content-Type': 'application/json', 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent } # convert body",
"given parameters. :param octet_streams: (key: file identifier, value: open(fileName, 'rb'))) pairs :type octet_streams:",
"headers=header) else: if data is None: res = requests.post(request_url, files=files, headers=header) else: res",
"__check_status_code(self, response): ''' Checks whether the status code is either 200 or 204,",
"header = {'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent} # build files if",
":param query_strings: params to be sent :type query_strings: str :param controller: swagger controller",
"controller): \"\"\"Sends a post request to the specified controller with the given universal_object",
"pdf4me.helper.token_generator import TokenGenerator class CustomHttp(object): def __init__(self, token, apiurl): self.token = token self.json_converter",
"a post request to the specified controller with the given universal_object as a",
"# send request if files is None: if data is None: raise Pdf4meClientException(\"Please",
"either 200 or 204, otw. throws a Pdf4meBackendException. :param response: post response :type",
"build values if len(values) != 0: data = {key: value for (key, value)",
"query_strings: str :param controller: swagger controller :type controller: str :return: post response \"\"\"",
"'User-Agent': self.userAgent} # build files if octet_streams is not None and len(octet_streams) !=",
"docLogs for error messages self.__check_docLogs_for_error_messages(res) # read content from response json_response = self.json_converter.load(res.text)",
"(key: identifier of value, value: content of value) pairs :type values: list :param",
"to be sent :type universal_object: object :param controller: swagger controller :type controller: str",
"token, apiurl): self.token = token self.json_converter = JsonConverter() self.url = \"https://api.pdf4me.com/\" if apiurl",
"octet_streams, values, controller): \"\"\"Builds a post requests from the given parameters. :param octet_streams:",
"headers=headers) # check status code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res)",
"octet_streams: (key: file identifier, value: open(fileName, 'rb'))) pairs :type octet_streams: list :param values:",
"raise Pdf4meBackendException('HTTP 500 ' + status_reason + \" : trace_id \" + trace_id",
":type values: list :param controller: swagger controller :type controller: str :return: post response",
"204: error = response.text raise Pdf4meBackendException('HTTP ' + str(status_code) + ': ' +",
"# prepare post request request_url = self.url + controller header = {'Authorization': 'Basic",
"controller headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic ' + self.token,",
":type octet_streams: list :param values: (key: identifier of value, value: content of value)",
"= \"pdf4me-python/0.8.24\" def post_universal_object(self, universal_object, controller): \"\"\"Sends a post request to the specified",
"# check status code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) return",
"return res.content def get_object(self, query_strings, controller): \"\"\"Sends a get request to the specified",
"= { 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent } # send request",
"# check docLogs for error messages self.__check_docLogs_for_error_messages(res) # read content from response json_response",
"len(octet_streams) != 0: files = {key: value for (key, value) in octet_streams} else:",
"sent :type query_strings: str :param controller: swagger controller :type controller: str :return: post",
"{key: value for (key, value) in octet_streams} else: files = None # build",
"self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def __check_status_code(self, response):",
"data is None: raise Pdf4meClientException(\"Please provide at least one value or an octet-stream.\")",
"error) def __check_docLogs_for_error_messages(self, response): ''' Checks whether the HTTP response's docLogs contain any",
"controller with the given query strings. :param query_strings: params to be sent :type",
"read content from response json_response = self.json_converter.load(res.text) return json_response def post_wrapper(self, octet_streams, values,",
"post request request_url = self.url + controller header = {'Authorization': 'Basic ' +",
"pairs :type values: list :param controller: swagger controller :type controller: str :return: post",
"\"pdf4me-python/0.8.24\" def post_universal_object(self, universal_object, controller): \"\"\"Sends a post request to the specified controller",
"value) in octet_streams} else: files = None # build values if len(values) !=",
"file identifier, value: open(fileName, 'rb'))) pairs :type octet_streams: list :param values: (key: identifier",
"\"\"\"Sends a get request to the specified controller with the given query strings.",
"query_strings: str :param controller: swagger controller :type controller: str :return: file \"\"\" #",
": trace_id \" + trace_id + \" : \" + server_error) elif status_code",
"else: res = requests.post(request_url, data=data, headers=header) else: if data is None: res =",
"swagger controller :type controller: str :return: post response \"\"\" # prepare post request",
"specified controller with the given universal_object as a body. :param universal_object: object to",
"specified controller with the given query strings. :param query_strings: params to be sent",
"get request to the specified controller with the given query strings. :param query_strings:",
"= JsonConverter() self.url = \"https://api.pdf4me.com/\" if apiurl is not None and len(apiurl) !=",
"class CustomHttp(object): def __init__(self, token, apiurl): self.token = token self.json_converter = JsonConverter() self.url",
"to be sent :type query_strings: str :param controller: swagger controller :type controller: str",
"' + status_reason + \" : trace_id \" + trace_id + \" :",
"values, controller): \"\"\"Builds a post requests from the given parameters. :param octet_streams: (key:",
"send request res = requests.post(request_url, data=body, headers=headers) # check status code self.__check_status_code(res) #",
"content of value) pairs :type values: list :param controller: swagger controller :type controller:",
"+ controller headers = { 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent }",
"status code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) # read content",
"self.token, 'User-Agent': self.userAgent} # build files if octet_streams is not None and len(octet_streams)",
"with the given universal_object as a body. :param universal_object: object to be sent",
"# check status code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) #",
"trace_id + \" : \" + server_error) elif status_code != 200 and status_code",
"'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent } # send request res =",
"res = requests.post(request_url, data=body, headers=headers) # check status code self.__check_status_code(res) # check docLogs",
"post_wrapper(self, octet_streams, values, controller): \"\"\"Builds a post requests from the given parameters. :param",
"self.token, 'User-Agent': self.userAgent } # convert body to json body = self.json_converter.dump(element=universal_object) #",
"post response \"\"\" # prepare post request request_url = self.url + controller headers",
":type controller: str :return: file \"\"\" # prepare post request request_url = self.url",
"sent :type universal_object: object :param controller: swagger controller :type controller: str :return: post",
"a post requests from the given parameters. :param octet_streams: (key: file identifier, value:",
"returns a file :param query_strings: params to be sent :type query_strings: str :param",
"Checks whether the HTTP response's docLogs contain any error message, in case of",
"Pdf4meBackendException. :param response: post response :type response: requests.Response :return: None ''' status_code =",
"least one value or an octet-stream.\") else: res = requests.post(request_url, data=data, headers=header) else:",
":type universal_object: object :param controller: swagger controller :type controller: str :return: post response",
"''' Checks whether the HTTP response's docLogs contain any error message, in case",
"Pdf4meBackendException from pdf4me.helper.response_checker import ResponseChecker # from pdf4me.helper.token_generator import TokenGenerator class CustomHttp(object): def",
"None # send request if files is None: if data is None: raise",
"a get request to the specified controller with the given query strings. :param",
"check status code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) # read",
"value: open(fileName, 'rb'))) pairs :type octet_streams: list :param values: (key: identifier of value,",
"\"https://api.pdf4me.com/\" if apiurl is not None and len(apiurl) != 0: self.url = apiurl",
"request_url = self.url + controller header = {'Authorization': 'Basic ' + self.token, 'User-Agent':",
"# read content from response json_response = self.json_converter.load(res.text) return json_response def get_wrapper(self, query_strings,",
"' + self.token, 'User-Agent': self.userAgent } # convert body to json body =",
": \" + error) def __check_docLogs_for_error_messages(self, response): ''' Checks whether the HTTP response's",
"CustomHttp(object): def __init__(self, token, apiurl): self.token = token self.json_converter = JsonConverter() self.url =",
"from pdf4me.helper.json_converter import JsonConverter from pdf4me.helper.pdf4me_exceptions import Pdf4meClientException, Pdf4meBackendException from pdf4me.helper.response_checker import ResponseChecker",
"messages self.__check_docLogs_for_error_messages(res) # read content from response json_response = self.json_converter.load(res.text) return json_response def",
"files=files, headers=header) else: res = requests.post(request_url, files=files, data=data, headers=header) # check status code",
"import Pdf4meClientException, Pdf4meBackendException from pdf4me.helper.response_checker import ResponseChecker # from pdf4me.helper.token_generator import TokenGenerator class",
"else: files = None # build values if len(values) != 0: data =",
"+ ': ' + status_reason + \" : \" + error) def __check_docLogs_for_error_messages(self,",
"res = requests.post(request_url, data=data, headers=header) else: if data is None: res = requests.post(request_url,",
":param universal_object: object to be sent :type universal_object: object :param controller: swagger controller",
"= requests.post(request_url, data=body, headers=headers) # check status code self.__check_status_code(res) # check docLogs for",
"otw. throws a Pdf4meBackendException. :param response: post response :type response: requests.Response :return: None",
"if files is None: if data is None: raise Pdf4meClientException(\"Please provide at least",
"from pdf4me.helper.pdf4me_exceptions import Pdf4meClientException, Pdf4meBackendException from pdf4me.helper.response_checker import ResponseChecker # from pdf4me.helper.token_generator import",
"if len(values) != 0: data = {key: value for (key, value) in values}",
"str :param controller: swagger controller :type controller: str :return: post response \"\"\" #",
"post request to the specified controller with the given universal_object as a body.",
"body to json body = self.json_converter.dump(element=universal_object) # send request res = requests.post(request_url, data=body,",
"is thrown. :param response: post response :type response: requests.Response :return: None ''' ResponseChecker().check_response_for_errors(response.text)",
"' + status_reason + \" : \" + error) def __check_docLogs_for_error_messages(self, response): '''",
"self.__check_docLogs_for_error_messages(res) return res.content def __check_status_code(self, response): ''' Checks whether the status code is",
"status code is either 200 or 204, otw. throws a Pdf4meBackendException. :param response:",
"files = None # build values if len(values) != 0: data = {key:",
"request res = requests.post(request_url, data=body, headers=headers) # check status code self.__check_status_code(res) # check",
"Pdf4meClientException(\"Please provide at least one value or an octet-stream.\") else: res = requests.post(request_url,",
"controller: swagger controller :type controller: str :return: post response \"\"\" # prepare post",
"requests.post(request_url, data=body, headers=headers) # check status code self.__check_status_code(res) # check docLogs for error",
"# check docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def __check_status_code(self, response): '''",
"post response \"\"\" # prepare post request request_url = self.url + controller header",
"# read content from response json_response = self.json_converter.load(res.text) return json_response def post_wrapper(self, octet_streams,",
"__check_docLogs_for_error_messages(self, response): ''' Checks whether the HTTP response's docLogs contain any error message,",
"res.content def __check_status_code(self, response): ''' Checks whether the status code is either 200",
"controller): \"\"\"Builds a post requests from the given parameters. :param octet_streams: (key: file",
"files = {key: value for (key, value) in octet_streams} else: files = None",
"requests.get(request_url, data=query_strings, headers=headers) # check status code self.__check_status_code(res) # check docLogs for error",
"# send request res = requests.post(request_url, data=body, headers=headers) # check status code self.__check_status_code(res)",
"' + self.token, 'User-Agent': self.userAgent} # build files if octet_streams is not None",
"of value) pairs :type values: list :param controller: swagger controller :type controller: str",
"data is None: res = requests.post(request_url, files=files, headers=header) else: res = requests.post(request_url, files=files,",
"data=body, headers=headers) # check status code self.__check_status_code(res) # check docLogs for error messages",
"any error message, in case of an error a Pdf4meBackendException is thrown. :param",
"(key, value) in octet_streams} else: files = None # build values if len(values)",
"value for (key, value) in octet_streams} else: files = None # build values",
":param octet_streams: (key: file identifier, value: open(fileName, 'rb'))) pairs :type octet_streams: list :param",
"get_wrapper(self, query_strings, controller): \"\"\"Sends a get request to the specified controller with the",
"from pdf4me.helper.token_generator import TokenGenerator class CustomHttp(object): def __init__(self, token, apiurl): self.token = token",
"to json body = self.json_converter.dump(element=universal_object) # send request res = requests.post(request_url, data=body, headers=headers)",
"swagger controller :type controller: str :return: file \"\"\" # prepare post request request_url",
"is None: if data is None: raise Pdf4meClientException(\"Please provide at least one value",
"+ \" : \" + error) def __check_docLogs_for_error_messages(self, response): ''' Checks whether the",
"!= 0: files = {key: value for (key, value) in octet_streams} else: files",
"if data is None: res = requests.post(request_url, files=files, headers=header) else: res = requests.post(request_url,",
"an octet-stream.\") else: res = requests.post(request_url, data=data, headers=header) else: if data is None:",
"# check docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def get_object(self, query_strings, controller):",
"controller with the given universal_object as a body. :param universal_object: object to be",
"code is either 200 or 204, otw. throws a Pdf4meBackendException. :param response: post",
"prepare post request request_url = self.url + controller headers = { 'Authorization': 'Basic",
"throws a Pdf4meBackendException. :param response: post response :type response: requests.Response :return: None '''",
"if apiurl is not None and len(apiurl) != 0: self.url = apiurl self.userAgent",
"error a Pdf4meBackendException is thrown. :param response: post response :type response: requests.Response :return:",
"at least one value or an octet-stream.\") else: res = requests.post(request_url, data=data, headers=header)",
"Pdf4meClientException, Pdf4meBackendException from pdf4me.helper.response_checker import ResponseChecker # from pdf4me.helper.token_generator import TokenGenerator class CustomHttp(object):",
"response json_response = self.json_converter.load(res.text) return json_response def post_wrapper(self, octet_streams, values, controller): \"\"\"Builds a",
"+ self.token, 'User-Agent': self.userAgent} # build files if octet_streams is not None and",
"response): ''' Checks whether the HTTP response's docLogs contain any error message, in",
"content from response json_response = self.json_converter.load(res.text) return json_response def post_wrapper(self, octet_streams, values, controller):",
"+ trace_id + \" : \" + server_error) elif status_code != 200 and",
"controller :type controller: str :return: file \"\"\" # prepare post request request_url =",
"self.userAgent } # send request res = requests.get(request_url, data=query_strings, headers=headers) # check status",
"value: content of value) pairs :type values: list :param controller: swagger controller :type",
"in case of an error a Pdf4meBackendException is thrown. :param response: post response",
"\"\"\"Sends a get request to the specified controller with the given query string",
"for error messages self.__check_docLogs_for_error_messages(res) return res.content def get_object(self, query_strings, controller): \"\"\"Sends a get",
"file :param query_strings: params to be sent :type query_strings: str :param controller: swagger",
":type response: requests.Response :return: None ''' status_code = response.status_code status_reason = response.reason if",
"response.status_code status_reason = response.reason if status_code == 500: server_error = self.json_converter.load(response.text)['error_message'] trace_id =",
"= self.json_converter.load(response.text)['error_message'] trace_id = self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP 500 ' + status_reason + \"",
"Pdf4meBackendException('HTTP ' + str(status_code) + ': ' + status_reason + \" : \"",
"response's docLogs contain any error message, in case of an error a Pdf4meBackendException",
"requests.post(request_url, files=files, data=data, headers=header) # check status code self.__check_status_code(res) # check docLogs for",
"request_url = self.url + controller headers = { 'Authorization': 'Basic ' + self.token,",
"is None: raise Pdf4meClientException(\"Please provide at least one value or an octet-stream.\") else:",
"'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent } #",
"universal_object as a body. :param universal_object: object to be sent :type universal_object: object",
"{key: value for (key, value) in values} else: data = None # send",
"identifier, value: open(fileName, 'rb'))) pairs :type octet_streams: list :param values: (key: identifier of",
"import ResponseChecker # from pdf4me.helper.token_generator import TokenGenerator class CustomHttp(object): def __init__(self, token, apiurl):",
"data=data, headers=header) else: if data is None: res = requests.post(request_url, files=files, headers=header) else:",
"import requests from pdf4me.helper.json_converter import JsonConverter from pdf4me.helper.pdf4me_exceptions import Pdf4meClientException, Pdf4meBackendException from pdf4me.helper.response_checker",
"# send request res = requests.get(request_url, data=query_strings, headers=headers) # check status code self.__check_status_code(res)",
"and len(octet_streams) != 0: files = {key: value for (key, value) in octet_streams}",
"response: requests.Response :return: None ''' status_code = response.status_code status_reason = response.reason if status_code",
"status_reason = response.reason if status_code == 500: server_error = self.json_converter.load(response.text)['error_message'] trace_id = self.json_converter.load(response.text)['trace_id']",
"+ controller header = {'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent} # build",
"= response.text raise Pdf4meBackendException('HTTP ' + str(status_code) + ': ' + status_reason +",
"return json_response def post_wrapper(self, octet_streams, values, controller): \"\"\"Builds a post requests from the",
"whether the HTTP response's docLogs contain any error message, in case of an",
"the HTTP response's docLogs contain any error message, in case of an error",
"or an octet-stream.\") else: res = requests.post(request_url, data=data, headers=header) else: if data is",
"files if octet_streams is not None and len(octet_streams) != 0: files = {key:",
"response \"\"\" # prepare post request request_url = self.url + controller header =",
"query_strings: params to be sent :type query_strings: str :param controller: swagger controller :type",
"= self.json_converter.load(res.text) return json_response def get_wrapper(self, query_strings, controller): \"\"\"Sends a get request to",
"500: server_error = self.json_converter.load(response.text)['error_message'] trace_id = self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP 500 ' + status_reason",
"self.json_converter.load(response.text)['error_message'] trace_id = self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP 500 ' + status_reason + \" :",
"trace_id = self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP 500 ' + status_reason + \" : trace_id",
"data = {key: value for (key, value) in values} else: data = None",
"one value or an octet-stream.\") else: res = requests.post(request_url, data=data, headers=header) else: if",
"the given universal_object as a body. :param universal_object: object to be sent :type",
"raise Pdf4meBackendException('HTTP ' + str(status_code) + ': ' + status_reason + \" :",
"res = requests.get(request_url, data=query_strings, headers=headers) # check status code self.__check_status_code(res) # check docLogs",
"None: raise Pdf4meClientException(\"Please provide at least one value or an octet-stream.\") else: res",
"read content from response json_response = self.json_converter.load(res.text) return json_response def get_wrapper(self, query_strings, controller):",
"query string and returns a file :param query_strings: params to be sent :type",
"None # build values if len(values) != 0: data = {key: value for",
":param response: post response :type response: requests.Response :return: None ''' status_code = response.status_code",
"None and len(apiurl) != 0: self.url = apiurl self.userAgent = \"pdf4me-python/0.8.24\" def post_universal_object(self,",
"for (key, value) in octet_streams} else: files = None # build values if",
"from response json_response = self.json_converter.load(res.text) return json_response def post_wrapper(self, octet_streams, values, controller): \"\"\"Builds",
": \" + server_error) elif status_code != 200 and status_code != 204: error",
"self.url + controller header = {'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent} #",
"len(values) != 0: data = {key: value for (key, value) in values} else:",
"in values} else: data = None # send request if files is None:",
"return res.content def __check_status_code(self, response): ''' Checks whether the status code is either",
"apiurl): self.token = token self.json_converter = JsonConverter() self.url = \"https://api.pdf4me.com/\" if apiurl is",
"is not None and len(octet_streams) != 0: files = {key: value for (key,",
"a get request to the specified controller with the given query string and",
"controller: swagger controller :type controller: str :return: file \"\"\" # prepare post request",
"# from pdf4me.helper.token_generator import TokenGenerator class CustomHttp(object): def __init__(self, token, apiurl): self.token =",
"'User-Agent': self.userAgent } # send request res = requests.get(request_url, data=query_strings, headers=headers) # check",
":param values: (key: identifier of value, value: content of value) pairs :type values:",
"post response :type response: requests.Response :return: None ''' status_code = response.status_code status_reason =",
"= token self.json_converter = JsonConverter() self.url = \"https://api.pdf4me.com/\" if apiurl is not None",
"!= 200 and status_code != 204: error = response.text raise Pdf4meBackendException('HTTP ' +",
"\" + error) def __check_docLogs_for_error_messages(self, response): ''' Checks whether the HTTP response's docLogs",
"error messages self.__check_docLogs_for_error_messages(res) # read content from response json_response = self.json_converter.load(res.text) return json_response",
"self.url + controller headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic '",
"TokenGenerator class CustomHttp(object): def __init__(self, token, apiurl): self.token = token self.json_converter = JsonConverter()",
"= apiurl self.userAgent = \"pdf4me-python/0.8.24\" def post_universal_object(self, universal_object, controller): \"\"\"Sends a post request",
"check docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def get_object(self, query_strings, controller): \"\"\"Sends",
"and len(apiurl) != 0: self.url = apiurl self.userAgent = \"pdf4me-python/0.8.24\" def post_universal_object(self, universal_object,",
"response): ''' Checks whether the status code is either 200 or 204, otw.",
"res.content def get_object(self, query_strings, controller): \"\"\"Sends a get request to the specified controller",
"status_reason + \" : trace_id \" + trace_id + \" : \" +",
"as a body. :param universal_object: object to be sent :type universal_object: object :param",
"json_response def post_wrapper(self, octet_streams, values, controller): \"\"\"Builds a post requests from the given",
"response \"\"\" # prepare post request request_url = self.url + controller headers =",
"universal_object, controller): \"\"\"Sends a post request to the specified controller with the given",
"requests.Response :return: None ''' status_code = response.status_code status_reason = response.reason if status_code ==",
"str(status_code) + ': ' + status_reason + \" : \" + error) def",
"a Pdf4meBackendException. :param response: post response :type response: requests.Response :return: None ''' status_code",
"= response.reason if status_code == 500: server_error = self.json_converter.load(response.text)['error_message'] trace_id = self.json_converter.load(response.text)['trace_id'] raise",
"\"\"\"Builds a post requests from the given parameters. :param octet_streams: (key: file identifier,",
"None and len(octet_streams) != 0: files = {key: value for (key, value) in",
"\" : \" + error) def __check_docLogs_for_error_messages(self, response): ''' Checks whether the HTTP",
"octet_streams: list :param values: (key: identifier of value, value: content of value) pairs",
"request to the specified controller with the given universal_object as a body. :param",
"'application/json', 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent } # convert body to",
"'Basic ' + self.token, 'User-Agent': self.userAgent } # convert body to json body",
"import TokenGenerator class CustomHttp(object): def __init__(self, token, apiurl): self.token = token self.json_converter =",
"convert body to json body = self.json_converter.dump(element=universal_object) # send request res = requests.post(request_url,",
"res = requests.post(request_url, files=files, headers=header) else: res = requests.post(request_url, files=files, data=data, headers=header) #",
"{'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent} # build files if octet_streams is",
"data=query_strings, headers=headers) # check status code self.__check_status_code(res) # check docLogs for error messages",
"'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent } # convert",
"contain any error message, in case of an error a Pdf4meBackendException is thrown.",
"pdf4me.helper.response_checker import ResponseChecker # from pdf4me.helper.token_generator import TokenGenerator class CustomHttp(object): def __init__(self, token,",
"'Basic ' + self.token, 'User-Agent': self.userAgent} # build files if octet_streams is not",
"response.text raise Pdf4meBackendException('HTTP ' + str(status_code) + ': ' + status_reason + \"",
"universal_object: object :param controller: swagger controller :type controller: str :return: post response \"\"\"",
"octet_streams} else: files = None # build values if len(values) != 0: data",
"a Pdf4meBackendException is thrown. :param response: post response :type response: requests.Response :return: None",
"return json_response def get_wrapper(self, query_strings, controller): \"\"\"Sends a get request to the specified",
"server_error = self.json_converter.load(response.text)['error_message'] trace_id = self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP 500 ' + status_reason +",
"the specified controller with the given query strings. :param query_strings: params to be",
"pairs :type octet_streams: list :param values: (key: identifier of value, value: content of",
"response :type response: requests.Response :return: None ''' status_code = response.status_code status_reason = response.reason",
"} # convert body to json body = self.json_converter.dump(element=universal_object) # send request res",
"(key, value) in values} else: data = None # send request if files",
"request res = requests.get(request_url, data=query_strings, headers=headers) # check status code self.__check_status_code(res) # check",
"pdf4me.helper.json_converter import JsonConverter from pdf4me.helper.pdf4me_exceptions import Pdf4meClientException, Pdf4meBackendException from pdf4me.helper.response_checker import ResponseChecker #",
"parameters. :param octet_streams: (key: file identifier, value: open(fileName, 'rb'))) pairs :type octet_streams: list",
"def get_object(self, query_strings, controller): \"\"\"Sends a get request to the specified controller with",
"else: if data is None: res = requests.post(request_url, files=files, headers=header) else: res =",
"and returns a file :param query_strings: params to be sent :type query_strings: str",
"\"\"\" # prepare post request request_url = self.url + controller headers = {",
"trace_id \" + trace_id + \" : \" + server_error) elif status_code !=",
"value) in values} else: data = None # send request if files is",
"JsonConverter() self.url = \"https://api.pdf4me.com/\" if apiurl is not None and len(apiurl) != 0:",
"token self.json_converter = JsonConverter() self.url = \"https://api.pdf4me.com/\" if apiurl is not None and",
"len(apiurl) != 0: self.url = apiurl self.userAgent = \"pdf4me-python/0.8.24\" def post_universal_object(self, universal_object, controller):",
"status code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def",
"values: (key: identifier of value, value: content of value) pairs :type values: list",
"get_object(self, query_strings, controller): \"\"\"Sends a get request to the specified controller with the",
"file \"\"\" # prepare post request request_url = self.url + controller headers =",
"self.__check_docLogs_for_error_messages(res) # read content from response json_response = self.json_converter.load(res.text) return json_response def post_wrapper(self,",
"be sent :type query_strings: str :param controller: swagger controller :type controller: str :return:",
"self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP 500 ' + status_reason + \" : trace_id \" +",
"__init__(self, token, apiurl): self.token = token self.json_converter = JsonConverter() self.url = \"https://api.pdf4me.com/\" if",
"strings. :param query_strings: params to be sent :type query_strings: str :param controller: swagger",
"query_strings, controller): \"\"\"Sends a get request to the specified controller with the given",
":type query_strings: str :param controller: swagger controller :type controller: str :return: post response",
"\" + server_error) elif status_code != 200 and status_code != 204: error =",
"the given query string and returns a file :param query_strings: params to be",
"= response.status_code status_reason = response.reason if status_code == 500: server_error = self.json_converter.load(response.text)['error_message'] trace_id",
"an error a Pdf4meBackendException is thrown. :param response: post response :type response: requests.Response",
"request request_url = self.url + controller headers = { 'Authorization': 'Basic ' +",
"+ status_reason + \" : \" + error) def __check_docLogs_for_error_messages(self, response): ''' Checks",
"to the specified controller with the given universal_object as a body. :param universal_object:",
"+ self.token, 'User-Agent': self.userAgent } # send request res = requests.get(request_url, data=query_strings, headers=headers)",
"= self.url + controller headers = { 'Authorization': 'Basic ' + self.token, 'User-Agent':",
"send request if files is None: if data is None: raise Pdf4meClientException(\"Please provide",
"value) pairs :type values: list :param controller: swagger controller :type controller: str :return:",
"status_code = response.status_code status_reason = response.reason if status_code == 500: server_error = self.json_converter.load(response.text)['error_message']",
"self.json_converter = JsonConverter() self.url = \"https://api.pdf4me.com/\" if apiurl is not None and len(apiurl)",
"controller: str :return: file \"\"\" # prepare post request request_url = self.url +",
"docLogs contain any error message, in case of an error a Pdf4meBackendException is",
"= { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent",
"controller :type controller: str :return: post response \"\"\" # prepare post request request_url",
"send request res = requests.get(request_url, data=query_strings, headers=headers) # check status code self.__check_status_code(res) #",
"not None and len(octet_streams) != 0: files = {key: value for (key, value)",
"+ str(status_code) + ': ' + status_reason + \" : \" + error)",
"str :return: post response \"\"\" # prepare post request request_url = self.url +",
"json body = self.json_converter.dump(element=universal_object) # send request res = requests.post(request_url, data=body, headers=headers) #",
"pdf4me.helper.pdf4me_exceptions import Pdf4meClientException, Pdf4meBackendException from pdf4me.helper.response_checker import ResponseChecker # from pdf4me.helper.token_generator import TokenGenerator",
"specified controller with the given query string and returns a file :param query_strings:",
"self.json_converter.dump(element=universal_object) # send request res = requests.post(request_url, data=body, headers=headers) # check status code",
":return: post response \"\"\" # prepare post request request_url = self.url + controller",
"200 or 204, otw. throws a Pdf4meBackendException. :param response: post response :type response:",
"ResponseChecker # from pdf4me.helper.token_generator import TokenGenerator class CustomHttp(object): def __init__(self, token, apiurl): self.token",
"headers = { 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent } # send",
"# prepare post request request_url = self.url + controller headers = { 'Accept':",
"body = self.json_converter.dump(element=universal_object) # send request res = requests.post(request_url, data=body, headers=headers) # check",
"200 and status_code != 204: error = response.text raise Pdf4meBackendException('HTTP ' + str(status_code)",
"self.__check_docLogs_for_error_messages(res) # read content from response json_response = self.json_converter.load(res.text) return json_response def get_wrapper(self,",
"be sent :type universal_object: object :param controller: swagger controller :type controller: str :return:",
"post request request_url = self.url + controller headers = { 'Authorization': 'Basic '",
"code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def get_object(self,",
"+ \" : trace_id \" + trace_id + \" : \" + server_error)",
"object to be sent :type universal_object: object :param controller: swagger controller :type controller:",
"given query string and returns a file :param query_strings: params to be sent",
"= requests.post(request_url, files=files, headers=header) else: res = requests.post(request_url, files=files, data=data, headers=header) # check",
"to the specified controller with the given query string and returns a file",
"response: post response :type response: requests.Response :return: None ''' status_code = response.status_code status_reason",
"self.url = \"https://api.pdf4me.com/\" if apiurl is not None and len(apiurl) != 0: self.url",
"body. :param universal_object: object to be sent :type universal_object: object :param controller: swagger",
"self.json_converter.load(res.text) return json_response def get_wrapper(self, query_strings, controller): \"\"\"Sends a get request to the",
"= self.url + controller header = {'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent}",
"data=data, headers=header) # check status code self.__check_status_code(res) # check docLogs for error messages",
"a file :param query_strings: params to be sent :type query_strings: str :param controller:",
"Checks whether the status code is either 200 or 204, otw. throws a",
"headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic ' + self.token, 'User-Agent':",
"= {key: value for (key, value) in values} else: data = None #",
"elif status_code != 200 and status_code != 204: error = response.text raise Pdf4meBackendException('HTTP",
"def post_universal_object(self, universal_object, controller): \"\"\"Sends a post request to the specified controller with",
"+ \" : \" + server_error) elif status_code != 200 and status_code !=",
"requests.post(request_url, files=files, headers=header) else: res = requests.post(request_url, files=files, data=data, headers=header) # check status",
"= self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP 500 ' + status_reason + \" : trace_id \"",
"'Basic ' + self.token, 'User-Agent': self.userAgent } # send request res = requests.get(request_url,",
"messages self.__check_docLogs_for_error_messages(res) return res.content def __check_status_code(self, response): ''' Checks whether the status code",
"': ' + status_reason + \" : \" + error) def __check_docLogs_for_error_messages(self, response):",
"headers=header) # check status code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res)",
"= self.json_converter.dump(element=universal_object) # send request res = requests.post(request_url, data=body, headers=headers) # check status",
":return: file \"\"\" # prepare post request request_url = self.url + controller headers",
"controller: str :return: post response \"\"\" # prepare post request request_url = self.url",
"response.reason if status_code == 500: server_error = self.json_converter.load(response.text)['error_message'] trace_id = self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP",
"= None # build values if len(values) != 0: data = {key: value",
"for error messages self.__check_docLogs_for_error_messages(res) return res.content def __check_status_code(self, response): ''' Checks whether the",
"None: if data is None: raise Pdf4meClientException(\"Please provide at least one value or",
"!= 0: self.url = apiurl self.userAgent = \"pdf4me-python/0.8.24\" def post_universal_object(self, universal_object, controller): \"\"\"Sends",
"provide at least one value or an octet-stream.\") else: res = requests.post(request_url, data=data,",
"string and returns a file :param query_strings: params to be sent :type query_strings:",
"str :return: file \"\"\" # prepare post request request_url = self.url + controller",
"'rb'))) pairs :type octet_streams: list :param values: (key: identifier of value, value: content",
"values} else: data = None # send request if files is None: if",
":type query_strings: str :param controller: swagger controller :type controller: str :return: file \"\"\"",
"Pdf4meBackendException is thrown. :param response: post response :type response: requests.Response :return: None '''",
"prepare post request request_url = self.url + controller header = {'Authorization': 'Basic '",
"controller headers = { 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent } #",
"+ status_reason + \" : trace_id \" + trace_id + \" : \"",
"import JsonConverter from pdf4me.helper.pdf4me_exceptions import Pdf4meClientException, Pdf4meBackendException from pdf4me.helper.response_checker import ResponseChecker # from",
"sent :type query_strings: str :param controller: swagger controller :type controller: str :return: file",
"requests.post(request_url, data=data, headers=header) else: if data is None: res = requests.post(request_url, files=files, headers=header)",
"case of an error a Pdf4meBackendException is thrown. :param response: post response :type",
"controller with the given query string and returns a file :param query_strings: params",
"from response json_response = self.json_converter.load(res.text) return json_response def get_wrapper(self, query_strings, controller): \"\"\"Sends a",
"= self.url + controller headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic",
"is not None and len(apiurl) != 0: self.url = apiurl self.userAgent = \"pdf4me-python/0.8.24\"",
"self.userAgent} # build files if octet_streams is not None and len(octet_streams) != 0:",
"# build values if len(values) != 0: data = {key: value for (key,",
"post_universal_object(self, universal_object, controller): \"\"\"Sends a post request to the specified controller with the",
"None ''' status_code = response.status_code status_reason = response.reason if status_code == 500: server_error",
"!= 204: error = response.text raise Pdf4meBackendException('HTTP ' + str(status_code) + ': '",
"Pdf4meBackendException('HTTP 500 ' + status_reason + \" : trace_id \" + trace_id +",
"controller): \"\"\"Sends a get request to the specified controller with the given query",
"list :param controller: swagger controller :type controller: str :return: post response \"\"\" #",
"self.userAgent } # convert body to json body = self.json_converter.dump(element=universal_object) # send request",
"the given parameters. :param octet_streams: (key: file identifier, value: open(fileName, 'rb'))) pairs :type",
"apiurl self.userAgent = \"pdf4me-python/0.8.24\" def post_universal_object(self, universal_object, controller): \"\"\"Sends a post request to",
"error messages self.__check_docLogs_for_error_messages(res) return res.content def get_object(self, query_strings, controller): \"\"\"Sends a get request",
"'User-Agent': self.userAgent } # convert body to json body = self.json_converter.dump(element=universal_object) # send",
"request to the specified controller with the given query string and returns a",
"with the given query string and returns a file :param query_strings: params to",
"the status code is either 200 or 204, otw. throws a Pdf4meBackendException. :param",
"is None: res = requests.post(request_url, files=files, headers=header) else: res = requests.post(request_url, files=files, data=data,",
"is either 200 or 204, otw. throws a Pdf4meBackendException. :param response: post response",
"a body. :param universal_object: object to be sent :type universal_object: object :param controller:",
"def __check_status_code(self, response): ''' Checks whether the status code is either 200 or",
"from pdf4me.helper.response_checker import ResponseChecker # from pdf4me.helper.token_generator import TokenGenerator class CustomHttp(object): def __init__(self,",
"json_response = self.json_converter.load(res.text) return json_response def post_wrapper(self, octet_streams, values, controller): \"\"\"Builds a post",
"the specified controller with the given query string and returns a file :param",
"= requests.get(request_url, data=query_strings, headers=headers) # check status code self.__check_status_code(res) # check docLogs for",
"None: res = requests.post(request_url, files=files, headers=header) else: res = requests.post(request_url, files=files, data=data, headers=header)",
"= {'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent} # build files if octet_streams",
"error message, in case of an error a Pdf4meBackendException is thrown. :param response:",
"error = response.text raise Pdf4meBackendException('HTTP ' + str(status_code) + ': ' + status_reason",
"message, in case of an error a Pdf4meBackendException is thrown. :param response: post",
"given query strings. :param query_strings: params to be sent :type query_strings: str :param",
"'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent } # convert body to json",
"if octet_streams is not None and len(octet_streams) != 0: files = {key: value",
":param controller: swagger controller :type controller: str :return: file \"\"\" # prepare post",
"# build files if octet_streams is not None and len(octet_streams) != 0: files",
":return: None ''' status_code = response.status_code status_reason = response.reason if status_code == 500:",
"500 ' + status_reason + \" : trace_id \" + trace_id + \"",
"code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def __check_status_code(self,",
"status_code != 200 and status_code != 204: error = response.text raise Pdf4meBackendException('HTTP '",
"requests from pdf4me.helper.json_converter import JsonConverter from pdf4me.helper.pdf4me_exceptions import Pdf4meClientException, Pdf4meBackendException from pdf4me.helper.response_checker import",
"not None and len(apiurl) != 0: self.url = apiurl self.userAgent = \"pdf4me-python/0.8.24\" def",
"self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def get_object(self, query_strings,",
"''' status_code = response.status_code status_reason = response.reason if status_code == 500: server_error =",
"else: data = None # send request if files is None: if data",
"with the given query strings. :param query_strings: params to be sent :type query_strings:",
"build files if octet_streams is not None and len(octet_streams) != 0: files =",
"prepare post request request_url = self.url + controller headers = { 'Accept': 'application/json',",
"request if files is None: if data is None: raise Pdf4meClientException(\"Please provide at",
"apiurl is not None and len(apiurl) != 0: self.url = apiurl self.userAgent =",
"JsonConverter from pdf4me.helper.pdf4me_exceptions import Pdf4meClientException, Pdf4meBackendException from pdf4me.helper.response_checker import ResponseChecker # from pdf4me.helper.token_generator",
":param controller: swagger controller :type controller: str :return: post response \"\"\" # prepare",
"raise Pdf4meClientException(\"Please provide at least one value or an octet-stream.\") else: res =",
"from the given parameters. :param octet_streams: (key: file identifier, value: open(fileName, 'rb'))) pairs",
"data = None # send request if files is None: if data is",
"the given query strings. :param query_strings: params to be sent :type query_strings: str",
"self.url = apiurl self.userAgent = \"pdf4me-python/0.8.24\" def post_universal_object(self, universal_object, controller): \"\"\"Sends a post",
"requests from the given parameters. :param octet_streams: (key: file identifier, value: open(fileName, 'rb')))",
"def post_wrapper(self, octet_streams, values, controller): \"\"\"Builds a post requests from the given parameters.",
"of value, value: content of value) pairs :type values: list :param controller: swagger",
"status_code != 204: error = response.text raise Pdf4meBackendException('HTTP ' + str(status_code) + ':",
"+ controller headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic ' +",
"check docLogs for error messages self.__check_docLogs_for_error_messages(res) # read content from response json_response =",
"0: data = {key: value for (key, value) in values} else: data =",
"if data is None: raise Pdf4meClientException(\"Please provide at least one value or an",
"= {key: value for (key, value) in octet_streams} else: files = None #",
"res = requests.post(request_url, files=files, data=data, headers=header) # check status code self.__check_status_code(res) # check",
"self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) # read content from response",
"self.token, 'User-Agent': self.userAgent } # send request res = requests.get(request_url, data=query_strings, headers=headers) #",
"json_response = self.json_converter.load(res.text) return json_response def get_wrapper(self, query_strings, controller): \"\"\"Sends a get request",
"== 500: server_error = self.json_converter.load(response.text)['error_message'] trace_id = self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP 500 ' +",
"\" + trace_id + \" : \" + server_error) elif status_code != 200",
"check docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def __check_status_code(self, response): ''' Checks",
"whether the status code is either 200 or 204, otw. throws a Pdf4meBackendException.",
"code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) # read content from",
"given universal_object as a body. :param universal_object: object to be sent :type universal_object:",
"check status code self.__check_status_code(res) # check docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content",
"universal_object: object to be sent :type universal_object: object :param controller: swagger controller :type",
"# prepare post request request_url = self.url + controller headers = { 'Authorization':",
"HTTP response's docLogs contain any error message, in case of an error a",
"object :param controller: swagger controller :type controller: str :return: post response \"\"\" #",
"to the specified controller with the given query strings. :param query_strings: params to",
"' + self.token, 'User-Agent': self.userAgent } # send request res = requests.get(request_url, data=query_strings,",
"messages self.__check_docLogs_for_error_messages(res) return res.content def get_object(self, query_strings, controller): \"\"\"Sends a get request to",
"self.url + controller headers = { 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent",
"value or an octet-stream.\") else: res = requests.post(request_url, data=data, headers=header) else: if data",
"request_url = self.url + controller headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization':",
"0: files = {key: value for (key, value) in octet_streams} else: files =",
"' + str(status_code) + ': ' + status_reason + \" : \" +",
"= requests.post(request_url, files=files, data=data, headers=header) # check status code self.__check_status_code(res) # check docLogs",
"request to the specified controller with the given query strings. :param query_strings: params",
"list :param values: (key: identifier of value, value: content of value) pairs :type",
"params to be sent :type query_strings: str :param controller: swagger controller :type controller:",
"values: list :param controller: swagger controller :type controller: str :return: post response \"\"\"",
"status_reason + \" : \" + error) def __check_docLogs_for_error_messages(self, response): ''' Checks whether",
"docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def get_object(self, query_strings, controller): \"\"\"Sends a",
"+ self.token, 'User-Agent': self.userAgent } # convert body to json body = self.json_converter.dump(element=universal_object)",
"docLogs for error messages self.__check_docLogs_for_error_messages(res) return res.content def __check_status_code(self, response): ''' Checks whether",
"# convert body to json body = self.json_converter.dump(element=universal_object) # send request res =",
"\" : \" + server_error) elif status_code != 200 and status_code != 204:",
"def __check_docLogs_for_error_messages(self, response): ''' Checks whether the HTTP response's docLogs contain any error",
"status_code == 500: server_error = self.json_converter.load(response.text)['error_message'] trace_id = self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP 500 '",
"request request_url = self.url + controller header = {'Authorization': 'Basic ' + self.token,",
"octet_streams is not None and len(octet_streams) != 0: files = {key: value for",
"def get_wrapper(self, query_strings, controller): \"\"\"Sends a get request to the specified controller with",
"query strings. :param query_strings: params to be sent :type query_strings: str :param controller:",
"else: res = requests.post(request_url, files=files, data=data, headers=header) # check status code self.__check_status_code(res) #",
"or 204, otw. throws a Pdf4meBackendException. :param response: post response :type response: requests.Response",
":type controller: str :return: post response \"\"\" # prepare post request request_url =",
"response json_response = self.json_converter.load(res.text) return json_response def get_wrapper(self, query_strings, controller): \"\"\"Sends a get",
"error messages self.__check_docLogs_for_error_messages(res) return res.content def __check_status_code(self, response): ''' Checks whether the status",
"+ error) def __check_docLogs_for_error_messages(self, response): ''' Checks whether the HTTP response's docLogs contain",
"{ 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent }",
"controller header = {'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent} # build files",
"} # send request res = requests.get(request_url, data=query_strings, headers=headers) # check status code",
"files=files, data=data, headers=header) # check status code self.__check_status_code(res) # check docLogs for error",
"content from response json_response = self.json_converter.load(res.text) return json_response def get_wrapper(self, query_strings, controller): \"\"\"Sends",
"(key: file identifier, value: open(fileName, 'rb'))) pairs :type octet_streams: list :param values: (key:",
"\"\"\" # prepare post request request_url = self.url + controller header = {'Authorization':",
"headers=header) else: res = requests.post(request_url, files=files, data=data, headers=header) # check status code self.__check_status_code(res)",
"204, otw. throws a Pdf4meBackendException. :param response: post response :type response: requests.Response :return:",
"request request_url = self.url + controller headers = { 'Accept': 'application/json', 'Content-Type': 'application/json',",
"get request to the specified controller with the given query string and returns",
"\"\"\"Sends a post request to the specified controller with the given universal_object as",
"post request request_url = self.url + controller headers = { 'Accept': 'application/json', 'Content-Type':",
"{ 'Authorization': 'Basic ' + self.token, 'User-Agent': self.userAgent } # send request res",
"self.json_converter.load(res.text) return json_response def post_wrapper(self, octet_streams, values, controller): \"\"\"Builds a post requests from",
"= requests.post(request_url, data=data, headers=header) else: if data is None: res = requests.post(request_url, files=files,",
"the specified controller with the given universal_object as a body. :param universal_object: object",
"in octet_streams} else: files = None # build values if len(values) != 0:",
"''' Checks whether the status code is either 200 or 204, otw. throws",
"self.userAgent = \"pdf4me-python/0.8.24\" def post_universal_object(self, universal_object, controller): \"\"\"Sends a post request to the",
"if status_code == 500: server_error = self.json_converter.load(response.text)['error_message'] trace_id = self.json_converter.load(response.text)['trace_id'] raise Pdf4meBackendException('HTTP 500"
] |
[
"utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-05-09",
"len(num)): if i != pos and num[pos] == \"0\": break cur = int(num[pos:i+1])",
"cur, \\ result + str(cur), results) else: self.dfs(num, target, i + 1, val",
"this problem and creating all test cases. ''' class Solution(object): def addOperators(self, num,",
"target, i + 1, cur, cur, \\ result + str(cur), results) else: self.dfs(num,",
"if val == target: results.append(result) return for i in range(pos, len(num)): if i",
"if pos == 0: self.dfs(num, target, i + 1, cur, cur, \\ result",
"target: int :rtype: List[str] \"\"\" results = [] if num: self.dfs(num, target, 0,",
"int(num[pos:i+1]) if pos == 0: self.dfs(num, target, i + 1, cur, cur, \\",
"num, target, pos, val, backup, result, results): if pos >= len(num): if val",
"in range(pos, len(num)): if i != pos and num[pos] == \"0\": break cur",
"all possibilities to add binary operators (not unary) +, -, or * between",
"''' Given a string that contains only digits 0-9 and a target value,",
"i != pos and num[pos] == \"0\": break cur = int(num[pos:i+1]) if pos",
"num: str :type target: int :rtype: List[str] \"\"\" results = [] if num:",
"''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-05-09 Last_modify: 2016-05-09",
"1, val + cur, cur, \\ result + \"+\" + str(cur), results) self.dfs(num,",
"results) self.dfs(num, target, i + 1, val - backup + backup * cur,",
"+ backup * cur, \\ backup * cur, result + \"*\" + str(cur),",
"* between the digits so they evaluate to the target value. Examples: \"123\",",
"0, 0, 0, \"\", results) return results def dfs(self, num, target, pos, val,",
"pos, val, backup, result, results): if pos >= len(num): if val == target:",
"target value, return all possibilities to add binary operators (not unary) +, -,",
"result + \"-\" + str(cur), results) self.dfs(num, target, i + 1, val -",
"that contains only digits 0-9 and a target value, return all possibilities to",
"\"123\", 6 -> [\"1+2+3\", \"1*2*3\"] \"232\", 8 -> [\"2*3+2\", \"2+3*2\"] \"105\", 5 ->",
"only digits 0-9 and a target value, return all possibilities to add binary",
"\\ result + \"+\" + str(cur), results) self.dfs(num, target, i + 1, val",
"== 0: self.dfs(num, target, i + 1, cur, cur, \\ result + str(cur),",
"i + 1, cur, cur, \\ result + str(cur), results) else: self.dfs(num, target,",
"results) self.dfs(num, target, i + 1, val - cur, -cur, \\ result +",
"Last_modify: 2016-05-09 ****************************************** ''' ''' Given a string that contains only digits 0-9",
"self.dfs(num, target, 0, 0, 0, \"\", results) return results def dfs(self, num, target,",
"\"105\", 5 -> [\"1*0+5\",\"10-5\"] \"00\", 0 -> [\"0+0\", \"0-0\", \"0*0\"] \"3456237490\", 9191 ->",
"i + 1, val - cur, -cur, \\ result + \"-\" + str(cur),",
"result + \"+\" + str(cur), results) self.dfs(num, target, i + 1, val -",
"value, return all possibilities to add binary operators (not unary) +, -, or",
"target value. Examples: \"123\", 6 -> [\"1+2+3\", \"1*2*3\"] \"232\", 8 -> [\"2*3+2\", \"2+3*2\"]",
"Created Time: 2016-05-09 Last_modify: 2016-05-09 ****************************************** ''' ''' Given a string that contains",
"operators (not unary) +, -, or * between the digits so they evaluate",
"so they evaluate to the target value. Examples: \"123\", 6 -> [\"1+2+3\", \"1*2*3\"]",
"\"0*0\"] \"3456237490\", 9191 -> [] Credits: Special thanks to @davidtan1890 for adding this",
"return results def dfs(self, num, target, pos, val, backup, result, results): if pos",
"\"+\" + str(cur), results) self.dfs(num, target, i + 1, val - cur, -cur,",
"\"1*2*3\"] \"232\", 8 -> [\"2*3+2\", \"2+3*2\"] \"105\", 5 -> [\"1*0+5\",\"10-5\"] \"00\", 0 ->",
"+ 1, val - backup + backup * cur, \\ backup * cur,",
"\"0-0\", \"0*0\"] \"3456237490\", 9191 -> [] Credits: Special thanks to @davidtan1890 for adding",
"i + 1, val - backup + backup * cur, \\ backup *",
"val - backup + backup * cur, \\ backup * cur, result +",
"-> [\"1*0+5\",\"10-5\"] \"00\", 0 -> [\"0+0\", \"0-0\", \"0*0\"] \"3456237490\", 9191 -> [] Credits:",
"Email: <EMAIL> Version: 0.0.1 Created Time: 2016-05-09 Last_modify: 2016-05-09 ****************************************** ''' ''' Given",
"[\"0+0\", \"0-0\", \"0*0\"] \"3456237490\", 9191 -> [] Credits: Special thanks to @davidtan1890 for",
"results def dfs(self, num, target, pos, val, backup, result, results): if pos >=",
"= int(num[pos:i+1]) if pos == 0: self.dfs(num, target, i + 1, cur, cur,",
"if i != pos and num[pos] == \"0\": break cur = int(num[pos:i+1]) if",
"target: results.append(result) return for i in range(pos, len(num)): if i != pos and",
"[] Credits: Special thanks to @davidtan1890 for adding this problem and creating all",
"i in range(pos, len(num)): if i != pos and num[pos] == \"0\": break",
"val == target: results.append(result) return for i in range(pos, len(num)): if i !=",
"+ str(cur), results) self.dfs(num, target, i + 1, val - backup + backup",
"problem and creating all test cases. ''' class Solution(object): def addOperators(self, num, target):",
"\"-\" + str(cur), results) self.dfs(num, target, i + 1, val - backup +",
"Time: 2016-05-09 Last_modify: 2016-05-09 ****************************************** ''' ''' Given a string that contains only",
"results) else: self.dfs(num, target, i + 1, val + cur, cur, \\ result",
":type target: int :rtype: List[str] \"\"\" results = [] if num: self.dfs(num, target,",
"-> [\"1+2+3\", \"1*2*3\"] \"232\", 8 -> [\"2*3+2\", \"2+3*2\"] \"105\", 5 -> [\"1*0+5\",\"10-5\"] \"00\",",
"!= pos and num[pos] == \"0\": break cur = int(num[pos:i+1]) if pos ==",
"def addOperators(self, num, target): \"\"\" :type num: str :type target: int :rtype: List[str]",
"str(cur), results) self.dfs(num, target, i + 1, val - backup + backup *",
"backup * cur, \\ backup * cur, result + \"*\" + str(cur), results)",
"coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time:",
"\"232\", 8 -> [\"2*3+2\", \"2+3*2\"] \"105\", 5 -> [\"1*0+5\",\"10-5\"] \"00\", 0 -> [\"0+0\",",
"self.dfs(num, target, i + 1, val - backup + backup * cur, \\",
"+, -, or * between the digits so they evaluate to the target",
"2016-05-09 ****************************************** ''' ''' Given a string that contains only digits 0-9 and",
"== \"0\": break cur = int(num[pos:i+1]) if pos == 0: self.dfs(num, target, i",
"a target value, return all possibilities to add binary operators (not unary) +,",
"= [] if num: self.dfs(num, target, 0, 0, 0, \"\", results) return results",
"python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version:",
"def dfs(self, num, target, pos, val, backup, result, results): if pos >= len(num):",
"8 -> [\"2*3+2\", \"2+3*2\"] \"105\", 5 -> [\"1*0+5\",\"10-5\"] \"00\", 0 -> [\"0+0\", \"0-0\",",
"zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-05-09 Last_modify: 2016-05-09 ****************************************** ''' '''",
"Solution(object): def addOperators(self, num, target): \"\"\" :type num: str :type target: int :rtype:",
"\"\"\" :type num: str :type target: int :rtype: List[str] \"\"\" results = []",
"\"\"\" results = [] if num: self.dfs(num, target, 0, 0, 0, \"\", results)",
"self.dfs(num, target, i + 1, cur, cur, \\ result + str(cur), results) else:",
"str(cur), results) self.dfs(num, target, i + 1, val - cur, -cur, \\ result",
"0, \"\", results) return results def dfs(self, num, target, pos, val, backup, result,",
"+ 1, val - cur, -cur, \\ result + \"-\" + str(cur), results)",
"cur, -cur, \\ result + \"-\" + str(cur), results) self.dfs(num, target, i +",
"# -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1",
"results.append(result) return for i in range(pos, len(num)): if i != pos and num[pos]",
"to the target value. Examples: \"123\", 6 -> [\"1+2+3\", \"1*2*3\"] \"232\", 8 ->",
"0-9 and a target value, return all possibilities to add binary operators (not",
"0: self.dfs(num, target, i + 1, cur, cur, \\ result + str(cur), results)",
"num: self.dfs(num, target, 0, 0, 0, \"\", results) return results def dfs(self, num,",
"<EMAIL> Version: 0.0.1 Created Time: 2016-05-09 Last_modify: 2016-05-09 ****************************************** ''' ''' Given a",
"[\"1*0+5\",\"10-5\"] \"00\", 0 -> [\"0+0\", \"0-0\", \"0*0\"] \"3456237490\", 9191 -> [] Credits: Special",
"val - cur, -cur, \\ result + \"-\" + str(cur), results) self.dfs(num, target,",
"adding this problem and creating all test cases. ''' class Solution(object): def addOperators(self,",
"possibilities to add binary operators (not unary) +, -, or * between the",
"5 -> [\"1*0+5\",\"10-5\"] \"00\", 0 -> [\"0+0\", \"0-0\", \"0*0\"] \"3456237490\", 9191 -> []",
"num, target): \"\"\" :type num: str :type target: int :rtype: List[str] \"\"\" results",
"#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL>",
"dfs(self, num, target, pos, val, backup, result, results): if pos >= len(num): if",
"range(pos, len(num)): if i != pos and num[pos] == \"0\": break cur =",
"results): if pos >= len(num): if val == target: results.append(result) return for i",
"cur, cur, \\ result + \"+\" + str(cur), results) self.dfs(num, target, i +",
"+ str(cur), results) else: self.dfs(num, target, i + 1, val + cur, cur,",
"pos == 0: self.dfs(num, target, i + 1, cur, cur, \\ result +",
"\"3456237490\", 9191 -> [] Credits: Special thanks to @davidtan1890 for adding this problem",
"\"\", results) return results def dfs(self, num, target, pos, val, backup, result, results):",
"digits so they evaluate to the target value. Examples: \"123\", 6 -> [\"1+2+3\",",
"pos and num[pos] == \"0\": break cur = int(num[pos:i+1]) if pos == 0:",
"-cur, \\ result + \"-\" + str(cur), results) self.dfs(num, target, i + 1,",
"and creating all test cases. ''' class Solution(object): def addOperators(self, num, target): \"\"\"",
"Version: 0.0.1 Created Time: 2016-05-09 Last_modify: 2016-05-09 ****************************************** ''' ''' Given a string",
"''' ''' Given a string that contains only digits 0-9 and a target",
"if num: self.dfs(num, target, 0, 0, 0, \"\", results) return results def dfs(self,",
"\\ result + \"-\" + str(cur), results) self.dfs(num, target, i + 1, val",
"[] if num: self.dfs(num, target, 0, 0, 0, \"\", results) return results def",
"backup + backup * cur, \\ backup * cur, result + \"*\" +",
"target): \"\"\" :type num: str :type target: int :rtype: List[str] \"\"\" results =",
"target, 0, 0, 0, \"\", results) return results def dfs(self, num, target, pos,",
"****************************************** ''' ''' Given a string that contains only digits 0-9 and a",
"for adding this problem and creating all test cases. ''' class Solution(object): def",
"== target: results.append(result) return for i in range(pos, len(num)): if i != pos",
"+ 1, cur, cur, \\ result + str(cur), results) else: self.dfs(num, target, i",
"\\ result + str(cur), results) else: self.dfs(num, target, i + 1, val +",
"1, cur, cur, \\ result + str(cur), results) else: self.dfs(num, target, i +",
"-, or * between the digits so they evaluate to the target value.",
"9191 -> [] Credits: Special thanks to @davidtan1890 for adding this problem and",
"else: self.dfs(num, target, i + 1, val + cur, cur, \\ result +",
"target, pos, val, backup, result, results): if pos >= len(num): if val ==",
"+ cur, cur, \\ result + \"+\" + str(cur), results) self.dfs(num, target, i",
"cur = int(num[pos:i+1]) if pos == 0: self.dfs(num, target, i + 1, cur,",
"int :rtype: List[str] \"\"\" results = [] if num: self.dfs(num, target, 0, 0,",
"if pos >= len(num): if val == target: results.append(result) return for i in",
"cur, \\ result + \"+\" + str(cur), results) self.dfs(num, target, i + 1,",
"Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-05-09 Last_modify: 2016-05-09 ****************************************** '''",
"between the digits so they evaluate to the target value. Examples: \"123\", 6",
"cases. ''' class Solution(object): def addOperators(self, num, target): \"\"\" :type num: str :type",
"the digits so they evaluate to the target value. Examples: \"123\", 6 ->",
"-*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-05-09 Last_modify:",
"value. Examples: \"123\", 6 -> [\"1+2+3\", \"1*2*3\"] \"232\", 8 -> [\"2*3+2\", \"2+3*2\"] \"105\",",
"- cur, -cur, \\ result + \"-\" + str(cur), results) self.dfs(num, target, i",
"1, val - backup + backup * cur, \\ backup * cur, result",
"- backup + backup * cur, \\ backup * cur, result + \"*\"",
"''' class Solution(object): def addOperators(self, num, target): \"\"\" :type num: str :type target:",
":rtype: List[str] \"\"\" results = [] if num: self.dfs(num, target, 0, 0, 0,",
":type num: str :type target: int :rtype: List[str] \"\"\" results = [] if",
"results) return results def dfs(self, num, target, pos, val, backup, result, results): if",
"+ \"+\" + str(cur), results) self.dfs(num, target, i + 1, val - cur,",
"\"2+3*2\"] \"105\", 5 -> [\"1*0+5\",\"10-5\"] \"00\", 0 -> [\"0+0\", \"0-0\", \"0*0\"] \"3456237490\", 9191",
"a string that contains only digits 0-9 and a target value, return all",
"0.0.1 Created Time: 2016-05-09 Last_modify: 2016-05-09 ****************************************** ''' ''' Given a string that",
"evaluate to the target value. Examples: \"123\", 6 -> [\"1+2+3\", \"1*2*3\"] \"232\", 8",
"creating all test cases. ''' class Solution(object): def addOperators(self, num, target): \"\"\" :type",
"-*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created",
"they evaluate to the target value. Examples: \"123\", 6 -> [\"1+2+3\", \"1*2*3\"] \"232\",",
"6 -> [\"1+2+3\", \"1*2*3\"] \"232\", 8 -> [\"2*3+2\", \"2+3*2\"] \"105\", 5 -> [\"1*0+5\",\"10-5\"]",
"to add binary operators (not unary) +, -, or * between the digits",
"backup, result, results): if pos >= len(num): if val == target: results.append(result) return",
"Special thanks to @davidtan1890 for adding this problem and creating all test cases.",
"the target value. Examples: \"123\", 6 -> [\"1+2+3\", \"1*2*3\"] \"232\", 8 -> [\"2*3+2\",",
"0 -> [\"0+0\", \"0-0\", \"0*0\"] \"3456237490\", 9191 -> [] Credits: Special thanks to",
"@davidtan1890 for adding this problem and creating all test cases. ''' class Solution(object):",
"pos >= len(num): if val == target: results.append(result) return for i in range(pos,",
"str :type target: int :rtype: List[str] \"\"\" results = [] if num: self.dfs(num,",
"for i in range(pos, len(num)): if i != pos and num[pos] == \"0\":",
"i + 1, val + cur, cur, \\ result + \"+\" + str(cur),",
"val + cur, cur, \\ result + \"+\" + str(cur), results) self.dfs(num, target,",
"self.dfs(num, target, i + 1, val - cur, -cur, \\ result + \"-\"",
"test cases. ''' class Solution(object): def addOperators(self, num, target): \"\"\" :type num: str",
"self.dfs(num, target, i + 1, val + cur, cur, \\ result + \"+\"",
"target, i + 1, val - cur, -cur, \\ result + \"-\" +",
"class Solution(object): def addOperators(self, num, target): \"\"\" :type num: str :type target: int",
"thanks to @davidtan1890 for adding this problem and creating all test cases. '''",
"***************************************** Author: zhlinh Email: <EMAIL> Version: 0.0.1 Created Time: 2016-05-09 Last_modify: 2016-05-09 ******************************************",
"and a target value, return all possibilities to add binary operators (not unary)",
"(not unary) +, -, or * between the digits so they evaluate to",
"unary) +, -, or * between the digits so they evaluate to the",
"to @davidtan1890 for adding this problem and creating all test cases. ''' class",
"0, 0, \"\", results) return results def dfs(self, num, target, pos, val, backup,",
"1, val - cur, -cur, \\ result + \"-\" + str(cur), results) self.dfs(num,",
"[\"2*3+2\", \"2+3*2\"] \"105\", 5 -> [\"1*0+5\",\"10-5\"] \"00\", 0 -> [\"0+0\", \"0-0\", \"0*0\"] \"3456237490\",",
"Credits: Special thanks to @davidtan1890 for adding this problem and creating all test",
"contains only digits 0-9 and a target value, return all possibilities to add",
"List[str] \"\"\" results = [] if num: self.dfs(num, target, 0, 0, 0, \"\",",
"num[pos] == \"0\": break cur = int(num[pos:i+1]) if pos == 0: self.dfs(num, target,",
"Given a string that contains only digits 0-9 and a target value, return",
">= len(num): if val == target: results.append(result) return for i in range(pos, len(num)):",
"result, results): if pos >= len(num): if val == target: results.append(result) return for",
"target, i + 1, val - backup + backup * cur, \\ backup",
"and num[pos] == \"0\": break cur = int(num[pos:i+1]) if pos == 0: self.dfs(num,",
"return for i in range(pos, len(num)): if i != pos and num[pos] ==",
"string that contains only digits 0-9 and a target value, return all possibilities",
"add binary operators (not unary) +, -, or * between the digits so",
"binary operators (not unary) +, -, or * between the digits so they",
"-> [] Credits: Special thanks to @davidtan1890 for adding this problem and creating",
"+ str(cur), results) self.dfs(num, target, i + 1, val - cur, -cur, \\",
"return all possibilities to add binary operators (not unary) +, -, or *",
"digits 0-9 and a target value, return all possibilities to add binary operators",
"\"0\": break cur = int(num[pos:i+1]) if pos == 0: self.dfs(num, target, i +",
"addOperators(self, num, target): \"\"\" :type num: str :type target: int :rtype: List[str] \"\"\"",
"[\"1+2+3\", \"1*2*3\"] \"232\", 8 -> [\"2*3+2\", \"2+3*2\"] \"105\", 5 -> [\"1*0+5\",\"10-5\"] \"00\", 0",
"2016-05-09 Last_modify: 2016-05-09 ****************************************** ''' ''' Given a string that contains only digits",
"break cur = int(num[pos:i+1]) if pos == 0: self.dfs(num, target, i + 1,",
"target, i + 1, val + cur, cur, \\ result + \"+\" +",
"cur, cur, \\ result + str(cur), results) else: self.dfs(num, target, i + 1,",
"Examples: \"123\", 6 -> [\"1+2+3\", \"1*2*3\"] \"232\", 8 -> [\"2*3+2\", \"2+3*2\"] \"105\", 5",
"result + str(cur), results) else: self.dfs(num, target, i + 1, val + cur,",
"str(cur), results) else: self.dfs(num, target, i + 1, val + cur, cur, \\",
"+ \"-\" + str(cur), results) self.dfs(num, target, i + 1, val - backup",
"\"00\", 0 -> [\"0+0\", \"0-0\", \"0*0\"] \"3456237490\", 9191 -> [] Credits: Special thanks",
"all test cases. ''' class Solution(object): def addOperators(self, num, target): \"\"\" :type num:",
"-> [\"0+0\", \"0-0\", \"0*0\"] \"3456237490\", 9191 -> [] Credits: Special thanks to @davidtan1890",
"results = [] if num: self.dfs(num, target, 0, 0, 0, \"\", results) return",
"val, backup, result, results): if pos >= len(num): if val == target: results.append(result)",
"-> [\"2*3+2\", \"2+3*2\"] \"105\", 5 -> [\"1*0+5\",\"10-5\"] \"00\", 0 -> [\"0+0\", \"0-0\", \"0*0\"]",
"or * between the digits so they evaluate to the target value. Examples:",
"len(num): if val == target: results.append(result) return for i in range(pos, len(num)): if",
"+ 1, val + cur, cur, \\ result + \"+\" + str(cur), results)"
] |
[
"<gh_stars>1-10 from typing import Any, TypeVar, Union T = TypeVar(\"T\") Fixture = Union[Any,",
"from typing import Any, TypeVar, Union T = TypeVar(\"T\") Fixture = Union[Any, T]"
] |
[
"ObjectDoesNotExist as ex: return get_error_response(ex), 404 except BadRequest as ex: return get_error_response(ex), 400",
"def handle_errors(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ObjectDoesNotExist as",
"func(*args, **kwargs) except ObjectDoesNotExist as ex: return get_error_response(ex), 404 except BadRequest as ex:",
"<gh_stars>0 from functools import wraps from wt.common.errors import ObjectDoesNotExist, BadRequest def get_error_response(ex): return",
"from functools import wraps from wt.common.errors import ObjectDoesNotExist, BadRequest def get_error_response(ex): return {",
"@wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ObjectDoesNotExist as ex: return",
"get_error_response(ex), 404 except BadRequest as ex: return get_error_response(ex), 400 return wrapper DUMMY_STATS =",
"{ \"code\": ex.error_code.value, \"message\": ex.message } def handle_errors(func): @wraps(func) def wrapper(*args, **kwargs): try:",
"BadRequest as ex: return get_error_response(ex), 400 return wrapper DUMMY_STATS = { \"progress\": 0,",
"\"estimated_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_duration\": 0, \"burned_cost\": { \"amount\": 0,",
"except BadRequest as ex: return get_error_response(ex), 400 return wrapper DUMMY_STATS = { \"progress\":",
"handle_errors(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ObjectDoesNotExist as ex:",
"wrapper DUMMY_STATS = { \"progress\": 0, \"estimated_duration\": 0, \"estimated_cost\": { \"amount\": 0, \"currency\":",
"0, \"currency\": \"CZK\", }, \"burned_duration\": 0, \"burned_cost\": { \"amount\": 0, \"currency\": \"CZK\", },",
"def get_error_response(ex): return { \"code\": ex.error_code.value, \"message\": ex.message } def handle_errors(func): @wraps(func) def",
"as ex: return get_error_response(ex), 404 except BadRequest as ex: return get_error_response(ex), 400 return",
"{ \"progress\": 0, \"estimated_duration\": 0, \"estimated_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_duration\":",
"\"estimated_duration\": 0, \"estimated_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_duration\": 0, \"burned_cost\": {",
"functools import wraps from wt.common.errors import ObjectDoesNotExist, BadRequest def get_error_response(ex): return { \"code\":",
"wt.common.errors import ObjectDoesNotExist, BadRequest def get_error_response(ex): return { \"code\": ex.error_code.value, \"message\": ex.message }",
"def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ObjectDoesNotExist as ex: return get_error_response(ex),",
"0, \"estimated_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_duration\": 0, \"burned_cost\": { \"amount\":",
"BadRequest def get_error_response(ex): return { \"code\": ex.error_code.value, \"message\": ex.message } def handle_errors(func): @wraps(func)",
"**kwargs) except ObjectDoesNotExist as ex: return get_error_response(ex), 404 except BadRequest as ex: return",
"\"code\": ex.error_code.value, \"message\": ex.message } def handle_errors(func): @wraps(func) def wrapper(*args, **kwargs): try: return",
"\"burned_duration\": 0, \"burned_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_expenditures_cost\": { \"amount\": 0,",
"= { \"progress\": 0, \"estimated_duration\": 0, \"estimated_cost\": { \"amount\": 0, \"currency\": \"CZK\", },",
"\"amount\": 0, \"currency\": \"CZK\", }, \"burned_expenditures_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, }",
"return func(*args, **kwargs) except ObjectDoesNotExist as ex: return get_error_response(ex), 404 except BadRequest as",
"ex.error_code.value, \"message\": ex.message } def handle_errors(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args,",
"as ex: return get_error_response(ex), 400 return wrapper DUMMY_STATS = { \"progress\": 0, \"estimated_duration\":",
"import wraps from wt.common.errors import ObjectDoesNotExist, BadRequest def get_error_response(ex): return { \"code\": ex.error_code.value,",
"try: return func(*args, **kwargs) except ObjectDoesNotExist as ex: return get_error_response(ex), 404 except BadRequest",
"ObjectDoesNotExist, BadRequest def get_error_response(ex): return { \"code\": ex.error_code.value, \"message\": ex.message } def handle_errors(func):",
"except ObjectDoesNotExist as ex: return get_error_response(ex), 404 except BadRequest as ex: return get_error_response(ex),",
"return get_error_response(ex), 400 return wrapper DUMMY_STATS = { \"progress\": 0, \"estimated_duration\": 0, \"estimated_cost\":",
"{ \"amount\": 0, \"currency\": \"CZK\", }, \"burned_expenditures_cost\": { \"amount\": 0, \"currency\": \"CZK\", },",
"**kwargs): try: return func(*args, **kwargs) except ObjectDoesNotExist as ex: return get_error_response(ex), 404 except",
"\"currency\": \"CZK\", }, \"burned_duration\": 0, \"burned_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_expenditures_cost\":",
"wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ObjectDoesNotExist as ex: return get_error_response(ex), 404",
"\"burned_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_expenditures_cost\": { \"amount\": 0, \"currency\": \"CZK\",",
"} def handle_errors(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ObjectDoesNotExist",
"return { \"code\": ex.error_code.value, \"message\": ex.message } def handle_errors(func): @wraps(func) def wrapper(*args, **kwargs):",
"400 return wrapper DUMMY_STATS = { \"progress\": 0, \"estimated_duration\": 0, \"estimated_cost\": { \"amount\":",
"\"progress\": 0, \"estimated_duration\": 0, \"estimated_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_duration\": 0,",
"from wt.common.errors import ObjectDoesNotExist, BadRequest def get_error_response(ex): return { \"code\": ex.error_code.value, \"message\": ex.message",
"ex: return get_error_response(ex), 400 return wrapper DUMMY_STATS = { \"progress\": 0, \"estimated_duration\": 0,",
"return get_error_response(ex), 404 except BadRequest as ex: return get_error_response(ex), 400 return wrapper DUMMY_STATS",
"ex: return get_error_response(ex), 404 except BadRequest as ex: return get_error_response(ex), 400 return wrapper",
"\"amount\": 0, \"currency\": \"CZK\", }, \"burned_duration\": 0, \"burned_cost\": { \"amount\": 0, \"currency\": \"CZK\",",
"0, \"estimated_duration\": 0, \"estimated_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_duration\": 0, \"burned_cost\":",
"return wrapper DUMMY_STATS = { \"progress\": 0, \"estimated_duration\": 0, \"estimated_cost\": { \"amount\": 0,",
"wraps from wt.common.errors import ObjectDoesNotExist, BadRequest def get_error_response(ex): return { \"code\": ex.error_code.value, \"message\":",
"0, \"burned_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_expenditures_cost\": { \"amount\": 0, \"currency\":",
"404 except BadRequest as ex: return get_error_response(ex), 400 return wrapper DUMMY_STATS = {",
"get_error_response(ex): return { \"code\": ex.error_code.value, \"message\": ex.message } def handle_errors(func): @wraps(func) def wrapper(*args,",
"ex.message } def handle_errors(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except",
"{ \"amount\": 0, \"currency\": \"CZK\", }, \"burned_duration\": 0, \"burned_cost\": { \"amount\": 0, \"currency\":",
"}, \"burned_duration\": 0, \"burned_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_expenditures_cost\": { \"amount\":",
"\"CZK\", }, \"burned_duration\": 0, \"burned_cost\": { \"amount\": 0, \"currency\": \"CZK\", }, \"burned_expenditures_cost\": {",
"DUMMY_STATS = { \"progress\": 0, \"estimated_duration\": 0, \"estimated_cost\": { \"amount\": 0, \"currency\": \"CZK\",",
"import ObjectDoesNotExist, BadRequest def get_error_response(ex): return { \"code\": ex.error_code.value, \"message\": ex.message } def",
"\"message\": ex.message } def handle_errors(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs)",
"get_error_response(ex), 400 return wrapper DUMMY_STATS = { \"progress\": 0, \"estimated_duration\": 0, \"estimated_cost\": {"
] |
[
"main(): \"\"\" Perform an optuna run according to the hyperparameters and directory locations",
"p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"], } # set auto learning rate finder param if \"auto_lr_find\"",
"= optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"] == \"random\": sampler = optuna.samplers.RandomSampler() # create an optuna",
"the final hyperparameters Returns: hyp_fix - dictionary where key is the hyperparameter name",
"with variable value hyperparameters by sampling a hyperparameter # value from the range",
"according to the hyperparameters and directory locations specified in 'config_path' \"\"\" torch.autograd.set_detect_anomaly(True) args",
"pathlib from collections import OrderedDict # Pytorch import torch import pytorch_lightning as pl",
"Set seeds for reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark =",
"run_config[\"ego_graph_path\"], ) return model, hyperparameters def build_trainer(run_config, hyperparameters, trial=None): \"\"\" Set up optuna",
"the folder specified by dir in the PROJECT ROOT # folder if \"local\"",
"directory + the study name run_config[\"study_path\"] = os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] ) print(\"Logging to",
"between all nodes in the graph run_config[\"subgraphs_path\"] = os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"] = os.path.join(task,",
"for score in model.metric_scores ] if run_config[\"optuna\"][\"opt_direction\"] == \"maximize\": return np.max(all_scores) else: return",
"= os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] ) ntrials = run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials} Trials of optuna\")",
"hparam_file.close() # dump trainer args to results dir tkwarg_file = open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\")",
"the model trainer.fit(model) # write results to the results dir if results_path is",
"trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"] # Create tensorboard logger lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if not",
"by 'monitor_metric' in the run config \"\"\" # get model and hyperparameter dict",
"General import numpy as np import random import argparse import json import commentjson",
"run_config hyp_optuna = { k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial) for k in dict(run_config[\"hyperparams_optuna\"]).keys() }",
"the json file specified by 'fname' \"\"\" with open(fname, \"rt\") as handle: return",
"hparam_file = open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\") results_serializable = {k: float(v) for k, v in",
"tensorboard logger lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if not os.path.exists(lgdir): os.makedirs(lgdir) logger = TensorBoardLogger(",
"filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", ) # if we use",
"print(\"Tensorboard logging at \", logger.log_dir) trainer_kwargs[\"logger\"] = logger # Save top three model",
"hyperparameters = build_model(run_config, trial) # build optuna trainer trainer, trainer_kwargs, results_path = build_trainer(",
"this ['batch_size', [ 64, 128]] if \"kwargs\" in param_dict: kwargs = dict(param_dict[\"kwargs\"]) return",
"np.min(all_scores) def main(): \"\"\" Perform an optuna run according to the hyperparameters and",
"config file run_config = read_json(args.config_path) # Set paths to data task = run_config[\"data\"][\"task\"]",
"run_config[\"graph_path\"] = os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"] = os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] = os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"]",
"\"early_stop_callback\", \"checkpoint_callback\"] if key in trainer_kwargs.keys() ] [trainer_kwargs.pop(key) for key in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs,",
"model trainer.fit(model) # write results to the results dir if results_path is not",
"else: run_config[\"tb\"][\"dir_full\"] = os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] ) ntrials = run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials} Trials",
"for the current trial hyperparameters = get_hyperparams_optuna(run_config, trial) # Set seeds for reproducibility",
"\"no_gpu\" in run_config else 1, \"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"], } #",
"callback if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer = pl.Trainer(**trainer_kwargs) return",
"containing information about the hyperparameter (range of values & type of sampler) e.g.{",
"and \"grid_search_space\" in run_config[\"optuna\"] ): sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"] == \"tpe\": sampler",
"run_config = read_json(args.config_path) # Set paths to data task = run_config[\"data\"][\"task\"] # paths",
"(e.g. batch_size) and value is the hyperparameter value \"\"\" # initialize the dict",
"\"progress_bar_refresh_rate\" in hyperparameters: p_refresh = hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh = 5 # set epochs,",
"monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", ) # if we use pruning, use the pytorch lightning pruning",
"run_config[\"optuna\"][\"opt_direction\"] == \"maximize\": return np.max(all_scores) else: return np.min(all_scores) def main(): \"\"\" Perform an",
"finder param if \"auto_lr_find\" in hyperparameters and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"] # Create",
"\"\"\" if \"progress_bar_refresh_rate\" in hyperparameters: p_refresh = hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh = 5 #",
"in 'config_path' \"\"\" torch.autograd.set_detect_anomaly(True) args = parse_arguments() # read in config file run_config",
"used to keep track of results Will load in # existing study if",
"# General import numpy as np import random import argparse import json import",
"k, trial) for k in dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna) return hyp_fix def build_model(run_config, trial=None):",
"else: p_refresh = 5 # set epochs, gpus, gradient clipping, etc. # if",
"config def parse_arguments(): \"\"\" Read in the config file specifying all of the",
"hyperparameters to results dir hparam_file = open(os.path.join(results_path, \"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close() #",
"results to the results dir if results_path is not None: hparam_file = open(os.path.join(results_path,",
"[ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score in model.metric_scores ] if run_config[\"optuna\"][\"opt_direction\"] == \"maximize\": return np.max(all_scores)",
"by 'name' from the range of values in 'param_dict' name: string specifying hyperparameter",
"\"gpus\": 0 if \"no_gpu\" in run_config else 1, \"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\":",
"] [trainer_kwargs.pop(key) for key in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close() # train the model",
"\"optuna_study_sqlite.db\") # specify sampler if ( run_config[\"optuna\"][\"sampler\"] == \"grid\" and \"grid_search_space\" in run_config[\"optuna\"]",
"specifying hyperparameter trial: optuna trial param_dict: dictionary containing information about the hyperparameter (range",
"= run_config[\"data\"][\"task\"] # paths to subgraphs, edge list, and shortest paths between all",
"run_config[\"optuna\"] ): sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"] == \"tpe\": sampler = optuna.samplers.TPESampler() elif",
"= os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"] = os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"] = os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] =",
"is the hyperparameter value \"\"\" # initialize the dict with the fixed hyperparameters",
"= PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer = pl.Trainer(**trainer_kwargs) return trainer, trainer_kwargs, logger.log_dir def",
"\"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"], } # set auto learning rate finder",
"the study name run_config[\"study_path\"] = os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] ) print(\"Logging to \", run_config[\"study_path\"])",
"locations specified in 'config_path' \"\"\" torch.autograd.set_detect_anomaly(True) args = parse_arguments() # read in config",
"key for key in [\"logger\", \"profiler\", \"early_stop_callback\", \"checkpoint_callback\"] if key in trainer_kwargs.keys() ]",
"run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], ) return model, hyperparameters def build_trainer(run_config,",
"= parse_arguments() # read in config file run_config = read_json(args.config_path) # Set paths",
"os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"] = os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] = os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"] = os.path.join(task,",
"hyperparameter dict model, hyperparameters = build_model(run_config, trial) # build optuna trainer trainer, trainer_kwargs,",
"os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] ) print(\"Logging to \", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) # get database",
") study.optimize( lambda trial: train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path = os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\")",
"specified in 'config_path' \"\"\" torch.autograd.set_detect_anomaly(True) args = parse_arguments() # read in config file",
"\"similarities/\") # get location of node embeddings run_config[\"embedding_path\"] = os.path.join(task, \"atom_features.pth\") # create",
"getattr(trial, module_name)(*args, **kwargs) else: return getattr(trial, module_name)(*args) def get_hyperparams_optuna(run_config, trial): \"\"\" Converts the",
"if \"auto_lr_find\" in hyperparameters and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"] # Create tensorboard logger",
"Perform an optuna run according to the hyperparameters and directory locations specified in",
"os.path.join(task, \"ego_graphs.txt\") # directory where similarity calculations will be stored run_config[\"similarities_path\"] = os.path.join(task,",
"pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbacks import ModelCheckpoint # Optuna import optuna from optuna.integration",
"collections import OrderedDict # Pytorch import torch import pytorch_lightning as pl from pytorch_lightning.loggers",
"we use pruning, use the pytorch lightning pruning callback if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] =",
"a single model whose hyperparameters are specified in the run config Returns the",
"& type of sampler) e.g.{ \"type\" : \"suggest_categorical\", \"args\" : [[ 64, 128]]",
"config to a dictionary of the final hyperparameters Returns: hyp_fix - dictionary where",
"train_model(run_config, trial=None): \"\"\" Train a single model whose hyperparameters are specified in the",
"then use CPU trainer_kwargs = { \"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\": 0 if \"no_gpu\" in",
"run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) # get database file db_file = os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") # specify",
"Converts the fixed and variable hyperparameters in the run config to a dictionary",
"# initialize SubGNN model = md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"],",
") if not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard logging at \", logger.log_dir) trainer_kwargs[\"logger\"] = logger",
"in the folder specified by dir in the PROJECT ROOT # folder if",
"dict(param_dict[\"kwargs\"]) return getattr(trial, module_name)(*args, **kwargs) else: return getattr(trial, module_name)(*args) def get_hyperparams_optuna(run_config, trial): \"\"\"",
"pruner=pruner, storage=\"sqlite:///\" + db_file, study_name=run_config[\"study_path\"], load_if_exists=True, ) study.optimize( lambda trial: train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"],",
"specified by dir in the PROJECT ROOT # folder if \"local\" in run_config[\"tb\"]",
"of values & type of sampler) e.g.{ \"type\" : \"suggest_categorical\", \"args\" : [[",
"np.max(all_scores) else: return np.min(all_scores) def main(): \"\"\" Perform an optuna run according to",
"logger lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if not os.path.exists(lgdir): os.makedirs(lgdir) logger = TensorBoardLogger( run_config[\"tb\"][\"dir_full\"],",
"# if 'no_gpu' in run config, then use CPU trainer_kwargs = { \"max_epochs\":",
"an optuna run according to the hyperparameters and directory locations specified in 'config_path'",
"hyperparameters def build_trainer(run_config, hyperparameters, trial=None): \"\"\" Set up optuna trainer \"\"\" if \"progress_bar_refresh_rate\"",
"to data task = run_config[\"data\"][\"task\"] # paths to subgraphs, edge list, and shortest",
"os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if not os.path.exists(lgdir): os.makedirs(lgdir) logger = TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\" +",
"os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard logging at \", logger.log_dir) trainer_kwargs[\"logger\"] = logger # Save top",
"= [name] args.extend( param_dict[\"args\"] ) # resulting list will look something like this",
"batch_size) and value is the hyperparameter value \"\"\" # initialize the dict with",
"complete study path is the tensorboard directory + the study name run_config[\"study_path\"] =",
"# create an optuna study with the specified sampler, pruner, direction (e.g. #",
"# the complete study path is the tensorboard directory + the study name",
"# dump hyperparameters to results dir hparam_file = open(os.path.join(results_path, \"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters, indent=4))",
"model checkpoints trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint( filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\",",
"args.extend( param_dict[\"args\"] ) # resulting list will look something like this ['batch_size', [",
"config file specifying all of the parameters \"\"\" parser = argparse.ArgumentParser(description=\"Learn subgraph embeddings\")",
"= {k: float(v) for k, v in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close() # return",
"database is used to keep track of results Will load in # existing",
"config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] ) ntrials = run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials} Trials of optuna\") if run_config[\"optuna\"][\"pruning\"]:",
"results_path = build_trainer( run_config, hyperparameters, trial ) # dump hyperparameters to results dir",
"np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # initialize SubGNN model",
"run_config[\"optuna\"][\"pruning\"]: pruner = optuna.pruners.MedianPruner() else: pruner = None # the complete study path",
"exists study = optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner, storage=\"sqlite:///\" + db_file, study_name=run_config[\"study_path\"], load_if_exists=True, )",
"a dictionary of the final hyperparameters Returns: hyp_fix - dictionary where key is",
"for the hyperparameter specified by 'name' from the range of values in 'param_dict'",
"trainer \"\"\" if \"progress_bar_refresh_rate\" in hyperparameters: p_refresh = hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh = 5",
"in the run config \"\"\" # get model and hyperparameter dict model, hyperparameters",
"subgraphs, edge list, and shortest paths between all nodes in the graph run_config[\"subgraphs_path\"]",
"# get database file db_file = os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") # specify sampler if (",
"specify sampler if ( run_config[\"optuna\"][\"sampler\"] == \"grid\" and \"grid_search_space\" in run_config[\"optuna\"] ): sampler",
"load in # existing study if one exists study = optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler,",
"existing study if one exists study = optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner, storage=\"sqlite:///\" +",
"with open(fname, \"rt\") as handle: return commentjson.load(handle, object_hook=OrderedDict) def get_optuna_suggest(param_dict, name, trial): \"\"\"",
"as pl from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbacks import ModelCheckpoint # Optuna import",
"information about the hyperparameter (range of values & type of sampler) e.g.{ \"type\"",
"hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh = 5 # set epochs, gpus, gradient clipping, etc. #",
"elif run_config[\"optuna\"][\"sampler\"] == \"tpe\": sampler = optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"] == \"random\": sampler =",
"value hyperparameters by sampling a hyperparameter # value from the range specified in",
"key in [\"logger\", \"profiler\", \"early_stop_callback\", \"checkpoint_callback\"] if key in trainer_kwargs.keys() ] [trainer_kwargs.pop(key) for",
"run config, then use CPU trainer_kwargs = { \"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\": 0 if",
"A SQLlite database is used to keep track of results Will load in",
"to the hyperparameters and directory locations specified in 'config_path' \"\"\" torch.autograd.set_detect_anomaly(True) args =",
"the parameters \"\"\" parser = argparse.ArgumentParser(description=\"Learn subgraph embeddings\") parser.add_argument(\"-config_path\", type=str, default=None, help=\"Load config",
"\"subgraphs.pth\") run_config[\"graph_path\"] = os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"] = os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] = os.path.join(task, \"degree_sequence.txt\")",
"name, trial): \"\"\" Returns a suggested value for the hyperparameter specified by 'name'",
"of values in 'param_dict' name: string specifying hyperparameter trial: optuna trial param_dict: dictionary",
"min) metric specified by 'monitor_metric' in the run config all_scores = [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy()",
"\"\"\" # initialize the dict with the fixed hyperparameters hyp_fix = dict(run_config[\"hyperparams_fix\"]) #",
"else: pruner = None # the complete study path is the tensorboard directory",
"study = optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner, storage=\"sqlite:///\" + db_file, study_name=run_config[\"study_path\"], load_if_exists=True, ) study.optimize(",
"'no_gpu' in run config, then use CPU trainer_kwargs = { \"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\":",
"} # set auto learning rate finder param if \"auto_lr_find\" in hyperparameters and",
"hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"] # Create tensorboard logger lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if",
") # resulting list will look something like this ['batch_size', [ 64, 128]]",
"name run_config[\"study_path\"] = os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] ) print(\"Logging to \", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True)",
"import numpy as np import random import argparse import json import commentjson import",
"tensorboard directory + the study name run_config[\"study_path\"] = os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] ) print(\"Logging",
"set auto learning rate finder param if \"auto_lr_find\" in hyperparameters and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"]",
"run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], ) return model, hyperparameters def build_trainer(run_config, hyperparameters, trial=None): \"\"\" Set up",
"and variable hyperparameters in the run config to a dictionary of the final",
"in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close() # return the max (or min) metric specified",
"elif run_config[\"optuna\"][\"sampler\"] == \"random\": sampler = optuna.samplers.RandomSampler() # create an optuna study with",
"optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner, storage=\"sqlite:///\" + db_file, study_name=run_config[\"study_path\"], load_if_exists=True, ) study.optimize( lambda trial:",
"\"degree_sequence.txt\") run_config[\"ego_graph_path\"] = os.path.join(task, \"ego_graphs.txt\") # directory where similarity calculations will be stored",
"initialize SubGNN model = md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"],",
"the fixed and variable hyperparameters in the run config to a dictionary of",
"track of results Will load in # existing study if one exists study",
"parse_arguments(): \"\"\" Read in the config file specifying all of the parameters \"\"\"",
"# if we use pruning, use the pytorch lightning pruning callback if run_config[\"optuna\"][\"pruning\"]:",
"import os import pathlib from collections import OrderedDict # Pytorch import torch import",
"hyperparameters in the run config to a dictionary of the final hyperparameters Returns:",
"Set up optuna trainer \"\"\" if \"progress_bar_refresh_rate\" in hyperparameters: p_refresh = hyperparameters[\"progress_bar_refresh_rate\"] else:",
"5 # set epochs, gpus, gradient clipping, etc. # if 'no_gpu' in run",
"model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close() # return the max (or min) metric specified by",
"Create tensorboard logger lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if not os.path.exists(lgdir): os.makedirs(lgdir) logger =",
"# existing study if one exists study = optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner, storage=\"sqlite:///\"",
"is not None: hparam_file = open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\") results_serializable = {k: float(v) for",
"def get_optuna_suggest(param_dict, name, trial): \"\"\" Returns a suggested value for the hyperparameter specified",
"\"\"\" module_name = param_dict[\"type\"] # e.g. suggest_categorical, suggest_float args = [name] args.extend( param_dict[\"args\"]",
"PROJECT ROOT # folder if \"local\" in run_config[\"tb\"] and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"]",
"from pytorch_lightning.callbacks import ModelCheckpoint # Optuna import optuna from optuna.integration import PyTorchLightningPruningCallback #",
"\"\"\" Read in the json file specified by 'fname' \"\"\" with open(fname, \"rt\")",
"study if one exists study = optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner, storage=\"sqlite:///\" + db_file,",
"a hyperparameter # value from the range specified in the run_config hyp_optuna =",
"directory in the folder specified by dir in the PROJECT ROOT # folder",
"Trials of optuna\") if run_config[\"optuna\"][\"pruning\"]: pruner = optuna.pruners.MedianPruner() else: pruner = None #",
"torch import pytorch_lightning as pl from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbacks import ModelCheckpoint",
"direction (e.g. # maximize) A SQLlite database is used to keep track of",
"Pytorch import torch import pytorch_lightning as pl from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbacks",
"optuna from optuna.integration import PyTorchLightningPruningCallback # Our Methods from . import SubGNN as",
"in # existing study if one exists study = optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner,",
"run config to a dictionary of the final hyperparameters Returns: hyp_fix - dictionary",
"hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close() # return the max (or min) metric specified by 'monitor_metric'",
"in hyperparameters and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"] # Create tensorboard logger lgdir =",
"\"edge_list.txt\") run_config[\"shortest_paths_path\"] = os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] = os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"] = os.path.join(task, \"ego_graphs.txt\")",
"get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial) for k in dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna) return hyp_fix def build_model(run_config,",
"the run config \"\"\" # get model and hyperparameter dict model, hyperparameters =",
"not None: hparam_file = open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\") results_serializable = {k: float(v) for k,",
"= os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving Study Results to\", optuna_results_path) joblib.dump(study, optuna_results_path) print(study.best_params) if __name__",
"in run config, then use CPU trainer_kwargs = { \"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\": 0",
"from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbacks import ModelCheckpoint # Optuna import optuna from",
"\"local\" in run_config[\"tb\"] and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"] = os.path.join( config.PROJECT_ROOT,",
"\"random\": sampler = optuna.samplers.RandomSampler() # create an optuna study with the specified sampler,",
"\"\"\" Train a single model whose hyperparameters are specified in the run config",
"build_model(run_config, trial=None): \"\"\" Creates SubGNN from the hyperparameters specified in the run config",
"sampler, pruner, direction (e.g. # maximize) A SQLlite database is used to keep",
"Optuna import optuna from optuna.integration import PyTorchLightningPruningCallback # Our Methods from . import",
"not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard logging at \", logger.log_dir) trainer_kwargs[\"logger\"] = logger # Save",
"in hyperparameters: p_refresh = hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh = 5 # set epochs, gpus,",
"study with the specified sampler, pruner, direction (e.g. # maximize) A SQLlite database",
"all of the parameters \"\"\" parser = argparse.ArgumentParser(description=\"Learn subgraph embeddings\") parser.add_argument(\"-config_path\", type=str, default=None,",
"\"\"\" Converts the fixed and variable hyperparameters in the run config to a",
"if \"local\" in run_config[\"tb\"] and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"] = os.path.join(",
"\"\"\" parser = argparse.ArgumentParser(description=\"Learn subgraph embeddings\") parser.add_argument(\"-config_path\", type=str, default=None, help=\"Load config file\") args",
"pruning, use the pytorch lightning pruning callback if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback( trial,",
"Returns a suggested value for the hyperparameter specified by 'name' from the range",
"# paths to subgraphs, edge list, and shortest paths between all nodes in",
"SubGNN model = md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], )",
"get model and hyperparameter dict model, hyperparameters = build_model(run_config, trial) # build optuna",
"monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer = pl.Trainer(**trainer_kwargs) return trainer, trainer_kwargs, logger.log_dir def train_model(run_config, trial=None): \"\"\"",
"in 'param_dict' name: string specifying hyperparameter trial: optuna trial param_dict: dictionary containing information",
"suggested value for the hyperparameter specified by 'name' from the range of values",
"use pruning, use the pytorch lightning pruning callback if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback(",
"os import pathlib from collections import OrderedDict # Pytorch import torch import pytorch_lightning",
"argparse.ArgumentParser(description=\"Learn subgraph embeddings\") parser.add_argument(\"-config_path\", type=str, default=None, help=\"Load config file\") args = parser.parse_args() return",
"run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\" + str(random.randint(0, 10000000)), ) if not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard logging",
"for reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False #",
"= run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials} Trials of optuna\") if run_config[\"optuna\"][\"pruning\"]: pruner = optuna.pruners.MedianPruner() else:",
"like this ['batch_size', [ 64, 128]] if \"kwargs\" in param_dict: kwargs = dict(param_dict[\"kwargs\"])",
"= run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"] = os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] ) ntrials = run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running",
"in run_config else 1, \"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"], } # set",
"= 5 # set epochs, gpus, gradient clipping, etc. # if 'no_gpu' in",
"data task = run_config[\"data\"][\"task\"] # paths to subgraphs, edge list, and shortest paths",
"pytorch_lightning as pl from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbacks import ModelCheckpoint # Optuna",
"is the hyperparameter name (e.g. batch_size) and value is the hyperparameter value \"\"\"",
"sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"] == \"tpe\": sampler = optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"] ==",
"config \"\"\" # get hyperparameters for the current trial hyperparameters = get_hyperparams_optuna(run_config, trial)",
"# Save top three model checkpoints trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint( filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ),",
"shortest paths between all nodes in the graph run_config[\"subgraphs_path\"] = os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"]",
"lightning pruning callback if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer =",
"n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path = os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving Study Results to\", optuna_results_path) joblib.dump(study, optuna_results_path)",
"run_config else 1, \"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"], } # set auto",
"module_name = param_dict[\"type\"] # e.g. suggest_categorical, suggest_float args = [name] args.extend( param_dict[\"args\"] )",
"something like this ['batch_size', [ 64, 128]] if \"kwargs\" in param_dict: kwargs =",
"trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer = pl.Trainer(**trainer_kwargs) return trainer, trainer_kwargs, logger.log_dir def train_model(run_config, trial=None):",
"os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] ) ntrials = run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials} Trials of optuna\") if",
"value \"\"\" # initialize the dict with the fixed hyperparameters hyp_fix = dict(run_config[\"hyperparams_fix\"])",
"import commentjson import joblib import os import pathlib from collections import OrderedDict #",
"(e.g. # maximize) A SQLlite database is used to keep track of results",
"config Returns the max (or min) metric specified by 'monitor_metric' in the run",
"k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial) for k in dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna) return hyp_fix def",
"hyperparameter value \"\"\" # initialize the dict with the fixed hyperparameters hyp_fix =",
"os.makedirs(logger.log_dir) print(\"Tensorboard logging at \", logger.log_dir) trainer_kwargs[\"logger\"] = logger # Save top three",
"= pl.Trainer(**trainer_kwargs) return trainer, trainer_kwargs, logger.log_dir def train_model(run_config, trial=None): \"\"\" Train a single",
"] if run_config[\"optuna\"][\"opt_direction\"] == \"maximize\": return np.max(all_scores) else: return np.min(all_scores) def main(): \"\"\"",
"Set paths to data task = run_config[\"data\"][\"task\"] # paths to subgraphs, edge list,",
"hyp_optuna = { k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial) for k in dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna)",
"train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path = os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving Study Results to\",",
"SQLlite database is used to keep track of results Will load in #",
"and value is the hyperparameter value \"\"\" # initialize the dict with the",
"clipping, etc. # if 'no_gpu' in run config, then use CPU trainer_kwargs =",
"indent=4)) hparam_file.close() # return the max (or min) metric specified by 'monitor_metric' in",
"dump hyperparameters to results dir hparam_file = open(os.path.join(results_path, \"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close()",
"\"kwargs\" in param_dict: kwargs = dict(param_dict[\"kwargs\"]) return getattr(trial, module_name)(*args, **kwargs) else: return getattr(trial,",
"1, \"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"], } # set auto learning rate",
"run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"] = os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] ) ntrials =",
"import SubGNN as md from SubGNN import config def parse_arguments(): \"\"\" Read in",
"the config file specifying all of the parameters \"\"\" parser = argparse.ArgumentParser(description=\"Learn subgraph",
"results Will load in # existing study if one exists study = optuna.create_study(",
"value is the hyperparameter value \"\"\" # initialize the dict with the fixed",
"random import argparse import json import commentjson import joblib import os import pathlib",
"args to results dir tkwarg_file = open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\") pop_keys = [ key",
"} \"\"\" module_name = param_dict[\"type\"] # e.g. suggest_categorical, suggest_float args = [name] args.extend(",
"pop_keys = [ key for key in [\"logger\", \"profiler\", \"early_stop_callback\", \"checkpoint_callback\"] if key",
"# write results to the results dir if results_path is not None: hparam_file",
"# dump trainer args to results dir tkwarg_file = open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\") pop_keys",
"file run_config = read_json(args.config_path) # Set paths to data task = run_config[\"data\"][\"task\"] #",
"[[ 64, 128]] } \"\"\" module_name = param_dict[\"type\"] # e.g. suggest_categorical, suggest_float args",
"argparse import json import commentjson import joblib import os import pathlib from collections",
"= optuna.pruners.MedianPruner() else: pruner = None # the complete study path is the",
"p_refresh = hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh = 5 # set epochs, gpus, gradient clipping,",
"variable value hyperparameters by sampling a hyperparameter # value from the range specified",
"import random import argparse import json import commentjson import joblib import os import",
"to results dir tkwarg_file = open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\") pop_keys = [ key for",
"= os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] = os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"] = os.path.join(task, \"ego_graphs.txt\") # directory",
"param_dict[\"args\"] ) # resulting list will look something like this ['batch_size', [ 64,",
"to \", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) # get database file db_file = os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\")",
"build optuna trainer trainer, trainer_kwargs, results_path = build_trainer( run_config, hyperparameters, trial ) #",
"key is the hyperparameter name (e.g. batch_size) and value is the hyperparameter value",
"run config all_scores = [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score in model.metric_scores ] if run_config[\"optuna\"][\"opt_direction\"]",
"optuna trial param_dict: dictionary containing information about the hyperparameter (range of values &",
"trainer_kwargs, logger.log_dir def train_model(run_config, trial=None): \"\"\" Train a single model whose hyperparameters are",
"initialize the dict with the fixed hyperparameters hyp_fix = dict(run_config[\"hyperparams_fix\"]) # update the",
"= dict(run_config[\"hyperparams_fix\"]) # update the dict with variable value hyperparameters by sampling a",
"# Set seeds for reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark",
"p_refresh = 5 # set epochs, gpus, gradient clipping, etc. # if 'no_gpu'",
"for key in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close() # train the model trainer.fit(model) #",
"in the run config to a dictionary of the final hyperparameters Returns: hyp_fix",
"sampler) e.g.{ \"type\" : \"suggest_categorical\", \"args\" : [[ 64, 128]] } \"\"\" module_name",
"variable hyperparameters in the run config to a dictionary of the final hyperparameters",
"dir if results_path is not None: hparam_file = open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\") results_serializable =",
"trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint( filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", ) #",
"\"grid_search_space\" in run_config[\"optuna\"] ): sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"] == \"tpe\": sampler =",
"hyperparameters = get_hyperparams_optuna(run_config, trial) # Set seeds for reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"])",
"learning rate finder param if \"auto_lr_find\" in hyperparameters and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"]",
"def parse_arguments(): \"\"\" Read in the config file specifying all of the parameters",
"resulting list will look something like this ['batch_size', [ 64, 128]] if \"kwargs\"",
"# directory where similarity calculations will be stored run_config[\"similarities_path\"] = os.path.join(task, \"similarities/\") #",
"study path is the tensorboard directory + the study name run_config[\"study_path\"] = os.path.join(",
"= parser.parse_args() return args def read_json(fname): \"\"\" Read in the json file specified",
"\"suggest_categorical\", \"args\" : [[ 64, 128]] } \"\"\" module_name = param_dict[\"type\"] # e.g.",
"type=str, default=None, help=\"Load config file\") args = parser.parse_args() return args def read_json(fname): \"\"\"",
"if ( run_config[\"optuna\"][\"sampler\"] == \"grid\" and \"grid_search_space\" in run_config[\"optuna\"] ): sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"])",
"trial: train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path = os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving Study Results",
"if \"progress_bar_refresh_rate\" in hyperparameters: p_refresh = hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh = 5 # set",
"= build_model(run_config, trial) # build optuna trainer trainer, trainer_kwargs, results_path = build_trainer( run_config,",
"etc. # if 'no_gpu' in run config, then use CPU trainer_kwargs = {",
"study.optimize( lambda trial: train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path = os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving",
"\"auto_lr_find\" in hyperparameters and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"] # Create tensorboard logger lgdir",
"hyp_fix = dict(run_config[\"hyperparams_fix\"]) # update the dict with variable value hyperparameters by sampling",
"from the range of values in 'param_dict' name: string specifying hyperparameter trial: optuna",
"= dict(param_dict[\"kwargs\"]) return getattr(trial, module_name)(*args, **kwargs) else: return getattr(trial, module_name)(*args) def get_hyperparams_optuna(run_config, trial):",
"print(\"Logging to \", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) # get database file db_file = os.path.join(run_config[\"study_path\"],",
"trial) # Set seeds for reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic = True",
"in the run config all_scores = [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score in model.metric_scores ]",
"hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close() # dump trainer args to results dir tkwarg_file = open(os.path.join(results_path,",
"the tensorboard directory + the study name run_config[\"study_path\"] = os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] )",
"not os.path.exists(lgdir): os.makedirs(lgdir) logger = TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\" + str(random.randint(0, 10000000)), )",
"optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"] == \"tpe\": sampler = optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"] == \"random\": sampler",
"trainer args to results dir tkwarg_file = open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\") pop_keys = [",
"study_name=run_config[\"study_path\"], load_if_exists=True, ) study.optimize( lambda trial: train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path =",
"directory locations specified in 'config_path' \"\"\" torch.autograd.set_detect_anomaly(True) args = parse_arguments() # read in",
"TensorBoardLogger from pytorch_lightning.callbacks import ModelCheckpoint # Optuna import optuna from optuna.integration import PyTorchLightningPruningCallback",
"else: return np.min(all_scores) def main(): \"\"\" Perform an optuna run according to the",
"\"ego_graphs.txt\") # directory where similarity calculations will be stored run_config[\"similarities_path\"] = os.path.join(task, \"similarities/\")",
"trial=None): \"\"\" Train a single model whose hyperparameters are specified in the run",
"= None # the complete study path is the tensorboard directory + the",
") print(\"Logging to \", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) # get database file db_file =",
"for key in [\"logger\", \"profiler\", \"early_stop_callback\", \"checkpoint_callback\"] if key in trainer_kwargs.keys() ] [trainer_kwargs.pop(key)",
"joblib import os import pathlib from collections import OrderedDict # Pytorch import torch",
"= os.path.join(task, \"similarities/\") # get location of node embeddings run_config[\"embedding_path\"] = os.path.join(task, \"atom_features.pth\")",
"write results to the results dir if results_path is not None: hparam_file =",
"run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials} Trials of optuna\") if run_config[\"optuna\"][\"pruning\"]: pruner = optuna.pruners.MedianPruner() else: pruner",
"create a tensorboard directory in the folder specified by dir in the PROJECT",
"from collections import OrderedDict # Pytorch import torch import pytorch_lightning as pl from",
"in param_dict: kwargs = dict(param_dict[\"kwargs\"]) return getattr(trial, module_name)(*args, **kwargs) else: return getattr(trial, module_name)(*args)",
"value from the range specified in the run_config hyp_optuna = { k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k],",
"the hyperparameter specified by 'name' from the range of values in 'param_dict' name:",
"get hyperparameters for the current trial hyperparameters = get_hyperparams_optuna(run_config, trial) # Set seeds",
"to a dictionary of the final hyperparameters Returns: hyp_fix - dictionary where key",
"args def read_json(fname): \"\"\" Read in the json file specified by 'fname' \"\"\"",
"logger.log_dir def train_model(run_config, trial=None): \"\"\" Train a single model whose hyperparameters are specified",
"values & type of sampler) e.g.{ \"type\" : \"suggest_categorical\", \"args\" : [[ 64,",
"db_file, study_name=run_config[\"study_path\"], load_if_exists=True, ) study.optimize( lambda trial: train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path",
"build_trainer(run_config, hyperparameters, trial=None): \"\"\" Set up optuna trainer \"\"\" if \"progress_bar_refresh_rate\" in hyperparameters:",
"the run config \"\"\" # get hyperparameters for the current trial hyperparameters =",
"folder specified by dir in the PROJECT ROOT # folder if \"local\" in",
"in the config file specifying all of the parameters \"\"\" parser = argparse.ArgumentParser(description=\"Learn",
"by dir in the PROJECT ROOT # folder if \"local\" in run_config[\"tb\"] and",
"'fname' \"\"\" with open(fname, \"rt\") as handle: return commentjson.load(handle, object_hook=OrderedDict) def get_optuna_suggest(param_dict, name,",
"pruner = None # the complete study path is the tensorboard directory +",
"# Optuna import optuna from optuna.integration import PyTorchLightningPruningCallback # Our Methods from .",
"one exists study = optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner, storage=\"sqlite:///\" + db_file, study_name=run_config[\"study_path\"], load_if_exists=True,",
"\"args\" : [[ 64, 128]] } \"\"\" module_name = param_dict[\"type\"] # e.g. suggest_categorical,",
"run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], ) return model, hyperparameters def build_trainer(run_config, hyperparameters, trial=None): \"\"\" Set",
"update the dict with variable value hyperparameters by sampling a hyperparameter # value",
"return getattr(trial, module_name)(*args) def get_hyperparams_optuna(run_config, trial): \"\"\" Converts the fixed and variable hyperparameters",
"trial): \"\"\" Converts the fixed and variable hyperparameters in the run config to",
"print(f\"Running {ntrials} Trials of optuna\") if run_config[\"optuna\"][\"pruning\"]: pruner = optuna.pruners.MedianPruner() else: pruner =",
"specified by 'monitor_metric' in the run config \"\"\" # get model and hyperparameter",
"seeds for reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False",
"[name] args.extend( param_dict[\"args\"] ) # resulting list will look something like this ['batch_size',",
"'monitor_metric' in the run config all_scores = [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score in model.metric_scores",
"'config_path' \"\"\" torch.autograd.set_detect_anomaly(True) args = parse_arguments() # read in config file run_config =",
"location of node embeddings run_config[\"embedding_path\"] = os.path.join(task, \"atom_features.pth\") # create a tensorboard directory",
"run_config[\"study_path\"] = os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] ) print(\"Logging to \", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) #",
"== \"random\": sampler = optuna.samplers.RandomSampler() # create an optuna study with the specified",
"= { \"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\": 0 if \"no_gpu\" in run_config else 1, \"num_sanity_val_steps\":",
"+ the study name run_config[\"study_path\"] = os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] ) print(\"Logging to \",",
"in the run config Returns the max (or min) metric specified by 'monitor_metric'",
"task = run_config[\"data\"][\"task\"] # paths to subgraphs, edge list, and shortest paths between",
"the results dir if results_path is not None: hparam_file = open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\")",
"Will load in # existing study if one exists study = optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"],",
"trial=None): \"\"\" Set up optuna trainer \"\"\" if \"progress_bar_refresh_rate\" in hyperparameters: p_refresh =",
"dictionary of the final hyperparameters Returns: hyp_fix - dictionary where key is the",
"max (or min) metric specified by 'monitor_metric' in the run config all_scores =",
"sampler = optuna.samplers.RandomSampler() # create an optuna study with the specified sampler, pruner,",
"the PROJECT ROOT # folder if \"local\" in run_config[\"tb\"] and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] =",
"values in 'param_dict' name: string specifying hyperparameter trial: optuna trial param_dict: dictionary containing",
"as handle: return commentjson.load(handle, object_hook=OrderedDict) def get_optuna_suggest(param_dict, name, trial): \"\"\" Returns a suggested",
"graph run_config[\"subgraphs_path\"] = os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"] = os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"] = os.path.join(task, \"shortest_path_matrix.npy\")",
"\"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"], } # set auto learning rate finder param if",
"\"type\" : \"suggest_categorical\", \"args\" : [[ 64, 128]] } \"\"\" module_name = param_dict[\"type\"]",
"dict with variable value hyperparameters by sampling a hyperparameter # value from the",
"getattr(trial, module_name)(*args) def get_hyperparams_optuna(run_config, trial): \"\"\" Converts the fixed and variable hyperparameters in",
"hyperparameters hyp_fix = dict(run_config[\"hyperparams_fix\"]) # update the dict with variable value hyperparameters by",
"def build_model(run_config, trial=None): \"\"\" Creates SubGNN from the hyperparameters specified in the run",
"= open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\") pop_keys = [ key for key in [\"logger\", \"profiler\",",
"the max (or min) metric specified by 'monitor_metric' in the run config all_scores",
"all_scores = [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score in model.metric_scores ] if run_config[\"optuna\"][\"opt_direction\"] == \"maximize\":",
"the complete study path is the tensorboard directory + the study name run_config[\"study_path\"]",
"logger # Save top three model checkpoints trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint( filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\"",
"os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] = os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"] = os.path.join(task, \"ego_graphs.txt\") # directory where",
"+ str(random.randint(0, 10000000)), ) if not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard logging at \", logger.log_dir)",
"paths to subgraphs, edge list, and shortest paths between all nodes in the",
"the current trial hyperparameters = get_hyperparams_optuna(run_config, trial) # Set seeds for reproducibility torch.manual_seed(hyperparameters[\"seed\"])",
"gpus, gradient clipping, etc. # if 'no_gpu' in run config, then use CPU",
"\"\"\" Read in the config file specifying all of the parameters \"\"\" parser",
"= { k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial) for k in dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna) return",
"hyperparameters specified in the run config \"\"\" # get hyperparameters for the current",
"logging at \", logger.log_dir) trainer_kwargs[\"logger\"] = logger # Save top three model checkpoints",
"run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"] = os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] ) ntrials = run_config[\"optuna\"][\"opt_n_trials\"]",
"dump trainer args to results dir tkwarg_file = open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\") pop_keys =",
"trial=None): \"\"\" Creates SubGNN from the hyperparameters specified in the run config \"\"\"",
"tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close() # train the model trainer.fit(model) # write results to the",
"return the max (or min) metric specified by 'monitor_metric' in the run config",
"k in dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna) return hyp_fix def build_model(run_config, trial=None): \"\"\" Creates SubGNN",
"object_hook=OrderedDict) def get_optuna_suggest(param_dict, name, trial): \"\"\" Returns a suggested value for the hyperparameter",
"if \"kwargs\" in param_dict: kwargs = dict(param_dict[\"kwargs\"]) return getattr(trial, module_name)(*args, **kwargs) else: return",
"will be stored run_config[\"similarities_path\"] = os.path.join(task, \"similarities/\") # get location of node embeddings",
") optuna_results_path = os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving Study Results to\", optuna_results_path) joblib.dump(study, optuna_results_path) print(study.best_params)",
"e.g.{ \"type\" : \"suggest_categorical\", \"args\" : [[ 64, 128]] } \"\"\" module_name =",
"in the graph run_config[\"subgraphs_path\"] = os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"] = os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"] =",
"if run_config[\"optuna\"][\"opt_direction\"] == \"maximize\": return np.max(all_scores) else: return np.min(all_scores) def main(): \"\"\" Perform",
"# Set paths to data task = run_config[\"data\"][\"task\"] # paths to subgraphs, edge",
"Returns: hyp_fix - dictionary where key is the hyperparameter name (e.g. batch_size) and",
"results dir tkwarg_file = open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\") pop_keys = [ key for key",
"edge list, and shortest paths between all nodes in the graph run_config[\"subgraphs_path\"] =",
"{ntrials} Trials of optuna\") if run_config[\"optuna\"][\"pruning\"]: pruner = optuna.pruners.MedianPruner() else: pruner = None",
"(or min) metric specified by 'monitor_metric' in the run config all_scores = [",
"in the run config \"\"\" # get hyperparameters for the current trial hyperparameters",
"= build_trainer( run_config, hyperparameters, trial ) # dump hyperparameters to results dir hparam_file",
"the specified sampler, pruner, direction (e.g. # maximize) A SQLlite database is used",
"torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # initialize SubGNN model = md.SubGNN_Chem( hyperparameters,",
"specified by 'fname' \"\"\" with open(fname, \"rt\") as handle: return commentjson.load(handle, object_hook=OrderedDict) def",
"use the pytorch lightning pruning callback if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"]",
"dictionary containing information about the hyperparameter (range of values & type of sampler)",
"- dictionary where key is the hyperparameter name (e.g. batch_size) and value is",
"hyp_fix def build_model(run_config, trial=None): \"\"\" Creates SubGNN from the hyperparameters specified in the",
"\"\"\" Set up optuna trainer \"\"\" if \"progress_bar_refresh_rate\" in hyperparameters: p_refresh = hyperparameters[\"progress_bar_refresh_rate\"]",
"trainer_kwargs[\"logger\"] = logger # Save top three model checkpoints trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint( filepath=os.path.join(",
"the run config all_scores = [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score in model.metric_scores ] if",
"range of values in 'param_dict' name: string specifying hyperparameter trial: optuna trial param_dict:",
"pl from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbacks import ModelCheckpoint # Optuna import optuna",
"from . import SubGNN as md from SubGNN import config def parse_arguments(): \"\"\"",
"up optuna trainer \"\"\" if \"progress_bar_refresh_rate\" in hyperparameters: p_refresh = hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh",
"os.path.join(task, \"atom_features.pth\") # create a tensorboard directory in the folder specified by dir",
"run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], ) return model, hyperparameters def build_trainer(run_config, hyperparameters, trial=None): \"\"\"",
"= TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\" + str(random.randint(0, 10000000)), ) if not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir)",
"Read in the config file specifying all of the parameters \"\"\" parser =",
"specified by 'name' from the range of values in 'param_dict' name: string specifying",
"trial ) # dump hyperparameters to results dir hparam_file = open(os.path.join(results_path, \"hyperparams.json\"), \"w\")",
"run_config[\"embedding_path\"] = os.path.join(task, \"atom_features.pth\") # create a tensorboard directory in the folder specified",
"logger.log_dir) trainer_kwargs[\"logger\"] = logger # Save top three model checkpoints trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint(",
"\"w\") hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close() # dump trainer args to results dir tkwarg_file =",
"parser.parse_args() return args def read_json(fname): \"\"\" Read in the json file specified by",
"verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", ) # if we use pruning, use the pytorch lightning",
"sampler = optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"] == \"random\": sampler = optuna.samplers.RandomSampler() # create an",
"numpy as np import random import argparse import json import commentjson import joblib",
"\"gradient_clip_val\": hyperparameters[\"grad_clip\"], } # set auto learning rate finder param if \"auto_lr_find\" in",
": [[ 64, 128]] } \"\"\" module_name = param_dict[\"type\"] # e.g. suggest_categorical, suggest_float",
"in [\"logger\", \"profiler\", \"early_stop_callback\", \"checkpoint_callback\"] if key in trainer_kwargs.keys() ] [trainer_kwargs.pop(key) for key",
"file specifying all of the parameters \"\"\" parser = argparse.ArgumentParser(description=\"Learn subgraph embeddings\") parser.add_argument(\"-config_path\",",
"of node embeddings run_config[\"embedding_path\"] = os.path.join(task, \"atom_features.pth\") # create a tensorboard directory in",
"hyperparameter specified by 'name' from the range of values in 'param_dict' name: string",
"in run_config[\"optuna\"] ): sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"] == \"tpe\": sampler = optuna.samplers.TPESampler()",
"def read_json(fname): \"\"\" Read in the json file specified by 'fname' \"\"\" with",
"(range of values & type of sampler) e.g.{ \"type\" : \"suggest_categorical\", \"args\" :",
"the hyperparameter (range of values & type of sampler) e.g.{ \"type\" : \"suggest_categorical\",",
"= md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], ) return model,",
"study name run_config[\"study_path\"] = os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] ) print(\"Logging to \", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True,",
"maximize) A SQLlite database is used to keep track of results Will load",
"SubGNN import config def parse_arguments(): \"\"\" Read in the config file specifying all",
"# set auto learning rate finder param if \"auto_lr_find\" in hyperparameters and hyperparameters[\"auto_lr_find\"]:",
"optuna_results_path = os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving Study Results to\", optuna_results_path) joblib.dump(study, optuna_results_path) print(study.best_params) if",
"nodes in the graph run_config[\"subgraphs_path\"] = os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"] = os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"]",
"torch.autograd.set_detect_anomaly(True) args = parse_arguments() # read in config file run_config = read_json(args.config_path) #",
"by sampling a hyperparameter # value from the range specified in the run_config",
"# build optuna trainer trainer, trainer_kwargs, results_path = build_trainer( run_config, hyperparameters, trial )",
"results_path is not None: hparam_file = open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\") results_serializable = {k: float(v)",
"run_config[\"ego_graph_path\"] = os.path.join(task, \"ego_graphs.txt\") # directory where similarity calculations will be stored run_config[\"similarities_path\"]",
"exist_ok=True) # get database file db_file = os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") # specify sampler if",
"run config Returns the max (or min) metric specified by 'monitor_metric' in the",
"\"\"\" # get model and hyperparameter dict model, hyperparameters = build_model(run_config, trial) #",
"by 'fname' \"\"\" with open(fname, \"rt\") as handle: return commentjson.load(handle, object_hook=OrderedDict) def get_optuna_suggest(param_dict,",
"name=run_config[\"tb\"][\"name\"], version=\"version_\" + str(random.randint(0, 10000000)), ) if not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard logging at",
"run_config[\"optuna\"][\"sampler\"] == \"tpe\": sampler = optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"] == \"random\": sampler = optuna.samplers.RandomSampler()",
"# train the model trainer.fit(model) # write results to the results dir if",
"= os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if not os.path.exists(lgdir): os.makedirs(lgdir) logger = TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\"",
"in the run_config hyp_optuna = { k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial) for k in",
"= argparse.ArgumentParser(description=\"Learn subgraph embeddings\") parser.add_argument(\"-config_path\", type=str, default=None, help=\"Load config file\") args = parser.parse_args()",
") return model, hyperparameters def build_trainer(run_config, hyperparameters, trial=None): \"\"\" Set up optuna trainer",
"for k in dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna) return hyp_fix def build_model(run_config, trial=None): \"\"\" Creates",
"read_json(args.config_path) # Set paths to data task = run_config[\"data\"][\"task\"] # paths to subgraphs,",
"type of sampler) e.g.{ \"type\" : \"suggest_categorical\", \"args\" : [[ 64, 128]] }",
"dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna) return hyp_fix def build_model(run_config, trial=None): \"\"\" Creates SubGNN from the",
"run according to the hyperparameters and directory locations specified in 'config_path' \"\"\" torch.autograd.set_detect_anomaly(True)",
"commentjson import joblib import os import pathlib from collections import OrderedDict # Pytorch",
"hyp_fix - dictionary where key is the hyperparameter name (e.g. batch_size) and value",
"hyperparameters Returns: hyp_fix - dictionary where key is the hyperparameter name (e.g. batch_size)",
"and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"] = os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] ) ntrials",
"hparam_file = open(os.path.join(results_path, \"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close() # dump trainer args to",
"\", logger.log_dir) trainer_kwargs[\"logger\"] = logger # Save top three model checkpoints trainer_kwargs[\"checkpoint_callback\"] =",
"model and hyperparameter dict model, hyperparameters = build_model(run_config, trial) # build optuna trainer",
"specified in the run config \"\"\" # get hyperparameters for the current trial",
"hyperparameters[\"max_epochs\"], \"gpus\": 0 if \"no_gpu\" in run_config else 1, \"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\": p_refresh,",
"= os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"] = os.path.join(task, \"ego_graphs.txt\") # directory where similarity calculations will",
"= os.path.join(task, \"ego_graphs.txt\") # directory where similarity calculations will be stored run_config[\"similarities_path\"] =",
"name (e.g. batch_size) and value is the hyperparameter value \"\"\" # initialize the",
"): sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"] == \"tpe\": sampler = optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"]",
"hyperparameters, trial ) # dump hyperparameters to results dir hparam_file = open(os.path.join(results_path, \"hyperparams.json\"),",
"PyTorchLightningPruningCallback # Our Methods from . import SubGNN as md from SubGNN import",
"\"optuna_study.pkl\") print(\"Saving Study Results to\", optuna_results_path) joblib.dump(study, optuna_results_path) print(study.best_params) if __name__ == \"__main__\":",
"args = [name] args.extend( param_dict[\"args\"] ) # resulting list will look something like",
"trainer, trainer_kwargs, logger.log_dir def train_model(run_config, trial=None): \"\"\" Train a single model whose hyperparameters",
"128]] if \"kwargs\" in param_dict: kwargs = dict(param_dict[\"kwargs\"]) return getattr(trial, module_name)(*args, **kwargs) else:",
"parser.add_argument(\"-config_path\", type=str, default=None, help=\"Load config file\") args = parser.parse_args() return args def read_json(fname):",
"the graph run_config[\"subgraphs_path\"] = os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"] = os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"] = os.path.join(task,",
"'param_dict' name: string specifying hyperparameter trial: optuna trial param_dict: dictionary containing information about",
"import argparse import json import commentjson import joblib import os import pathlib from",
"save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", ) # if we use pruning, use the pytorch",
"= os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") # specify sampler if ( run_config[\"optuna\"][\"sampler\"] == \"grid\" and \"grid_search_space\"",
"pl.Trainer(**trainer_kwargs) return trainer, trainer_kwargs, logger.log_dir def train_model(run_config, trial=None): \"\"\" Train a single model",
"the range of values in 'param_dict' name: string specifying hyperparameter trial: optuna trial",
"optuna.pruners.MedianPruner() else: pruner = None # the complete study path is the tensorboard",
"def build_trainer(run_config, hyperparameters, trial=None): \"\"\" Set up optuna trainer \"\"\" if \"progress_bar_refresh_rate\" in",
"trainer_kwargs = { \"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\": 0 if \"no_gpu\" in run_config else 1,",
"0 if \"no_gpu\" in run_config else 1, \"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"],",
"config, then use CPU trainer_kwargs = { \"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\": 0 if \"no_gpu\"",
"score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score in model.metric_scores ] if run_config[\"optuna\"][\"opt_direction\"] == \"maximize\": return np.max(all_scores) else:",
"\"\"\" with open(fname, \"rt\") as handle: return commentjson.load(handle, object_hook=OrderedDict) def get_optuna_suggest(param_dict, name, trial):",
"dir in the PROJECT ROOT # folder if \"local\" in run_config[\"tb\"] and run_config[\"tb\"][\"local\"]:",
"import pytorch_lightning as pl from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbacks import ModelCheckpoint #",
"fixed hyperparameters hyp_fix = dict(run_config[\"hyperparams_fix\"]) # update the dict with variable value hyperparameters",
"float(v) for k, v in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close() # return the max",
"return commentjson.load(handle, object_hook=OrderedDict) def get_optuna_suggest(param_dict, name, trial): \"\"\" Returns a suggested value for",
"range specified in the run_config hyp_optuna = { k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial) for",
"10000000)), ) if not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard logging at \", logger.log_dir) trainer_kwargs[\"logger\"] =",
"kwargs = dict(param_dict[\"kwargs\"]) return getattr(trial, module_name)(*args, **kwargs) else: return getattr(trial, module_name)(*args) def get_hyperparams_optuna(run_config,",
"trainer = pl.Trainer(**trainer_kwargs) return trainer, trainer_kwargs, logger.log_dir def train_model(run_config, trial=None): \"\"\" Train a",
"a suggested value for the hyperparameter specified by 'name' from the range of",
"open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\") pop_keys = [ key for key in [\"logger\", \"profiler\", \"early_stop_callback\",",
"**kwargs) else: return getattr(trial, module_name)(*args) def get_hyperparams_optuna(run_config, trial): \"\"\" Converts the fixed and",
"import OrderedDict # Pytorch import torch import pytorch_lightning as pl from pytorch_lightning.loggers import",
"dictionary where key is the hyperparameter name (e.g. batch_size) and value is the",
"= [ key for key in [\"logger\", \"profiler\", \"early_stop_callback\", \"checkpoint_callback\"] if key in",
"tensorboard directory in the folder specified by dir in the PROJECT ROOT #",
"for k, v in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close() # return the max (or",
"ntrials = run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials} Trials of optuna\") if run_config[\"optuna\"][\"pruning\"]: pruner = optuna.pruners.MedianPruner()",
"# return the max (or min) metric specified by 'monitor_metric' in the run",
"dir tkwarg_file = open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\") pop_keys = [ key for key in",
"min) metric specified by 'monitor_metric' in the run config \"\"\" # get model",
"open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\") results_serializable = {k: float(v) for k, v in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable,",
"from optuna.integration import PyTorchLightningPruningCallback # Our Methods from . import SubGNN as md",
"auto learning rate finder param if \"auto_lr_find\" in hyperparameters and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] =",
"subgraph embeddings\") parser.add_argument(\"-config_path\", type=str, default=None, help=\"Load config file\") args = parser.parse_args() return args",
"key in trainer_kwargs.keys() ] [trainer_kwargs.pop(key) for key in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close() #",
"embeddings run_config[\"embedding_path\"] = os.path.join(task, \"atom_features.pth\") # create a tensorboard directory in the folder",
"get_hyperparams_optuna(run_config, trial) # Set seeds for reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic =",
"lambda trial: train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path = os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving Study",
"if we use pruning, use the pytorch lightning pruning callback if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"]",
"if key in trainer_kwargs.keys() ] [trainer_kwargs.pop(key) for key in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close()",
"if one exists study = optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner, storage=\"sqlite:///\" + db_file, study_name=run_config[\"study_path\"],",
"get location of node embeddings run_config[\"embedding_path\"] = os.path.join(task, \"atom_features.pth\") # create a tensorboard",
"stored run_config[\"similarities_path\"] = os.path.join(task, \"similarities/\") # get location of node embeddings run_config[\"embedding_path\"] =",
"if not os.path.exists(lgdir): os.makedirs(lgdir) logger = TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\" + str(random.randint(0, 10000000)),",
"\", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) # get database file db_file = os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") #",
"dict with the fixed hyperparameters hyp_fix = dict(run_config[\"hyperparams_fix\"]) # update the dict with",
"# get hyperparameters for the current trial hyperparameters = get_hyperparams_optuna(run_config, trial) # Set",
"trial param_dict: dictionary containing information about the hyperparameter (range of values & type",
"database file db_file = os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") # specify sampler if ( run_config[\"optuna\"][\"sampler\"] ==",
"if \"no_gpu\" in run_config else 1, \"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"], }",
"trial) for k in dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna) return hyp_fix def build_model(run_config, trial=None): \"\"\"",
"key in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close() # train the model trainer.fit(model) # write",
"optuna trainer \"\"\" if \"progress_bar_refresh_rate\" in hyperparameters: p_refresh = hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh =",
"\"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\": 0 if \"no_gpu\" in run_config else 1, \"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\":",
"top three model checkpoints trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint( filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3, verbose=True,",
"run_config[\"tb\"][\"name\"]) if not os.path.exists(lgdir): os.makedirs(lgdir) logger = TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\" + str(random.randint(0,",
"calculations will be stored run_config[\"similarities_path\"] = os.path.join(task, \"similarities/\") # get location of node",
"\"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close() # dump trainer args to results dir tkwarg_file",
"# Create tensorboard logger lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if not os.path.exists(lgdir): os.makedirs(lgdir) logger",
"Creates SubGNN from the hyperparameters specified in the run config \"\"\" # get",
"= open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\") results_serializable = {k: float(v) for k, v in model.metric_scores[-1].items()}",
"single model whose hyperparameters are specified in the run config Returns the max",
"torch.backends.cudnn.benchmark = False # initialize SubGNN model = md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"],",
"metric specified by 'monitor_metric' in the run config \"\"\" # get model and",
"[trainer_kwargs.pop(key) for key in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close() # train the model trainer.fit(model)",
"run_config[\"shortest_paths_path\"] = os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] = os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"] = os.path.join(task, \"ego_graphs.txt\") #",
"gradient clipping, etc. # if 'no_gpu' in run config, then use CPU trainer_kwargs",
"hyperparameters for the current trial hyperparameters = get_hyperparams_optuna(run_config, trial) # Set seeds for",
"n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path = os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving Study Results to\", optuna_results_path) joblib.dump(study,",
"three model checkpoints trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint( filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"],",
"epochs, gpus, gradient clipping, etc. # if 'no_gpu' in run config, then use",
"value for the hyperparameter specified by 'name' from the range of values in",
"CPU trainer_kwargs = { \"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\": 0 if \"no_gpu\" in run_config else",
"Our Methods from . import SubGNN as md from SubGNN import config def",
"create an optuna study with the specified sampler, pruner, direction (e.g. # maximize)",
"str(random.randint(0, 10000000)), ) if not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard logging at \", logger.log_dir) trainer_kwargs[\"logger\"]",
"in model.metric_scores ] if run_config[\"optuna\"][\"opt_direction\"] == \"maximize\": return np.max(all_scores) else: return np.min(all_scores) def",
"parse_arguments() # read in config file run_config = read_json(args.config_path) # Set paths to",
"to subgraphs, edge list, and shortest paths between all nodes in the graph",
"trainer.fit(model) # write results to the results dir if results_path is not None:",
"args = parse_arguments() # read in config file run_config = read_json(args.config_path) # Set",
"where similarity calculations will be stored run_config[\"similarities_path\"] = os.path.join(task, \"similarities/\") # get location",
"and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"] # Create tensorboard logger lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"])",
"list, and shortest paths between all nodes in the graph run_config[\"subgraphs_path\"] = os.path.join(task,",
"where key is the hyperparameter name (e.g. batch_size) and value is the hyperparameter",
"current trial hyperparameters = get_hyperparams_optuna(run_config, trial) # Set seeds for reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"])",
"os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"] = os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"] = os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] = os.path.join(task,",
"to keep track of results Will load in # existing study if one",
"= False # initialize SubGNN model = md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"],",
"get_hyperparams_optuna(run_config, trial): \"\"\" Converts the fixed and variable hyperparameters in the run config",
"\"maximize\": return np.max(all_scores) else: return np.min(all_scores) def main(): \"\"\" Perform an optuna run",
"torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # initialize SubGNN",
"config \"\"\" # get model and hyperparameter dict model, hyperparameters = build_model(run_config, trial)",
"specified in the run_config hyp_optuna = { k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial) for k",
"optuna trainer trainer, trainer_kwargs, results_path = build_trainer( run_config, hyperparameters, trial ) # dump",
"hparam_file.close() # return the max (or min) metric specified by 'monitor_metric' in the",
"return getattr(trial, module_name)(*args, **kwargs) else: return getattr(trial, module_name)(*args) def get_hyperparams_optuna(run_config, trial): \"\"\" Converts",
"model.metric_scores ] if run_config[\"optuna\"][\"opt_direction\"] == \"maximize\": return np.max(all_scores) else: return np.min(all_scores) def main():",
"sampler if ( run_config[\"optuna\"][\"sampler\"] == \"grid\" and \"grid_search_space\" in run_config[\"optuna\"] ): sampler =",
"trainer_kwargs.keys() ] [trainer_kwargs.pop(key) for key in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close() # train the",
"if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer = pl.Trainer(**trainer_kwargs) return trainer,",
"k, v in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close() # return the max (or min)",
"and directory locations specified in 'config_path' \"\"\" torch.autograd.set_detect_anomaly(True) args = parse_arguments() # read",
"+ db_file, study_name=run_config[\"study_path\"], load_if_exists=True, ) study.optimize( lambda trial: train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], )",
"# Pytorch import torch import pytorch_lightning as pl from pytorch_lightning.loggers import TensorBoardLogger from",
"pruner, direction (e.g. # maximize) A SQLlite database is used to keep track",
"# get location of node embeddings run_config[\"embedding_path\"] = os.path.join(task, \"atom_features.pth\") # create a",
"and hyperparameter dict model, hyperparameters = build_model(run_config, trial) # build optuna trainer trainer,",
"at \", logger.log_dir) trainer_kwargs[\"logger\"] = logger # Save top three model checkpoints trainer_kwargs[\"checkpoint_callback\"]",
"torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # initialize SubGNN model = md.SubGNN_Chem(",
"a tensorboard directory in the folder specified by dir in the PROJECT ROOT",
"return model, hyperparameters def build_trainer(run_config, hyperparameters, trial=None): \"\"\" Set up optuna trainer \"\"\"",
"run_config, hyperparameters, trial ) # dump hyperparameters to results dir hparam_file = open(os.path.join(results_path,",
"with the fixed hyperparameters hyp_fix = dict(run_config[\"hyperparams_fix\"]) # update the dict with variable",
"\"final_metric_scores.json\"), \"w\") results_serializable = {k: float(v) for k, v in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4))",
"[ 64, 128]] if \"kwargs\" in param_dict: kwargs = dict(param_dict[\"kwargs\"]) return getattr(trial, module_name)(*args,",
"hyperparameters and directory locations specified in 'config_path' \"\"\" torch.autograd.set_detect_anomaly(True) args = parse_arguments() #",
"\"\"\" Perform an optuna run according to the hyperparameters and directory locations specified",
"\"\"\" Returns a suggested value for the hyperparameter specified by 'name' from the",
"import ModelCheckpoint # Optuna import optuna from optuna.integration import PyTorchLightningPruningCallback # Our Methods",
"md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], ) return model, hyperparameters",
"Methods from . import SubGNN as md from SubGNN import config def parse_arguments():",
"\"w\") pop_keys = [ key for key in [\"logger\", \"profiler\", \"early_stop_callback\", \"checkpoint_callback\"] if",
"reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # initialize",
"None # the complete study path is the tensorboard directory + the study",
"import json import commentjson import joblib import os import pathlib from collections import",
"Save top three model checkpoints trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint( filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3,",
"dir hparam_file = open(os.path.join(results_path, \"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close() # dump trainer args",
"is used to keep track of results Will load in # existing study",
"model, hyperparameters def build_trainer(run_config, hyperparameters, trial=None): \"\"\" Set up optuna trainer \"\"\" if",
"= optuna.create_study( direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner, storage=\"sqlite:///\" + db_file, study_name=run_config[\"study_path\"], load_if_exists=True, ) study.optimize( lambda",
"version=\"version_\" + str(random.randint(0, 10000000)), ) if not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard logging at \",",
"the hyperparameters and directory locations specified in 'config_path' \"\"\" torch.autograd.set_detect_anomaly(True) args = parse_arguments()",
"read_json(fname): \"\"\" Read in the json file specified by 'fname' \"\"\" with open(fname,",
"lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if not os.path.exists(lgdir): os.makedirs(lgdir) logger = TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"],",
"= logger # Save top three model checkpoints trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint( filepath=os.path.join( logger.log_dir,",
"get database file db_file = os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") # specify sampler if ( run_config[\"optuna\"][\"sampler\"]",
"suggest_float args = [name] args.extend( param_dict[\"args\"] ) # resulting list will look something",
"= hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh = 5 # set epochs, gpus, gradient clipping, etc.",
"128]] } \"\"\" module_name = param_dict[\"type\"] # e.g. suggest_categorical, suggest_float args = [name]",
"\"grid\" and \"grid_search_space\" in run_config[\"optuna\"] ): sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"] == \"tpe\":",
"SubGNN as md from SubGNN import config def parse_arguments(): \"\"\" Read in the",
"'monitor_metric' in the run config \"\"\" # get model and hyperparameter dict model,",
"indent=4)) tkwarg_file.close() # train the model trainer.fit(model) # write results to the results",
"hyperparameters[\"grad_clip\"], } # set auto learning rate finder param if \"auto_lr_find\" in hyperparameters",
": \"suggest_categorical\", \"args\" : [[ 64, 128]] } \"\"\" module_name = param_dict[\"type\"] #",
"the range specified in the run_config hyp_optuna = { k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial)",
"\"checkpoint_callback\"] if key in trainer_kwargs.keys() ] [trainer_kwargs.pop(key) for key in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4))",
"), save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", ) # if we use pruning, use the",
"md from SubGNN import config def parse_arguments(): \"\"\" Read in the config file",
"def train_model(run_config, trial=None): \"\"\" Train a single model whose hyperparameters are specified in",
"hyperparameter # value from the range specified in the run_config hyp_optuna = {",
"run config \"\"\" # get model and hyperparameter dict model, hyperparameters = build_model(run_config,",
"== \"grid\" and \"grid_search_space\" in run_config[\"optuna\"] ): sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"] ==",
"and shortest paths between all nodes in the graph run_config[\"subgraphs_path\"] = os.path.join(task, \"subgraphs.pth\")",
"fixed and variable hyperparameters in the run config to a dictionary of the",
"optuna.integration import PyTorchLightningPruningCallback # Our Methods from . import SubGNN as md from",
"in dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna) return hyp_fix def build_model(run_config, trial=None): \"\"\" Creates SubGNN from",
"optuna\") if run_config[\"optuna\"][\"pruning\"]: pruner = optuna.pruners.MedianPruner() else: pruner = None # the complete",
"path is the tensorboard directory + the study name run_config[\"study_path\"] = os.path.join( run_config[\"tb\"][\"dir_full\"],",
"in the PROJECT ROOT # folder if \"local\" in run_config[\"tb\"] and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"]",
"= [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score in model.metric_scores ] if run_config[\"optuna\"][\"opt_direction\"] == \"maximize\": return",
"the hyperparameter name (e.g. batch_size) and value is the hyperparameter value \"\"\" #",
"PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer = pl.Trainer(**trainer_kwargs) return trainer, trainer_kwargs, logger.log_dir def train_model(run_config,",
"if run_config[\"optuna\"][\"pruning\"]: pruner = optuna.pruners.MedianPruner() else: pruner = None # the complete study",
"json file specified by 'fname' \"\"\" with open(fname, \"rt\") as handle: return commentjson.load(handle,",
"checkpoints trainer_kwargs[\"checkpoint_callback\"] = ModelCheckpoint( filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", )",
"param if \"auto_lr_find\" in hyperparameters and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"] # Create tensorboard",
"config file\") args = parser.parse_args() return args def read_json(fname): \"\"\" Read in the",
"# value from the range specified in the run_config hyp_optuna = { k:",
"the dict with the fixed hyperparameters hyp_fix = dict(run_config[\"hyperparams_fix\"]) # update the dict",
"os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving Study Results to\", optuna_results_path) joblib.dump(study, optuna_results_path) print(study.best_params) if __name__ ==",
"indent=4)) hparam_file.close() # dump trainer args to results dir tkwarg_file = open(os.path.join(results_path, \"trainer_kwargs.json\"),",
"optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"] == \"random\": sampler = optuna.samplers.RandomSampler() # create an optuna study",
"= open(os.path.join(results_path, \"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close() # dump trainer args to results",
"sampler=sampler, pruner=pruner, storage=\"sqlite:///\" + db_file, study_name=run_config[\"study_path\"], load_if_exists=True, ) study.optimize( lambda trial: train_model(run_config, trial),",
"the fixed hyperparameters hyp_fix = dict(run_config[\"hyperparams_fix\"]) # update the dict with variable value",
"return trainer, trainer_kwargs, logger.log_dir def train_model(run_config, trial=None): \"\"\" Train a single model whose",
") # if we use pruning, use the pytorch lightning pruning callback if",
"hyperparameters and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"] # Create tensorboard logger lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"],",
"import optuna from optuna.integration import PyTorchLightningPruningCallback # Our Methods from . import SubGNN",
"import config def parse_arguments(): \"\"\" Read in the config file specifying all of",
"# e.g. suggest_categorical, suggest_float args = [name] args.extend( param_dict[\"args\"] ) # resulting list",
"model, hyperparameters = build_model(run_config, trial) # build optuna trainer trainer, trainer_kwargs, results_path =",
"mode=\"max\", ) # if we use pruning, use the pytorch lightning pruning callback",
"trial): \"\"\" Returns a suggested value for the hyperparameter specified by 'name' from",
"results dir if results_path is not None: hparam_file = open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\") results_serializable",
"of sampler) e.g.{ \"type\" : \"suggest_categorical\", \"args\" : [[ 64, 128]] } \"\"\"",
"get_optuna_suggest(param_dict, name, trial): \"\"\" Returns a suggested value for the hyperparameter specified by",
"open(os.path.join(results_path, \"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close() # dump trainer args to results dir",
"\"w\") results_serializable = {k: float(v) for k, v in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close()",
"\"tpe\": sampler = optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"] == \"random\": sampler = optuna.samplers.RandomSampler() # create",
"metric specified by 'monitor_metric' in the run config all_scores = [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for",
"trial: optuna trial param_dict: dictionary containing information about the hyperparameter (range of values",
"node embeddings run_config[\"embedding_path\"] = os.path.join(task, \"atom_features.pth\") # create a tensorboard directory in the",
"# Our Methods from . import SubGNN as md from SubGNN import config",
"paths between all nodes in the graph run_config[\"subgraphs_path\"] = os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"] =",
"# resulting list will look something like this ['batch_size', [ 64, 128]] if",
"\"\"\" # get hyperparameters for the current trial hyperparameters = get_hyperparams_optuna(run_config, trial) #",
"return np.max(all_scores) else: return np.min(all_scores) def main(): \"\"\" Perform an optuna run according",
"in config file run_config = read_json(args.config_path) # Set paths to data task =",
"else 1, \"num_sanity_val_steps\": 0, \"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"], } # set auto learning",
"max (or min) metric specified by 'monitor_metric' in the run config \"\"\" #",
"= param_dict[\"type\"] # e.g. suggest_categorical, suggest_float args = [name] args.extend( param_dict[\"args\"] ) #",
"run_config[\"tb\"][\"dir\"] ) ntrials = run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials} Trials of optuna\") if run_config[\"optuna\"][\"pruning\"]: pruner",
"db_file = os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") # specify sampler if ( run_config[\"optuna\"][\"sampler\"] == \"grid\" and",
"handle: return commentjson.load(handle, object_hook=OrderedDict) def get_optuna_suggest(param_dict, name, trial): \"\"\" Returns a suggested value",
"\"atom_features.pth\") # create a tensorboard directory in the folder specified by dir in",
"parser = argparse.ArgumentParser(description=\"Learn subgraph embeddings\") parser.add_argument(\"-config_path\", type=str, default=None, help=\"Load config file\") args =",
"final hyperparameters Returns: hyp_fix - dictionary where key is the hyperparameter name (e.g.",
"run_config[\"data\"][\"task\"] # paths to subgraphs, edge list, and shortest paths between all nodes",
"os.makedirs(lgdir) logger = TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\" + str(random.randint(0, 10000000)), ) if not",
"specified in the run config Returns the max (or min) metric specified by",
"score in model.metric_scores ] if run_config[\"optuna\"][\"opt_direction\"] == \"maximize\": return np.max(all_scores) else: return np.min(all_scores)",
"OrderedDict # Pytorch import torch import pytorch_lightning as pl from pytorch_lightning.loggers import TensorBoardLogger",
"['batch_size', [ 64, 128]] if \"kwargs\" in param_dict: kwargs = dict(param_dict[\"kwargs\"]) return getattr(trial,",
"paths to data task = run_config[\"data\"][\"task\"] # paths to subgraphs, edge list, and",
"== \"maximize\": return np.max(all_scores) else: return np.min(all_scores) def main(): \"\"\" Perform an optuna",
"hyperparameter trial: optuna trial param_dict: dictionary containing information about the hyperparameter (range of",
"keep track of results Will load in # existing study if one exists",
"results dir hparam_file = open(os.path.join(results_path, \"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close() # dump trainer",
"as np import random import argparse import json import commentjson import joblib import",
"e.g. suggest_categorical, suggest_float args = [name] args.extend( param_dict[\"args\"] ) # resulting list will",
"list will look something like this ['batch_size', [ 64, 128]] if \"kwargs\" in",
"SubGNN from the hyperparameters specified in the run config \"\"\" # get hyperparameters",
"[\"logger\", \"profiler\", \"early_stop_callback\", \"checkpoint_callback\"] if key in trainer_kwargs.keys() ] [trainer_kwargs.pop(key) for key in",
"import TensorBoardLogger from pytorch_lightning.callbacks import ModelCheckpoint # Optuna import optuna from optuna.integration import",
"os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") # specify sampler if ( run_config[\"optuna\"][\"sampler\"] == \"grid\" and \"grid_search_space\" in",
"== \"tpe\": sampler = optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"] == \"random\": sampler = optuna.samplers.RandomSampler() #",
"direction=run_config[\"optuna\"][\"opt_direction\"], sampler=sampler, pruner=pruner, storage=\"sqlite:///\" + db_file, study_name=run_config[\"study_path\"], load_if_exists=True, ) study.optimize( lambda trial: train_model(run_config,",
"trial) # build optuna trainer trainer, trainer_kwargs, results_path = build_trainer( run_config, hyperparameters, trial",
"run config \"\"\" # get hyperparameters for the current trial hyperparameters = get_hyperparams_optuna(run_config,",
"\"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", ) # if we use pruning, use",
"if results_path is not None: hparam_file = open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\") results_serializable = {k:",
"64, 128]] if \"kwargs\" in param_dict: kwargs = dict(param_dict[\"kwargs\"]) return getattr(trial, module_name)(*args, **kwargs)",
"os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"] = os.path.join(task, \"ego_graphs.txt\") # directory where similarity calculations will be",
"torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # initialize SubGNN model =",
"import PyTorchLightningPruningCallback # Our Methods from . import SubGNN as md from SubGNN",
"in the json file specified by 'fname' \"\"\" with open(fname, \"rt\") as handle:",
"# specify sampler if ( run_config[\"optuna\"][\"sampler\"] == \"grid\" and \"grid_search_space\" in run_config[\"optuna\"] ):",
"\"trainer_kwargs.json\"), \"w\") pop_keys = [ key for key in [\"logger\", \"profiler\", \"early_stop_callback\", \"checkpoint_callback\"]",
"in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close() # train the model trainer.fit(model) # write results",
"\"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] = os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"] = os.path.join(task, \"ego_graphs.txt\") # directory where similarity",
"dict model, hyperparameters = build_model(run_config, trial) # build optuna trainer trainer, trainer_kwargs, results_path",
"True torch.backends.cudnn.benchmark = False # initialize SubGNN model = md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"],",
"run_config[\"similarities_path\"] = os.path.join(task, \"similarities/\") # get location of node embeddings run_config[\"embedding_path\"] = os.path.join(task,",
"\"rt\") as handle: return commentjson.load(handle, object_hook=OrderedDict) def get_optuna_suggest(param_dict, name, trial): \"\"\" Returns a",
"of results Will load in # existing study if one exists study =",
"None: hparam_file = open(os.path.join(results_path, \"final_metric_scores.json\"), \"w\") results_serializable = {k: float(v) for k, v",
"from SubGNN import config def parse_arguments(): \"\"\" Read in the config file specifying",
"load_if_exists=True, ) study.optimize( lambda trial: train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path = os.path.join(run_config[\"study_path\"],",
"dict(run_config[\"hyperparams_fix\"]) # update the dict with variable value hyperparameters by sampling a hyperparameter",
"= ModelCheckpoint( filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", ) # if",
"the pytorch lightning pruning callback if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] )",
"specified by 'monitor_metric' in the run config all_scores = [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score",
"parameters \"\"\" parser = argparse.ArgumentParser(description=\"Learn subgraph embeddings\") parser.add_argument(\"-config_path\", type=str, default=None, help=\"Load config file\")",
"(or min) metric specified by 'monitor_metric' in the run config \"\"\" # get",
"param_dict[\"type\"] # e.g. suggest_categorical, suggest_float args = [name] args.extend( param_dict[\"args\"] ) # resulting",
") ntrials = run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials} Trials of optuna\") if run_config[\"optuna\"][\"pruning\"]: pruner =",
") # dump hyperparameters to results dir hparam_file = open(os.path.join(results_path, \"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters,",
"hyperparameters, trial=None): \"\"\" Set up optuna trainer \"\"\" if \"progress_bar_refresh_rate\" in hyperparameters: p_refresh",
"look something like this ['batch_size', [ 64, 128]] if \"kwargs\" in param_dict: kwargs",
"build_model(run_config, trial) # build optuna trainer trainer, trainer_kwargs, results_path = build_trainer( run_config, hyperparameters,",
"pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) # get database file db_file = os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") # specify sampler",
"= optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"] == \"tpe\": sampler = optuna.samplers.TPESampler() elif run_config[\"optuna\"][\"sampler\"] == \"random\":",
"trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer = pl.Trainer(**trainer_kwargs) return trainer, trainer_kwargs, logger.log_dir",
"hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], ) return model, hyperparameters def",
"TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\" + str(random.randint(0, 10000000)), ) if not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard",
"trainer_kwargs, results_path = build_trainer( run_config, hyperparameters, trial ) # dump hyperparameters to results",
"logger = TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\" + str(random.randint(0, 10000000)), ) if not os.path.exists(logger.log_dir):",
"pruning callback if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer = pl.Trainer(**trainer_kwargs)",
"run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], ) return model, hyperparameters def build_trainer(run_config, hyperparameters,",
"# update the dict with variable value hyperparameters by sampling a hyperparameter #",
"hyperparameter name (e.g. batch_size) and value is the hyperparameter value \"\"\" # initialize",
"be stored run_config[\"similarities_path\"] = os.path.join(task, \"similarities/\") # get location of node embeddings run_config[\"embedding_path\"]",
"embeddings\") parser.add_argument(\"-config_path\", type=str, default=None, help=\"Load config file\") args = parser.parse_args() return args def",
"module_name)(*args, **kwargs) else: return getattr(trial, module_name)(*args) def get_hyperparams_optuna(run_config, trial): \"\"\" Converts the fixed",
"return hyp_fix def build_model(run_config, trial=None): \"\"\" Creates SubGNN from the hyperparameters specified in",
"the run config Returns the max (or min) metric specified by 'monitor_metric' in",
"# read in config file run_config = read_json(args.config_path) # Set paths to data",
"run_config[\"degree_sequence_path\"] = os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"] = os.path.join(task, \"ego_graphs.txt\") # directory where similarity calculations",
"similarity calculations will be stored run_config[\"similarities_path\"] = os.path.join(task, \"similarities/\") # get location of",
"file\") args = parser.parse_args() return args def read_json(fname): \"\"\" Read in the json",
"= os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] ) print(\"Logging to \", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) # get",
"= optuna.samplers.RandomSampler() # create an optuna study with the specified sampler, pruner, direction",
"by 'monitor_metric' in the run config all_scores = [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score in",
"'name' from the range of values in 'param_dict' name: string specifying hyperparameter trial:",
"def get_hyperparams_optuna(run_config, trial): \"\"\" Converts the fixed and variable hyperparameters in the run",
"all nodes in the graph run_config[\"subgraphs_path\"] = os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"] = os.path.join(task, \"edge_list.txt\")",
"pytorch_lightning.callbacks import ModelCheckpoint # Optuna import optuna from optuna.integration import PyTorchLightningPruningCallback # Our",
"ModelCheckpoint # Optuna import optuna from optuna.integration import PyTorchLightningPruningCallback # Our Methods from",
"# get model and hyperparameter dict model, hyperparameters = build_model(run_config, trial) # build",
"json import commentjson import joblib import os import pathlib from collections import OrderedDict",
"return np.min(all_scores) def main(): \"\"\" Perform an optuna run according to the hyperparameters",
"if not os.path.exists(logger.log_dir): os.makedirs(logger.log_dir) print(\"Tensorboard logging at \", logger.log_dir) trainer_kwargs[\"logger\"] = logger #",
"run_config[\"tb\"][\"name\"] ) print(\"Logging to \", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) # get database file db_file",
"= os.path.join(task, \"atom_features.pth\") # create a tensorboard directory in the folder specified by",
"the hyperparameter value \"\"\" # initialize the dict with the fixed hyperparameters hyp_fix",
"import torch import pytorch_lightning as pl from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbacks import",
". import SubGNN as md from SubGNN import config def parse_arguments(): \"\"\" Read",
"build_trainer( run_config, hyperparameters, trial ) # dump hyperparameters to results dir hparam_file =",
"v in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close() # return the max (or min) metric",
"an optuna study with the specified sampler, pruner, direction (e.g. # maximize) A",
"hyperparameters are specified in the run config Returns the max (or min) metric",
"to results dir hparam_file = open(os.path.join(results_path, \"hyperparams.json\"), \"w\") hparam_file.write(json.dumps(hyperparameters, indent=4)) hparam_file.close() # dump",
"in trainer_kwargs.keys() ] [trainer_kwargs.pop(key) for key in pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close() # train",
"pruner = optuna.pruners.MedianPruner() else: pruner = None # the complete study path is",
"0, \"progress_bar_refresh_rate\": p_refresh, \"gradient_clip_val\": hyperparameters[\"grad_clip\"], } # set auto learning rate finder param",
"will look something like this ['batch_size', [ 64, 128]] if \"kwargs\" in param_dict:",
"in run_config[\"tb\"] and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"] = os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"]",
"trial hyperparameters = get_hyperparams_optuna(run_config, trial) # Set seeds for reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"])",
"import pathlib from collections import OrderedDict # Pytorch import torch import pytorch_lightning as",
"Read in the json file specified by 'fname' \"\"\" with open(fname, \"rt\") as",
"of optuna\") if run_config[\"optuna\"][\"pruning\"]: pruner = optuna.pruners.MedianPruner() else: pruner = None # the",
"specifying all of the parameters \"\"\" parser = argparse.ArgumentParser(description=\"Learn subgraph embeddings\") parser.add_argument(\"-config_path\", type=str,",
"{k: float(v) for k, v in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close() # return the",
"{ k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial) for k in dict(run_config[\"hyperparams_optuna\"]).keys() } hyp_fix.update(hyp_optuna) return hyp_fix",
"the hyperparameters specified in the run config \"\"\" # get hyperparameters for the",
"sampling a hyperparameter # value from the range specified in the run_config hyp_optuna",
"run_config[\"tb\"][\"dir_full\"] = os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] ) ntrials = run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials} Trials of",
"run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"] ) print(\"Logging to \", run_config[\"study_path\"]) pathlib.Path(run_config[\"study_path\"]).mkdir(parents=True, exist_ok=True) # get database file",
"about the hyperparameter (range of values & type of sampler) e.g.{ \"type\" :",
"param_dict: kwargs = dict(param_dict[\"kwargs\"]) return getattr(trial, module_name)(*args, **kwargs) else: return getattr(trial, module_name)(*args) def",
"optuna.samplers.RandomSampler() # create an optuna study with the specified sampler, pruner, direction (e.g.",
"param_dict: dictionary containing information about the hyperparameter (range of values & type of",
"run_config[\"tb\"] and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"] = os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] )",
"of the final hyperparameters Returns: hyp_fix - dictionary where key is the hyperparameter",
"the run_config hyp_optuna = { k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k, trial) for k in dict(run_config[\"hyperparams_optuna\"]).keys()",
"hyp_fix.update(hyp_optuna) return hyp_fix def build_model(run_config, trial=None): \"\"\" Creates SubGNN from the hyperparameters specified",
"specified sampler, pruner, direction (e.g. # maximize) A SQLlite database is used to",
"def main(): \"\"\" Perform an optuna run according to the hyperparameters and directory",
"default=None, help=\"Load config file\") args = parser.parse_args() return args def read_json(fname): \"\"\" Read",
"hyperparameter (range of values & type of sampler) e.g.{ \"type\" : \"suggest_categorical\", \"args\"",
"help=\"Load config file\") args = parser.parse_args() return args def read_json(fname): \"\"\" Read in",
"directory where similarity calculations will be stored run_config[\"similarities_path\"] = os.path.join(task, \"similarities/\") # get",
"trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"], ) optuna_results_path = os.path.join(run_config[\"study_path\"], \"optuna_study.pkl\") print(\"Saving Study Results to\", optuna_results_path)",
"hyperparameters by sampling a hyperparameter # value from the range specified in the",
"# create a tensorboard directory in the folder specified by dir in the",
"file specified by 'fname' \"\"\" with open(fname, \"rt\") as handle: return commentjson.load(handle, object_hook=OrderedDict)",
"ROOT # folder if \"local\" in run_config[\"tb\"] and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"] else:",
"to the results dir if results_path is not None: hparam_file = open(os.path.join(results_path, \"final_metric_scores.json\"),",
"the dict with variable value hyperparameters by sampling a hyperparameter # value from",
"Returns the max (or min) metric specified by 'monitor_metric' in the run config",
"run_config[\"optuna\"][\"sampler\"] == \"random\": sampler = optuna.samplers.RandomSampler() # create an optuna study with the",
"args = parser.parse_args() return args def read_json(fname): \"\"\" Read in the json file",
"open(fname, \"rt\") as handle: return commentjson.load(handle, object_hook=OrderedDict) def get_optuna_suggest(param_dict, name, trial): \"\"\" Returns",
"module_name)(*args) def get_hyperparams_optuna(run_config, trial): \"\"\" Converts the fixed and variable hyperparameters in the",
"as md from SubGNN import config def parse_arguments(): \"\"\" Read in the config",
"name: string specifying hyperparameter trial: optuna trial param_dict: dictionary containing information about the",
"# folder if \"local\" in run_config[\"tb\"] and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"]",
"file db_file = os.path.join(run_config[\"study_path\"], \"optuna_study_sqlite.db\") # specify sampler if ( run_config[\"optuna\"][\"sampler\"] == \"grid\"",
"whose hyperparameters are specified in the run config Returns the max (or min)",
"optuna run according to the hyperparameters and directory locations specified in 'config_path' \"\"\"",
"\"\"\" torch.autograd.set_detect_anomaly(True) args = parse_arguments() # read in config file run_config = read_json(args.config_path)",
"train the model trainer.fit(model) # write results to the results dir if results_path",
"np import random import argparse import json import commentjson import joblib import os",
"= hyperparameters[\"auto_lr_find\"] # Create tensorboard logger lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if not os.path.exists(lgdir):",
"ModelCheckpoint( filepath=os.path.join( logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", ) # if we",
"tkwarg_file.close() # train the model trainer.fit(model) # write results to the results dir",
"( run_config[\"optuna\"][\"sampler\"] == \"grid\" and \"grid_search_space\" in run_config[\"optuna\"] ): sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif",
"print(\"Saving Study Results to\", optuna_results_path) joblib.dump(study, optuna_results_path) print(study.best_params) if __name__ == \"__main__\": main()",
"\"profiler\", \"early_stop_callback\", \"checkpoint_callback\"] if key in trainer_kwargs.keys() ] [trainer_kwargs.pop(key) for key in pop_keys]",
"False # initialize SubGNN model = md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"],",
"} hyp_fix.update(hyp_optuna) return hyp_fix def build_model(run_config, trial=None): \"\"\" Creates SubGNN from the hyperparameters",
") trainer = pl.Trainer(**trainer_kwargs) return trainer, trainer_kwargs, logger.log_dir def train_model(run_config, trial=None): \"\"\" Train",
"# initialize the dict with the fixed hyperparameters hyp_fix = dict(run_config[\"hyperparams_fix\"]) # update",
"pop_keys] tkwarg_file.write(json.dumps(trainer_kwargs, indent=4)) tkwarg_file.close() # train the model trainer.fit(model) # write results to",
"with the specified sampler, pruner, direction (e.g. # maximize) A SQLlite database is",
"# maximize) A SQLlite database is used to keep track of results Will",
"set epochs, gpus, gradient clipping, etc. # if 'no_gpu' in run config, then",
"model whose hyperparameters are specified in the run config Returns the max (or",
"Train a single model whose hyperparameters are specified in the run config Returns",
"trainer, trainer_kwargs, results_path = build_trainer( run_config, hyperparameters, trial ) # dump hyperparameters to",
"is the tensorboard directory + the study name run_config[\"study_path\"] = os.path.join( run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]",
"from the range specified in the run_config hyp_optuna = { k: get_optuna_suggest(run_config[\"hyperparams_optuna\"][k], k,",
"storage=\"sqlite:///\" + db_file, study_name=run_config[\"study_path\"], load_if_exists=True, ) study.optimize( lambda trial: train_model(run_config, trial), n_trials=run_config[\"optuna\"][\"opt_n_trials\"], n_jobs=run_config[\"optuna\"][\"opt_n_cores\"],",
"import joblib import os import pathlib from collections import OrderedDict # Pytorch import",
"run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], ) return model, hyperparameters def build_trainer(run_config, hyperparameters, trial=None):",
"64, 128]] } \"\"\" module_name = param_dict[\"type\"] # e.g. suggest_categorical, suggest_float args =",
"suggest_categorical, suggest_float args = [name] args.extend( param_dict[\"args\"] ) # resulting list will look",
"run_config[\"subgraphs_path\"] = os.path.join(task, \"subgraphs.pth\") run_config[\"graph_path\"] = os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"] = os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"]",
"= os.path.join(task, \"edge_list.txt\") run_config[\"shortest_paths_path\"] = os.path.join(task, \"shortest_path_matrix.npy\") run_config[\"degree_sequence_path\"] = os.path.join(task, \"degree_sequence.txt\") run_config[\"ego_graph_path\"] =",
"model = md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"], run_config[\"subgraphs_path\"], run_config[\"embedding_path\"], run_config[\"similarities_path\"], run_config[\"shortest_paths_path\"], run_config[\"degree_sequence_path\"], run_config[\"ego_graph_path\"], ) return",
"of the parameters \"\"\" parser = argparse.ArgumentParser(description=\"Learn subgraph embeddings\") parser.add_argument(\"-config_path\", type=str, default=None, help=\"Load",
"run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer = pl.Trainer(**trainer_kwargs) return trainer, trainer_kwargs,",
"from the hyperparameters specified in the run config \"\"\" # get hyperparameters for",
"string specifying hyperparameter trial: optuna trial param_dict: dictionary containing information about the hyperparameter",
"return args def read_json(fname): \"\"\" Read in the json file specified by 'fname'",
"commentjson.load(handle, object_hook=OrderedDict) def get_optuna_suggest(param_dict, name, trial): \"\"\" Returns a suggested value for the",
"rate finder param if \"auto_lr_find\" in hyperparameters and hyperparameters[\"auto_lr_find\"]: trainer_kwargs[\"auto_lr_find\"] = hyperparameters[\"auto_lr_find\"] #",
"= read_json(args.config_path) # Set paths to data task = run_config[\"data\"][\"task\"] # paths to",
"if 'no_gpu' in run config, then use CPU trainer_kwargs = { \"max_epochs\": hyperparameters[\"max_epochs\"],",
"pytorch lightning pruning callback if run_config[\"optuna\"][\"pruning\"]: trainer_kwargs[\"early_stop_callback\"] = PyTorchLightningPruningCallback( trial, monitor=run_config[\"optuna\"][\"monitor_metric\"] ) trainer",
"tkwarg_file = open(os.path.join(results_path, \"trainer_kwargs.json\"), \"w\") pop_keys = [ key for key in [\"logger\",",
"\"\"\" Creates SubGNN from the hyperparameters specified in the run config \"\"\" #",
"logger.log_dir, \"{epoch}-{val_micro_f1:.2f}-{val_acc:.2f}-{val_auroc:.2f}\" ), save_top_k=3, verbose=True, monitor=run_config[\"optuna\"][\"monitor_metric\"], mode=\"max\", ) # if we use pruning,",
"run_config[\"optuna\"][\"sampler\"] == \"grid\" and \"grid_search_space\" in run_config[\"optuna\"] ): sampler = optuna.samplers.GridSampler(run_config[\"optuna\"][\"grid_search_space\"]) elif run_config[\"optuna\"][\"sampler\"]",
"read in config file run_config = read_json(args.config_path) # Set paths to data task",
"folder if \"local\" in run_config[\"tb\"] and run_config[\"tb\"][\"local\"]: run_config[\"tb\"][\"dir_full\"] = run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"] =",
"hyperparameters[\"auto_lr_find\"] # Create tensorboard logger lgdir = os.path.join(run_config[\"tb\"][\"dir_full\"], run_config[\"tb\"][\"name\"]) if not os.path.exists(lgdir): os.makedirs(lgdir)",
"= get_hyperparams_optuna(run_config, trial) # Set seeds for reproducibility torch.manual_seed(hyperparameters[\"seed\"]) np.random.seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed(hyperparameters[\"seed\"]) torch.cuda.manual_seed_all(hyperparameters[\"seed\"]) torch.backends.cudnn.deterministic",
"config all_scores = [ score[run_config[\"optuna\"][\"monitor_metric\"]].numpy() for score in model.metric_scores ] if run_config[\"optuna\"][\"opt_direction\"] ==",
"optuna study with the specified sampler, pruner, direction (e.g. # maximize) A SQLlite",
"run_config[\"tb\"][\"dir\"] else: run_config[\"tb\"][\"dir_full\"] = os.path.join( config.PROJECT_ROOT, run_config[\"tb\"][\"dir\"] ) ntrials = run_config[\"optuna\"][\"opt_n_trials\"] print(f\"Running {ntrials}",
"the run config to a dictionary of the final hyperparameters Returns: hyp_fix -",
"are specified in the run config Returns the max (or min) metric specified",
"hyperparameters: p_refresh = hyperparameters[\"progress_bar_refresh_rate\"] else: p_refresh = 5 # set epochs, gpus, gradient",
"results_serializable = {k: float(v) for k, v in model.metric_scores[-1].items()} hparam_file.write(json.dumps(results_serializable, indent=4)) hparam_file.close() #",
"else: return getattr(trial, module_name)(*args) def get_hyperparams_optuna(run_config, trial): \"\"\" Converts the fixed and variable",
"trainer trainer, trainer_kwargs, results_path = build_trainer( run_config, hyperparameters, trial ) # dump hyperparameters",
"# set epochs, gpus, gradient clipping, etc. # if 'no_gpu' in run config,",
"[ key for key in [\"logger\", \"profiler\", \"early_stop_callback\", \"checkpoint_callback\"] if key in trainer_kwargs.keys()",
"the max (or min) metric specified by 'monitor_metric' in the run config \"\"\"",
"os.path.join(task, \"similarities/\") # get location of node embeddings run_config[\"embedding_path\"] = os.path.join(task, \"atom_features.pth\") #",
"{ \"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\": 0 if \"no_gpu\" in run_config else 1, \"num_sanity_val_steps\": 0,",
"= True torch.backends.cudnn.benchmark = False # initialize SubGNN model = md.SubGNN_Chem( hyperparameters, run_config[\"graph_path\"],",
"use CPU trainer_kwargs = { \"max_epochs\": hyperparameters[\"max_epochs\"], \"gpus\": 0 if \"no_gpu\" in run_config",
"os.path.exists(lgdir): os.makedirs(lgdir) logger = TensorBoardLogger( run_config[\"tb\"][\"dir_full\"], name=run_config[\"tb\"][\"name\"], version=\"version_\" + str(random.randint(0, 10000000)), ) if"
] |
[
"重新定义数据长度 #当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时 对其直接进行sum #1.每行128字节 #2.算出多少行 #3.reshape (行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with",
"第i次循环所应偏移的长度 with self.bp.if_scope(i < calc_loop_count - 1): calc_size.assign(process_count) with self.bp.else_scope(): calc_size.assign(total_count_in_core % process_count)",
"= temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def compute_body(self): one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\")",
"ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"to # permit persons to whom the Software is furnished to do so,",
"= self.bp.Scalar(dtype = bangpy.int32,name = \"col_count\",value = self.col_count) reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和",
"实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size], nram_buffer_in0[:calc_size]) # build a executable module f =",
"target, task_num): self.dtype = dtype self.target = target self.task_num = task_num self.bp =",
"to # the following conditions: # # The above copyright notice and this",
"WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"(the # \"Software\"), to deal in the Software without restriction, including # without",
"THE SOFTWARE. # pylint: disable=missing-docstring, invalid-name, too-many-locals \"\"\"A multi-platform code link example test",
"self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype, scope=\"global\" ) nram_buffer_in0 = self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\",",
"CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size = round_down( (TARGET(self.target).nram_size",
"self.bp.for_range(0,remain -1) as j: buffer[start_index] = buffer[start_index] + buffer[current_end_index + j +1] data_length.assign(data_length",
"the data in the two buffers. \"\"\" def __init__(self, dtype, target, task_num): self.dtype",
"1][current_col_index] with self.bp.if_scope(col_count >= count_for_128_align): reshape_buffer = temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count])",
"\"Software\"), to deal in the Software without restriction, including # without limitation the",
"test for BANGPy TCP.\"\"\" import numpy as np import bangpy from bangpy import",
"self.bp.Buffer( shape=(process_count,), name=\"test_buffer\", dtype=self.dtype, scope=\"nram\", ) calc_loop_count.assign((total_count_in_core + process_count - 1) // process_count)",
"of this software and associated documentation files (the # \"Software\"), to deal in",
"- i -1) with self.bp.for_range(0,row_count - 1) as j: buffer[0][current_col_index] = buffer[0][current_col_index] +",
"buffer_out = self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype, scope=\"global\" ) nram_buffer_in0 = self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\",",
"self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def compute_body(self): one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\") remain = self.bp.Scalar(bangpy.int32,\"remain\") current_core_start",
"= self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size =",
"end_index 结束索引 # 计算一维数组 start_index 至 end_index 范围内的和 并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index): data_length =",
"dtype self.target = target self.task_num = task_num self.bp = tcp.TCP(target) self.length = self.bp.SizeVar(\"length\")",
"= \"exp\" class Exp(object): \"\"\"Operator description: Add the data in the two buffers.",
"with self.bp.for_range(0,remain -1) as j: buffer[start_index] = buffer[start_index] + buffer[current_end_index + j +1]",
"self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index])",
"= tcp.TCP(target) self.length = self.bp.SizeVar(\"length\") self.nram_size = TARGET(target).nram_size self.dtype_sz = dtype.bytes self.col_count =",
"with self.bp.if_scope(current_end_index != 0): with self.bp.for_range(0,remain) as i: buffer[start_index] = buffer[start_index] + buffer[current_end_index",
"self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位 with self.bp.for_range(0,row_count) as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer",
"the Software, and to # permit persons to whom the Software is furnished",
"conditions: # # The above copyright notice and this permission notice shall be",
"#核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId < remain): #如果存在余数 将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count + 1) * self.bp.taskId",
"furnished to do so, subject to # the following conditions: # # The",
"# end_index 结束索引 # 计算一维数组 start_index 至 end_index 范围内的和 并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index): data_length",
"and this permission notice shall be included # in all copies or substantial",
"-1) as j: buffer[start_index] = buffer[start_index] + buffer[current_end_index + j +1] data_length.assign(data_length -",
"or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE",
"= self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain +1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain != 0):",
"self.col_count = self.bp.Var(\"col_count\") self.row_count = self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1, 1) # buffer 源数据 #",
"#当满足一次对齐时 对其直接进行sum #1.每行128字节 #2.算出多少行 #3.reshape (行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index])",
"#self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def compute_body(self): one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\") remain = self.bp.Scalar(bangpy.int32,\"remain\") current_core_start =",
"i: once_loop_start.assign(current_core_start + process_count * i) #当前核心数据开始的位置 + 第i次循环所应偏移的长度 with self.bp.if_scope(i < calc_loop_count",
"whom the Software is furnished to do so, subject to # the following",
"person obtaining a # copy of this software and associated documentation files (the",
"#self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count = self.bp.Scalar(dtype = bangpy.int32,name = \"row_count\",value = self.row_count) col_count =",
"NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"# without limitation the rights to use, copy, modify, merge, publish, # distribute,",
"IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"i] with self.bp.else_scope(): with self.bp.for_range(0,remain -1) as j: buffer[start_index] = buffer[start_index] + buffer[current_end_index",
"calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count = self.bp.Scalar(dtype = bangpy.int32,name = \"row_count\",value = self.row_count)",
"i: current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i -1) with self.bp.for_range(0,row_count - 1) as j:",
"= self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\")",
"OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS",
"# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, #",
"with self.bp.if_scope(col_remain != 0): with self.bp.for_range(0,col_remain) as i: current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i",
"dtype=self.dtype, scope=\"global\" ) nram_buffer_in0 = self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\", ) test_buffer =",
"+ one_core_count - 1) total_count_in_core.assign(current_core_end - current_core_start + 1) # buffer_in0 = self.bp.Buffer(",
"+1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain != 0): with self.bp.if_scope(current_end_index != 0):",
"Exp(object): \"\"\"Operator description: Add the data in the two buffers. \"\"\" def __init__(self,",
"- row_count 列数0 - col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz) #",
"nram_avable_size = round_down( (TARGET(self.target).nram_size - 30* 1024) // 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分)",
"nram_avable_size // self.dtype_sz #核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId < remain): #如果存在余数 将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count +",
"- 1): calc_size.assign(process_count) with self.bp.else_scope(): calc_size.assign(total_count_in_core % process_count) with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start +",
"Cambricon, Inc. # # Permission is hereby granted, free of charge, to any",
"once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size = round_down( (TARGET(self.target).nram_size - 30* 1024)",
"by Cambricon, Inc. # # Permission is hereby granted, free of charge, to",
"\"col_count\",value = self.col_count) reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算",
"and/or sell copies of the Software, and to # permit persons to whom",
"rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies",
"reshape_buffer = temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def compute_body(self): one_core_count =",
"+1] data_length.assign(data_length - remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时 对其直接进行sum #1.每行128字节 #2.算出多少行 #3.reshape (行,128字节数据个数)",
"1) # buffer 源数据 # start_index 起始索引 # end_index 结束索引 # 计算一维数组 start_index",
"j +1] data_length.assign(data_length - remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时 对其直接进行sum #1.每行128字节 #2.算出多少行 #3.reshape",
"BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN",
"limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or",
"row_count 列数0 - col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz) # 当前数据类型下",
"test_buffer = self.bp.Buffer( shape=(process_count,), name=\"test_buffer\", dtype=self.dtype, scope=\"nram\", ) calc_loop_count.assign((total_count_in_core + process_count - 1)",
"in UNION1 task_num = 1 #由4 改为64 f = Exp(dtype, target, task_num).compute_body() return",
"without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense,",
"current_core_end.assign((one_core_count + 1) * remain + one_core_count * (self.bp.taskId - remain) + one_core_count",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF #",
"# ) buffer_in0 = self.bp.Buffer( shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" ) buffer_out = self.bp.Buffer(",
"once_loop_start.assign(current_core_start + process_count * i) #当前核心数据开始的位置 + 第i次循环所应偏移的长度 with self.bp.if_scope(i < calc_loop_count -",
"modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and",
"# pylint: disable=missing-docstring, invalid-name, too-many-locals \"\"\"A multi-platform code link example test for BANGPy",
"i -1) with self.bp.for_range(0,row_count - 1) as j: buffer[0][current_col_index] = buffer[0][current_col_index] + buffer[j",
"ALIGN_LENGTH, TARGET from bangpy.tcp.runtime import TaskType from bangpy.tcp.util import round_up, round_down DTYPES =",
"count_for_128_align): reshape_buffer = temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def compute_body(self): one_core_count",
"round_down DTYPES = [bangpy.float32] TARGET_LIST = [\"mlu290\"] KERNEL_NAME = \"exp\" class Exp(object): \"\"\"Operator",
"- 1) total_count_in_core.assign(current_core_end - current_core_start + 1) # buffer_in0 = self.bp.Buffer( # shape=(self.length,),",
"= self.bp.SizeVar(\"length\") self.nram_size = TARGET(target).nram_size self.dtype_sz = dtype.bytes self.col_count = self.bp.Var(\"col_count\") self.row_count =",
"\"row_count\",value = self.row_count) col_count = self.bp.Scalar(dtype = bangpy.int32,name = \"col_count\",value = self.col_count) reshape_buffer",
"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"from bangpy.platform.bang_config import ALIGN_LENGTH, TARGET from bangpy.tcp.runtime import TaskType from bangpy.tcp.util import round_up,",
"name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\", ) test_buffer = self.bp.Buffer( shape=(process_count,), name=\"test_buffer\", dtype=self.dtype, scope=\"nram\", ) calc_loop_count.assign((total_count_in_core",
"self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位 with self.bp.for_range(0,row_count) as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据 #temp_buffer",
"KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"(33,33) #二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size], nram_buffer_in0[:calc_size]) #",
"disable=missing-docstring, invalid-name, too-many-locals \"\"\"A multi-platform code link example test for BANGPy TCP.\"\"\" import",
"in the two buffers. \"\"\" def __init__(self, dtype, target, task_num): self.dtype = dtype",
"f @tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME) def build_exp(dtype=None, target=None): # tasktype fixed in UNION1 task_num",
"# \"Software\"), to deal in the Software without restriction, including # without limitation",
"# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE",
"结果放在每行首位 with self.bp.for_range(0,row_count) as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count 行数 #col_count",
"self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\", ) test_buffer = self.bp.Buffer( shape=(process_count,), name=\"test_buffer\", dtype=self.dtype, scope=\"nram\",",
"with self.bp.for_range(0,row_count - 1) as j: buffer[0][current_col_index] = buffer[0][current_col_index] + buffer[j + 1][current_col_index]",
"1) #此处应该不需要减1 待验证 python切片会自动将上标减1 with self.bp.else_scope(): current_core_start.assign((one_core_count + 1) * remain + one_core_count",
"one_core_count * (self.bp.taskId - remain)) current_core_end.assign((one_core_count + 1) * remain + one_core_count *",
"with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) #",
"THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #",
"= [bangpy.float32] TARGET_LIST = [\"mlu290\"] KERNEL_NAME = \"exp\" class Exp(object): \"\"\"Operator description: Add",
"- current_core_start + 1) # buffer_in0 = self.bp.Buffer( # shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\"",
"in the Software without restriction, including # without limitation the rights to use,",
"#当前核心数据结束索引 total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\")",
"- 1) // process_count) with self.bp.for_range(0, calc_loop_count) as i: once_loop_start.assign(current_core_start + process_count *",
"= self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align) current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain) with self.bp.if_scope(col_remain != 0):",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT",
"KERNEL_NAME) def build_exp(dtype=None, target=None): # tasktype fixed in UNION1 task_num = 1 #由4",
"example test for BANGPy TCP.\"\"\" import numpy as np import bangpy from bangpy",
"# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT",
"too-many-locals \"\"\"A multi-platform code link example test for BANGPy TCP.\"\"\" import numpy as",
"+ 第i次循环所应偏移的长度 with self.bp.if_scope(i < calc_loop_count - 1): calc_size.assign(process_count) with self.bp.else_scope(): calc_size.assign(total_count_in_core %",
"= self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size = round_down( (TARGET(self.target).nram_size -",
"% process_count) with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start + calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count =",
"this software and associated documentation files (the # \"Software\"), to deal in the",
"1, 1) # buffer 源数据 # start_index 起始索引 # end_index 结束索引 # 计算一维数组",
") nram_buffer_in0 = self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\", ) test_buffer = self.bp.Buffer( shape=(process_count,),",
"row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位",
"nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size], nram_buffer_in0[:calc_size])",
"= self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size = round_down( (TARGET(self.target).nram_size - 30* 1024) //",
"scope=\"nram\", ) calc_loop_count.assign((total_count_in_core + process_count - 1) // process_count) with self.bp.for_range(0, calc_loop_count) as",
"two buffers. \"\"\" def __init__(self, dtype, target, task_num): self.dtype = dtype self.target =",
"0): with self.bp.for_range(0,remain) as i: buffer[start_index] = buffer[start_index] + buffer[current_end_index + i] with",
"with self.bp.if_scope(remain != 0): with self.bp.if_scope(current_end_index != 0): with self.bp.for_range(0,remain) as i: buffer[start_index]",
">= count_for_128_align): reshape_buffer = temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def compute_body(self):",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"# in all copies or substantial portions of the Software. # # THE",
"CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH",
"buffer[j + 1][current_col_index] with self.bp.if_scope(col_count >= count_for_128_align): reshape_buffer = temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,))",
"PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS",
"of the Software, and to # permit persons to whom the Software is",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT",
"THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR",
"i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count 行数 #col_count 列数 #该函数将计算传入的行数 0 -",
"=self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz) # 当前数据类型下 128个字节 对应了多少个元素 col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align) current_col_count",
"in all copies or substantial portions of the Software. # # THE SOFTWARE",
"OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION",
"范围内的和 并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index): data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index +1 )#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128",
"= self.row_count) col_count = self.bp.Scalar(dtype = bangpy.int32,name = \"col_count\",value = self.col_count) reshape_buffer =",
"def compute_body(self): one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\") remain = self.bp.Scalar(bangpy.int32,\"remain\") current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end",
"= self.bp.Scalar(bangpy.int32,\"one_core_count\") remain = self.bp.Scalar(bangpy.int32,\"remain\") current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引",
"TARGET from bangpy.tcp.runtime import TaskType from bangpy.tcp.util import round_up, round_down DTYPES = [bangpy.float32]",
"[bangpy.float32] TARGET_LIST = [\"mlu290\"] KERNEL_NAME = \"exp\" class Exp(object): \"\"\"Operator description: Add the",
"name=\"test_buffer\", dtype=self.dtype, scope=\"nram\", ) calc_loop_count.assign((total_count_in_core + process_count - 1) // process_count) with self.bp.for_range(0,",
"count_for_128_align) current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain) with self.bp.if_scope(col_remain != 0): with self.bp.for_range(0,col_remain) as",
"#当前核心数据开始索引 current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start =",
"0): with self.bp.for_range(0,col_remain) as i: current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i -1) with self.bp.for_range(0,row_count",
"__init__(self, dtype, target, task_num): self.dtype = dtype self.target = target self.task_num = task_num",
"buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位 with self.bp.for_range(0,row_count) as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1)",
"= self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index +1 )#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引 remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length",
"= round_down( (TARGET(self.target).nram_size - 30* 1024) // 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length",
"# shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" # ) buffer_in0 = self.bp.Buffer( shape=(self.length,), name=\"INPUT0\", dtype=self.dtype,",
"+ j +1] data_length.assign(data_length - remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时 对其直接进行sum #1.每行128字节 #2.算出多少行",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM,",
"shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" # ) buffer_in0 = self.bp.Buffer( shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\"",
"shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\", ) test_buffer = self.bp.Buffer( shape=(process_count,), name=\"test_buffer\", dtype=self.dtype, scope=\"nram\", )",
"# self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位 with self.bp.for_range(0,row_count) as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据",
"128个字节 对应了多少个元素 col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align) current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain) with",
"buffer_in0[once_loop_start:once_loop_start + calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count = self.bp.Scalar(dtype = bangpy.int32,name = \"row_count\",value",
"(self.bp.taskId + 1) - 1) #此处应该不需要减1 待验证 python切片会自动将上标减1 with self.bp.else_scope(): current_core_start.assign((one_core_count + 1)",
"bangpy from bangpy import tcp from bangpy.common import utils, load_op_by_type from bangpy.platform.bang_config import",
"def build_exp(dtype=None, target=None): # tasktype fixed in UNION1 task_num = 1 #由4 改为64",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE #",
"1) // process_count) with self.bp.for_range(0, calc_loop_count) as i: once_loop_start.assign(current_core_start + process_count * i)",
"= self.bp.Scalar(dtype = bangpy.int32,name = \"row_count\",value = self.row_count) col_count = self.bp.Scalar(dtype = bangpy.int32,name",
"= self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME, ) return f @tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME) def build_exp(dtype=None,",
"self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start + calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count = self.bp.Scalar(dtype = bangpy.int32,name",
"is hereby granted, free of charge, to any person obtaining a # copy",
"1) # buffer_in0 = self.bp.Buffer( # shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" # ) buffer_in0",
"self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count = self.bp.Scalar(dtype = bangpy.int32,name = \"row_count\",value = self.row_count) col_count",
"and to # permit persons to whom the Software is furnished to do",
"self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size = round_down(",
"TARGET(target).nram_size self.dtype_sz = dtype.bytes self.col_count = self.bp.Var(\"col_count\") self.row_count = self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1, 1)",
"col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz) # 当前数据类型下 128个字节 对应了多少个元素 col_remain",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING",
"is furnished to do so, subject to # the following conditions: # #",
"self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count 行数 #col_count 列数 #该函数将计算传入的行数 0 - row_count",
"并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index): data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index +1 )#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 //",
"self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain +1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上",
"the following conditions: # # The above copyright notice and this permission notice",
"nram_buffer_in0[:calc_size]) # build a executable module f = self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME, )",
"target self.task_num = task_num self.bp = tcp.TCP(target) self.length = self.bp.SizeVar(\"length\") self.nram_size = TARGET(target).nram_size",
"+ buffer[current_end_index + i] with self.bp.else_scope(): with self.bp.for_range(0,remain -1) as j: buffer[start_index] =",
"#self.bp.print(\"sumpool->\",buffer[start_index]) row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和",
"process_count) with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start + calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count = self.bp.Scalar(dtype",
"two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz) # 当前数据类型下 128个字节 对应了多少个元素 col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count %",
"charge, to any person obtaining a # copy of this software and associated",
"并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size], nram_buffer_in0[:calc_size]) # build a executable module f",
"= buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位 with self.bp.for_range(0,row_count) as i:",
"self.bp.if_scope(col_remain != 0): with self.bp.for_range(0,col_remain) as i: current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i -1)",
"dtype=self.dtype, scope=\"global\" ) buffer_out = self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype, scope=\"global\" ) nram_buffer_in0 =",
"当前数据类型下 128个字节 对应了多少个元素 col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align) current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain)",
"load_op_by_type from bangpy.platform.bang_config import ALIGN_LENGTH, TARGET from bangpy.tcp.runtime import TaskType from bangpy.tcp.util import",
"源数据 # start_index 起始索引 # end_index 结束索引 # 计算一维数组 start_index 至 end_index 范围内的和",
"remain + one_core_count * (self.bp.taskId - remain)) current_core_end.assign((one_core_count + 1) * remain +",
"tcp.TCP(target) self.length = self.bp.SizeVar(\"length\") self.nram_size = TARGET(target).nram_size self.dtype_sz = dtype.bytes self.col_count = self.bp.Var(\"col_count\")",
") buffer_in0 = self.bp.Buffer( shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" ) buffer_out = self.bp.Buffer( shape=(self.length,),",
"Inc. # # Permission is hereby granted, free of charge, to any person",
"TCP.\"\"\" import numpy as np import bangpy from bangpy import tcp from bangpy.common",
"reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位 with self.bp.for_range(0,row_count) as",
"self.bp.if_scope(remain != 0): with self.bp.if_scope(current_end_index != 0): with self.bp.for_range(0,remain) as i: buffer[start_index] =",
"= self.bp.Buffer( # shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" # ) buffer_in0 = self.bp.Buffer( shape=(self.length,),",
",128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length % self.task_num)#分任务时的余数 process_count = nram_avable_size // self.dtype_sz #核心一次最多计算的长度",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR",
"import round_up, round_down DTYPES = [bangpy.float32] TARGET_LIST = [\"mlu290\"] KERNEL_NAME = \"exp\" class",
"#将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain != 0): with self.bp.if_scope(current_end_index != 0): with self.bp.for_range(0,remain) as i:",
"(TARGET(self.target).nram_size - 30* 1024) // 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length % self.task_num)#分任务时的余数",
"# buffer 源数据 # start_index 起始索引 # end_index 结束索引 # 计算一维数组 start_index 至",
"#3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer =",
"process_count - 1) // process_count) with self.bp.for_range(0, calc_loop_count) as i: once_loop_start.assign(current_core_start + process_count",
"-1) row_count = self.bp.Scalar(dtype = bangpy.int32,name = \"row_count\",value = self.row_count) col_count = self.bp.Scalar(dtype",
"#row_count 行数 #col_count 列数 #该函数将计算传入的行数 0 - row_count 列数0 - col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def",
"self.bp.launch_task(self.task_num, 1, 1) # buffer 源数据 # start_index 起始索引 # end_index 结束索引 #",
"#二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size], nram_buffer_in0[:calc_size]) # build",
"[\"mlu290\"] KERNEL_NAME = \"exp\" class Exp(object): \"\"\"Operator description: Add the data in the",
"copy of this software and associated documentation files (the # \"Software\"), to deal",
"a executable module f = self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME, ) return f @tcp.register_mlu_op(DTYPES,",
"fixed in UNION1 task_num = 1 #由4 改为64 f = Exp(dtype, target, task_num).compute_body()",
"with self.bp.if_scope(col_count >= count_for_128_align): reshape_buffer = temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0])",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # pylint: disable=missing-docstring, invalid-name,",
"dtype, target, task_num): self.dtype = dtype self.target = target self.task_num = task_num self.bp",
"SOFTWARE. # pylint: disable=missing-docstring, invalid-name, too-many-locals \"\"\"A multi-platform code link example test for",
"self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i -1) with self.bp.for_range(0,row_count - 1) as j: buffer[0][current_col_index] = buffer[0][current_col_index]",
"self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size], nram_buffer_in0[:calc_size]) # build a executable module f = self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,],",
"self.row_count = self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1, 1) # buffer 源数据 # start_index 起始索引 #",
"# distribute, sublicense, and/or sell copies of the Software, and to # permit",
"the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell",
"- col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz) # 当前数据类型下 128个字节 对应了多少个元素",
"self.bp.if_scope(i < calc_loop_count - 1): calc_size.assign(process_count) with self.bp.else_scope(): calc_size.assign(total_count_in_core % process_count) with self.bp.block(\"data_copy\"):",
"as i: buffer[start_index] = buffer[start_index] + buffer[current_end_index + i] with self.bp.else_scope(): with self.bp.for_range(0,remain",
"+ buffer[current_end_index + j +1] data_length.assign(data_length - remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时 对其直接进行sum",
"\"exp\" class Exp(object): \"\"\"Operator description: Add the data in the two buffers. \"\"\"",
"+1 )#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引 remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index",
"scope=\"global\" # ) buffer_in0 = self.bp.Buffer( shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" ) buffer_out =",
"#col_count 列数 #该函数将计算传入的行数 0 - row_count 列数0 - col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align",
"+ 1) * self.bp.taskId ) current_core_end.assign((one_core_count + 1) * (self.bp.taskId + 1) -",
"self.bp.else_scope(): current_core_start.assign((one_core_count + 1) * remain + one_core_count * (self.bp.taskId - remain)) current_core_end.assign((one_core_count",
"from bangpy.tcp.util import round_up, round_down DTYPES = [bangpy.float32] TARGET_LIST = [\"mlu290\"] KERNEL_NAME =",
"(行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer",
"1) * (self.bp.taskId + 1) - 1) #此处应该不需要减1 待验证 python切片会自动将上标减1 with self.bp.else_scope(): current_core_start.assign((one_core_count",
"shape=(process_count,), name=\"test_buffer\", dtype=self.dtype, scope=\"nram\", ) calc_loop_count.assign((total_count_in_core + process_count - 1) // process_count) with",
"\"\"\"Operator description: Add the data in the two buffers. \"\"\" def __init__(self, dtype,",
"# tasktype fixed in UNION1 task_num = 1 #由4 改为64 f = Exp(dtype,",
"// self.dtype_sz #核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId < remain): #如果存在余数 将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count + 1)",
")#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引 remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index =",
"!= 0): with self.bp.for_range(0,col_remain) as i: current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i -1) with",
"dtype=self.dtype, scope=\"global\" # ) buffer_in0 = self.bp.Buffer( shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" ) buffer_out",
"不进行下面 #当满足一次对齐时 对其直接进行sum #1.每行128字节 #2.算出多少行 #3.reshape (行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64])",
"i: buffer[start_index] = buffer[start_index] + buffer[current_end_index + i] with self.bp.else_scope(): with self.bp.for_range(0,remain -1)",
"self.col_count) reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"(C) [2021] by Cambricon, Inc. # # Permission is hereby granted, free of",
"self.bp.Scalar(bangpy.int32,\"one_core_count\") remain = self.bp.Scalar(bangpy.int32,\"remain\") current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core",
"i) #当前核心数据开始的位置 + 第i次循环所应偏移的长度 with self.bp.if_scope(i < calc_loop_count - 1): calc_size.assign(process_count) with self.bp.else_scope():",
"process_count) with self.bp.for_range(0, calc_loop_count) as i: once_loop_start.assign(current_core_start + process_count * i) #当前核心数据开始的位置 +",
"self.bp.SizeVar(\"length\") self.nram_size = TARGET(target).nram_size self.dtype_sz = dtype.bytes self.col_count = self.bp.Var(\"col_count\") self.row_count = self.bp.Var(\"row_count\")",
"for BANGPy TCP.\"\"\" import numpy as np import bangpy from bangpy import tcp",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain != 0): with self.bp.if_scope(current_end_index != 0): with self.bp.for_range(0,remain) as",
"#当前核心数据开始的位置 + 第i次循环所应偏移的长度 with self.bp.if_scope(i < calc_loop_count - 1): calc_size.assign(process_count) with self.bp.else_scope(): calc_size.assign(total_count_in_core",
"with self.bp.if_scope(i < calc_loop_count - 1): calc_size.assign(process_count) with self.bp.else_scope(): calc_size.assign(total_count_in_core % process_count) with",
"round_down( (TARGET(self.target).nram_size - 30* 1024) // 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length %",
"= buffer[0][current_col_index] + buffer[j + 1][current_col_index] with self.bp.if_scope(col_count >= count_for_128_align): reshape_buffer = temp_buffer.reshape([row_count,current_col_count])",
"% self.task_num)#分任务时的余数 process_count = nram_avable_size // self.dtype_sz #核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId < remain): #如果存在余数",
"对应了多少个元素 col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align) current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain) with self.bp.if_scope(col_remain",
"-1) with self.bp.for_range(0,row_count - 1) as j: buffer[0][current_col_index] = buffer[0][current_col_index] + buffer[j +",
"(self.bp.taskId - remain) + one_core_count - 1) total_count_in_core.assign(current_core_end - current_core_start + 1) #",
"count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain +1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with",
"self.bp.for_range(0, calc_loop_count) as i: once_loop_start.assign(current_core_start + process_count * i) #当前核心数据开始的位置 + 第i次循环所应偏移的长度 with",
"to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of",
"with self.bp.if_scope(self.bp.taskId < remain): #如果存在余数 将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count + 1) * self.bp.taskId )",
"+1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain != 0): with self.bp.if_scope(current_end_index != 0): with self.bp.for_range(0,remain)",
"associated documentation files (the # \"Software\"), to deal in the Software without restriction,",
"#temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count 行数 #col_count 列数 #该函数将计算传入的行数 0 - row_count 列数0 - col_count的这个矩形范围内每列的和",
"calc_loop_count) as i: once_loop_start.assign(current_core_start + process_count * i) #当前核心数据开始的位置 + 第i次循环所应偏移的长度 with self.bp.if_scope(i",
"buffer_in0 = self.bp.Buffer( shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" ) buffer_out = self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\",",
"计算一维数组 start_index 至 end_index 范围内的和 并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index): data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index",
"+ calc_size], nram_buffer_in0[:calc_size]) # build a executable module f = self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out],",
"+ 1) * (self.bp.taskId + 1) - 1) #此处应该不需要减1 待验证 python切片会自动将上标减1 with self.bp.else_scope():",
"LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE",
"granted, free of charge, to any person obtaining a # copy of this",
"self.target = target self.task_num = task_num self.bp = tcp.TCP(target) self.length = self.bp.SizeVar(\"length\") self.nram_size",
"self.dtype_sz) # 当前数据类型下 128个字节 对应了多少个元素 col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align) current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count",
"self.task_num)#分任务时的余数 process_count = nram_avable_size // self.dtype_sz #核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId < remain): #如果存在余数 将其均摊给各核",
"% count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain +1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上",
"one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\") remain = self.bp.Scalar(bangpy.int32,\"remain\") current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\")",
"start_index 至 end_index 范围内的和 并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index): data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index +1",
"* (self.bp.taskId + 1) - 1) #此处应该不需要减1 待验证 python切片会自动将上标减1 with self.bp.else_scope(): current_core_start.assign((one_core_count +",
"count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz) # 当前数据类型下 128个字节 对应了多少个元素 col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align)",
"j: buffer[start_index] = buffer[start_index] + buffer[current_end_index + j +1] data_length.assign(data_length - remain)#刨除不足部分 重新定义数据长度",
"#如果存在余数 将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count + 1) * self.bp.taskId ) current_core_end.assign((one_core_count + 1) *",
"publish, # distribute, sublicense, and/or sell copies of the Software, and to #",
"one_dimensional_sum(self,buffer,start_index,end_index): data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index +1 )#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引 remain",
"name=\"OUTPUT\", dtype=self.dtype, scope=\"global\" ) nram_buffer_in0 = self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\", ) test_buffer",
"f = self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME, ) return f @tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME) def",
"% count_for_128_align) current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain) with self.bp.if_scope(col_remain != 0): with self.bp.for_range(0,col_remain)",
"nram_buffer_in0 = self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\", ) test_buffer = self.bp.Buffer( shape=(process_count,), name=\"test_buffer\",",
"= bangpy.int32,name = \"col_count\",value = self.col_count) reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题",
"self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index +1 )#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引 remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length %",
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING",
"+ 1) * remain + one_core_count * (self.bp.taskId - remain)) current_core_end.assign((one_core_count + 1)",
"data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index +1 )#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引 remain =",
"remain.assign(self.length % self.task_num)#分任务时的余数 process_count = nram_avable_size // self.dtype_sz #核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId < remain):",
"(self.bp.taskId - remain)) current_core_end.assign((one_core_count + 1) * remain + one_core_count * (self.bp.taskId -",
"* remain + one_core_count * (self.bp.taskId - remain) + one_core_count - 1) total_count_in_core.assign(current_core_end",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A",
"WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN",
"= self.bp.Buffer( shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" ) buffer_out = self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype,",
"distribute, sublicense, and/or sell copies of the Software, and to # permit persons",
"列数0 - col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz) # 当前数据类型下 128个字节",
"= nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size],",
"* (self.bp.taskId - remain) + one_core_count - 1) total_count_in_core.assign(current_core_end - current_core_start + 1)",
"self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行",
"be included # in all copies or substantial portions of the Software. #",
"obtaining a # copy of this software and associated documentation files (the #",
"AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE",
"#self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def compute_body(self): one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\") remain =",
"+ one_core_count * (self.bp.taskId - remain)) current_core_end.assign((one_core_count + 1) * remain + one_core_count",
"buffer[start_index] + buffer[current_end_index + j +1] data_length.assign(data_length - remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时",
"- remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时 对其直接进行sum #1.每行128字节 #2.算出多少行 #3.reshape (行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的",
"row_count = self.bp.Scalar(dtype = bangpy.int32,name = \"row_count\",value = self.row_count) col_count = self.bp.Scalar(dtype =",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS",
"shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" ) buffer_out = self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype, scope=\"global\" )",
"as i: once_loop_start.assign(current_core_start + process_count * i) #当前核心数据开始的位置 + 第i次循环所应偏移的长度 with self.bp.if_scope(i <",
"as j: buffer[start_index] = buffer[start_index] + buffer[current_end_index + j +1] data_length.assign(data_length - remain)#刨除不足部分",
"< calc_loop_count - 1): calc_size.assign(process_count) with self.bp.else_scope(): calc_size.assign(total_count_in_core % process_count) with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size],",
"including # without limitation the rights to use, copy, modify, merge, publish, #",
"+ one_core_count * (self.bp.taskId - remain) + one_core_count - 1) total_count_in_core.assign(current_core_end - current_core_start",
"EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM,",
"将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count + 1) * self.bp.taskId ) current_core_end.assign((one_core_count + 1) * (self.bp.taskId",
"scope=\"global\" ) nram_buffer_in0 = self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\", ) test_buffer = self.bp.Buffer(",
"- col_remain) with self.bp.if_scope(col_remain != 0): with self.bp.for_range(0,col_remain) as i: current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count",
"return f @tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME) def build_exp(dtype=None, target=None): # tasktype fixed in UNION1",
"与buffer所占内存空间大小相等的nram存储 #row_count 行数 #col_count 列数 #该函数将计算传入的行数 0 - row_count 列数0 - col_count的这个矩形范围内每列的和 并将结果写在源数据的首行",
"permission notice shall be included # in all copies or substantial portions of",
"buffer[start_index] = buffer[start_index] + buffer[current_end_index + i] with self.bp.else_scope(): with self.bp.for_range(0,remain -1) as",
"data_length.assign(data_length - remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时 对其直接进行sum #1.每行128字节 #2.算出多少行 #3.reshape (行,128字节数据个数) #3.对其sumpool",
"= self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype, scope=\"global\" ) nram_buffer_in0 = self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype,",
"NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY #",
"sublicense, and/or sell copies of the Software, and to # permit persons to",
"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL",
"name=\"INPUT0\", dtype=self.dtype, scope=\"global\" ) buffer_out = self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype, scope=\"global\" ) nram_buffer_in0",
"as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count 行数 #col_count 列数 #该函数将计算传入的行数 0",
"+ i] with self.bp.else_scope(): with self.bp.for_range(0,remain -1) as j: buffer[start_index] = buffer[start_index] +",
"self.bp.Scalar(dtype = bangpy.int32,name = \"row_count\",value = self.row_count) col_count = self.bp.Scalar(dtype = bangpy.int32,name =",
"// 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length % self.task_num)#分任务时的余数 process_count = nram_avable_size //",
"= bangpy.int32,name = \"row_count\",value = self.row_count) col_count = self.bp.Scalar(dtype = bangpy.int32,name = \"col_count\",value",
"col_count = self.bp.Scalar(dtype = bangpy.int32,name = \"col_count\",value = self.col_count) reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33)",
"# Permission is hereby granted, free of charge, to any person obtaining a",
"def __init__(self, dtype, target, task_num): self.dtype = dtype self.target = target self.task_num =",
"buffer[0][current_col_index] + buffer[j + 1][current_col_index] with self.bp.if_scope(col_count >= count_for_128_align): reshape_buffer = temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0])",
"this permission notice shall be included # in all copies or substantial portions",
"bangpy.int32,name = \"row_count\",value = self.row_count) col_count = self.bp.Scalar(dtype = bangpy.int32,name = \"col_count\",value =",
"remain +1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain != 0): with self.bp.if_scope(current_end_index !=",
"buffer[0][current_col_index] = buffer[0][current_col_index] + buffer[j + 1][current_col_index] with self.bp.if_scope(col_count >= count_for_128_align): reshape_buffer =",
"第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size], nram_buffer_in0[:calc_size]) # build a executable",
"and associated documentation files (the # \"Software\"), to deal in the Software without",
"from bangpy import tcp from bangpy.common import utils, load_op_by_type from bangpy.platform.bang_config import ALIGN_LENGTH,",
"bangpy import tcp from bangpy.common import utils, load_op_by_type from bangpy.platform.bang_config import ALIGN_LENGTH, TARGET",
"DEALINGS IN THE SOFTWARE. # pylint: disable=missing-docstring, invalid-name, too-many-locals \"\"\"A multi-platform code link",
"\"\"\" def __init__(self, dtype, target, task_num): self.dtype = dtype self.target = target self.task_num",
"- remain +1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain != 0): with self.bp.if_scope(current_end_index",
"self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size = round_down( (TARGET(self.target).nram_size - 30* 1024) // 2",
"<filename>bangpy-ops/ops/sum/sum.py<gh_stars>0 # Copyright (C) [2021] by Cambricon, Inc. # # Permission is hereby",
"# buffer_in0 = self.bp.Buffer( # shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" # ) buffer_in0 =",
"+ 1) * remain + one_core_count * (self.bp.taskId - remain) + one_core_count -",
"= self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain) with self.bp.if_scope(col_remain != 0): with self.bp.for_range(0,col_remain) as i: current_col_index",
"scope=\"nram\", ) test_buffer = self.bp.Buffer( shape=(process_count,), name=\"test_buffer\", dtype=self.dtype, scope=\"nram\", ) calc_loop_count.assign((total_count_in_core + process_count",
"so, subject to # the following conditions: # # The above copyright notice",
"notice and this permission notice shall be included # in all copies or",
"self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size =",
"+ 1) # buffer_in0 = self.bp.Buffer( # shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" # )",
"# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # pylint:",
"self.row_count) col_count = self.bp.Scalar(dtype = bangpy.int32,name = \"col_count\",value = self.col_count) reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])#",
"= \"col_count\",value = self.col_count) reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理",
"DTYPES = [bangpy.float32] TARGET_LIST = [\"mlu290\"] KERNEL_NAME = \"exp\" class Exp(object): \"\"\"Operator description:",
"persons to whom the Software is furnished to do so, subject to #",
"do so, subject to # the following conditions: # # The above copyright",
"compute_body(self): one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\") remain = self.bp.Scalar(bangpy.int32,\"remain\") current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end =",
"= self.bp.Scalar(bangpy.int32,\"remain\") current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\")",
"BANGPy TCP.\"\"\" import numpy as np import bangpy from bangpy import tcp from",
"remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时 对其直接进行sum #1.每行128字节 #2.算出多少行 #3.reshape (行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上",
"as np import bangpy from bangpy import tcp from bangpy.common import utils, load_op_by_type",
"np import bangpy from bangpy import tcp from bangpy.common import utils, load_op_by_type from",
"inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME, ) return f @tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME) def build_exp(dtype=None, target=None): #",
"task_num self.bp = tcp.TCP(target) self.length = self.bp.SizeVar(\"length\") self.nram_size = TARGET(target).nram_size self.dtype_sz = dtype.bytes",
"dtype.bytes self.col_count = self.bp.Var(\"col_count\") self.row_count = self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1, 1) # buffer 源数据",
"permit persons to whom the Software is furnished to do so, subject to",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT",
"self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start + calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count = self.bp.Scalar(dtype = bangpy.int32,name =",
"executable module f = self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME, ) return f @tcp.register_mlu_op(DTYPES, TARGET_LIST,",
"with self.bp.for_range(0,row_count) as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count 行数 #col_count 列数",
"j: buffer[0][current_col_index] = buffer[0][current_col_index] + buffer[j + 1][current_col_index] with self.bp.if_scope(col_count >= count_for_128_align): reshape_buffer",
"self.dtype = dtype self.target = target self.task_num = task_num self.bp = tcp.TCP(target) self.length",
"python切片会自动将上标减1 with self.bp.else_scope(): current_core_start.assign((one_core_count + 1) * remain + one_core_count * (self.bp.taskId -",
"import tcp from bangpy.common import utils, load_op_by_type from bangpy.platform.bang_config import ALIGN_LENGTH, TARGET from",
"use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the",
"# 当前数据类型下 128个字节 对应了多少个元素 col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align) current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count -",
"the Software without restriction, including # without limitation the rights to use, copy,",
"from bangpy.common import utils, load_op_by_type from bangpy.platform.bang_config import ALIGN_LENGTH, TARGET from bangpy.tcp.runtime import",
"BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR",
"remain)) current_core_end.assign((one_core_count + 1) * remain + one_core_count * (self.bp.taskId - remain) +",
"copies of the Software, and to # permit persons to whom the Software",
"1) * remain + one_core_count * (self.bp.taskId - remain)) current_core_end.assign((one_core_count + 1) *",
"self.bp.Scalar(bangpy.int32,\"remain\") current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count",
"import TaskType from bangpy.tcp.util import round_up, round_down DTYPES = [bangpy.float32] TARGET_LIST = [\"mlu290\"]",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER",
"two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位 with self.bp.for_range(0,row_count) as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR",
"= self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size",
"#2.算出多少行 #3.reshape (行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row =",
"ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain) with self.bp.if_scope(col_remain != 0): with self.bp.for_range(0,col_remain) as i: current_col_index =",
"* i) #当前核心数据开始的位置 + 第i次循环所应偏移的长度 with self.bp.if_scope(i < calc_loop_count - 1): calc_size.assign(process_count) with",
"target=None): # tasktype fixed in UNION1 task_num = 1 #由4 改为64 f =",
"= self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\", ) test_buffer = self.bp.Buffer( shape=(process_count,), name=\"test_buffer\", dtype=self.dtype,",
"files (the # \"Software\"), to deal in the Software without restriction, including #",
"bangpy.tcp.util import round_up, round_down DTYPES = [bangpy.float32] TARGET_LIST = [\"mlu290\"] KERNEL_NAME = \"exp\"",
"Software, and to # permit persons to whom the Software is furnished to",
"所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,))",
"UNION1 task_num = 1 #由4 改为64 f = Exp(dtype, target, task_num).compute_body() return f",
"self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def compute_body(self): one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\") remain = self.bp.Scalar(bangpy.int32,\"remain\")",
"IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF",
"one_core_count - 1) total_count_in_core.assign(current_core_end - current_core_start + 1) # buffer_in0 = self.bp.Buffer( #",
"Add the data in the two buffers. \"\"\" def __init__(self, dtype, target, task_num):",
"TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"with self.bp.for_range(0,col_remain) as i: current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i -1) with self.bp.for_range(0,row_count -",
"reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start +",
"with self.bp.for_range(0, calc_loop_count) as i: once_loop_start.assign(current_core_start + process_count * i) #当前核心数据开始的位置 + 第i次循环所应偏移的长度",
"#1.每行128字节 #2.算出多少行 #3.reshape (行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row",
"as j: buffer[0][current_col_index] = buffer[0][current_col_index] + buffer[j + 1][current_col_index] with self.bp.if_scope(col_count >= count_for_128_align):",
"col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align) current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain) with self.bp.if_scope(col_remain !=",
"to deal in the Software without restriction, including # without limitation the rights",
"remain): #如果存在余数 将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count + 1) * self.bp.taskId ) current_core_end.assign((one_core_count + 1)",
"bangpy.int32,name = \"col_count\",value = self.col_count) reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示",
"The above copyright notice and this permission notice shall be included # in",
"self.bp = tcp.TCP(target) self.length = self.bp.SizeVar(\"length\") self.nram_size = TARGET(target).nram_size self.dtype_sz = dtype.bytes self.col_count",
"module f = self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME, ) return f @tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME)",
"shall be included # in all copies or substantial portions of the Software.",
"link example test for BANGPy TCP.\"\"\" import numpy as np import bangpy from",
"# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"OTHER DEALINGS IN THE SOFTWARE. # pylint: disable=missing-docstring, invalid-name, too-many-locals \"\"\"A multi-platform code",
"bangpy.platform.bang_config import ALIGN_LENGTH, TARGET from bangpy.tcp.runtime import TaskType from bangpy.tcp.util import round_up, round_down",
"included # in all copies or substantial portions of the Software. # #",
"OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER",
"self.bp.Buffer( shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" ) buffer_out = self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype, scope=\"global\"",
"documentation files (the # \"Software\"), to deal in the Software without restriction, including",
") test_buffer = self.bp.Buffer( shape=(process_count,), name=\"test_buffer\", dtype=self.dtype, scope=\"nram\", ) calc_loop_count.assign((total_count_in_core + process_count -",
"结束索引 # 计算一维数组 start_index 至 end_index 范围内的和 并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index): data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index",
"TaskType from bangpy.tcp.util import round_up, round_down DTYPES = [bangpy.float32] TARGET_LIST = [\"mlu290\"] KERNEL_NAME",
"calc_size.assign(total_count_in_core % process_count) with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start + calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count",
"行数 #col_count 列数 #该函数将计算传入的行数 0 - row_count 列数0 - col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count):",
"self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME, ) return f @tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME) def build_exp(dtype=None, target=None):",
"free of charge, to any person obtaining a # copy of this software",
"current_core_end.assign((one_core_count + 1) * (self.bp.taskId + 1) - 1) #此处应该不需要减1 待验证 python切片会自动将上标减1 with",
"= task_num self.bp = tcp.TCP(target) self.length = self.bp.SizeVar(\"length\") self.nram_size = TARGET(target).nram_size self.dtype_sz =",
"end_index 范围内的和 并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index): data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index +1 )#传进来得数据长度 count_for_128_align",
"USE OR OTHER DEALINGS IN THE SOFTWARE. # pylint: disable=missing-docstring, invalid-name, too-many-locals \"\"\"A",
"# # The above copyright notice and this permission notice shall be included",
"- 1) #此处应该不需要减1 待验证 python切片会自动将上标减1 with self.bp.else_scope(): current_core_start.assign((one_core_count + 1) * remain +",
"ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"不足对齐得数据个数 current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain +1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain",
"self.bp.for_range(0,remain) as i: buffer[start_index] = buffer[start_index] + buffer[current_end_index + i] with self.bp.else_scope(): with",
") return f @tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME) def build_exp(dtype=None, target=None): # tasktype fixed in",
"1) * self.bp.taskId ) current_core_end.assign((one_core_count + 1) * (self.bp.taskId + 1) - 1)",
"- remain)) current_core_end.assign((one_core_count + 1) * remain + one_core_count * (self.bp.taskId - remain)",
"build a executable module f = self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME, ) return f",
"对其直接进行sum #1.每行128字节 #2.算出多少行 #3.reshape (行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index])",
"Permission is hereby granted, free of charge, to any person obtaining a #",
"< remain): #如果存在余数 将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count + 1) * self.bp.taskId ) current_core_end.assign((one_core_count +",
"from bangpy.tcp.runtime import TaskType from bangpy.tcp.util import round_up, round_down DTYPES = [bangpy.float32] TARGET_LIST",
"ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE",
"import ALIGN_LENGTH, TARGET from bangpy.tcp.runtime import TaskType from bangpy.tcp.util import round_up, round_down DTYPES",
"merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to",
"self.bp.Var(\"col_count\") self.row_count = self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1, 1) # buffer 源数据 # start_index 起始索引",
"bangpy.common import utils, load_op_by_type from bangpy.platform.bang_config import ALIGN_LENGTH, TARGET from bangpy.tcp.runtime import TaskType",
"OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR",
"self.bp.if_scope(self.bp.taskId < remain): #如果存在余数 将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count + 1) * self.bp.taskId ) current_core_end.assign((one_core_count",
"self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size], nram_buffer_in0[:calc_size]) # build a executable module f = self.bp.BuildBANG(",
"data in the two buffers. \"\"\" def __init__(self, dtype, target, task_num): self.dtype =",
"因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align])",
"Software is furnished to do so, subject to # the following conditions: #",
"= buffer[start_index] + buffer[current_end_index + j +1] data_length.assign(data_length - remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时 不进行下面",
"the Software is furnished to do so, subject to # the following conditions:",
"列数 #该函数将计算传入的行数 0 - row_count 列数0 - col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128",
"self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align) current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain) with self.bp.if_scope(col_remain != 0): with",
"# copy of this software and associated documentation files (the # \"Software\"), to",
"!= 0): with self.bp.for_range(0,remain) as i: buffer[start_index] = buffer[start_index] + buffer[current_end_index + i]",
"= dtype self.target = target self.task_num = task_num self.bp = tcp.TCP(target) self.length =",
"#buffer 源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count 行数 #col_count 列数 #该函数将计算传入的行数 0 - row_count 列数0",
"buffers. \"\"\" def __init__(self, dtype, target, task_num): self.dtype = dtype self.target = target",
"- 1) as j: buffer[0][current_col_index] = buffer[0][current_col_index] + buffer[j + 1][current_col_index] with self.bp.if_scope(col_count",
"total_count_in_core.assign(current_core_end - current_core_start + 1) # buffer_in0 = self.bp.Buffer( # shape=(self.length,), name=\"INPUT0\", dtype=self.dtype,",
"start_index +1 )#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引 remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后 不足对齐得数据个数",
"numpy as np import bangpy from bangpy import tcp from bangpy.common import utils,",
"= [\"mlu290\"] KERNEL_NAME = \"exp\" class Exp(object): \"\"\"Operator description: Add the data in",
"此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size], nram_buffer_in0[:calc_size]) # build a executable module",
"tasktype fixed in UNION1 task_num = 1 #由4 改为64 f = Exp(dtype, target,",
"hereby granted, free of charge, to any person obtaining a # copy of",
"# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY,",
"OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE,",
"self.dtype_sz = dtype.bytes self.col_count = self.bp.Var(\"col_count\") self.row_count = self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1, 1) #",
"剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain != 0): with self.bp.if_scope(current_end_index != 0): with",
"taskId从0起 current_core_start.assign((one_core_count + 1) * self.bp.taskId ) current_core_end.assign((one_core_count + 1) * (self.bp.taskId +",
"count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引 remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index",
"tcp from bangpy.common import utils, load_op_by_type from bangpy.platform.bang_config import ALIGN_LENGTH, TARGET from bangpy.tcp.runtime",
"Copyright (C) [2021] by Cambricon, Inc. # # Permission is hereby granted, free",
"one_core_count * (self.bp.taskId - remain) + one_core_count - 1) total_count_in_core.assign(current_core_end - current_core_start +",
"buffer[current_end_index + j +1] data_length.assign(data_length - remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时 对其直接进行sum #1.每行128字节",
"current_core_start + 1) # buffer_in0 = self.bp.Buffer( # shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" #",
"self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain +1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain != 0): with",
"+ calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count = self.bp.Scalar(dtype = bangpy.int32,name = \"row_count\",value =",
"* (self.bp.taskId - remain)) current_core_end.assign((one_core_count + 1) * remain + one_core_count * (self.bp.taskId",
"# start_index 起始索引 # end_index 结束索引 # 计算一维数组 start_index 至 end_index 范围内的和 并将结果写在start_index除",
"current_col_count = self.bp.Scalar(bangpy.int32,\"current_col_count\",col_count - col_remain) with self.bp.if_scope(col_remain != 0): with self.bp.for_range(0,col_remain) as i:",
"+ buffer[j + 1][current_col_index] with self.bp.if_scope(col_count >= count_for_128_align): reshape_buffer = temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count])",
"- remain) + one_core_count - 1) total_count_in_core.assign(current_core_end - current_core_start + 1) # buffer_in0",
"any person obtaining a # copy of this software and associated documentation files",
"1) * remain + one_core_count * (self.bp.taskId - remain) + one_core_count - 1)",
"// process_count) with self.bp.for_range(0, calc_loop_count) as i: once_loop_start.assign(current_core_start + process_count * i) #当前核心数据开始的位置",
"utils, load_op_by_type from bangpy.platform.bang_config import ALIGN_LENGTH, TARGET from bangpy.tcp.runtime import TaskType from bangpy.tcp.util",
"copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software,",
"* self.bp.taskId ) current_core_end.assign((one_core_count + 1) * (self.bp.taskId + 1) - 1) #此处应该不需要减1",
"HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN",
"# Copyright (C) [2021] by Cambricon, Inc. # # Permission is hereby granted,",
"WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT",
"= self.bp.Var(\"col_count\") self.row_count = self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1, 1) # buffer 源数据 # start_index",
"self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def compute_body(self): one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\") remain = self.bp.Scalar(bangpy.int32,\"remain\") current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\")",
"+ process_count * i) #当前核心数据开始的位置 + 第i次循环所应偏移的长度 with self.bp.if_scope(i < calc_loop_count - 1):",
"= buffer[start_index] + buffer[current_end_index + i] with self.bp.else_scope(): with self.bp.for_range(0,remain -1) as j:",
"copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY,",
"as i: current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i -1) with self.bp.for_range(0,row_count - 1) as",
"multi-platform code link example test for BANGPy TCP.\"\"\" import numpy as np import",
"current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count =",
"process_count = nram_avable_size // self.dtype_sz #核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId < remain): #如果存在余数 将其均摊给各核 taskId从0起",
"task_num): self.dtype = dtype self.target = target self.task_num = task_num self.bp = tcp.TCP(target)",
"buffer[start_index] = buffer[start_index] + buffer[current_end_index + j +1] data_length.assign(data_length - remain)#刨除不足部分 重新定义数据长度 #当数据长度不足一次对齐时",
"def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz) # 当前数据类型下 128个字节 对应了多少个元素 col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count",
"SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES",
"portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"= \"row_count\",value = self.row_count) col_count = self.bp.Scalar(dtype = bangpy.int32,name = \"col_count\",value = self.col_count)",
"build_exp(dtype=None, target=None): # tasktype fixed in UNION1 task_num = 1 #由4 改为64 f",
"outputs=[buffer_out], kernel_name=KERNEL_NAME, ) return f @tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME) def build_exp(dtype=None, target=None): # tasktype",
"current_core_start.assign((one_core_count + 1) * self.bp.taskId ) current_core_end.assign((one_core_count + 1) * (self.bp.taskId + 1)",
"def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位 with self.bp.for_range(0,row_count) as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储",
") buffer_out = self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype, scope=\"global\" ) nram_buffer_in0 = self.bp.Buffer( shape=(process_count,),",
"1) as j: buffer[0][current_col_index] = buffer[0][current_col_index] + buffer[j + 1][current_col_index] with self.bp.if_scope(col_count >=",
"[2021] by Cambricon, Inc. # # Permission is hereby granted, free of charge,",
"#该函数将计算传入的行数 0 - row_count 列数0 - col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 //",
"self.bp.if_scope(current_end_index != 0): with self.bp.for_range(0,remain) as i: buffer[start_index] = buffer[start_index] + buffer[current_end_index +",
"self.bp.Buffer( # shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" # ) buffer_in0 = self.bp.Buffer( shape=(self.length,), name=\"INPUT0\",",
"invalid-name, too-many-locals \"\"\"A multi-platform code link example test for BANGPy TCP.\"\"\" import numpy",
"+ 1) - 1) #此处应该不需要减1 待验证 python切片会自动将上标减1 with self.bp.else_scope(): current_core_start.assign((one_core_count + 1) *",
"current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i -1) with self.bp.for_range(0,row_count - 1) as j: buffer[0][current_col_index]",
"1) total_count_in_core.assign(current_core_end - current_core_start + 1) # buffer_in0 = self.bp.Buffer( # shape=(self.length,), name=\"INPUT0\",",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # pylint: disable=missing-docstring,",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED",
"round_up, round_down DTYPES = [bangpy.float32] TARGET_LIST = [\"mlu290\"] KERNEL_NAME = \"exp\" class Exp(object):",
"process_count * i) #当前核心数据开始的位置 + 第i次循环所应偏移的长度 with self.bp.if_scope(i < calc_loop_count - 1): calc_size.assign(process_count)",
"#3.reshape (行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align): self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align)",
"notice shall be included # in all copies or substantial portions of the",
"self.bp.else_scope(): with self.bp.for_range(0,remain -1) as j: buffer[start_index] = buffer[start_index] + buffer[current_end_index + j",
"self.bp.taskId ) current_core_end.assign((one_core_count + 1) * (self.bp.taskId + 1) - 1) #此处应该不需要减1 待验证",
"temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def compute_body(self): one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\") remain",
"\"\"\"A multi-platform code link example test for BANGPy TCP.\"\"\" import numpy as np",
"WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"buffer 源数据 # start_index 起始索引 # end_index 结束索引 # 计算一维数组 start_index 至 end_index",
"of charge, to any person obtaining a # copy of this software and",
"self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size = round_down( (TARGET(self.target).nram_size - 30*",
"calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size = round_down( (TARGET(self.target).nram_size - 30* 1024) // 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\")",
"calc_loop_count - 1): calc_size.assign(process_count) with self.bp.else_scope(): calc_size.assign(total_count_in_core % process_count) with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start",
"self.nram_size = TARGET(target).nram_size self.dtype_sz = dtype.bytes self.col_count = self.bp.Var(\"col_count\") self.row_count = self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num,",
"=self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引 remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index -",
"remain + one_core_count * (self.bp.taskId - remain) + one_core_count - 1) total_count_in_core.assign(current_core_end -",
"self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1, 1) # buffer 源数据 # start_index 起始索引 # end_index 结束索引",
"self.bp.for_range(0,col_remain) as i: current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i -1) with self.bp.for_range(0,row_count - 1)",
"to do so, subject to # the following conditions: # # The above",
"- start_index +1 )#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引 remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后",
"substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"TARGET_LIST = [\"mlu290\"] KERNEL_NAME = \"exp\" class Exp(object): \"\"\"Operator description: Add the data",
"restriction, including # without limitation the rights to use, copy, modify, merge, publish,",
"class Exp(object): \"\"\"Operator description: Add the data in the two buffers. \"\"\" def",
"= TARGET(target).nram_size self.dtype_sz = dtype.bytes self.col_count = self.bp.Var(\"col_count\") self.row_count = self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1,",
"OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"self.bp.print(buffer[0:64]) self.bp.sum(buffer[start_index:current_end_index],buffer[start_index:current_end_index]) #self.bp.print(\"sumpool->\",buffer[start_index]) row = self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index]) def",
"LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION",
"import bangpy from bangpy import tcp from bangpy.common import utils, load_op_by_type from bangpy.platform.bang_config",
"calc_size], nram_buffer_in0[:calc_size]) # build a executable module f = self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME,",
"without restriction, including # without limitation the rights to use, copy, modify, merge,",
"buffer[start_index] + buffer[current_end_index + i] with self.bp.else_scope(): with self.bp.for_range(0,remain -1) as j: buffer[start_index]",
"@tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME) def build_exp(dtype=None, target=None): # tasktype fixed in UNION1 task_num =",
"self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start",
"buffer[current_end_index + i] with self.bp.else_scope(): with self.bp.for_range(0,remain -1) as j: buffer[start_index] = buffer[start_index]",
"with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start + calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1) row_count = self.bp.Scalar(dtype =",
"# # Permission is hereby granted, free of charge, to any person obtaining",
"all copies or substantial portions of the Software. # # THE SOFTWARE IS",
") current_core_end.assign((one_core_count + 1) * (self.bp.taskId + 1) - 1) #此处应该不需要减1 待验证 python切片会自动将上标减1",
"current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\")",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED,",
"deal in the Software without restriction, including # without limitation the rights to",
"= self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count - i -1) with self.bp.for_range(0,row_count - 1) as j: buffer[0][current_col_index] =",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS #",
"self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size = round_down( (TARGET(self.target).nram_size - 30* 1024) // 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length //",
"= self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size = round_down( (TARGET(self.target).nram_size - 30* 1024) // 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length",
"待验证 python切片会自动将上标减1 with self.bp.else_scope(): current_core_start.assign((one_core_count + 1) * remain + one_core_count * (self.bp.taskId",
"= self.col_count) reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和 #此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count)",
"源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count 行数 #col_count 列数 #该函数将计算传入的行数 0 - row_count 列数0 -",
"OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR",
"def one_dimensional_sum(self,buffer,start_index,end_index): data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index +1 )#传进来得数据长度 count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)#128字节是几个占几个索引",
"1): calc_size.assign(process_count) with self.bp.else_scope(): calc_size.assign(total_count_in_core % process_count) with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start + calc_size])",
"// self.dtype_sz)#128字节是几个占几个索引 remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain",
"# The above copyright notice and this permission notice shall be included #",
"OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO",
"OR OTHER DEALINGS IN THE SOFTWARE. # pylint: disable=missing-docstring, invalid-name, too-many-locals \"\"\"A multi-platform",
"起始索引 # end_index 结束索引 # 计算一维数组 start_index 至 end_index 范围内的和 并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index):",
"TARGET_LIST, KERNEL_NAME) def build_exp(dtype=None, target=None): # tasktype fixed in UNION1 task_num = 1",
"self.bp.Scalar(dtype = bangpy.int32,name = \"col_count\",value = self.col_count) reshape_buffer = nram_buffer_in0[0:calc_size].reshape([row_count,col_count])# (33,33) #二维数组按列求和 #此处需注意",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length % self.task_num)#分任务时的余数 process_count = nram_avable_size // self.dtype_sz #核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId <",
"the two buffers. \"\"\" def __init__(self, dtype, target, task_num): self.dtype = dtype self.target",
"pylint: disable=missing-docstring, invalid-name, too-many-locals \"\"\"A multi-platform code link example test for BANGPy TCP.\"\"\"",
"bangpy.tcp.runtime import TaskType from bangpy.tcp.util import round_up, round_down DTYPES = [bangpy.float32] TARGET_LIST =",
"self.dtype_sz)#128字节是几个占几个索引 remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain +1)#刨去不足后",
"self.dtype_sz #核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId < remain): #如果存在余数 将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count + 1) *",
"0 - row_count 列数0 - col_count的这个矩形范围内每列的和 并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz)",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE",
"Software without restriction, including # without limitation the rights to use, copy, modify,",
"shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype, scope=\"global\" ) nram_buffer_in0 = self.bp.Buffer( shape=(process_count,), name=\"GALA_IN\", dtype=self.dtype, scope=\"nram\", )",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. # pylint: disable=missing-docstring, invalid-name, too-many-locals",
"# 计算一维数组 start_index 至 end_index 范围内的和 并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index): data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index -",
"remain) + one_core_count - 1) total_count_in_core.assign(current_core_end - current_core_start + 1) # buffer_in0 =",
"self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位 with self.bp.for_range(0,row_count)",
"import numpy as np import bangpy from bangpy import tcp from bangpy.common import",
"self.bp.else_scope(): calc_size.assign(total_count_in_core % process_count) with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start + calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size -1)",
"sell copies of the Software, and to # permit persons to whom the",
"= dtype.bytes self.col_count = self.bp.Var(\"col_count\") self.row_count = self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1, 1) # buffer",
"self.bp.if_scope(col_count >= count_for_128_align): reshape_buffer = temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0]) self.bp.memcpy(buffer[0][0:current_col_count],reshape_buffer[0][0:current_col_count]) #self.bp.print(\"data_res->\",buffer[0]) def",
"following conditions: # # The above copyright notice and this permission notice shall",
"calc_size.assign(process_count) with self.bp.else_scope(): calc_size.assign(total_count_in_core % process_count) with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start + calc_size]) self.bp.print(\"calc_size-->\",calc_size)",
"kernel_name=KERNEL_NAME, ) return f @tcp.register_mlu_op(DTYPES, TARGET_LIST, KERNEL_NAME) def build_exp(dtype=None, target=None): # tasktype fixed",
"并将结果写在源数据的首行 def two_dimension_col_sum(self,buffer,temp_buffer,row_count,col_count): count_for_128_align =self.bp.Scalar(bangpy.int32,\"count_for_128_align\",128 // self.dtype_sz) # 当前数据类型下 128个字节 对应了多少个元素 col_remain =",
"#self.bp.print(\"data_res->\",buffer[0]) def compute_body(self): one_core_count = self.bp.Scalar(bangpy.int32,\"one_core_count\") remain = self.bp.Scalar(bangpy.int32,\"remain\") current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引",
"total_count_in_core = self.bp.Scalar(bangpy.int32,\"total_count_in_core\") calc_loop_count = self.bp.Scalar(bangpy.int32,\"calc_loop_count\") once_loop_start = self.bp.Scalar(bangpy.int32,\"once_loop_start\") calc_size = self.bp.Scalar(bangpy.int32,\"calc_size\") nram_avable_size",
"+ process_count - 1) // process_count) with self.bp.for_range(0, calc_loop_count) as i: once_loop_start.assign(current_core_start +",
"with self.bp.for_range(0,remain) as i: buffer[start_index] = buffer[start_index] + buffer[current_end_index + i] with self.bp.else_scope():",
"subject to # the following conditions: # # The above copyright notice and",
"# the following conditions: # # The above copyright notice and this permission",
"计算二维数组每行的和 结果放在每行首位 with self.bp.for_range(0,row_count) as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count 行数",
"one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length % self.task_num)#分任务时的余数 process_count = nram_avable_size // self.dtype_sz #核心一次最多计算的长度 with",
"#此处需注意 第二个buffer参数上标索引越界的问题 此处只是展示 并未进行处理 实际使用时应以每次传入函数数据的实际尺寸计算 self.two_dimension_col_sum(reshape_buffer,test_buffer[0:row_count*col_count],row_count,col_count) self.bp.memcpy(buffer_out[once_loop_start:once_loop_start + calc_size], nram_buffer_in0[:calc_size]) # build a",
"buffer_in0 = self.bp.Buffer( # shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" # ) buffer_in0 = self.bp.Buffer(",
"current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain +1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1 这里图省事就直接加上 #将末尾不能对齐的部分循环加到第一个元素上 with self.bp.if_scope(remain !=",
"remain = self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain +1)#刨去不足后 剩余可以对齐长度得末尾索引",
"with self.bp.else_scope(): calc_size.assign(total_count_in_core % process_count) with self.bp.block(\"data_copy\"): self.bp.memcpy(nram_buffer_in0[0:calc_size], buffer_in0[once_loop_start:once_loop_start + calc_size]) self.bp.print(\"calc_size-->\",calc_size) #self.one_dimensional_sum(nram_buffer_in0,0,calc_size",
"!= 0): with self.bp.if_scope(current_end_index != 0): with self.bp.for_range(0,remain) as i: buffer[start_index] = buffer[start_index]",
"col_remain) with self.bp.if_scope(col_remain != 0): with self.bp.for_range(0,col_remain) as i: current_col_index = self.bp.Scalar(bangpy.int32,\"current_col_index\",col_count -",
"THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. #",
"# permit persons to whom the Software is furnished to do so, subject",
"DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR",
"+ 1][current_col_index] with self.bp.if_scope(col_count >= count_for_128_align): reshape_buffer = temp_buffer.reshape([row_count,current_col_count]) #self.bp.print(\"data_before_calc->\",buffer[0]) self.bp.memcpy(reshape_buffer[:,:],buffer[:,0:current_col_count]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row_count,),(1,)) #self.bp.print(\"temp_after_calc->\",reshape_buffer[0])",
"dtype=self.dtype, scope=\"nram\", ) test_buffer = self.bp.Buffer( shape=(process_count,), name=\"test_buffer\", dtype=self.dtype, scope=\"nram\", ) calc_loop_count.assign((total_count_in_core +",
"#此处应该不需要减1 待验证 python切片会自动将上标减1 with self.bp.else_scope(): current_core_start.assign((one_core_count + 1) * remain + one_core_count *",
"a # copy of this software and associated documentation files (the # \"Software\"),",
"30* 1024) // 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length % self.task_num)#分任务时的余数 process_count =",
"// self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length % self.task_num)#分任务时的余数 process_count = nram_avable_size // self.dtype_sz #核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId",
"1) - 1) #此处应该不需要减1 待验证 python切片会自动将上标减1 with self.bp.else_scope(): current_core_start.assign((one_core_count + 1) * remain",
"* remain + one_core_count * (self.bp.taskId - remain)) current_core_end.assign((one_core_count + 1) * remain",
"copyright notice and this permission notice shall be included # in all copies",
"= self.bp.Scalar(bangpy.int32,\"remain\",data_length % count_for_128_align)#128对齐后 不足对齐得数据个数 current_end_index = self.bp.Scalar(bangpy.int32,\"current_end_index\",end_index - remain +1)#刨去不足后 剩余可以对齐长度得末尾索引 +1是因为python数组切片语法[a:b]会对b自动-1",
"description: Add the data in the two buffers. \"\"\" def __init__(self, dtype, target,",
"self.length = self.bp.SizeVar(\"length\") self.nram_size = TARGET(target).nram_size self.dtype_sz = dtype.bytes self.col_count = self.bp.Var(\"col_count\") self.row_count",
"start_index 起始索引 # end_index 结束索引 # 计算一维数组 start_index 至 end_index 范围内的和 并将结果写在start_index除 def",
"// self.dtype_sz) # 当前数据类型下 128个字节 对应了多少个元素 col_remain = self.bp.Scalar(bangpy.int32,\"col_remain\",col_count % count_for_128_align) current_col_count =",
"software and associated documentation files (the # \"Software\"), to deal in the Software",
"remain = self.bp.Scalar(bangpy.int32,\"remain\") current_core_start = self.bp.Scalar(bangpy.int32,\"current_core_start\") #当前核心数据开始索引 current_core_end = self.bp.Scalar(bangpy.int32,\"current_core_end\") #当前核心数据结束索引 total_count_in_core =",
"至 end_index 范围内的和 并将结果写在start_index除 def one_dimensional_sum(self,buffer,start_index,end_index): data_length = self.bp.Scalar(bangpy.int32,\"data_length\",end_index - start_index +1 )#传进来得数据长度",
"with self.bp.else_scope(): current_core_start.assign((one_core_count + 1) * remain + one_core_count * (self.bp.taskId - remain))",
"= self.bp.Scalar(bangpy.int32,\"row\",data_length/count_for_128_align) reshape_buffer = buffer[start_index:current_end_index].reshape([row,count_for_128_align]) self.bp.sumpool(reshape_buffer,reshape_buffer,(row,),(1,)) # self.bp.print(\"sumpool->\",buffer[start_index]) def two_dimension_row_sum(self,buffer,row_count,col_count):#按行 计算二维数组每行的和 结果放在每行首位 with",
"= self.bp.Buffer( shape=(process_count,), name=\"test_buffer\", dtype=self.dtype, scope=\"nram\", ) calc_loop_count.assign((total_count_in_core + process_count - 1) //",
") calc_loop_count.assign((total_count_in_core + process_count - 1) // process_count) with self.bp.for_range(0, calc_loop_count) as i:",
"KERNEL_NAME = \"exp\" class Exp(object): \"\"\"Operator description: Add the data in the two",
"to any person obtaining a # copy of this software and associated documentation",
"FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF",
"to whom the Software is furnished to do so, subject to # the",
"name=\"INPUT0\", dtype=self.dtype, scope=\"global\" # ) buffer_in0 = self.bp.Buffer( shape=(self.length,), name=\"INPUT0\", dtype=self.dtype, scope=\"global\" )",
"self.task_num = task_num self.bp = tcp.TCP(target) self.length = self.bp.SizeVar(\"length\") self.nram_size = TARGET(target).nram_size self.dtype_sz",
"IN THE SOFTWARE. # pylint: disable=missing-docstring, invalid-name, too-many-locals \"\"\"A multi-platform code link example",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"current_core_start.assign((one_core_count + 1) * remain + one_core_count * (self.bp.taskId - remain)) current_core_end.assign((one_core_count +",
"import utils, load_op_by_type from bangpy.platform.bang_config import ALIGN_LENGTH, TARGET from bangpy.tcp.runtime import TaskType from",
"= nram_avable_size // self.dtype_sz #核心一次最多计算的长度 with self.bp.if_scope(self.bp.taskId < remain): #如果存在余数 将其均摊给各核 taskId从0起 current_core_start.assign((one_core_count",
"with self.bp.else_scope(): with self.bp.for_range(0,remain -1) as j: buffer[start_index] = buffer[start_index] + buffer[current_end_index +",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS",
"2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length % self.task_num)#分任务时的余数 process_count = nram_avable_size // self.dtype_sz",
"dtype=self.dtype, scope=\"nram\", ) calc_loop_count.assign((total_count_in_core + process_count - 1) // process_count) with self.bp.for_range(0, calc_loop_count)",
"0): with self.bp.if_scope(current_end_index != 0): with self.bp.for_range(0,remain) as i: buffer[start_index] = buffer[start_index] +",
"scope=\"global\" ) buffer_out = self.bp.Buffer( shape=(self.length,), name=\"OUTPUT\", dtype=self.dtype, scope=\"global\" ) nram_buffer_in0 = self.bp.Buffer(",
"= target self.task_num = task_num self.bp = tcp.TCP(target) self.length = self.bp.SizeVar(\"length\") self.nram_size =",
"# build a executable module f = self.bp.BuildBANG( inputs=[buffer_in0,self.row_count,self.col_count,], outputs=[buffer_out], kernel_name=KERNEL_NAME, ) return",
"self.bp.for_range(0,row_count - 1) as j: buffer[0][current_col_index] = buffer[0][current_col_index] + buffer[j + 1][current_col_index] with",
"1024) // 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length % self.task_num)#分任务时的余数 process_count = nram_avable_size",
"= self.bp.Var(\"row_count\") self.bp.launch_task(self.task_num, 1, 1) # buffer 源数据 # start_index 起始索引 # end_index",
"#当数据长度不足一次对齐时 不进行下面 #当满足一次对齐时 对其直接进行sum #1.每行128字节 #2.算出多少行 #3.reshape (行,128字节数据个数) #3.对其sumpool 因为之后每行第一个元素是需要的 所以最终结果直接在buffer[start_index]上 with self.bp.if_scope(data_length>=count_for_128_align):",
"code link example test for BANGPy TCP.\"\"\" import numpy as np import bangpy",
"- 30* 1024) // 2 ,128)#self.bp.Scalar(bangpy.int32,\"nram_avable_size\") one_core_count.assign(self.length // self.task_num)#每个核均摊计算量(按索引分) remain.assign(self.length % self.task_num)#分任务时的余数 process_count",
"FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE",
"self.bp.for_range(0,row_count) as i: self.one_dimensional_sum(buffer[i][:],0,col_count-1) #buffer 源数据 #temp_buffer 与buffer所占内存空间大小相等的nram存储 #row_count 行数 #col_count 列数 #该函数将计算传入的行数",
"calc_loop_count.assign((total_count_in_core + process_count - 1) // process_count) with self.bp.for_range(0, calc_loop_count) as i: once_loop_start.assign(current_core_start",
"AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"above copyright notice and this permission notice shall be included # in all"
] |
[
"[\"Y\"], # A list of output blobs ... ) print(\"Type of the created",
"workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label', label) m = model_helper.ModelHelper(name=\"my_first_net\") # create model weight = m.param_init_net.XavierFill([],",
"print(\"temp=\", temp) # pyplot.hist(temp.flatten(), bins=50) # pyplot.title(\"ddd of Z\") def model_helper_test(): data =",
"@author:chaowei @file: main.py @time: 2019/07/18 \"\"\" from __future__ import absolute_import from __future__ import",
"# switch the workspace. print(\"After Switch Workspace ................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs in",
"created op is: {}\".format(type(op))) print(\"content: \\n\") print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32)) print(\"current blobs in",
"'X' ?: {}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob X X = np.random.randn(2, 3).astype(np.float32) print(\"Generated X from",
"\"GaussianFill\", [], # GaussianFill does not need any parameters. [\"W\"], shape=[100, 100], mean=1.0,",
"import time from caffe2.python import core, workspace from caffe2.proto import caffe2_pb2 from caffe2.python",
"coding:utf-8 _*_ \"\"\" @author:chaowei @file: main.py @time: 2019/07/18 \"\"\" from __future__ import absolute_import",
"(np.random.rand(16)*10).astype(np.int32) # create the label workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label', label) m = model_helper.ModelHelper(name=\"my_first_net\") #",
"Z\") def model_helper_test(): data = np.random.rand(16, 100).astype(np.float32) # create the input data label",
"in the workspace:{}\".format(workspace.Blobs())) def operators_test(): # create operator. op = core.CreateOperator( \"Relu\", #",
"of Z\") def model_helper_test(): data = np.random.rand(16, 100).astype(np.float32) # create the input data",
"to run. [\"X\"], # A list of input blobs by their names [\"Y\"],",
"the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) # run op print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\")))",
"Workspace ................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) def operators_test(): # create",
"# run op print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1",
"X) # 将 blob 传入 workspace print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) print(\"Workspace has",
"[\"W\"], shape=[100, 100], mean=1.0, std=1.0, ) print(\"content of op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1) temp =",
"m.param_init_net.XavierFill([], 'fc_w', shape=[10, 100]) bias = m.param_init_net.ConstantFill([], 'fc_b', shape=[10, ]) fc_1 = m.net.FC([\"data\",",
"create the label workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label', label) m = model_helper.ModelHelper(name=\"my_first_net\") # create model",
"\\n\") print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32)) print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) # run",
"import model_helper def workspace_test(): print(\"current blobs in the workspace : {}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs",
"{}\".format(type(op))) print(\"content: \\n\") print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32)) print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op)",
"print(\"Workspace has blob 'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))",
"that if 'gutentag' does not exist, create one workspace.SwitchWorkspace(\"gutentag\", True) # switch the",
"workspace.FetchBlob(\"X\")) # print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current workspace: {}\".format(workspace.CurrentWorkspace())) # 查看当前workspace print(\"current blobs in",
"model_helper_test(): data = np.random.rand(16, 100).astype(np.float32) # create the input data label = (np.random.rand(16)*10).astype(np.int32)",
"the workspace: {}\".format(workspace.Blobs())) # The second parameter 'True' indicates that if 'gutentag' does",
"= model_helper.ModelHelper(name=\"my_first_net\") # create model weight = m.param_init_net.XavierFill([], 'fc_w', shape=[10, 100]) bias =",
"in the workspace : {}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs print(\"Workspace has blob 'X' ?: {}\".format(workspace.HasBlob(\"X\")))",
"m = model_helper.ModelHelper(name=\"my_first_net\") # create model weight = m.param_init_net.XavierFill([], 'fc_w', shape=[10, 100]) bias",
"print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current workspace: {}\".format(workspace.CurrentWorkspace())) # 查看当前workspace print(\"current blobs in the workspace:",
"bias = m.param_init_net.ConstantFill([], 'fc_b', shape=[10, ]) fc_1 = m.net.FC([\"data\", \"fc_w\", \"fc_b\"], \"fc1\") pred",
"matplotlib import pyplot import numpy as np import time from caffe2.python import core,",
"op = core.CreateOperator( \"Relu\", # The type of operator that we want to",
"print(str(op1)) workspace.RunOperatorOnce(op1) temp = workspace.FetchBlob(\"W\") print(\"temp=\", temp) # pyplot.hist(temp.flatten(), bins=50) # pyplot.title(\"ddd of",
"from caffe2.python import model_helper def workspace_test(): print(\"current blobs in the workspace : {}\".format(workspace.Blobs))",
"blobs in the workspace:{}\".format(workspace.Blobs())) print(\"Workspace has blob 'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob",
"print_function # from matplotlib import pyplot import numpy as np import time from",
"the input data label = (np.random.rand(16)*10).astype(np.int32) # create the label workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label',",
"time from caffe2.python import core, workspace from caffe2.proto import caffe2_pb2 from caffe2.python import",
"from matplotlib import pyplot import numpy as np import time from caffe2.python import",
"blobs in the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1 = core.CreateOperator( \"GaussianFill\", [],",
"print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass if __name__ == '__main__': # workspace_test() operators_test() # model_helper_test()",
"np.random.rand(16, 100).astype(np.float32) # create the input data label = (np.random.rand(16)*10).astype(np.int32) # create the",
"# _*_ coding:utf-8 _*_ \"\"\" @author:chaowei @file: main.py @time: 2019/07/18 \"\"\" from __future__",
"# create operator. op = core.CreateOperator( \"Relu\", # The type of operator that",
"= m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\", \"loss\"]) print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass if __name__",
"one workspace.SwitchWorkspace(\"gutentag\", True) # switch the workspace. print(\"After Switch Workspace ................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace()))",
"print(\"current blobs in the workspace: {}\".format(workspace.Blobs())) # The second parameter 'True' indicates that",
"from caffe2.proto import caffe2_pb2 from caffe2.python import model_helper def workspace_test(): print(\"current blobs in",
"of input blobs by their names [\"Y\"], # A list of output blobs",
"workspace.FetchBlob(\"W\") print(\"temp=\", temp) # pyplot.hist(temp.flatten(), bins=50) # pyplot.title(\"ddd of Z\") def model_helper_test(): data",
"has blob 'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) #",
"blobs by their names [\"Y\"], # A list of output blobs ... )",
"we want to run. [\"X\"], # A list of input blobs by their",
"100]) bias = m.param_init_net.ConstantFill([], 'fc_b', shape=[10, ]) fc_1 = m.net.FC([\"data\", \"fc_w\", \"fc_b\"], \"fc1\")",
"2019/07/18 \"\"\" from __future__ import absolute_import from __future__ import division from __future__ import",
"np.random.randn(2, 3).astype(np.float32)) print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) # run op print(\"current blobs",
"weight = m.param_init_net.XavierFill([], 'fc_w', shape=[10, 100]) bias = m.param_init_net.ConstantFill([], 'fc_b', shape=[10, ]) fc_1",
"m.param_init_net.ConstantFill([], 'fc_b', shape=[10, ]) fc_1 = m.net.FC([\"data\", \"fc_w\", \"fc_b\"], \"fc1\") pred = m.net.Sigmoid(fc_1,",
"# The type of operator that we want to run. [\"X\"], # A",
"_*_ \"\"\" @author:chaowei @file: main.py @time: 2019/07/18 \"\"\" from __future__ import absolute_import from",
"# 从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) # print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current workspace: {}\".format(workspace.CurrentWorkspace()))",
"temp) # pyplot.hist(temp.flatten(), bins=50) # pyplot.title(\"ddd of Z\") def model_helper_test(): data = np.random.rand(16,",
"workspace.RunOperatorOnce(op) # run op print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1)))",
"second parameter 'True' indicates that if 'gutentag' does not exist, create one workspace.SwitchWorkspace(\"gutentag\",",
"print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) def operators_test(): # create operator. op",
"core.CreateOperator( \"Relu\", # The type of operator that we want to run. [\"X\"],",
"caffe2.proto import caffe2_pb2 from caffe2.python import model_helper def workspace_test(): print(\"current blobs in the",
"[\"X\"], # A list of input blobs by their names [\"Y\"], # A",
"\"label\"], [\"softmax\", \"loss\"]) print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass if __name__ == '__main__':",
"the workspace : {}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs print(\"Workspace has blob 'X' ?: {}\".format(workspace.HasBlob(\"X\"))) #",
"# pyplot.title(\"ddd of Z\") def model_helper_test(): data = np.random.rand(16, 100).astype(np.float32) # create the",
"of operator that we want to run. [\"X\"], # A list of input",
"# create model weight = m.param_init_net.XavierFill([], 'fc_w', shape=[10, 100]) bias = m.param_init_net.ConstantFill([], 'fc_b',",
"from __future__ import division from __future__ import print_function # from matplotlib import pyplot",
"print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1 = core.CreateOperator( \"GaussianFill\",",
"print(\"Type of the created op is: {}\".format(type(op))) print(\"content: \\n\") print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32))",
"= core.CreateOperator( \"Relu\", # The type of operator that we want to run.",
"@file: main.py @time: 2019/07/18 \"\"\" from __future__ import absolute_import from __future__ import division",
"workspace: {}\".format(workspace.Blobs())) # The second parameter 'True' indicates that if 'gutentag' does not",
"not exist, create one workspace.SwitchWorkspace(\"gutentag\", True) # switch the workspace. print(\"After Switch Workspace",
"of output blobs ... ) print(\"Type of the created op is: {}\".format(type(op))) print(\"content:",
"print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) print(\"Workspace has blob 'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) #",
"print(\"Generated X from numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\", X) # 将 blob 传入 workspace print(\"current",
"core.CreateOperator( \"GaussianFill\", [], # GaussianFill does not need any parameters. [\"W\"], shape=[100, 100],",
"import pyplot import numpy as np import time from caffe2.python import core, workspace",
"workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32)) print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) # run op print(\"current",
"?: {}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob X X = np.random.randn(2, 3).astype(np.float32) print(\"Generated X from numpy:",
"print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) def operators_test(): # create operator. op = core.CreateOperator(",
"caffe2.python import model_helper def workspace_test(): print(\"current blobs in the workspace : {}\".format(workspace.Blobs)) #",
"the workspace:{}\".format(workspace.Blobs())) def operators_test(): # create operator. op = core.CreateOperator( \"Relu\", # The",
"print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1 = core.CreateOperator( \"GaussianFill\", [], # GaussianFill does not need",
"operator. op = core.CreateOperator( \"Relu\", # The type of operator that we want",
"numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\", X) # 将 blob 传入 workspace print(\"current blobs in the",
"any parameters. [\"W\"], shape=[100, 100], mean=1.0, std=1.0, ) print(\"content of op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1)",
"shape=[10, ]) fc_1 = m.net.FC([\"data\", \"fc_w\", \"fc_b\"], \"fc1\") pred = m.net.Sigmoid(fc_1, \"pred\") softmax,",
"判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) # print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current workspace: {}\".format(workspace.CurrentWorkspace())) # 查看当前workspace print(\"current",
"__future__ import division from __future__ import print_function # from matplotlib import pyplot import",
"caffe2.python import core, workspace from caffe2.proto import caffe2_pb2 from caffe2.python import model_helper def",
"list of output blobs ... ) print(\"Type of the created op is: {}\".format(type(op)))",
"the label workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label', label) m = model_helper.ModelHelper(name=\"my_first_net\") # create model weight",
"indicates that if 'gutentag' does not exist, create one workspace.SwitchWorkspace(\"gutentag\", True) # switch",
"op1 = core.CreateOperator( \"GaussianFill\", [], # GaussianFill does not need any parameters. [\"W\"],",
"from caffe2.python import core, workspace from caffe2.proto import caffe2_pb2 from caffe2.python import model_helper",
"run. [\"X\"], # A list of input blobs by their names [\"Y\"], #",
"blobs in the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) # run op print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs()))",
"python # _*_ coding:utf-8 _*_ \"\"\" @author:chaowei @file: main.py @time: 2019/07/18 \"\"\" from",
"in the workspace:{}\".format(workspace.Blobs())) print(\"Workspace has blob 'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob #",
"# create the label workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label', label) m = model_helper.ModelHelper(name=\"my_first_net\") # create",
"# 将 blob 传入 workspace print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) print(\"Workspace has blob",
"in the workspace: {}\".format(workspace.Blobs())) # The second parameter 'True' indicates that if 'gutentag'",
"np.random.randn(2, 3).astype(np.float32) print(\"Generated X from numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\", X) # 将 blob 传入",
"workspace: {}\".format(workspace.CurrentWorkspace())) # 查看当前workspace print(\"current blobs in the workspace: {}\".format(workspace.Blobs())) # The second",
"workspace.FetchBlob(\"X\"))) print(\"current workspace: {}\".format(workspace.CurrentWorkspace())) # 查看当前workspace print(\"current blobs in the workspace: {}\".format(workspace.Blobs())) #",
") print(\"Type of the created op is: {}\".format(type(op))) print(\"content: \\n\") print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2,",
"op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1) temp = workspace.FetchBlob(\"W\") print(\"temp=\", temp) # pyplot.hist(temp.flatten(), bins=50) # pyplot.title(\"ddd",
"in the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) # run op print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\")))",
"判断是否有blob X X = np.random.randn(2, 3).astype(np.float32) print(\"Generated X from numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\", X)",
"import caffe2_pb2 from caffe2.python import model_helper def workspace_test(): print(\"current blobs in the workspace",
"#!usr/bin/env python # _*_ coding:utf-8 _*_ \"\"\" @author:chaowei @file: main.py @time: 2019/07/18 \"\"\"",
"not need any parameters. [\"W\"], shape=[100, 100], mean=1.0, std=1.0, ) print(\"content of op1:\\n\")",
"shape=[100, 100], mean=1.0, std=1.0, ) print(\"content of op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1) temp = workspace.FetchBlob(\"W\")",
"[\"softmax\", \"loss\"]) print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass if __name__ == '__main__': #",
"label) m = model_helper.ModelHelper(name=\"my_first_net\") # create model weight = m.param_init_net.XavierFill([], 'fc_w', shape=[10, 100])",
"pred = m.net.Sigmoid(fc_1, \"pred\") softmax, loss = m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\", \"loss\"]) print(\"m.net=\", m.net.Proto())",
"print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1 = core.CreateOperator( \"GaussianFill\", [], # GaussianFill does not need any",
"from __future__ import print_function # from matplotlib import pyplot import numpy as np",
"fc_1 = m.net.FC([\"data\", \"fc_w\", \"fc_b\"], \"fc1\") pred = m.net.Sigmoid(fc_1, \"pred\") softmax, loss =",
"1))) op1 = core.CreateOperator( \"GaussianFill\", [], # GaussianFill does not need any parameters.",
"pyplot import numpy as np import time from caffe2.python import core, workspace from",
"type of operator that we want to run. [\"X\"], # A list of",
"data label = (np.random.rand(16)*10).astype(np.int32) # create the label workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label', label) m",
"传入 workspace print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) print(\"Workspace has blob 'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched",
"data) workspace.FeedBlob('label', label) m = model_helper.ModelHelper(name=\"my_first_net\") # create model weight = m.param_init_net.XavierFill([], 'fc_w',",
"parameter 'True' indicates that if 'gutentag' does not exist, create one workspace.SwitchWorkspace(\"gutentag\", True)",
"blobs ... ) print(\"Type of the created op is: {}\".format(type(op))) print(\"content: \\n\") print(str(op))",
"# A list of input blobs by their names [\"Y\"], # A list",
"in the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1 = core.CreateOperator( \"GaussianFill\", [], #",
"100).astype(np.float32) # create the input data label = (np.random.rand(16)*10).astype(np.int32) # create the label",
"blobs in the workspace: {}\".format(workspace.Blobs())) # The second parameter 'True' indicates that if",
"the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1 = core.CreateOperator( \"GaussianFill\", [], # GaussianFill",
"create model weight = m.param_init_net.XavierFill([], 'fc_w', shape=[10, 100]) bias = m.param_init_net.ConstantFill([], 'fc_b', shape=[10,",
"input blobs by their names [\"Y\"], # A list of output blobs ...",
"import numpy as np import time from caffe2.python import core, workspace from caffe2.proto",
"temp = workspace.FetchBlob(\"W\") print(\"temp=\", temp) # pyplot.hist(temp.flatten(), bins=50) # pyplot.title(\"ddd of Z\") def",
"Switch Workspace ................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) def operators_test(): #",
"查看workspace里面所有的blobs print(\"Workspace has blob 'X' ?: {}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob X X = np.random.randn(2,",
"np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current workspace: {}\".format(workspace.CurrentWorkspace())) # 查看当前workspace print(\"current blobs in the workspace: {}\".format(workspace.Blobs()))",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function #",
"= core.CreateOperator( \"GaussianFill\", [], # GaussianFill does not need any parameters. [\"W\"], shape=[100,",
"= (np.random.rand(16)*10).astype(np.int32) # create the label workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label', label) m = model_helper.ModelHelper(name=\"my_first_net\")",
"blob 传入 workspace print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) print(\"Workspace has blob 'X' ?{}\".format(workspace.HasBlob(\"X\")))",
"3).astype(np.float32)) print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) # run op print(\"current blobs in",
"m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\", \"loss\"]) print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass if __name__ ==",
"X = np.random.randn(2, 3).astype(np.float32) print(\"Generated X from numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\", X) # 将",
"blobs in the workspace:{}\".format(workspace.Blobs())) def operators_test(): # create operator. op = core.CreateOperator( \"Relu\",",
"of the created op is: {}\".format(type(op))) print(\"content: \\n\") print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32)) print(\"current",
"std=1.0, ) print(\"content of op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1) temp = workspace.FetchBlob(\"W\") print(\"temp=\", temp) #",
"the created op is: {}\".format(type(op))) print(\"content: \\n\") print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32)) print(\"current blobs",
"pyplot.hist(temp.flatten(), bins=50) # pyplot.title(\"ddd of Z\") def model_helper_test(): data = np.random.rand(16, 100).astype(np.float32) #",
"<reponame>ForrestHeiYing/tutorials<gh_stars>0 #!usr/bin/env python # _*_ coding:utf-8 _*_ \"\"\" @author:chaowei @file: main.py @time: 2019/07/18",
"# create the input data label = (np.random.rand(16)*10).astype(np.int32) # create the label workspace.FeedBlob(\"data\",",
"# 判断是否有blob X X = np.random.randn(2, 3).astype(np.float32) print(\"Generated X from numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\",",
"]) fc_1 = m.net.FC([\"data\", \"fc_w\", \"fc_b\"], \"fc1\") pred = m.net.Sigmoid(fc_1, \"pred\") softmax, loss",
"their names [\"Y\"], # A list of output blobs ... ) print(\"Type of",
"op print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1 = core.CreateOperator(",
"\"\"\" @author:chaowei @file: main.py @time: 2019/07/18 \"\"\" from __future__ import absolute_import from __future__",
"as np import time from caffe2.python import core, workspace from caffe2.proto import caffe2_pb2",
"workspace from caffe2.proto import caffe2_pb2 from caffe2.python import model_helper def workspace_test(): print(\"current blobs",
"op is: {}\".format(type(op))) print(\"content: \\n\") print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32)) print(\"current blobs in the",
"= np.random.randn(2, 3).astype(np.float32) print(\"Generated X from numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\", X) # 将 blob",
"np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) # print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current workspace: {}\".format(workspace.CurrentWorkspace())) # 查看当前workspace print(\"current blobs",
"input data label = (np.random.rand(16)*10).astype(np.int32) # create the label workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label', label)",
"is: {}\".format(type(op))) print(\"content: \\n\") print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32)) print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs()))",
"create operator. op = core.CreateOperator( \"Relu\", # The type of operator that we",
"of op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1) temp = workspace.FetchBlob(\"W\") print(\"temp=\", temp) # pyplot.hist(temp.flatten(), bins=50) #",
"does not need any parameters. [\"W\"], shape=[100, 100], mean=1.0, std=1.0, ) print(\"content of",
"data = np.random.rand(16, 100).astype(np.float32) # create the input data label = (np.random.rand(16)*10).astype(np.int32) #",
"blob 'X' ?: {}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob X X = np.random.randn(2, 3).astype(np.float32) print(\"Generated X",
"exist, create one workspace.SwitchWorkspace(\"gutentag\", True) # switch the workspace. print(\"After Switch Workspace ................\")",
"__future__ import absolute_import from __future__ import division from __future__ import print_function # from",
"= workspace.FetchBlob(\"W\") print(\"temp=\", temp) # pyplot.hist(temp.flatten(), bins=50) # pyplot.title(\"ddd of Z\") def model_helper_test():",
"The second parameter 'True' indicates that if 'gutentag' does not exist, create one",
"m.net.FC([\"data\", \"fc_w\", \"fc_b\"], \"fc1\") pred = m.net.Sigmoid(fc_1, \"pred\") softmax, loss = m.net.SoftmaxWithLoss([pred, \"label\"],",
"workspace. print(\"After Switch Workspace ................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) def",
"operator that we want to run. [\"X\"], # A list of input blobs",
"'fc_b', shape=[10, ]) fc_1 = m.net.FC([\"data\", \"fc_w\", \"fc_b\"], \"fc1\") pred = m.net.Sigmoid(fc_1, \"pred\")",
"workspace.SwitchWorkspace(\"gutentag\", True) # switch the workspace. print(\"After Switch Workspace ................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current",
"{}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob X X = np.random.randn(2, 3).astype(np.float32) print(\"Generated X from numpy: \\n{}\".format(X))",
"X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) # print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current workspace:",
"= m.param_init_net.ConstantFill([], 'fc_b', shape=[10, ]) fc_1 = m.net.FC([\"data\", \"fc_w\", \"fc_b\"], \"fc1\") pred =",
"caffe2_pb2 from caffe2.python import model_helper def workspace_test(): print(\"current blobs in the workspace :",
"# 查看当前workspace print(\"current blobs in the workspace: {}\".format(workspace.Blobs())) # The second parameter 'True'",
"= m.net.FC([\"data\", \"fc_w\", \"fc_b\"], \"fc1\") pred = m.net.Sigmoid(fc_1, \"pred\") softmax, loss = m.net.SoftmaxWithLoss([pred,",
"# print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current workspace: {}\".format(workspace.CurrentWorkspace())) # 查看当前workspace print(\"current blobs in the",
"print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) # run op print(\"current blobs in the",
"names [\"Y\"], # A list of output blobs ... ) print(\"Type of the",
"print(\"current workspace: {}\".format(workspace.CurrentWorkspace())) # 查看当前workspace print(\"current blobs in the workspace: {}\".format(workspace.Blobs())) # The",
"by their names [\"Y\"], # A list of output blobs ... ) print(\"Type",
"# pyplot.hist(temp.flatten(), bins=50) # pyplot.title(\"ddd of Z\") def model_helper_test(): data = np.random.rand(16, 100).astype(np.float32)",
"X X = np.random.randn(2, 3).astype(np.float32) print(\"Generated X from numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\", X) #",
"pyplot.title(\"ddd of Z\") def model_helper_test(): data = np.random.rand(16, 100).astype(np.float32) # create the input",
"workspace.RunOperatorOnce(op1) temp = workspace.FetchBlob(\"W\") print(\"temp=\", temp) # pyplot.hist(temp.flatten(), bins=50) # pyplot.title(\"ddd of Z\")",
"print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32)) print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) # run op",
"model_helper.ModelHelper(name=\"my_first_net\") # create model weight = m.param_init_net.XavierFill([], 'fc_w', shape=[10, 100]) bias = m.param_init_net.ConstantFill([],",
"create the input data label = (np.random.rand(16)*10).astype(np.int32) # create the label workspace.FeedBlob(\"data\", data)",
"shape=[10, 100]) bias = m.param_init_net.ConstantFill([], 'fc_b', shape=[10, ]) fc_1 = m.net.FC([\"data\", \"fc_w\", \"fc_b\"],",
": {}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs print(\"Workspace has blob 'X' ?: {}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob X",
"A list of input blobs by their names [\"Y\"], # A list of",
"GaussianFill does not need any parameters. [\"W\"], shape=[100, 100], mean=1.0, std=1.0, ) print(\"content",
"\"pred\") softmax, loss = m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\", \"loss\"]) print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net)",
"workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) # run op print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"),",
"core, workspace from caffe2.proto import caffe2_pb2 from caffe2.python import model_helper def workspace_test(): print(\"current",
"need any parameters. [\"W\"], shape=[100, 100], mean=1.0, std=1.0, ) print(\"content of op1:\\n\") print(str(op1))",
"= m.param_init_net.XavierFill([], 'fc_w', shape=[10, 100]) bias = m.param_init_net.ConstantFill([], 'fc_b', shape=[10, ]) fc_1 =",
"m.net.Sigmoid(fc_1, \"pred\") softmax, loss = m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\", \"loss\"]) print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto())",
"np import time from caffe2.python import core, workspace from caffe2.proto import caffe2_pb2 from",
"?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) # print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")))",
"main.py @time: 2019/07/18 \"\"\" from __future__ import absolute_import from __future__ import division from",
"print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass if __name__ == '__main__': # workspace_test() operators_test()",
"workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1 = core.CreateOperator( \"GaussianFill\", [], # GaussianFill does",
"model_helper def workspace_test(): print(\"current blobs in the workspace : {}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs print(\"Workspace",
"{}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs print(\"Workspace has blob 'X' ?: {}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob X X",
"@time: 2019/07/18 \"\"\" from __future__ import absolute_import from __future__ import division from __future__",
"workspace.FeedBlob(\"X\", X) # 将 blob 传入 workspace print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) print(\"Workspace",
"the workspace:{}\".format(workspace.Blobs())) print(\"Workspace has blob 'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常",
"import division from __future__ import print_function # from matplotlib import pyplot import numpy",
"将 blob 传入 workspace print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) print(\"Workspace has blob 'X'",
"workspace.FeedBlob('label', label) m = model_helper.ModelHelper(name=\"my_first_net\") # create model weight = m.param_init_net.XavierFill([], 'fc_w', shape=[10,",
"print(\"content of op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1) temp = workspace.FetchBlob(\"W\") print(\"temp=\", temp) # pyplot.hist(temp.flatten(), bins=50)",
"workspace print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) print(\"Workspace has blob 'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\")))",
"print(\"After Switch Workspace ................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) def operators_test():",
"import absolute_import from __future__ import division from __future__ import print_function # from matplotlib",
"does not exist, create one workspace.SwitchWorkspace(\"gutentag\", True) # switch the workspace. print(\"After Switch",
"_*_ coding:utf-8 _*_ \"\"\" @author:chaowei @file: main.py @time: 2019/07/18 \"\"\" from __future__ import",
"# 查看workspace里面所有的blobs print(\"Workspace has blob 'X' ?: {}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob X X =",
"= m.net.Sigmoid(fc_1, \"pred\") softmax, loss = m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\", \"loss\"]) print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\",",
"\"fc_b\"], \"fc1\") pred = m.net.Sigmoid(fc_1, \"pred\") softmax, loss = m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\", \"loss\"])",
"m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass if __name__ == '__main__': # workspace_test() operators_test() # model_helper_test() pass",
"# from matplotlib import pyplot import numpy as np import time from caffe2.python",
"True) # switch the workspace. print(\"After Switch Workspace ................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs",
"workspace : {}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs print(\"Workspace has blob 'X' ?: {}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob",
"def operators_test(): # create operator. op = core.CreateOperator( \"Relu\", # The type of",
"run op print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1 =",
"\\n{}\".format(X)) workspace.FeedBlob(\"X\", X) # 将 blob 传入 workspace print(\"current blobs in the workspace:{}\".format(workspace.Blobs()))",
"switch the workspace. print(\"After Switch Workspace ................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs in the",
"absolute_import from __future__ import division from __future__ import print_function # from matplotlib import",
"# The second parameter 'True' indicates that if 'gutentag' does not exist, create",
"= np.random.rand(16, 100).astype(np.float32) # create the input data label = (np.random.rand(16)*10).astype(np.int32) # create",
"\"fc_w\", \"fc_b\"], \"fc1\") pred = m.net.Sigmoid(fc_1, \"pred\") softmax, loss = m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\",",
"list of input blobs by their names [\"Y\"], # A list of output",
"blobs in the workspace : {}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs print(\"Workspace has blob 'X' ?:",
"create one workspace.SwitchWorkspace(\"gutentag\", True) # switch the workspace. print(\"After Switch Workspace ................\") print(\"current",
"has blob 'X' ?: {}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob X X = np.random.randn(2, 3).astype(np.float32) print(\"Generated",
"# A list of output blobs ... ) print(\"Type of the created op",
"division from __future__ import print_function # from matplotlib import pyplot import numpy as",
"print(\"X:\\n{}\\n\".format(workspace.FetchBlob(\"X\"))) print(\"Y:\\n{}\\n\".format(workspace.FetchBlob(\"Y\"))) print(\"Expected:\\n{}\\n\".format(np.maximum(workspace.FetchBlob(\"X\"), 1))) op1 = core.CreateOperator( \"GaussianFill\", [], # GaussianFill does not",
"100], mean=1.0, std=1.0, ) print(\"content of op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1) temp = workspace.FetchBlob(\"W\") print(\"temp=\",",
"从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) # print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current workspace: {}\".format(workspace.CurrentWorkspace())) #",
"'True' indicates that if 'gutentag' does not exist, create one workspace.SwitchWorkspace(\"gutentag\", True) #",
"print(\"content: \\n\") print(str(op)) workspace.FeedBlob(\"X\", np.random.randn(2, 3).astype(np.float32)) print(\"current blobs in the workspace:{}\\n\".format(workspace.Blobs())) workspace.RunOperatorOnce(op) #",
"print(\"current blobs in the workspace : {}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs print(\"Workspace has blob 'X'",
"{}\".format(workspace.Blobs())) # The second parameter 'True' indicates that if 'gutentag' does not exist,",
"numpy as np import time from caffe2.python import core, workspace from caffe2.proto import",
") print(\"content of op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1) temp = workspace.FetchBlob(\"W\") print(\"temp=\", temp) # pyplot.hist(temp.flatten(),",
"print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) # print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current",
"softmax, loss = m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\", \"loss\"]) print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass",
"3).astype(np.float32) print(\"Generated X from numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\", X) # 将 blob 传入 workspace",
"__future__ import print_function # from matplotlib import pyplot import numpy as np import",
"The type of operator that we want to run. [\"X\"], # A list",
"[], # GaussianFill does not need any parameters. [\"W\"], shape=[100, 100], mean=1.0, std=1.0,",
"X from numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\", X) # 将 blob 传入 workspace print(\"current blobs",
"def model_helper_test(): data = np.random.rand(16, 100).astype(np.float32) # create the input data label =",
"mean=1.0, std=1.0, ) print(\"content of op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1) temp = workspace.FetchBlob(\"W\") print(\"temp=\", temp)",
"import print_function # from matplotlib import pyplot import numpy as np import time",
"\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function",
"import core, workspace from caffe2.proto import caffe2_pb2 from caffe2.python import model_helper def workspace_test():",
"'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) # print(\"a=\", np.testing.assert_array_equal(X,",
"workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) def operators_test(): # create operator. op =",
"want to run. [\"X\"], # A list of input blobs by their names",
"{}\".format(workspace.CurrentWorkspace())) # 查看当前workspace print(\"current blobs in the workspace: {}\".format(workspace.Blobs())) # The second parameter",
"workspace:{}\".format(workspace.Blobs())) print(\"Workspace has blob 'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X,",
"loss = m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\", \"loss\"]) print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass if",
"# GaussianFill does not need any parameters. [\"W\"], shape=[100, 100], mean=1.0, std=1.0, )",
"bins=50) # pyplot.title(\"ddd of Z\") def model_helper_test(): data = np.random.rand(16, 100).astype(np.float32) # create",
"if 'gutentag' does not exist, create one workspace.SwitchWorkspace(\"gutentag\", True) # switch the workspace.",
"... ) print(\"Type of the created op is: {}\".format(type(op))) print(\"content: \\n\") print(str(op)) workspace.FeedBlob(\"X\",",
"print(\"Workspace has blob 'X' ?: {}\".format(workspace.HasBlob(\"X\"))) # 判断是否有blob X X = np.random.randn(2, 3).astype(np.float32)",
"'gutentag' does not exist, create one workspace.SwitchWorkspace(\"gutentag\", True) # switch the workspace. print(\"After",
"m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass if __name__ == '__main__': # workspace_test() operators_test() #",
"\"Relu\", # The type of operator that we want to run. [\"X\"], #",
"from numpy: \\n{}\".format(X)) workspace.FeedBlob(\"X\", X) # 将 blob 传入 workspace print(\"current blobs in",
"workspace:{}\".format(workspace.Blobs())) def operators_test(): # create operator. op = core.CreateOperator( \"Relu\", # The type",
"查看当前workspace print(\"current blobs in the workspace: {}\".format(workspace.Blobs())) # The second parameter 'True' indicates",
"the workspace. print(\"After Switch Workspace ................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs in the workspace:{}\".format(workspace.Blobs()))",
"blob 'X' ?{}\".format(workspace.HasBlob(\"X\"))) print(\"Fethched X:\\n{}\".format(workspace.FetchBlob(\"X\"))) # 从workspace里面读取blob # 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) # print(\"a=\",",
"that we want to run. [\"X\"], # A list of input blobs by",
"................\") print(\"current workspace:{}\".format(workspace.CurrentWorkspace())) print(\"current blobs in the workspace:{}\".format(workspace.Blobs())) def operators_test(): # create operator.",
"\"loss\"]) print(\"m.net=\", m.net.Proto()) print(\"m.param_init_net.Proto=\", m.param_init_net.Proto()) workspace.RunNetOnce(m.param_init_net) pass if __name__ == '__main__': # workspace_test()",
"label = (np.random.rand(16)*10).astype(np.int32) # create the label workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label', label) m =",
"parameters. [\"W\"], shape=[100, 100], mean=1.0, std=1.0, ) print(\"content of op1:\\n\") print(str(op1)) workspace.RunOperatorOnce(op1) temp",
"operators_test(): # create operator. op = core.CreateOperator( \"Relu\", # The type of operator",
"A list of output blobs ... ) print(\"Type of the created op is:",
"\"fc1\") pred = m.net.Sigmoid(fc_1, \"pred\") softmax, loss = m.net.SoftmaxWithLoss([pred, \"label\"], [\"softmax\", \"loss\"]) print(\"m.net=\",",
"# 判断两个矩阵是否相等,不等会抛出异常 np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\")) # print(\"a=\", np.testing.assert_array_equal(X, workspace.FetchBlob(\"X\"))) print(\"current workspace: {}\".format(workspace.CurrentWorkspace())) # 查看当前workspace",
"output blobs ... ) print(\"Type of the created op is: {}\".format(type(op))) print(\"content: \\n\")",
"def workspace_test(): print(\"current blobs in the workspace : {}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs print(\"Workspace has",
"workspace_test(): print(\"current blobs in the workspace : {}\".format(workspace.Blobs)) # 查看workspace里面所有的blobs print(\"Workspace has blob",
"label workspace.FeedBlob(\"data\", data) workspace.FeedBlob('label', label) m = model_helper.ModelHelper(name=\"my_first_net\") # create model weight =",
"'fc_w', shape=[10, 100]) bias = m.param_init_net.ConstantFill([], 'fc_b', shape=[10, ]) fc_1 = m.net.FC([\"data\", \"fc_w\",",
"model weight = m.param_init_net.XavierFill([], 'fc_w', shape=[10, 100]) bias = m.param_init_net.ConstantFill([], 'fc_b', shape=[10, ])"
] |
[
"coding: utf-8 -*- \"\"\" Created on Sun Oct 17 01:42:08 2021 @author: mhasan13",
"forward(self, input): self.out = torch.zeros(1,1) self.a_membrane = self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input) # self.membrane =",
"= torch.zeros_like(input) out[input > 0] = 1.0 return out @staticmethod def backward(ctx, grad_output):",
"(1-self.leak_mem)*(input) # self.membrane = self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane = self.leak_mem*self.membrane + self.fc(self.a_membrane) self.out[self.membrane",
"import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt import",
"# self.membrane = self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane = self.leak_mem*self.membrane + self.fc(self.a_membrane) self.out[self.membrane >",
"as F import matplotlib.pyplot as plt import numpy as np import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\"",
"F.threshold(1.0 - torch.abs(input), 0, 0) return grad def PoissonGen(inp, rescale_fac=2.0): rand_inp = torch.rand_like(inp)",
"F import matplotlib.pyplot as plt import numpy as np import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class",
"in_dim=1, num_cls=1): super(Net, self).__init__() self.threshold = 1 self.leak_mem = leak_mem self.fc = nn.Linear(in_dim,",
"= torch.zeros(in_dim, num_cls) self.a_membrane = torch.zeros(in_dim, num_cls) def forward(self, input): self.out = torch.zeros(1,1)",
"= self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane = self.leak_mem*self.membrane + self.fc(self.a_membrane) self.out[self.membrane > self.threshold] =",
"= 1. self.membrane[self.membrane > self.threshold] = 0. return self.out, self.membrane, self.a_membrane # input",
"PoissonGen(x) class Net(nn.Module): def __init__(self, leak_mem=0.95, in_dim=1, num_cls=1): super(Net, self).__init__() self.threshold = 1",
"num_cls=1): super(Net, self).__init__() self.threshold = 1 self.leak_mem = leak_mem self.fc = nn.Linear(in_dim, num_cls,",
"= [] membrane = [] a_membrane = [] spike = [] for t",
"= 0. return self.out, self.membrane, self.a_membrane # input = torch.ones(1,1) net = Net()",
"torch.abs(input), 0, 0) return grad def PoissonGen(inp, rescale_fac=2.0): rand_inp = torch.rand_like(inp) return torch.mul(torch.le(rand_inp",
"for i in range(10): y[i] = PoissonGen(x) class Net(nn.Module): def __init__(self, leak_mem=0.95, in_dim=1,",
"= ctx.saved_tensors grad_input = grad_output.clone() grad = grad_input * 0.3 * F.threshold(1.0 -",
"out = [] membrane = [] a_membrane = [] spike = [] for",
"= 1 self.leak_mem = leak_mem self.fc = nn.Linear(in_dim, num_cls, bias=False) self.membrane = torch.zeros(in_dim,",
"= torch.zeros(1,1) self.a_membrane = self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input) # self.membrane = self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane)",
"https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import torch import torch.nn as nn import torch.nn.functional as F import",
"self.out, self.membrane, self.a_membrane # input = torch.ones(1,1) net = Net() net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]]))",
"x = torch.tensor(1.0) y = torch.zeros(10) tt = torch.arange(10) for i in range(10):",
"return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp)).float(), torch.sign(inp)) x = torch.tensor(1.0) y = torch.zeros(10) tt",
"torch.tensor(1.0) y = torch.zeros(10) tt = torch.arange(10) for i in range(10): y[i] =",
"self.threshold] = 1. self.membrane[self.membrane > self.threshold] = 0. return self.out, self.membrane, self.a_membrane #",
"= [] spike = [] for t in range(40): input = PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy())",
"num_cls) self.a_membrane = torch.zeros(in_dim, num_cls) def forward(self, input): self.out = torch.zeros(1,1) self.a_membrane =",
"torch.rand_like(inp) return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp)).float(), torch.sign(inp)) x = torch.tensor(1.0) y = torch.zeros(10)",
"Oct 17 01:42:08 2021 @author: mhasan13 using exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import torch",
"input = torch.ones(1,1) net = Net() net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]])) out = [] membrane",
"@author: mhasan13 using exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import torch import torch.nn as nn",
"forward(ctx, input): ctx.save_for_backward(input) out = torch.zeros_like(input) out[input > 0] = 1.0 return out",
"y[i] = PoissonGen(x) class Net(nn.Module): def __init__(self, leak_mem=0.95, in_dim=1, num_cls=1): super(Net, self).__init__() self.threshold",
"= PoissonGen(x) class Net(nn.Module): def __init__(self, leak_mem=0.95, in_dim=1, num_cls=1): super(Net, self).__init__() self.threshold =",
"* F.threshold(1.0 - torch.abs(input), 0, 0) return grad def PoissonGen(inp, rescale_fac=2.0): rand_inp =",
"-*- \"\"\" Created on Sun Oct 17 01:42:08 2021 @author: mhasan13 using exmaple",
"self.leak_mem = leak_mem self.fc = nn.Linear(in_dim, num_cls, bias=False) self.membrane = torch.zeros(in_dim, num_cls) self.a_membrane",
"self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input) # self.membrane = self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane = self.leak_mem*self.membrane +",
"grad_output): input, = ctx.saved_tensors grad_input = grad_output.clone() grad = grad_input * 0.3 *",
"bias=False) self.membrane = torch.zeros(in_dim, num_cls) self.a_membrane = torch.zeros(in_dim, num_cls) def forward(self, input): self.out",
"matplotlib.pyplot as plt import numpy as np import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function): @staticmethod",
"class Net(nn.Module): def __init__(self, leak_mem=0.95, in_dim=1, num_cls=1): super(Net, self).__init__() self.threshold = 1 self.leak_mem",
"def __init__(self, leak_mem=0.95, in_dim=1, num_cls=1): super(Net, self).__init__() self.threshold = 1 self.leak_mem = leak_mem",
"> self.threshold] = 0. return self.out, self.membrane, self.a_membrane # input = torch.ones(1,1) net",
"def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output.clone() grad = grad_input *",
"ctx.save_for_backward(input) out = torch.zeros_like(input) out[input > 0] = 1.0 return out @staticmethod def",
"torch.arange(10) for i in range(10): y[i] = PoissonGen(x) class Net(nn.Module): def __init__(self, leak_mem=0.95,",
"17 01:42:08 2021 @author: mhasan13 using exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import torch import",
"@staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output.clone() grad = grad_input",
"in range(10): y[i] = PoissonGen(x) class Net(nn.Module): def __init__(self, leak_mem=0.95, in_dim=1, num_cls=1): super(Net,",
"utf-8 -*- \"\"\" Created on Sun Oct 17 01:42:08 2021 @author: mhasan13 using",
"Sun Oct 17 01:42:08 2021 @author: mhasan13 using exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import",
"as plt import numpy as np import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function): @staticmethod def",
"exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import torch import torch.nn as nn import torch.nn.functional as",
"using exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import torch import torch.nn as nn import torch.nn.functional",
"0, 0) return grad def PoissonGen(inp, rescale_fac=2.0): rand_inp = torch.rand_like(inp) return torch.mul(torch.le(rand_inp *",
"range(40): input = PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0) a, b, c = net(input) out.append(a.detach().numpy()[0])",
"input = PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0) a, b, c = net(input) out.append(a.detach().numpy()[0]) membrane.append(b.detach().numpy()[0])",
"self.a_membrane = self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input) # self.membrane = self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane =",
"net = Net() net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]])) out = [] membrane = [] a_membrane",
"net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]])) out = [] membrane = [] a_membrane = [] spike",
"self.threshold = 1 self.leak_mem = leak_mem self.fc = nn.Linear(in_dim, num_cls, bias=False) self.membrane =",
"= torch.zeros(10) tt = torch.arange(10) for i in range(10): y[i] = PoissonGen(x) class",
"1. self.membrane[self.membrane > self.threshold] = 0. return self.out, self.membrane, self.a_membrane # input =",
"def forward(ctx, input): ctx.save_for_backward(input) out = torch.zeros_like(input) out[input > 0] = 1.0 return",
"[] spike = [] for t in range(40): input = PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0)",
"numpy as np import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input)",
"class SpikingActivation(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) out = torch.zeros_like(input) out[input > 0]",
"grad_output.clone() grad = grad_input * 0.3 * F.threshold(1.0 - torch.abs(input), 0, 0) return",
"for t in range(40): input = PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0) a, b, c",
"= torch.ones(1,1) net = Net() net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]])) out = [] membrane =",
"torch.zeros(1,1) self.a_membrane = self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input) # self.membrane = self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane",
"grad_input = grad_output.clone() grad = grad_input * 0.3 * F.threshold(1.0 - torch.abs(input), 0,",
"self.threshold] = 0. return self.out, self.membrane, self.a_membrane # input = torch.ones(1,1) net =",
"= torch.tensor(1.0) y = torch.zeros(10) tt = torch.arange(10) for i in range(10): y[i]",
"self.a_membrane = torch.zeros(in_dim, num_cls) def forward(self, input): self.out = torch.zeros(1,1) self.a_membrane = self.leak_mem*self.a_membrane",
"+ self.fc(self.a_membrane) self.out[self.membrane > self.threshold] = 1. self.membrane[self.membrane > self.threshold] = 0. return",
"torch.nn.functional as F import matplotlib.pyplot as plt import numpy as np import os",
"PoissonGen(inp, rescale_fac=2.0): rand_inp = torch.rand_like(inp) return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp)).float(), torch.sign(inp)) x =",
"super(Net, self).__init__() self.threshold = 1 self.leak_mem = leak_mem self.fc = nn.Linear(in_dim, num_cls, bias=False)",
"- torch.abs(input), 0, 0) return grad def PoissonGen(inp, rescale_fac=2.0): rand_inp = torch.rand_like(inp) return",
"0) return grad def PoissonGen(inp, rescale_fac=2.0): rand_inp = torch.rand_like(inp) return torch.mul(torch.le(rand_inp * rescale_fac,",
"01:42:08 2021 @author: mhasan13 using exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import torch import torch.nn",
"-*- coding: utf-8 -*- \"\"\" Created on Sun Oct 17 01:42:08 2021 @author:",
"input): self.out = torch.zeros(1,1) self.a_membrane = self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input) # self.membrane = self.leak_mem*self.membrane",
"input.unsqueeze_(0) input.unsqueeze_(0) a, b, c = net(input) out.append(a.detach().numpy()[0]) membrane.append(b.detach().numpy()[0]) a_membrane.append(c.detach().numpy()[0]) plt.stem(spike) plt.plot(a_membrane) plt.plot(membrane)",
"import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as",
"num_cls, bias=False) self.membrane = torch.zeros(in_dim, num_cls) self.a_membrane = torch.zeros(in_dim, num_cls) def forward(self, input):",
"self.membrane, self.a_membrane # input = torch.ones(1,1) net = Net() net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]])) out",
"self.leak_mem*self.membrane + self.fc(self.a_membrane) self.out[self.membrane > self.threshold] = 1. self.membrane[self.membrane > self.threshold] = 0.",
"rescale_fac, torch.abs(inp)).float(), torch.sign(inp)) x = torch.tensor(1.0) y = torch.zeros(10) tt = torch.arange(10) for",
"out @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output.clone() grad =",
"2021 @author: mhasan13 using exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import torch import torch.nn as",
"backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output.clone() grad = grad_input * 0.3",
"> self.threshold] = 1. self.membrane[self.membrane > self.threshold] = 0. return self.out, self.membrane, self.a_membrane",
"leak_mem self.fc = nn.Linear(in_dim, num_cls, bias=False) self.membrane = torch.zeros(in_dim, num_cls) self.a_membrane = torch.zeros(in_dim,",
"[] membrane = [] a_membrane = [] spike = [] for t in",
"= [] for t in range(40): input = PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0) a,",
"= grad_input * 0.3 * F.threshold(1.0 - torch.abs(input), 0, 0) return grad def",
"np import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) out =",
"rand_inp = torch.rand_like(inp) return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp)).float(), torch.sign(inp)) x = torch.tensor(1.0) y",
"self.fc(self.a_membrane) self.out[self.membrane > self.threshold] = 1. self.membrane[self.membrane > self.threshold] = 0. return self.out,",
"[] a_membrane = [] spike = [] for t in range(40): input =",
"0] = 1.0 return out @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input",
"(1-self.leak_mem)*self.fc(self.a_membrane) self.membrane = self.leak_mem*self.membrane + self.fc(self.a_membrane) self.out[self.membrane > self.threshold] = 1. self.membrane[self.membrane >",
"import torch.nn.functional as F import matplotlib.pyplot as plt import numpy as np import",
"self.membrane = torch.zeros(in_dim, num_cls) self.a_membrane = torch.zeros(in_dim, num_cls) def forward(self, input): self.out =",
"from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import torch import torch.nn as nn import torch.nn.functional as F",
"__init__(self, leak_mem=0.95, in_dim=1, num_cls=1): super(Net, self).__init__() self.threshold = 1 self.leak_mem = leak_mem self.fc",
"tt = torch.arange(10) for i in range(10): y[i] = PoissonGen(x) class Net(nn.Module): def",
"Created on Sun Oct 17 01:42:08 2021 @author: mhasan13 using exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py",
"mhasan13 using exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\" import torch import torch.nn as nn import",
"range(10): y[i] = PoissonGen(x) class Net(nn.Module): def __init__(self, leak_mem=0.95, in_dim=1, num_cls=1): super(Net, self).__init__()",
"Net(nn.Module): def __init__(self, leak_mem=0.95, in_dim=1, num_cls=1): super(Net, self).__init__() self.threshold = 1 self.leak_mem =",
"leak_mem=0.95, in_dim=1, num_cls=1): super(Net, self).__init__() self.threshold = 1 self.leak_mem = leak_mem self.fc =",
"<filename>initial/initial_1.py # -*- coding: utf-8 -*- \"\"\" Created on Sun Oct 17 01:42:08",
"self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane = self.leak_mem*self.membrane + self.fc(self.a_membrane) self.out[self.membrane > self.threshold] = 1.",
"as nn import torch.nn.functional as F import matplotlib.pyplot as plt import numpy as",
"t in range(40): input = PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0) a, b, c =",
"+ (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane = self.leak_mem*self.membrane + self.fc(self.a_membrane) self.out[self.membrane > self.threshold] = 1. self.membrane[self.membrane",
"torch.zeros(in_dim, num_cls) def forward(self, input): self.out = torch.zeros(1,1) self.a_membrane = self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input)",
"@staticmethod def forward(ctx, input): ctx.save_for_backward(input) out = torch.zeros_like(input) out[input > 0] = 1.0",
"= grad_output.clone() grad = grad_input * 0.3 * F.threshold(1.0 - torch.abs(input), 0, 0)",
"self.out = torch.zeros(1,1) self.a_membrane = self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input) # self.membrane = self.leak_mem*self.membrane +",
"# -*- coding: utf-8 -*- \"\"\" Created on Sun Oct 17 01:42:08 2021",
"as np import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) out",
"# input = torch.ones(1,1) net = Net() net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]])) out = []",
"torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp)).float(), torch.sign(inp)) x = torch.tensor(1.0) y = torch.zeros(10) tt =",
"import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) out = torch.zeros_like(input)",
"import numpy as np import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function): @staticmethod def forward(ctx, input):",
"self.membrane = self.leak_mem*self.membrane + self.fc(self.a_membrane) self.out[self.membrane > self.threshold] = 1. self.membrane[self.membrane > self.threshold]",
"input.unsqueeze_(0) a, b, c = net(input) out.append(a.detach().numpy()[0]) membrane.append(b.detach().numpy()[0]) a_membrane.append(c.detach().numpy()[0]) plt.stem(spike) plt.plot(a_membrane) plt.plot(membrane) plt.plot(out)",
"num_cls) def forward(self, input): self.out = torch.zeros(1,1) self.a_membrane = self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input) #",
"out = torch.zeros_like(input) out[input > 0] = 1.0 return out @staticmethod def backward(ctx,",
"ctx.saved_tensors grad_input = grad_output.clone() grad = grad_input * 0.3 * F.threshold(1.0 - torch.abs(input),",
"torch.nn.Parameter(torch.tensor([[0.5]])) out = [] membrane = [] a_membrane = [] spike = []",
"spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0) a, b, c = net(input) out.append(a.detach().numpy()[0]) membrane.append(b.detach().numpy()[0]) a_membrane.append(c.detach().numpy()[0]) plt.stem(spike) plt.plot(a_membrane)",
"import matplotlib.pyplot as plt import numpy as np import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function):",
"+ (1-self.leak_mem)*(input) # self.membrane = self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane = self.leak_mem*self.membrane + self.fc(self.a_membrane)",
"in range(40): input = PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0) a, b, c = net(input)",
"self).__init__() self.threshold = 1 self.leak_mem = leak_mem self.fc = nn.Linear(in_dim, num_cls, bias=False) self.membrane",
"os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) out = torch.zeros_like(input) out[input >",
"\"\"\" import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot",
"* rescale_fac, torch.abs(inp)).float(), torch.sign(inp)) x = torch.tensor(1.0) y = torch.zeros(10) tt = torch.arange(10)",
"grad_input * 0.3 * F.threshold(1.0 - torch.abs(input), 0, 0) return grad def PoissonGen(inp,",
"self.a_membrane # input = torch.ones(1,1) net = Net() net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]])) out =",
"torch.sign(inp)) x = torch.tensor(1.0) y = torch.zeros(10) tt = torch.arange(10) for i in",
"input): ctx.save_for_backward(input) out = torch.zeros_like(input) out[input > 0] = 1.0 return out @staticmethod",
"1.0 return out @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output.clone()",
"i in range(10): y[i] = PoissonGen(x) class Net(nn.Module): def __init__(self, leak_mem=0.95, in_dim=1, num_cls=1):",
"torch.ones(1,1) net = Net() net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]])) out = [] membrane = []",
"= torch.zeros(in_dim, num_cls) def forward(self, input): self.out = torch.zeros(1,1) self.a_membrane = self.leak_mem*self.a_membrane +",
"1 self.leak_mem = leak_mem self.fc = nn.Linear(in_dim, num_cls, bias=False) self.membrane = torch.zeros(in_dim, num_cls)",
"rescale_fac=2.0): rand_inp = torch.rand_like(inp) return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp)).float(), torch.sign(inp)) x = torch.tensor(1.0)",
"= self.leak_mem*self.membrane + self.fc(self.a_membrane) self.out[self.membrane > self.threshold] = 1. self.membrane[self.membrane > self.threshold] =",
"torch.zeros(10) tt = torch.arange(10) for i in range(10): y[i] = PoissonGen(x) class Net(nn.Module):",
"self.membrane = self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane = self.leak_mem*self.membrane + self.fc(self.a_membrane) self.out[self.membrane > self.threshold]",
"= nn.Linear(in_dim, num_cls, bias=False) self.membrane = torch.zeros(in_dim, num_cls) self.a_membrane = torch.zeros(in_dim, num_cls) def",
"torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt import numpy",
"out[input > 0] = 1.0 return out @staticmethod def backward(ctx, grad_output): input, =",
"input, = ctx.saved_tensors grad_input = grad_output.clone() grad = grad_input * 0.3 * F.threshold(1.0",
"= torch.nn.Parameter(torch.tensor([[0.5]])) out = [] membrane = [] a_membrane = [] spike =",
"grad = grad_input * 0.3 * F.threshold(1.0 - torch.abs(input), 0, 0) return grad",
"SpikingActivation(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) out = torch.zeros_like(input) out[input > 0] =",
"Net() net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]])) out = [] membrane = [] a_membrane = []",
"= torch.rand_like(inp) return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp)).float(), torch.sign(inp)) x = torch.tensor(1.0) y =",
"torch.abs(inp)).float(), torch.sign(inp)) x = torch.tensor(1.0) y = torch.zeros(10) tt = torch.arange(10) for i",
"nn.Linear(in_dim, num_cls, bias=False) self.membrane = torch.zeros(in_dim, num_cls) self.a_membrane = torch.zeros(in_dim, num_cls) def forward(self,",
"y = torch.zeros(10) tt = torch.arange(10) for i in range(10): y[i] = PoissonGen(x)",
"spike = [] for t in range(40): input = PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0)",
"= torch.arange(10) for i in range(10): y[i] = PoissonGen(x) class Net(nn.Module): def __init__(self,",
"0.3 * F.threshold(1.0 - torch.abs(input), 0, 0) return grad def PoissonGen(inp, rescale_fac=2.0): rand_inp",
"self.fc = nn.Linear(in_dim, num_cls, bias=False) self.membrane = torch.zeros(in_dim, num_cls) self.a_membrane = torch.zeros(in_dim, num_cls)",
"return grad def PoissonGen(inp, rescale_fac=2.0): rand_inp = torch.rand_like(inp) return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp)).float(),",
"* 0.3 * F.threshold(1.0 - torch.abs(input), 0, 0) return grad def PoissonGen(inp, rescale_fac=2.0):",
"grad def PoissonGen(inp, rescale_fac=2.0): rand_inp = torch.rand_like(inp) return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp)).float(), torch.sign(inp))",
"def forward(self, input): self.out = torch.zeros(1,1) self.a_membrane = self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input) # self.membrane",
"a_membrane = [] spike = [] for t in range(40): input = PoissonGen(torch.tensor(1.))",
"self.membrane[self.membrane > self.threshold] = 0. return self.out, self.membrane, self.a_membrane # input = torch.ones(1,1)",
"nn import torch.nn.functional as F import matplotlib.pyplot as plt import numpy as np",
"return self.out, self.membrane, self.a_membrane # input = torch.ones(1,1) net = Net() net.fc.weight =",
"= Net() net.fc.weight = torch.nn.Parameter(torch.tensor([[0.5]])) out = [] membrane = [] a_membrane =",
"= [] a_membrane = [] spike = [] for t in range(40): input",
"[] for t in range(40): input = PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0) a, b,",
"= 1.0 return out @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input =",
"0. return self.out, self.membrane, self.a_membrane # input = torch.ones(1,1) net = Net() net.fc.weight",
"def PoissonGen(inp, rescale_fac=2.0): rand_inp = torch.rand_like(inp) return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp)).float(), torch.sign(inp)) x",
"PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0) a, b, c = net(input) out.append(a.detach().numpy()[0]) membrane.append(b.detach().numpy()[0]) a_membrane.append(c.detach().numpy()[0]) plt.stem(spike)",
"plt import numpy as np import os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function): @staticmethod def forward(ctx,",
"torch.zeros_like(input) out[input > 0] = 1.0 return out @staticmethod def backward(ctx, grad_output): input,",
"\"\"\" Created on Sun Oct 17 01:42:08 2021 @author: mhasan13 using exmaple from",
"torch.zeros(in_dim, num_cls) self.a_membrane = torch.zeros(in_dim, num_cls) def forward(self, input): self.out = torch.zeros(1,1) self.a_membrane",
"on Sun Oct 17 01:42:08 2021 @author: mhasan13 using exmaple from https://github.com/Intelligent-Computing-Lab-Yale/BNTT-Batch-Normalization-Through-Time/blob/main/model.py \"\"\"",
"os os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\" class SpikingActivation(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) out = torch.zeros_like(input) out[input",
"membrane = [] a_membrane = [] spike = [] for t in range(40):",
"self.out[self.membrane > self.threshold] = 1. self.membrane[self.membrane > self.threshold] = 0. return self.out, self.membrane,",
"= PoissonGen(torch.tensor(1.)) spike.append(input.detach().numpy()) input.unsqueeze_(0) input.unsqueeze_(0) a, b, c = net(input) out.append(a.detach().numpy()[0]) membrane.append(b.detach().numpy()[0]) a_membrane.append(c.detach().numpy()[0])",
"return out @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output.clone() grad",
"= leak_mem self.fc = nn.Linear(in_dim, num_cls, bias=False) self.membrane = torch.zeros(in_dim, num_cls) self.a_membrane =",
"torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt",
"= self.leak_mem*self.a_membrane + (1-self.leak_mem)*(input) # self.membrane = self.leak_mem*self.membrane + (1-self.leak_mem)*self.fc(self.a_membrane) self.membrane = self.leak_mem*self.membrane",
"> 0] = 1.0 return out @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors"
] |
[
"program; if not, see <http://www.gnu.org/licenses/>. ## import sigrokdecode as srd class Decoder(srd.Decoder): api_version",
"the GNU General Public License as published by ## the Free Software Foundation;",
"port', 'Out', 'O']]) elif b == 2: self.putx([0, ['Polarity inversion register', 'Pol', 'P']])",
"Copyright (C) 2014 alberink <<EMAIL>> ## ## This program is free software; you",
"'ADDRESS READ': self.state = 'READ IO REGS2' self.chip = databyte return elif self.state",
"GNU General Public License ## along with this program; if not, see <http://www.gnu.org/licenses/>.",
"State machine. if self.state == 'IDLE': # Wait for an I²C START condition.",
"('warnings', 'Warnings', (2,)), ) def __init__(self): self.reset() def reset(self): self.state = 'IDLE' self.chip",
"= 'IDLE' def decode(self, ss, es, data): cmd, databyte = data # Store",
"self.state = 'IDLE' self.chip = -1 elif self.state == 'READ IO REGS': #",
"3: self.putx([0, ['Configuration register', 'Conf', 'C']]) def check_correct_chip(self, addr): if addr not in",
"'START REPEAT': self.state = 'READ IO REGS' return # Otherwise: Get data bytes",
"terms of the GNU General Public License as published by ## the Free",
"## This file is part of the libsigrokdecode project. ## ## Copyright (C)",
"expander.' license = 'gplv2+' inputs = ['i2c'] outputs = [] tags = ['Embedded/industrial',",
"read operation. if cmd == 'ADDRESS READ': self.state = 'READ IO REGS2' self.chip",
"have received a copy of the GNU General Public License ## along with",
"'GET SLAVE ADDR': self.chip = databyte self.state = 'GET REG ADDR' elif self.state",
"'START': return self.state = 'GET SLAVE ADDR' elif self.state == 'GET SLAVE ADDR':",
"handle_write_reg(self, b): if b == 0: self.putx([0, ['Input port', 'In', 'I']]) elif b",
"<http://www.gnu.org/licenses/>. ## import sigrokdecode as srd class Decoder(srd.Decoder): api_version = 3 id =",
"warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##",
"should have received a copy of the GNU General Public License ## along",
"'Register value'), ('warning', 'Warning'), ) annotation_rows = ( ('regs', 'Registers', (0, 1)), ('warnings',",
"slave 0x%02X not a TCA6408A ' 'compatible chip.' % addr]]) self.state = 'IDLE'",
"ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR",
"General Public License for more details. ## ## You should have received a",
"## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY",
"to read. if cmd == 'START REPEAT': self.state = 'READ IO REGS' return",
"cmd == 'ADDRESS READ': self.state = 'READ IO REGS2' self.chip = databyte return",
"= 'Texas Instruments TCA6408A 8-bit I²C I/O expander.' license = 'gplv2+' inputs =",
"Free Software Foundation; either version 2 of the License, or ## (at your",
"TCA6408A 8-bit I²C I/O expander.' license = 'gplv2+' inputs = ['i2c'] outputs =",
"'I']]) elif b == 1: self.putx([0, ['Output port', 'Out', 'O']]) elif b ==",
"as srd class Decoder(srd.Decoder): api_version = 3 id = 'tca6408a' name = 'TI",
"['Polarity inverted: %02X' % b]]) def handle_reg_0x03(self, b): self.putx([1, ['Configuration: %02X' % b]])",
"is distributed in the hope that it will be useful, ## but WITHOUT",
"self.state = 'IDLE' def decode(self, ss, es, data): cmd, databyte = data #",
"['i2c'] outputs = [] tags = ['Embedded/industrial', 'IC'] annotations = ( ('register', 'Register",
"annotations = ( ('register', 'Register type'), ('value', 'Register value'), ('warning', 'Warning'), ) annotation_rows",
"% b]]) def handle_write_reg(self, b): if b == 0: self.putx([0, ['Input port', 'In',",
"ADDR': # Wait for a data write (master selects the slave register). if",
"b ]]) def handle_reg_0x02(self, b): self.putx([1, ['Polarity inverted: %02X' % b]]) def handle_reg_0x03(self,",
"along with this program; if not, see <http://www.gnu.org/licenses/>. ## import sigrokdecode as srd",
"of inputs: %02X' % b]]) def handle_reg_0x01(self, b): self.putx([1, ['Outputs set: %02X' %",
") annotation_rows = ( ('regs', 'Registers', (0, 1)), ('warnings', 'Warnings', (2,)), ) def",
"data bytes until a STOP condition occurs. if cmd == 'DATA WRITE': handle_reg",
"software; you can redistribute it and/or modify ## it under the terms of",
"if b == 0: self.putx([0, ['Input port', 'In', 'I']]) elif b == 1:",
"2014 alberink <<EMAIL>> ## ## This program is free software; you can redistribute",
"sigrokdecode as srd class Decoder(srd.Decoder): api_version = 3 id = 'tca6408a' name =",
"## ## You should have received a copy of the GNU General Public",
"(0x20, 0x21): self.putx([2, ['Warning: I²C slave 0x%02X not a TCA6408A ' 'compatible chip.'",
"== 'DATA WRITE': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd ==",
"## ## This program is distributed in the hope that it will be",
"self.putx([0, ['Configuration register', 'Conf', 'C']]) def check_correct_chip(self, addr): if addr not in (0x20,",
"= databyte self.handle_write_reg(self.reg) self.state = 'WRITE IO REGS' elif self.state == 'WRITE IO",
"IO REGS': # If we see a Repeated Start here, the master wants",
"(C) 2014 alberink <<EMAIL>> ## ## This program is free software; you can",
"== 'GET SLAVE ADDR': self.chip = databyte self.state = 'GET REG ADDR' elif",
"of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU",
"decode(self, ss, es, data): cmd, databyte = data # Store the start/end samples",
"as published by ## the Free Software Foundation; either version 2 of the",
"I²C I/O expander.' license = 'gplv2+' inputs = ['i2c'] outputs = [] tags",
"the ## GNU General Public License for more details. ## ## You should",
"Wait for an address read operation. if cmd == 'ADDRESS READ': self.state =",
"## Copyright (C) 2014 alberink <<EMAIL>> ## ## This program is free software;",
"IO REGS2' self.chip = databyte return elif self.state == 'READ IO REGS2': if",
"= -1 elif self.state == 'READ IO REGS': # Wait for an address",
"# If we see a Repeated Start here, the master wants to read.",
"def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def putx(self, data): self.put(self.ss, self.es, self.out_ann, data) def",
"REGS2': if cmd == 'DATA READ': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte)",
"= ss, es # State machine. if self.state == 'IDLE': # Wait for",
"REG ADDR' elif self.state == 'GET REG ADDR': # Wait for a data",
"'Pol', 'P']]) elif b == 3: self.putx([0, ['Configuration register', 'Conf', 'C']]) def check_correct_chip(self,",
"Wait for a data write (master selects the slave register). if cmd in",
"data): self.put(self.ss, self.es, self.out_ann, data) def handle_reg_0x00(self, b): self.putx([1, ['State of inputs: %02X'",
"## (at your option) any later version. ## ## This program is distributed",
"databyte self.state = 'GET REG ADDR' elif self.state == 'GET REG ADDR': #",
"see <http://www.gnu.org/licenses/>. ## import sigrokdecode as srd class Decoder(srd.Decoder): api_version = 3 id",
"data): cmd, databyte = data # Store the start/end samples of this I²C",
"until a STOP condition occurs. if cmd == 'DATA WRITE': handle_reg = getattr(self,",
"'IDLE': # Wait for an I²C START condition. if cmd != 'START': return",
"2012 <NAME> <<EMAIL>> ## Copyright (C) 2013 <NAME> <<EMAIL>> ## Copyright (C) 2014",
"self.state = 'WRITE IO REGS' elif self.state == 'WRITE IO REGS': # If",
"## it under the terms of the GNU General Public License as published",
"the Free Software Foundation; either version 2 of the License, or ## (at",
"annotation_rows = ( ('regs', 'Registers', (0, 1)), ('warnings', 'Warnings', (2,)), ) def __init__(self):",
"elif self.state == 'READ IO REGS': # Wait for an address read operation.",
"or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License",
"(0, 1)), ('warnings', 'Warnings', (2,)), ) def __init__(self): self.reset() def reset(self): self.state =",
"cmd, databyte = data # Store the start/end samples of this I²C packet.",
"useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ##",
"self.register(srd.OUTPUT_ANN) def putx(self, data): self.put(self.ss, self.es, self.out_ann, data) def handle_reg_0x00(self, b): self.putx([1, ['State",
"License for more details. ## ## You should have received a copy of",
"%02X' % b ]]) def handle_reg_0x02(self, b): self.putx([1, ['Polarity inverted: %02X' % b]])",
"== 3: self.putx([0, ['Configuration register', 'Conf', 'C']]) def check_correct_chip(self, addr): if addr not",
"self.putx([0, ['Output port', 'Out', 'O']]) elif b == 2: self.putx([0, ['Polarity inversion register',",
"== 1: self.putx([0, ['Output port', 'Out', 'O']]) elif b == 2: self.putx([0, ['Polarity",
"<NAME> <<EMAIL>> ## Copyright (C) 2014 alberink <<EMAIL>> ## ## This program is",
"['Output port', 'Out', 'O']]) elif b == 2: self.putx([0, ['Polarity inversion register', 'Pol',",
"% addr]]) self.state = 'IDLE' def decode(self, ss, es, data): cmd, databyte =",
"handle_reg_0x01(self, b): self.putx([1, ['Outputs set: %02X' % b ]]) def handle_reg_0x02(self, b): self.putx([1,",
"b): self.putx([1, ['Polarity inverted: %02X' % b]]) def handle_reg_0x03(self, b): self.putx([1, ['Configuration: %02X'",
"inversion register', 'Pol', 'P']]) elif b == 3: self.putx([0, ['Configuration register', 'Conf', 'C']])",
"under the terms of the GNU General Public License as published by ##",
"that it will be useful, ## but WITHOUT ANY WARRANTY; without even the",
"or ## (at your option) any later version. ## ## This program is",
"handle_reg_0x02(self, b): self.putx([1, ['Polarity inverted: %02X' % b]]) def handle_reg_0x03(self, b): self.putx([1, ['Configuration:",
"the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without",
"'READ IO REGS2' self.chip = databyte return elif self.state == 'READ IO REGS2':",
"self.chip = -1 elif self.state == 'READ IO REGS': # Wait for an",
"READ': self.state = 'READ IO REGS2' self.chip = databyte return elif self.state ==",
"start/end samples of this I²C packet. self.ss, self.es = ss, es # State",
"= ['Embedded/industrial', 'IC'] annotations = ( ('register', 'Register type'), ('value', 'Register value'), ('warning',",
"api_version = 3 id = 'tca6408a' name = 'TI TCA6408A' longname = 'Texas",
"% b]]) def handle_reg_0x01(self, b): self.putx([1, ['Outputs set: %02X' % b ]]) def",
"Public License ## along with this program; if not, see <http://www.gnu.org/licenses/>. ## import",
"%02X' % b]]) def handle_reg_0x03(self, b): self.putx([1, ['Configuration: %02X' % b]]) def handle_write_reg(self,",
"is part of the libsigrokdecode project. ## ## Copyright (C) 2012 <NAME> <<EMAIL>>",
"self.putx([1, ['Polarity inverted: %02X' % b]]) def handle_reg_0x03(self, b): self.putx([1, ['Configuration: %02X' %",
"= 'Texas Instruments TCA6408A' desc = 'Texas Instruments TCA6408A 8-bit I²C I/O expander.'",
"self.state = 'GET SLAVE ADDR' elif self.state == 'GET SLAVE ADDR': self.chip =",
"self.state = 'READ IO REGS2' self.chip = databyte return elif self.state == 'READ",
"Copyright (C) 2013 <NAME> <<EMAIL>> ## Copyright (C) 2014 alberink <<EMAIL>> ## ##",
"elif b == 2: self.putx([0, ['Polarity inversion register', 'Pol', 'P']]) elif b ==",
"it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied",
"TCA6408A' desc = 'Texas Instruments TCA6408A 8-bit I²C I/O expander.' license = 'gplv2+'",
"handle_reg_0x00(self, b): self.putx([1, ['State of inputs: %02X' % b]]) def handle_reg_0x01(self, b): self.putx([1,",
"ss, es, data): cmd, databyte = data # Store the start/end samples of",
"ADDR' elif self.state == 'GET SLAVE ADDR': self.chip = databyte self.state = 'GET",
"Store the start/end samples of this I²C packet. self.ss, self.es = ss, es",
"== 'START REPEAT': self.state = 'READ IO REGS' return # Otherwise: Get data",
"Get data bytes until a STOP condition occurs. if cmd == 'DATA WRITE':",
"== 'READ IO REGS2': if cmd == 'DATA READ': handle_reg = getattr(self, 'handle_reg_0x%02x'",
"['Input port', 'In', 'I']]) elif b == 1: self.putx([0, ['Output port', 'Out', 'O']])",
"condition. if cmd != 'START': return self.state = 'GET SLAVE ADDR' elif self.state",
"Decoder(srd.Decoder): api_version = 3 id = 'tca6408a' name = 'TI TCA6408A' longname =",
"= ( ('register', 'Register type'), ('value', 'Register value'), ('warning', 'Warning'), ) annotation_rows =",
"'tca6408a' name = 'TI TCA6408A' longname = 'Texas Instruments TCA6408A' desc = 'Texas",
"## This program is distributed in the hope that it will be useful,",
"= 'IDLE' self.chip = -1 def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def putx(self, data):",
"b): self.putx([1, ['Configuration: %02X' % b]]) def handle_write_reg(self, b): if b == 0:",
"self.chip = -1 def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def putx(self, data): self.put(self.ss, self.es,",
"2013 <NAME> <<EMAIL>> ## Copyright (C) 2014 alberink <<EMAIL>> ## ## This program",
"['Polarity inversion register', 'Pol', 'P']]) elif b == 3: self.putx([0, ['Configuration register', 'Conf',",
"!= 'START': return self.state = 'GET SLAVE ADDR' elif self.state == 'GET SLAVE",
"b == 1: self.putx([0, ['Output port', 'Out', 'O']]) elif b == 2: self.putx([0,",
"[] tags = ['Embedded/industrial', 'IC'] annotations = ( ('register', 'Register type'), ('value', 'Register",
"even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"('ADDRESS READ', 'ADDRESS WRITE'): self.check_correct_chip(databyte) if cmd != 'DATA WRITE': return self.reg =",
"port', 'In', 'I']]) elif b == 1: self.putx([0, ['Output port', 'Out', 'O']]) elif",
"['Configuration register', 'Conf', 'C']]) def check_correct_chip(self, addr): if addr not in (0x20, 0x21):",
"if cmd == 'ADDRESS READ': self.state = 'READ IO REGS2' self.chip = databyte",
"-1 elif self.state == 'READ IO REGS': # Wait for an address read",
"'Conf', 'C']]) def check_correct_chip(self, addr): if addr not in (0x20, 0x21): self.putx([2, ['Warning:",
"PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ##",
"bytes until a STOP condition occurs. if cmd == 'DATA WRITE': handle_reg =",
"read. if cmd == 'START REPEAT': self.state = 'READ IO REGS' return #",
"def handle_reg_0x00(self, b): self.putx([1, ['State of inputs: %02X' % b]]) def handle_reg_0x01(self, b):",
"= self.register(srd.OUTPUT_ANN) def putx(self, data): self.put(self.ss, self.es, self.out_ann, data) def handle_reg_0x00(self, b): self.putx([1,",
"self.state == 'GET REG ADDR': # Wait for a data write (master selects",
"== 'ADDRESS READ': self.state = 'READ IO REGS2' self.chip = databyte return elif",
"REPEAT': self.state = 'READ IO REGS' return # Otherwise: Get data bytes until",
"'READ IO REGS2': if cmd == 'DATA READ': handle_reg = getattr(self, 'handle_reg_0x%02x' %",
"operation. if cmd == 'ADDRESS READ': self.state = 'READ IO REGS2' self.chip =",
"== 'DATA READ': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd ==",
"id = 'tca6408a' name = 'TI TCA6408A' longname = 'Texas Instruments TCA6408A' desc",
"Otherwise: Get data bytes until a STOP condition occurs. if cmd == 'DATA",
"__init__(self): self.reset() def reset(self): self.state = 'IDLE' self.chip = -1 def start(self): self.out_ann",
"handle_reg(databyte) elif cmd == 'STOP': self.state = 'IDLE' self.chip = -1 elif self.state",
"'IDLE' def decode(self, ss, es, data): cmd, databyte = data # Store the",
"'DATA WRITE': return self.reg = databyte self.handle_write_reg(self.reg) self.state = 'WRITE IO REGS' elif",
"# Wait for an I²C START condition. if cmd != 'START': return self.state",
"elif self.state == 'READ IO REGS2': if cmd == 'DATA READ': handle_reg =",
"cmd == 'DATA READ': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd",
"free software; you can redistribute it and/or modify ## it under the terms",
"data) def handle_reg_0x00(self, b): self.putx([1, ['State of inputs: %02X' % b]]) def handle_reg_0x01(self,",
"Public License for more details. ## ## You should have received a copy",
"IO REGS': # Wait for an address read operation. if cmd == 'ADDRESS",
"1: self.putx([0, ['Output port', 'Out', 'O']]) elif b == 2: self.putx([0, ['Polarity inversion",
"reset(self): self.state = 'IDLE' self.chip = -1 def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def",
"if not, see <http://www.gnu.org/licenses/>. ## import sigrokdecode as srd class Decoder(srd.Decoder): api_version =",
"TCA6408A ' 'compatible chip.' % addr]]) self.state = 'IDLE' def decode(self, ss, es,",
"redistribute it and/or modify ## it under the terms of the GNU General",
"= 'GET SLAVE ADDR' elif self.state == 'GET SLAVE ADDR': self.chip = databyte",
"license = 'gplv2+' inputs = ['i2c'] outputs = [] tags = ['Embedded/industrial', 'IC']",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public",
"occurs. if cmd == 'DATA WRITE': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte)",
"received a copy of the GNU General Public License ## along with this",
"machine. if self.state == 'IDLE': # Wait for an I²C START condition. if",
"= 'WRITE IO REGS' elif self.state == 'WRITE IO REGS': # If we",
"addr not in (0x20, 0x21): self.putx([2, ['Warning: I²C slave 0x%02X not a TCA6408A",
"ADDR' elif self.state == 'GET REG ADDR': # Wait for a data write",
"= ['i2c'] outputs = [] tags = ['Embedded/industrial', 'IC'] annotations = ( ('register',",
"= -1 def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def putx(self, data): self.put(self.ss, self.es, self.out_ann,",
"the master wants to read. if cmd == 'START REPEAT': self.state = 'READ",
"'IDLE' self.chip = -1 elif self.state == 'READ IO REGS': # Wait for",
"== 'GET REG ADDR': # Wait for a data write (master selects the",
"# Otherwise: Get data bytes until a STOP condition occurs. if cmd ==",
"= getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd == 'STOP': self.state = 'IDLE'",
"not, see <http://www.gnu.org/licenses/>. ## import sigrokdecode as srd class Decoder(srd.Decoder): api_version = 3",
"'Register type'), ('value', 'Register value'), ('warning', 'Warning'), ) annotation_rows = ( ('regs', 'Registers',",
"databyte return elif self.state == 'READ IO REGS2': if cmd == 'DATA READ':",
"<<EMAIL>> ## Copyright (C) 2014 alberink <<EMAIL>> ## ## This program is free",
"inputs = ['i2c'] outputs = [] tags = ['Embedded/industrial', 'IC'] annotations = (",
"name = 'TI TCA6408A' longname = 'Texas Instruments TCA6408A' desc = 'Texas Instruments",
"= 3 id = 'tca6408a' name = 'TI TCA6408A' longname = 'Texas Instruments",
"% self.reg) handle_reg(databyte) elif cmd == 'STOP': self.state = 'IDLE' self.chip = -1",
"2: self.putx([0, ['Polarity inversion register', 'Pol', 'P']]) elif b == 3: self.putx([0, ['Configuration",
"start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def putx(self, data): self.put(self.ss, self.es, self.out_ann, data) def handle_reg_0x00(self,",
"self.es, self.out_ann, data) def handle_reg_0x00(self, b): self.putx([1, ['State of inputs: %02X' % b]])",
"I²C START condition. if cmd != 'START': return self.state = 'GET SLAVE ADDR'",
"GNU General Public License as published by ## the Free Software Foundation; either",
"self.putx([1, ['State of inputs: %02X' % b]]) def handle_reg_0x01(self, b): self.putx([1, ['Outputs set:",
"Wait for an I²C START condition. if cmd != 'START': return self.state =",
"self.check_correct_chip(databyte) if cmd != 'DATA WRITE': return self.reg = databyte self.handle_write_reg(self.reg) self.state =",
"if cmd != 'DATA WRITE': return self.reg = databyte self.handle_write_reg(self.reg) self.state = 'WRITE",
"== 'STOP': self.state = 'IDLE' self.chip = -1 elif self.state == 'READ IO",
"'DATA WRITE': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd == 'STOP':",
"register', 'Pol', 'P']]) elif b == 3: self.putx([0, ['Configuration register', 'Conf', 'C']]) def",
"['Embedded/industrial', 'IC'] annotations = ( ('register', 'Register type'), ('value', 'Register value'), ('warning', 'Warning'),",
"Instruments TCA6408A' desc = 'Texas Instruments TCA6408A 8-bit I²C I/O expander.' license =",
"elif self.state == 'GET SLAVE ADDR': self.chip = databyte self.state = 'GET REG",
"def putx(self, data): self.put(self.ss, self.es, self.out_ann, data) def handle_reg_0x00(self, b): self.putx([1, ['State of",
"a TCA6408A ' 'compatible chip.' % addr]]) self.state = 'IDLE' def decode(self, ss,",
"version. ## ## This program is distributed in the hope that it will",
"this program; if not, see <http://www.gnu.org/licenses/>. ## import sigrokdecode as srd class Decoder(srd.Decoder):",
"self.reset() def reset(self): self.state = 'IDLE' self.chip = -1 def start(self): self.out_ann =",
"es # State machine. if self.state == 'IDLE': # Wait for an I²C",
"WRITE'): self.check_correct_chip(databyte) if cmd != 'DATA WRITE': return self.reg = databyte self.handle_write_reg(self.reg) self.state",
"<NAME> <<EMAIL>> ## Copyright (C) 2013 <NAME> <<EMAIL>> ## Copyright (C) 2014 alberink",
"= 'gplv2+' inputs = ['i2c'] outputs = [] tags = ['Embedded/industrial', 'IC'] annotations",
"0x21): self.putx([2, ['Warning: I²C slave 0x%02X not a TCA6408A ' 'compatible chip.' %",
"of the GNU General Public License as published by ## the Free Software",
"<<EMAIL>> ## Copyright (C) 2013 <NAME> <<EMAIL>> ## Copyright (C) 2014 alberink <<EMAIL>>",
"self.putx([2, ['Warning: I²C slave 0x%02X not a TCA6408A ' 'compatible chip.' % addr]])",
"cmd in ('ADDRESS READ', 'ADDRESS WRITE'): self.check_correct_chip(databyte) if cmd != 'DATA WRITE': return",
"2 of the License, or ## (at your option) any later version. ##",
"'WRITE IO REGS' elif self.state == 'WRITE IO REGS': # If we see",
"self.putx([0, ['Input port', 'In', 'I']]) elif b == 1: self.putx([0, ['Output port', 'Out',",
"IO REGS' elif self.state == 'WRITE IO REGS': # If we see a",
"def handle_reg_0x02(self, b): self.putx([1, ['Polarity inverted: %02X' % b]]) def handle_reg_0x03(self, b): self.putx([1,",
"not a TCA6408A ' 'compatible chip.' % addr]]) self.state = 'IDLE' def decode(self,",
"## ## This program is free software; you can redistribute it and/or modify",
"self.reg = databyte self.handle_write_reg(self.reg) self.state = 'WRITE IO REGS' elif self.state == 'WRITE",
"a data write (master selects the slave register). if cmd in ('ADDRESS READ',",
"= 'GET REG ADDR' elif self.state == 'GET REG ADDR': # Wait for",
"elif b == 3: self.putx([0, ['Configuration register', 'Conf', 'C']]) def check_correct_chip(self, addr): if",
"def __init__(self): self.reset() def reset(self): self.state = 'IDLE' self.chip = -1 def start(self):",
"= data # Store the start/end samples of this I²C packet. self.ss, self.es",
"0x%02X not a TCA6408A ' 'compatible chip.' % addr]]) self.state = 'IDLE' def",
"self.out_ann = self.register(srd.OUTPUT_ANN) def putx(self, data): self.put(self.ss, self.es, self.out_ann, data) def handle_reg_0x00(self, b):",
"file is part of the libsigrokdecode project. ## ## Copyright (C) 2012 <NAME>",
"['Outputs set: %02X' % b ]]) def handle_reg_0x02(self, b): self.putx([1, ['Polarity inverted: %02X'",
"packet. self.ss, self.es = ss, es # State machine. if self.state == 'IDLE':",
"'TI TCA6408A' longname = 'Texas Instruments TCA6408A' desc = 'Texas Instruments TCA6408A 8-bit",
"PURPOSE. See the ## GNU General Public License for more details. ## ##",
"option) any later version. ## ## This program is distributed in the hope",
"b == 3: self.putx([0, ['Configuration register', 'Conf', 'C']]) def check_correct_chip(self, addr): if addr",
"cmd != 'DATA WRITE': return self.reg = databyte self.handle_write_reg(self.reg) self.state = 'WRITE IO",
"getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd == 'STOP': self.state = 'IDLE' self.chip",
"= [] tags = ['Embedded/industrial', 'IC'] annotations = ( ('register', 'Register type'), ('value',",
"== 'READ IO REGS': # Wait for an address read operation. if cmd",
"libsigrokdecode project. ## ## Copyright (C) 2012 <NAME> <<EMAIL>> ## Copyright (C) 2013",
"License as published by ## the Free Software Foundation; either version 2 of",
"## You should have received a copy of the GNU General Public License",
"the libsigrokdecode project. ## ## Copyright (C) 2012 <NAME> <<EMAIL>> ## Copyright (C)",
"self.put(self.ss, self.es, self.out_ann, data) def handle_reg_0x00(self, b): self.putx([1, ['State of inputs: %02X' %",
"'GET REG ADDR' elif self.state == 'GET REG ADDR': # Wait for a",
"self.putx([1, ['Configuration: %02X' % b]]) def handle_write_reg(self, b): if b == 0: self.putx([0,",
"inverted: %02X' % b]]) def handle_reg_0x03(self, b): self.putx([1, ['Configuration: %02X' % b]]) def",
"['Configuration: %02X' % b]]) def handle_write_reg(self, b): if b == 0: self.putx([0, ['Input",
"License ## along with this program; if not, see <http://www.gnu.org/licenses/>. ## import sigrokdecode",
"'Texas Instruments TCA6408A' desc = 'Texas Instruments TCA6408A 8-bit I²C I/O expander.' license",
"== 0: self.putx([0, ['Input port', 'In', 'I']]) elif b == 1: self.putx([0, ['Output",
"condition occurs. if cmd == 'DATA WRITE': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg)",
"elif b == 1: self.putx([0, ['Output port', 'Out', 'O']]) elif b == 2:",
"version 2 of the License, or ## (at your option) any later version.",
"addr): if addr not in (0x20, 0x21): self.putx([2, ['Warning: I²C slave 0x%02X not",
"can redistribute it and/or modify ## it under the terms of the GNU",
"check_correct_chip(self, addr): if addr not in (0x20, 0x21): self.putx([2, ['Warning: I²C slave 0x%02X",
"it under the terms of the GNU General Public License as published by",
"type'), ('value', 'Register value'), ('warning', 'Warning'), ) annotation_rows = ( ('regs', 'Registers', (0,",
"register', 'Conf', 'C']]) def check_correct_chip(self, addr): if addr not in (0x20, 0x21): self.putx([2,",
"FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for",
") def __init__(self): self.reset() def reset(self): self.state = 'IDLE' self.chip = -1 def",
"the License, or ## (at your option) any later version. ## ## This",
"desc = 'Texas Instruments TCA6408A 8-bit I²C I/O expander.' license = 'gplv2+' inputs",
"of the GNU General Public License ## along with this program; if not,",
"databyte = data # Store the start/end samples of this I²C packet. self.ss,",
"READ': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd == 'STOP': self.state",
"'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd == 'STOP': self.state = 'IDLE' self.chip =",
"your option) any later version. ## ## This program is distributed in the",
"if addr not in (0x20, 0x21): self.putx([2, ['Warning: I²C slave 0x%02X not a",
"longname = 'Texas Instruments TCA6408A' desc = 'Texas Instruments TCA6408A 8-bit I²C I/O",
"IO REGS2': if cmd == 'DATA READ': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg)",
"A PARTICULAR PURPOSE. See the ## GNU General Public License for more details.",
"we see a Repeated Start here, the master wants to read. if cmd",
"chip.' % addr]]) self.state = 'IDLE' def decode(self, ss, es, data): cmd, databyte",
"data write (master selects the slave register). if cmd in ('ADDRESS READ', 'ADDRESS",
"( ('register', 'Register type'), ('value', 'Register value'), ('warning', 'Warning'), ) annotation_rows = (",
"START condition. if cmd != 'START': return self.state = 'GET SLAVE ADDR' elif",
"'O']]) elif b == 2: self.putx([0, ['Polarity inversion register', 'Pol', 'P']]) elif b",
"data # Store the start/end samples of this I²C packet. self.ss, self.es =",
"an I²C START condition. if cmd != 'START': return self.state = 'GET SLAVE",
"## ## This file is part of the libsigrokdecode project. ## ## Copyright",
"see a Repeated Start here, the master wants to read. if cmd ==",
"of the libsigrokdecode project. ## ## Copyright (C) 2012 <NAME> <<EMAIL>> ## Copyright",
"Public License as published by ## the Free Software Foundation; either version 2",
"be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of",
"'GET SLAVE ADDR' elif self.state == 'GET SLAVE ADDR': self.chip = databyte self.state",
"details. ## ## You should have received a copy of the GNU General",
"address read operation. if cmd == 'ADDRESS READ': self.state = 'READ IO REGS2'",
"REGS' elif self.state == 'WRITE IO REGS': # If we see a Repeated",
"' 'compatible chip.' % addr]]) self.state = 'IDLE' def decode(self, ss, es, data):",
"'C']]) def check_correct_chip(self, addr): if addr not in (0x20, 0x21): self.putx([2, ['Warning: I²C",
"self.reg) handle_reg(databyte) elif cmd == 'STOP': self.state = 'IDLE' self.chip = -1 elif",
"== 2: self.putx([0, ['Polarity inversion register', 'Pol', 'P']]) elif b == 3: self.putx([0,",
"it and/or modify ## it under the terms of the GNU General Public",
"but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or",
"8-bit I²C I/O expander.' license = 'gplv2+' inputs = ['i2c'] outputs = []",
"REG ADDR': # Wait for a data write (master selects the slave register).",
"0: self.putx([0, ['Input port', 'In', 'I']]) elif b == 1: self.putx([0, ['Output port',",
"General Public License as published by ## the Free Software Foundation; either version",
"WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS",
"alberink <<EMAIL>> ## ## This program is free software; you can redistribute it",
"(C) 2013 <NAME> <<EMAIL>> ## Copyright (C) 2014 alberink <<EMAIL>> ## ## This",
"See the ## GNU General Public License for more details. ## ## You",
"READ', 'ADDRESS WRITE'): self.check_correct_chip(databyte) if cmd != 'DATA WRITE': return self.reg = databyte",
"%02X' % b]]) def handle_reg_0x01(self, b): self.putx([1, ['Outputs set: %02X' % b ]])",
"es, data): cmd, databyte = data # Store the start/end samples of this",
"modify ## it under the terms of the GNU General Public License as",
"# State machine. if self.state == 'IDLE': # Wait for an I²C START",
"handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd == 'STOP': self.state =",
"for an I²C START condition. if cmd != 'START': return self.state = 'GET",
"self.state == 'READ IO REGS2': if cmd == 'DATA READ': handle_reg = getattr(self,",
"a copy of the GNU General Public License ## along with this program;",
"def handle_reg_0x03(self, b): self.putx([1, ['Configuration: %02X' % b]]) def handle_write_reg(self, b): if b",
"self.handle_write_reg(self.reg) self.state = 'WRITE IO REGS' elif self.state == 'WRITE IO REGS': #",
"the terms of the GNU General Public License as published by ## the",
"you can redistribute it and/or modify ## it under the terms of the",
"I/O expander.' license = 'gplv2+' inputs = ['i2c'] outputs = [] tags =",
"General Public License ## along with this program; if not, see <http://www.gnu.org/licenses/>. ##",
"databyte self.handle_write_reg(self.reg) self.state = 'WRITE IO REGS' elif self.state == 'WRITE IO REGS':",
"the GNU General Public License ## along with this program; if not, see",
"self.out_ann, data) def handle_reg_0x00(self, b): self.putx([1, ['State of inputs: %02X' % b]]) def",
"== 'WRITE IO REGS': # If we see a Repeated Start here, the",
"= 'READ IO REGS2' self.chip = databyte return elif self.state == 'READ IO",
"(master selects the slave register). if cmd in ('ADDRESS READ', 'ADDRESS WRITE'): self.check_correct_chip(databyte)",
"FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more",
"for an address read operation. if cmd == 'ADDRESS READ': self.state = 'READ",
"ADDR': self.chip = databyte self.state = 'GET REG ADDR' elif self.state == 'GET",
"putx(self, data): self.put(self.ss, self.es, self.out_ann, data) def handle_reg_0x00(self, b): self.putx([1, ['State of inputs:",
"not in (0x20, 0x21): self.putx([2, ['Warning: I²C slave 0x%02X not a TCA6408A '",
"import sigrokdecode as srd class Decoder(srd.Decoder): api_version = 3 id = 'tca6408a' name",
"('value', 'Register value'), ('warning', 'Warning'), ) annotation_rows = ( ('regs', 'Registers', (0, 1)),",
"REGS2' self.chip = databyte return elif self.state == 'READ IO REGS2': if cmd",
"'READ IO REGS': # Wait for an address read operation. if cmd ==",
"'IC'] annotations = ( ('register', 'Register type'), ('value', 'Register value'), ('warning', 'Warning'), )",
"b == 2: self.putx([0, ['Polarity inversion register', 'Pol', 'P']]) elif b == 3:",
"]]) def handle_reg_0x02(self, b): self.putx([1, ['Polarity inverted: %02X' % b]]) def handle_reg_0x03(self, b):",
"b]]) def handle_write_reg(self, b): if b == 0: self.putx([0, ['Input port', 'In', 'I']])",
"# Wait for a data write (master selects the slave register). if cmd",
"You should have received a copy of the GNU General Public License ##",
"License, or ## (at your option) any later version. ## ## This program",
"STOP condition occurs. if cmd == 'DATA WRITE': handle_reg = getattr(self, 'handle_reg_0x%02x' %",
"self.chip = databyte self.state = 'GET REG ADDR' elif self.state == 'GET REG",
"'GET REG ADDR': # Wait for a data write (master selects the slave",
"= 'IDLE' self.chip = -1 elif self.state == 'READ IO REGS': # Wait",
"self.state == 'GET SLAVE ADDR': self.chip = databyte self.state = 'GET REG ADDR'",
"def reset(self): self.state = 'IDLE' self.chip = -1 def start(self): self.out_ann = self.register(srd.OUTPUT_ANN)",
"elif self.state == 'GET REG ADDR': # Wait for a data write (master",
"cmd == 'STOP': self.state = 'IDLE' self.chip = -1 elif self.state == 'READ",
"This file is part of the libsigrokdecode project. ## ## Copyright (C) 2012",
"tags = ['Embedded/industrial', 'IC'] annotations = ( ('register', 'Register type'), ('value', 'Register value'),",
"<<EMAIL>> ## ## This program is free software; you can redistribute it and/or",
"in ('ADDRESS READ', 'ADDRESS WRITE'): self.check_correct_chip(databyte) if cmd != 'DATA WRITE': return self.reg",
"3 id = 'tca6408a' name = 'TI TCA6408A' longname = 'Texas Instruments TCA6408A'",
"addr]]) self.state = 'IDLE' def decode(self, ss, es, data): cmd, databyte = data",
"'Registers', (0, 1)), ('warnings', 'Warnings', (2,)), ) def __init__(self): self.reset() def reset(self): self.state",
"REGS': # If we see a Repeated Start here, the master wants to",
"('register', 'Register type'), ('value', 'Register value'), ('warning', 'Warning'), ) annotation_rows = ( ('regs',",
"in the hope that it will be useful, ## but WITHOUT ANY WARRANTY;",
"(2,)), ) def __init__(self): self.reset() def reset(self): self.state = 'IDLE' self.chip = -1",
"WRITE': return self.reg = databyte self.handle_write_reg(self.reg) self.state = 'WRITE IO REGS' elif self.state",
"Repeated Start here, the master wants to read. if cmd == 'START REPEAT':",
"self.state = 'IDLE' self.chip = -1 def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def putx(self,",
"return # Otherwise: Get data bytes until a STOP condition occurs. if cmd",
"and/or modify ## it under the terms of the GNU General Public License",
"'Out', 'O']]) elif b == 2: self.putx([0, ['Polarity inversion register', 'Pol', 'P']]) elif",
"b): if b == 0: self.putx([0, ['Input port', 'In', 'I']]) elif b ==",
"hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even",
"IO REGS' return # Otherwise: Get data bytes until a STOP condition occurs.",
"'READ IO REGS' return # Otherwise: Get data bytes until a STOP condition",
"implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"distributed in the hope that it will be useful, ## but WITHOUT ANY",
"b): self.putx([1, ['Outputs set: %02X' % b ]]) def handle_reg_0x02(self, b): self.putx([1, ['Polarity",
"If we see a Repeated Start here, the master wants to read. if",
"wants to read. if cmd == 'START REPEAT': self.state = 'READ IO REGS'",
"GNU General Public License for more details. ## ## You should have received",
"'WRITE IO REGS': # If we see a Repeated Start here, the master",
"by ## the Free Software Foundation; either version 2 of the License, or",
"b): self.putx([1, ['State of inputs: %02X' % b]]) def handle_reg_0x01(self, b): self.putx([1, ['Outputs",
"SLAVE ADDR': self.chip = databyte self.state = 'GET REG ADDR' elif self.state ==",
"part of the libsigrokdecode project. ## ## Copyright (C) 2012 <NAME> <<EMAIL>> ##",
"self.state == 'WRITE IO REGS': # If we see a Repeated Start here,",
"register). if cmd in ('ADDRESS READ', 'ADDRESS WRITE'): self.check_correct_chip(databyte) if cmd != 'DATA",
"cmd != 'START': return self.state = 'GET SLAVE ADDR' elif self.state == 'GET",
"## GNU General Public License for more details. ## ## You should have",
"## This program is free software; you can redistribute it and/or modify ##",
"% b ]]) def handle_reg_0x02(self, b): self.putx([1, ['Polarity inverted: %02X' % b]]) def",
"if cmd in ('ADDRESS READ', 'ADDRESS WRITE'): self.check_correct_chip(databyte) if cmd != 'DATA WRITE':",
"## the Free Software Foundation; either version 2 of the License, or ##",
"= 'tca6408a' name = 'TI TCA6408A' longname = 'Texas Instruments TCA6408A' desc =",
"'compatible chip.' % addr]]) self.state = 'IDLE' def decode(self, ss, es, data): cmd,",
"in (0x20, 0x21): self.putx([2, ['Warning: I²C slave 0x%02X not a TCA6408A ' 'compatible",
"elif self.state == 'WRITE IO REGS': # If we see a Repeated Start",
"## Copyright (C) 2013 <NAME> <<EMAIL>> ## Copyright (C) 2014 alberink <<EMAIL>> ##",
"def handle_write_reg(self, b): if b == 0: self.putx([0, ['Input port', 'In', 'I']]) elif",
"This program is distributed in the hope that it will be useful, ##",
"return self.reg = databyte self.handle_write_reg(self.reg) self.state = 'WRITE IO REGS' elif self.state ==",
"project. ## ## Copyright (C) 2012 <NAME> <<EMAIL>> ## Copyright (C) 2013 <NAME>",
"for more details. ## ## You should have received a copy of the",
"value'), ('warning', 'Warning'), ) annotation_rows = ( ('regs', 'Registers', (0, 1)), ('warnings', 'Warnings',",
"= 'READ IO REGS' return # Otherwise: Get data bytes until a STOP",
"!= 'DATA WRITE': return self.reg = databyte self.handle_write_reg(self.reg) self.state = 'WRITE IO REGS'",
"class Decoder(srd.Decoder): api_version = 3 id = 'tca6408a' name = 'TI TCA6408A' longname",
"either version 2 of the License, or ## (at your option) any later",
"## along with this program; if not, see <http://www.gnu.org/licenses/>. ## import sigrokdecode as",
"self.state == 'READ IO REGS': # Wait for an address read operation. if",
"Instruments TCA6408A 8-bit I²C I/O expander.' license = 'gplv2+' inputs = ['i2c'] outputs",
"('warning', 'Warning'), ) annotation_rows = ( ('regs', 'Registers', (0, 1)), ('warnings', 'Warnings', (2,)),",
"if cmd == 'START REPEAT': self.state = 'READ IO REGS' return # Otherwise:",
"= 'TI TCA6408A' longname = 'Texas Instruments TCA6408A' desc = 'Texas Instruments TCA6408A",
"%02X' % b]]) def handle_write_reg(self, b): if b == 0: self.putx([0, ['Input port',",
"cmd == 'DATA WRITE': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd",
"return self.state = 'GET SLAVE ADDR' elif self.state == 'GET SLAVE ADDR': self.chip",
"a STOP condition occurs. if cmd == 'DATA WRITE': handle_reg = getattr(self, 'handle_reg_0x%02x'",
"outputs = [] tags = ['Embedded/industrial', 'IC'] annotations = ( ('register', 'Register type'),",
"master wants to read. if cmd == 'START REPEAT': self.state = 'READ IO",
"b]]) def handle_reg_0x01(self, b): self.putx([1, ['Outputs set: %02X' % b ]]) def handle_reg_0x02(self,",
"the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"b]]) def handle_reg_0x03(self, b): self.putx([1, ['Configuration: %02X' % b]]) def handle_write_reg(self, b): if",
"ss, es # State machine. if self.state == 'IDLE': # Wait for an",
"## ## Copyright (C) 2012 <NAME> <<EMAIL>> ## Copyright (C) 2013 <NAME> <<EMAIL>>",
"with this program; if not, see <http://www.gnu.org/licenses/>. ## import sigrokdecode as srd class",
"self.state = 'READ IO REGS' return # Otherwise: Get data bytes until a",
"1)), ('warnings', 'Warnings', (2,)), ) def __init__(self): self.reset() def reset(self): self.state = 'IDLE'",
"copy of the GNU General Public License ## along with this program; if",
"an address read operation. if cmd == 'ADDRESS READ': self.state = 'READ IO",
"self.ss, self.es = ss, es # State machine. if self.state == 'IDLE': #",
"(at your option) any later version. ## ## This program is distributed in",
"inputs: %02X' % b]]) def handle_reg_0x01(self, b): self.putx([1, ['Outputs set: %02X' % b",
"# Store the start/end samples of this I²C packet. self.ss, self.es = ss,",
"'P']]) elif b == 3: self.putx([0, ['Configuration register', 'Conf', 'C']]) def check_correct_chip(self, addr):",
"Foundation; either version 2 of the License, or ## (at your option) any",
"later version. ## ## This program is distributed in the hope that it",
"published by ## the Free Software Foundation; either version 2 of the License,",
"if cmd != 'START': return self.state = 'GET SLAVE ADDR' elif self.state ==",
"## Copyright (C) 2012 <NAME> <<EMAIL>> ## Copyright (C) 2013 <NAME> <<EMAIL>> ##",
"write (master selects the slave register). if cmd in ('ADDRESS READ', 'ADDRESS WRITE'):",
"'ADDRESS WRITE'): self.check_correct_chip(databyte) if cmd != 'DATA WRITE': return self.reg = databyte self.handle_write_reg(self.reg)",
"WRITE': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd == 'STOP': self.state",
"return elif self.state == 'READ IO REGS2': if cmd == 'DATA READ': handle_reg",
"here, the master wants to read. if cmd == 'START REPEAT': self.state =",
"I²C packet. self.ss, self.es = ss, es # State machine. if self.state ==",
"-1 def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def putx(self, data): self.put(self.ss, self.es, self.out_ann, data)",
"== 'IDLE': # Wait for an I²C START condition. if cmd != 'START':",
"'Warning'), ) annotation_rows = ( ('regs', 'Registers', (0, 1)), ('warnings', 'Warnings', (2,)), )",
"self.es = ss, es # State machine. if self.state == 'IDLE': # Wait",
"self.putx([0, ['Polarity inversion register', 'Pol', 'P']]) elif b == 3: self.putx([0, ['Configuration register',",
"def decode(self, ss, es, data): cmd, databyte = data # Store the start/end",
"more details. ## ## You should have received a copy of the GNU",
"Start here, the master wants to read. if cmd == 'START REPEAT': self.state",
"REGS': # Wait for an address read operation. if cmd == 'ADDRESS READ':",
"program is free software; you can redistribute it and/or modify ## it under",
"is free software; you can redistribute it and/or modify ## it under the",
"( ('regs', 'Registers', (0, 1)), ('warnings', 'Warnings', (2,)), ) def __init__(self): self.reset() def",
"def check_correct_chip(self, addr): if addr not in (0x20, 0x21): self.putx([2, ['Warning: I²C slave",
"## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General",
"if cmd == 'DATA READ': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif",
"= ( ('regs', 'Registers', (0, 1)), ('warnings', 'Warnings', (2,)), ) def __init__(self): self.reset()",
"samples of this I²C packet. self.ss, self.es = ss, es # State machine.",
"a Repeated Start here, the master wants to read. if cmd == 'START",
"the slave register). if cmd in ('ADDRESS READ', 'ADDRESS WRITE'): self.check_correct_chip(databyte) if cmd",
"(C) 2012 <NAME> <<EMAIL>> ## Copyright (C) 2013 <NAME> <<EMAIL>> ## Copyright (C)",
"if self.state == 'IDLE': # Wait for an I²C START condition. if cmd",
"self.state = 'GET REG ADDR' elif self.state == 'GET REG ADDR': # Wait",
"'Texas Instruments TCA6408A 8-bit I²C I/O expander.' license = 'gplv2+' inputs = ['i2c']",
"set: %02X' % b ]]) def handle_reg_0x02(self, b): self.putx([1, ['Polarity inverted: %02X' %",
"program is distributed in the hope that it will be useful, ## but",
"I²C slave 0x%02X not a TCA6408A ' 'compatible chip.' % addr]]) self.state =",
"TCA6408A' longname = 'Texas Instruments TCA6408A' desc = 'Texas Instruments TCA6408A 8-bit I²C",
"'IDLE' self.chip = -1 def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def putx(self, data): self.put(self.ss,",
"cmd == 'START REPEAT': self.state = 'READ IO REGS' return # Otherwise: Get",
"handle_reg_0x03(self, b): self.putx([1, ['Configuration: %02X' % b]]) def handle_write_reg(self, b): if b ==",
"REGS' return # Otherwise: Get data bytes until a STOP condition occurs. if",
"This program is free software; you can redistribute it and/or modify ## it",
"of this I²C packet. self.ss, self.es = ss, es # State machine. if",
"'Warnings', (2,)), ) def __init__(self): self.reset() def reset(self): self.state = 'IDLE' self.chip =",
"['Warning: I²C slave 0x%02X not a TCA6408A ' 'compatible chip.' % addr]]) self.state",
"elif cmd == 'STOP': self.state = 'IDLE' self.chip = -1 elif self.state ==",
"Copyright (C) 2012 <NAME> <<EMAIL>> ## Copyright (C) 2013 <NAME> <<EMAIL>> ## Copyright",
"will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty",
"if cmd == 'DATA WRITE': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif",
"this I²C packet. self.ss, self.es = ss, es # State machine. if self.state",
"'In', 'I']]) elif b == 1: self.putx([0, ['Output port', 'Out', 'O']]) elif b",
"Software Foundation; either version 2 of the License, or ## (at your option)",
"without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"SLAVE ADDR' elif self.state == 'GET SLAVE ADDR': self.chip = databyte self.state =",
"'STOP': self.state = 'IDLE' self.chip = -1 elif self.state == 'READ IO REGS':",
"# Wait for an address read operation. if cmd == 'ADDRESS READ': self.state",
"('regs', 'Registers', (0, 1)), ('warnings', 'Warnings', (2,)), ) def __init__(self): self.reset() def reset(self):",
"slave register). if cmd in ('ADDRESS READ', 'ADDRESS WRITE'): self.check_correct_chip(databyte) if cmd !=",
"'gplv2+' inputs = ['i2c'] outputs = [] tags = ['Embedded/industrial', 'IC'] annotations =",
"srd class Decoder(srd.Decoder): api_version = 3 id = 'tca6408a' name = 'TI TCA6408A'",
"## import sigrokdecode as srd class Decoder(srd.Decoder): api_version = 3 id = 'tca6408a'",
"the start/end samples of this I²C packet. self.ss, self.es = ss, es #",
"any later version. ## ## This program is distributed in the hope that",
"self.putx([1, ['Outputs set: %02X' % b ]]) def handle_reg_0x02(self, b): self.putx([1, ['Polarity inverted:",
"self.chip = databyte return elif self.state == 'READ IO REGS2': if cmd ==",
"of the License, or ## (at your option) any later version. ## ##",
"['State of inputs: %02X' % b]]) def handle_reg_0x01(self, b): self.putx([1, ['Outputs set: %02X'",
"self.state == 'IDLE': # Wait for an I²C START condition. if cmd !=",
"= databyte self.state = 'GET REG ADDR' elif self.state == 'GET REG ADDR':",
"= databyte return elif self.state == 'READ IO REGS2': if cmd == 'DATA",
"WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A",
"selects the slave register). if cmd in ('ADDRESS READ', 'ADDRESS WRITE'): self.check_correct_chip(databyte) if",
"'DATA READ': handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg) handle_reg(databyte) elif cmd == 'STOP':",
"for a data write (master selects the slave register). if cmd in ('ADDRESS",
"def handle_reg_0x01(self, b): self.putx([1, ['Outputs set: %02X' % b ]]) def handle_reg_0x02(self, b):",
"% b]]) def handle_reg_0x03(self, b): self.putx([1, ['Configuration: %02X' % b]]) def handle_write_reg(self, b):",
"b == 0: self.putx([0, ['Input port', 'In', 'I']]) elif b == 1: self.putx([0,"
] |
[
"pluto.coms.utils import server_utils as srv from pluto.coms.utils import certification as crt from pluto.coms.utils",
"purposes. self._bundle_factory = bundle_factory self._tokens = set() self._accounts = {} self._broker = broker",
"data_bundle_pb2 as dtb from pluto.coms.utils import server_utils as srv from pluto.coms.utils import certification",
"clients data... token = str(uuid.uuid4()) self._config.store({client_name: {'url': client_url, 'token': token}}) return token def",
"server): broker_rpc.add_BrokerServicer_to_server(self._acc, server) class Controllable(object): '''encapsulates utilities for remotely controlling a strategy.''' def",
"request, context): '''creates a bundle based on the specified 'domains' and sends the",
"token is incorrect') def add_token(self, token): self._tokens.add(token) def add_account(self, account): self._accounts[account.token] = account",
"strategy.''' def __init__(self, name, controllable_channel): self._name = name self._capital = 0.0 # reference",
"live=False): '''this function is an iterable (generator) ''' if data_frequency == 'daily': df",
"return token def _create_channel(self, url): return srv.create_channel(url, self._ca) def start(self): self._client_account.start() def stop(self,",
"Orders(self, request, context): self._check_metadata(context) for order in self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order) def _get_dict_values(self, dict_):",
"'''Encapsulates the controller service. This class manages a portfolio of strategies (performs tests",
"style = LimitOrder(request.limit_price) elif req_style == br_msg.OrderParams.STOP_ORDER: style = StopOrder(request.stop_price) elif req_style ==",
"conversions as cv from pluto.utils import files class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available services per-client'''",
"server that listens to some generated port... # one client account per server.",
"= 'controller' subject.alternative_names = [self._url] # TODO: how do pod ip's,services etc work?",
"secure channel). The client communicate with the # account through this channel. #",
"is aggregated, for caching purposes. self._bundle_factory = bundle_factory self._tokens = set() self._accounts =",
"identified # add token to the client so that it can recognise clients",
"pluto.utils import files class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available services per-client''' # todo: must check",
"account through this channel. # the client must store this url permanently, so",
"self._client_account.start() def stop(self, grace=None): self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory): def __init__(self, url): super(ControllerCertificateFactory, self).__init__() self._url",
"def __init__(self, broker, bundle_factory): # the bundle factory is aggregated, for caching purposes.",
"data bundles.''' super(ControllerMainServer, self).__init__(controller_url, key, certificate) self._bdf = bundle_factory self._key = key self._cert",
"StopLimitOrder, StopOrder, LimitOrder from protos import controller_service_pb2 as ctl, controllable_service_pb2_grpc as cbl_rpc, \\",
"key)''' try: conf = self._load_config(client_name) return conf['token'] except KeyError: #create a token and",
"self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order) def _get_dict_values(self, dict_): return dict_.values() def BatchOrder(self, request_iterator, context): raise",
"class ControllerCertificateFactory(crt.CertificateFactory): def __init__(self, url): super(ControllerCertificateFactory, self).__init__() self._url = url def _create_certificate(self, root_path,",
"returns data by chunks of 1KB by default. self._check_metadata(context) for chunk in self._bundle_factory.get_bundle(request.country_code):",
"StopOrder, LimitOrder from protos import controller_service_pb2 as ctl, controllable_service_pb2_grpc as cbl_rpc, \\ controllable_service_pb2",
"MarketOrder() elif req_style == br_msg.OrderParams.LIMIT_ORDER: style = LimitOrder(request.limit_price) elif req_style == br_msg.OrderParams.STOP_ORDER: style",
"#the controllable sends its url controllable_url = request.url client_name = request.name #a token",
"broker_pb2 as br_msg, \\ controller_service_pb2_grpc as ctl_rpc, data_bundle_pb2 as dtb from pluto.coms.utils import",
"data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live, maximum_leverage=max_leverage )): yield cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates",
"specified 'domains' and sends the bundle as a stream of bytes.''' # note:",
"certificate request or returns a certificate if one exists...''' # create the subject",
"super(ControllerMainServer, self).__init__(controller_url, key, certificate) self._bdf = bundle_factory self._key = key self._cert = certificate",
"\\ controller_service_pb2_grpc as ctl_rpc, data_bundle_pb2 as dtb from pluto.coms.utils import server_utils as srv",
"request, context): raise NotImplementedError def PositionsState(self, request, context): raise NotImplementedError def Transactions(self, request,",
"= cbl.RunParams.DAY elif data_frequency == 'minutely': df = cbl.RunParams.MINUTE else: raise ValueError('No data",
"#todo: when and how should we run the controllables? => should we schedule",
"return ctl.RegisterReply(url=self._account_url, token=token) def _load_config(self, name): try: return next(self._config.load())[name] except FileNotFoundError: raise KeyError",
"so that we can remotely control it self._ctr = cbl_rpc.ControllableStub(controllable_channel) # each strategy",
"broker_url self._client_account = BrokerMainServer(bundle_factory, broker_url, key, certificate) # TODO: finish this function (registration",
"a portfolio of strategies (performs tests routines, assigns capital etc.''' # TODO: upon",
"TODO: upon termination, we need to save the generated urls, and relaunch the",
"token = str(uuid.uuid4()) self._config.store({client_name: {'url': client_url, 'token': token}}) return token def _create_channel(self, url):",
"request_iterator, context): raise NotImplementedError def CancelAllOrdersForAsset(self, request, context): raise NotImplementedError def PositionsState(self, request,",
"to the client (through a secure channel). The client communicate with the #",
"authenticated'] return builder.get_certificate_signing_request(subject, key) class ControllerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, controller_url, broker_url, key=None, certificate=None):",
"the generated access url to the client (through a secure channel). The client",
"the metadata... def __init__(self, broker, bundle_factory): # the bundle factory is aggregated, for",
"self._create_token(client_name, controllable_url) controllable = Controllable( client_name, self._create_channel(controllable_url) ) #todo: when and how should",
"type {} is supported'.format(data_frequency)) for perf in self._ctr.Run( cbl.RunParams( capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end),",
"def PositionsState(self, request, context): raise NotImplementedError def Transactions(self, request, context): self._check_metadata(context) for trx",
"LimitOrder from protos import controller_service_pb2 as ctl, controllable_service_pb2_grpc as cbl_rpc, \\ controllable_service_pb2 as",
"cv.to_proto_order(order) def _get_dict_values(self, dict_): return dict_.values() def BatchOrder(self, request_iterator, context): raise NotImplementedError def",
"import files class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available services per-client''' # todo: must check the",
"as broker_rpc, broker_pb2 as br_msg, \\ controller_service_pb2_grpc as ctl_rpc, data_bundle_pb2 as dtb from",
"MarketOrder, StopLimitOrder, StopOrder, LimitOrder from protos import controller_service_pb2 as ctl, controllable_service_pb2_grpc as cbl_rpc,",
"per-client''' # todo: must check the metadata... def __init__(self, broker, bundle_factory): # the",
"# add token to the client so that it can recognise clients return",
"style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order style argument') def GetDataBundle(self, request, context): '''creates a",
")): yield cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates the controller service. This class manages",
"client can be id-ed beyond run lifetime. #the controllable sends its url controllable_url",
"url and maps it to the client url (which is the key)''' try:",
"srv from pluto.coms.utils import certification as crt from pluto.coms.utils import conversions as cv",
"bundle based on the specified 'domains' and sends the bundle as a stream",
"controlling a strategy.''' def __init__(self, name, controllable_channel): self._name = name self._capital = 0.0",
"listens to some generated port... # one client account per server. @property def",
"frequency of type {} is supported'.format(data_frequency)) for perf in self._ctr.Run( cbl.RunParams( capital_base=self._capital, data_frequency=df,",
"broker_url, key=None, certificate=None, ca=None): # list of controllables (strategies) self._controllables = {} self._bundle_factory",
"or returns a certificate if one exists...''' # create the subject of the",
"cbl_rpc, \\ controllable_service_pb2 as cbl, broker_pb2_grpc as broker_rpc, broker_pb2 as br_msg, \\ controller_service_pb2_grpc",
"name): try: return next(self._config.load())[name] except FileNotFoundError: raise KeyError def _create_token(self, client_name, client_url): '''creates",
"if one exists...''' # create the subject of the certificate request subject.common_name =",
"order in self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order) def _get_dict_values(self, dict_): return dict_.values() def BatchOrder(self, request_iterator,",
"request.style style = None if req_style == br_msg.OrderParams.MARKET_ORDER: style = MarketOrder() elif req_style",
"run(self, start, end, max_leverage, data_frequency='daily', metrics_set='default', live=False): '''this function is an iterable (generator)",
"grace=None): self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory): def __init__(self, url): super(ControllerCertificateFactory, self).__init__() self._url = url def",
"LimitOrder(request.limit_price) elif req_style == br_msg.OrderParams.STOP_ORDER: style = StopOrder(request.stop_price) elif req_style == br_msg.OrderParams.STOP_LIMIT_ORDER: style",
"__init__(self, bundle_factory, broker_url, key=None, certificate=None, ca=None): # list of controllables (strategies) self._controllables =",
"start, end, max_leverage, data_frequency='daily', metrics_set='default', live=False): '''this function is an iterable (generator) '''",
"self._ctr = cbl_rpc.ControllableStub(controllable_channel) # each strategy controller has a server that listens to",
"the generated urls, and relaunch the services # that server on those urls.",
"perf in self._ctr.Run( cbl.RunParams( capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live, maximum_leverage=max_leverage )): yield",
"self._key = key self._cert = certificate self._ca = ca self._config = files.JsonFile('controller/config') self._account_url",
"end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live, maximum_leverage=max_leverage )): yield cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates the controller",
"context): '''creates a bundle based on the specified 'domains' and sends the bundle",
"super(BrokerMainServer, self).__init__(broker_url, key, certificate) self._acc = BrokerServicer(bundle_factory, broker) def add_token(self, token): self._acc.add_token(token) def",
"req_style == br_msg.OrderParams.MARKET_ORDER: style = MarketOrder() elif req_style == br_msg.OrderParams.LIMIT_ORDER: style = LimitOrder(request.limit_price)",
"url (which is the key)''' try: conf = self._load_config(client_name) return conf['token'] except KeyError:",
"request, context): raise NotImplementedError def Orders(self, request, context): self._check_metadata(context) for order in self._get_dict_values(self._broker.orders()):",
"one client account per server. @property def capital(self): return self._capital @capital.setter def capital(self,",
"raise NotImplementedError def CancelAllOrdersForAsset(self, request, context): raise NotImplementedError def PositionsState(self, request, context): raise",
"{} self._bundle_factory = bundle_factory self._key = key self._cert = certificate self._ca = ca",
"url to the client (through a secure channel). The client communicate with the",
"= {} self._broker = broker def _check_metadata(self, context): metadata = dict(context.invocation_metadata()) token =",
"def _check_metadata(self, context): metadata = dict(context.invocation_metadata()) token = metadata['Token'] if not token in",
"# each strategy controller has a server that listens to some generated port...",
"portfolio of strategies (performs tests routines, assigns capital etc.''' # TODO: upon termination,",
"from zipline.finance.execution import MarketOrder, StopLimitOrder, StopOrder, LimitOrder from protos import controller_service_pb2 as ctl,",
"= self._create_token(client_name, controllable_url) controllable = Controllable( client_name, self._create_channel(controllable_url) ) #todo: when and how",
"the # account through this channel. # the client must store this url",
"raise KeyError def _create_token(self, client_name, client_url): '''creates a url and maps it to",
"next(self._config.load())[name] except FileNotFoundError: raise KeyError def _create_token(self, client_name, client_url): '''creates a url and",
"ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates the controller service. This class manages a portfolio of strategies",
"addresses: pod ip, pod dns, master IP... builder = crt.CertificateSigningRequestBuilder() builder.name = 'controller'",
"== 'minutely': df = cbl.RunParams.MINUTE else: raise ValueError('No data frequency of type {}",
"a token and store clients data... token = str(uuid.uuid4()) self._config.store({client_name: {'url': client_url, 'token':",
"the client so that it can recognise clients return ctl.RegisterReply(url=self._account_url, token=token) def _load_config(self,",
"signature','key encipherment', 'data encipherment','server auth'] builder.groups = ['system: authenticated'] return builder.get_certificate_signing_request(subject, key) class",
"raise NotImplementedError def Transactions(self, request, context): self._check_metadata(context) for trx in self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx)",
"def run(self, start, end, max_leverage, data_frequency='daily', metrics_set='default', live=False): '''this function is an iterable",
"def Register(self, request, context): '''the controllable calls this function to be registered''' #",
"store clients data... token = str(uuid.uuid4()) self._config.store({client_name: {'url': client_url, 'token': token}}) return token",
"a stream of bytes.''' # note: returns data by chunks of 1KB by",
"class BrokerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, broker_url, broker, key=None, certificate=None): super(BrokerMainServer, self).__init__(broker_url, key, certificate)",
"BatchOrder(self, request_iterator, context): raise NotImplementedError def CancelAllOrdersForAsset(self, request, context): raise NotImplementedError def PositionsState(self,",
"aggregated, for caching purposes. self._bundle_factory = bundle_factory self._tokens = set() self._accounts = {}",
"in self._ctr.Run( cbl.RunParams( capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live, maximum_leverage=max_leverage )): yield cv.from_proto_performance_packet(perf)",
"that it can be identified # add token to the client so that",
"br_msg.OrderParams.MARKET_ORDER: style = MarketOrder() elif req_style == br_msg.OrderParams.LIMIT_ORDER: style = LimitOrder(request.limit_price) elif req_style",
"so that it can recognise clients return ctl.RegisterReply(url=self._account_url, token=token) def _load_config(self, name): try:",
"self).__init__() self._url = url def _create_certificate(self, root_path, cert_name, key, subject): '''creates a certificate",
"is incorrect') def add_token(self, token): self._tokens.add(token) def add_account(self, account): self._accounts[account.token] = account def",
"self._controllables[token] = controllable # send the generated access url to the client (through",
"StopLimitOrder(request.limit_price, request.stop_price) if style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order style",
"supported'.format(data_frequency)) for perf in self._ctr.Run( cbl.RunParams( capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live, maximum_leverage=max_leverage",
"None if req_style == br_msg.OrderParams.MARKET_ORDER: style = MarketOrder() elif req_style == br_msg.OrderParams.LIMIT_ORDER: style",
"be identified # add token to the client so that it can recognise",
"it to the client url (which is the key)''' try: conf = self._load_config(client_name)",
"def _get_dict_values(self, dict_): return dict_.values() def BatchOrder(self, request_iterator, context): raise NotImplementedError def CancelAllOrdersForAsset(self,",
"br_msg, \\ controller_service_pb2_grpc as ctl_rpc, data_bundle_pb2 as dtb from pluto.coms.utils import server_utils as",
"return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order style argument') def GetDataBundle(self, request,",
"methods aren't necessary raise NotImplementedError def PortfolioState(self, request, context): raise NotImplementedError def Orders(self,",
"request, context): self._check_metadata(context) for trx in self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx) def SingleOrder(self, request, context):",
"finish this function (registration of the controllable) def Register(self, request, context): '''the controllable",
"do pod ip's,services etc work? # additional addresses: pod ip, pod dns, master",
"with the # account through this channel. # the client must store this",
"self._cert = certificate self._blt = broker_url def _add_servicer_to_server(self, server): ctl_rpc.add_ControllerServicer_to_server(ControllerServicer( self._bdf, self._blt, self._key,",
"= cbl_rpc.ControllableStub(controllable_channel) # each strategy controller has a server that listens to some",
"yield dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, broker_url, broker, key=None, certificate=None): super(BrokerMainServer, self).__init__(broker_url,",
"self._check_metadata(context) for chunk in self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, broker_url,",
"self._tokens = set() self._accounts = {} self._broker = broker def _check_metadata(self, context): metadata",
"manages a portfolio of strategies (performs tests routines, assigns capital etc.''' # TODO:",
"ctl_rpc, data_bundle_pb2 as dtb from pluto.coms.utils import server_utils as srv from pluto.coms.utils import",
"def __init__(self, url): super(ControllerCertificateFactory, self).__init__() self._url = url def _create_certificate(self, root_path, cert_name, key,",
"'controller' builder.usages = ['digital signature','key encipherment', 'data encipherment','server auth'] builder.groups = ['system: authenticated']",
"argument') def GetDataBundle(self, request, context): '''creates a bundle based on the specified 'domains'",
"return dict_.values() def BatchOrder(self, request_iterator, context): raise NotImplementedError def CancelAllOrdersForAsset(self, request, context): raise",
"#create a token and store clients data... token = str(uuid.uuid4()) self._config.store({client_name: {'url': client_url,",
"# the client must store this url permanently, so that it can be",
"capital etc.''' # TODO: upon termination, we need to save the generated urls,",
"import certification as crt from pluto.coms.utils import conversions as cv from pluto.utils import",
"key, subject): '''creates a certificate request or returns a certificate if one exists...'''",
"TODO: how do pod ip's,services etc work? # additional addresses: pod ip, pod",
"__init__(self, bundle_factory, controller_url, broker_url, key=None, certificate=None): '''the bundle_factory is an abstraction for creating",
"start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live, maximum_leverage=max_leverage )): yield cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates the",
"cbl.RunParams.DAY elif data_frequency == 'minutely': df = cbl.RunParams.MINUTE else: raise ValueError('No data frequency",
"pluto.coms.utils import conversions as cv from pluto.utils import files class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available",
"= LimitOrder(request.limit_price) elif req_style == br_msg.OrderParams.STOP_ORDER: style = StopOrder(request.stop_price) elif req_style == br_msg.OrderParams.STOP_LIMIT_ORDER:",
"be id-ed beyond run lifetime. #the controllable sends its url controllable_url = request.url",
"schedule periodic back-testings? # keep track of controllables so that we can control",
"aren't necessary raise NotImplementedError def PortfolioState(self, request, context): raise NotImplementedError def Orders(self, request,",
"'token': token}}) return token def _create_channel(self, url): return srv.create_channel(url, self._ca) def start(self): self._client_account.start()",
"and how should we run the controllables? => should we schedule periodic back-testings?",
"bundle_factory): # the bundle factory is aggregated, for caching purposes. self._bundle_factory = bundle_factory",
"subject of the certificate request subject.common_name = 'controller' subject.alternative_names = [self._url] # TODO:",
"_check_metadata(self, context): metadata = dict(context.invocation_metadata()) token = metadata['Token'] if not token in self._tokens:",
"to save the generated urls, and relaunch the services # that server on",
"= value def run(self, start, end, max_leverage, data_frequency='daily', metrics_set='default', live=False): '''this function is",
"control it self._ctr = cbl_rpc.ControllableStub(controllable_channel) # each strategy controller has a server that",
"client communicate with the # account through this channel. # the client must",
"client account per server. @property def capital(self): return self._capital @capital.setter def capital(self, value):",
"as dtb from pluto.coms.utils import server_utils as srv from pluto.coms.utils import certification as",
"= crt.CertificateSigningRequestBuilder() builder.name = 'controller' builder.usages = ['digital signature','key encipherment', 'data encipherment','server auth']",
"so that it can be identified # add token to the client so",
"= MarketOrder() elif req_style == br_msg.OrderParams.LIMIT_ORDER: style = LimitOrder(request.limit_price) elif req_style == br_msg.OrderParams.STOP_ORDER:",
"= StopLimitOrder(request.limit_price, request.stop_price) if style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order",
"an iterable (generator) ''' if data_frequency == 'daily': df = cbl.RunParams.DAY elif data_frequency",
"self._account_url = broker_url self._client_account = BrokerMainServer(bundle_factory, broker_url, key, certificate) # TODO: finish this",
"the client can be id-ed beyond run lifetime. #the controllable sends its url",
"so that we can control them etc. self._controllables[token] = controllable # send the",
"encipherment', 'data encipherment','server auth'] builder.groups = ['system: authenticated'] return builder.get_certificate_signing_request(subject, key) class ControllerMainServer(srv.MainServerFactory):",
"The client communicate with the # account through this channel. # the client",
"etc work? # additional addresses: pod ip, pod dns, master IP... builder =",
"url): return srv.create_channel(url, self._ca) def start(self): self._client_account.start() def stop(self, grace=None): self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory):",
"ControllerCertificateFactory(crt.CertificateFactory): def __init__(self, url): super(ControllerCertificateFactory, self).__init__() self._url = url def _create_certificate(self, root_path, cert_name,",
"as srv from pluto.coms.utils import certification as crt from pluto.coms.utils import conversions as",
"def AccountState(self, request, context): # todo: these methods aren't necessary raise NotImplementedError def",
"self._bundle_factory = bundle_factory self._key = key self._cert = certificate self._ca = ca self._config",
"that we can remotely control it self._ctr = cbl_rpc.ControllableStub(controllable_channel) # each strategy controller",
"token): self._acc.add_token(token) def _add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc, server) class Controllable(object): '''encapsulates utilities for remotely",
"trx in self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx) def SingleOrder(self, request, context): self._check_metadata(context) req_style = request.style",
"self._check_metadata(context) req_style = request.style style = None if req_style == br_msg.OrderParams.MARKET_ORDER: style =",
"can be identified # add token to the client so that it can",
"ControllerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, controller_url, broker_url, key=None, certificate=None): '''the bundle_factory is an abstraction",
"= cbl.RunParams.MINUTE else: raise ValueError('No data frequency of type {} is supported'.format(data_frequency)) for",
"of bytes.''' # note: returns data by chunks of 1KB by default. self._check_metadata(context)",
"to the client url (which is the key)''' try: conf = self._load_config(client_name) return",
"request or returns a certificate if one exists...''' # create the subject of",
"certificate=None, ca=None): # list of controllables (strategies) self._controllables = {} self._bundle_factory = bundle_factory",
"root_path, cert_name, key, subject): '''creates a certificate request or returns a certificate if",
"an abstraction for creating data bundles.''' super(ControllerMainServer, self).__init__(controller_url, key, certificate) self._bdf = bundle_factory",
"import controller_service_pb2 as ctl, controllable_service_pb2_grpc as cbl_rpc, \\ controllable_service_pb2 as cbl, broker_pb2_grpc as",
"if not token in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided token is incorrect') def add_token(self,",
"context): self._check_metadata(context) req_style = request.style style = None if req_style == br_msg.OrderParams.MARKET_ORDER: style",
"self).__init__(controller_url, key, certificate) self._bdf = bundle_factory self._key = key self._cert = certificate self._blt",
"the subject of the certificate request subject.common_name = 'controller' subject.alternative_names = [self._url] #",
"ca self._config = files.JsonFile('controller/config') self._account_url = broker_url self._client_account = BrokerMainServer(bundle_factory, broker_url, key, certificate)",
"name, controllable_channel): self._name = name self._capital = 0.0 # reference to the controllable",
"self._controllables = {} self._bundle_factory = bundle_factory self._key = key self._cert = certificate self._ca",
"= BrokerMainServer(bundle_factory, broker_url, key, certificate) # TODO: finish this function (registration of the",
"= account def AccountState(self, request, context): # todo: these methods aren't necessary raise",
"grpc from zipline.finance.execution import MarketOrder, StopLimitOrder, StopOrder, LimitOrder from protos import controller_service_pb2 as",
"br_msg.OrderParams.STOP_ORDER: style = StopOrder(request.stop_price) elif req_style == br_msg.OrderParams.STOP_LIMIT_ORDER: style = StopLimitOrder(request.limit_price, request.stop_price) if",
"controller has a server that listens to some generated port... # one client",
"data_frequency == 'minutely': df = cbl.RunParams.MINUTE else: raise ValueError('No data frequency of type",
"certificate self._ca = ca self._config = files.JsonFile('controller/config') self._account_url = broker_url self._client_account = BrokerMainServer(bundle_factory,",
"a certificate if one exists...''' # create the subject of the certificate request",
"def CancelAllOrdersForAsset(self, request, context): raise NotImplementedError def PositionsState(self, request, context): raise NotImplementedError def",
"# keep track of controllables so that we can control them etc. self._controllables[token]",
"dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, broker_url, broker, key=None, certificate=None): super(BrokerMainServer, self).__init__(broker_url, key,",
"how do pod ip's,services etc work? # additional addresses: pod ip, pod dns,",
"keep track of controllables so that we can control them etc. self._controllables[token] =",
"send the generated access url to the client (through a secure channel). The",
"This class manages a portfolio of strategies (performs tests routines, assigns capital etc.'''",
"= files.JsonFile('controller/config') self._account_url = broker_url self._client_account = BrokerMainServer(bundle_factory, broker_url, key, certificate) # TODO:",
"@capital.setter def capital(self, value): self._capital = value def run(self, start, end, max_leverage, data_frequency='daily',",
"req_style = request.style style = None if req_style == br_msg.OrderParams.MARKET_ORDER: style = MarketOrder()",
"== br_msg.OrderParams.STOP_LIMIT_ORDER: style = StopLimitOrder(request.limit_price, request.stop_price) if style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style)) else:",
"bundle_factory self._key = key self._cert = certificate self._blt = broker_url def _add_servicer_to_server(self, server):",
"controllable_url = request.url client_name = request.name #a token is generated token = self._create_token(client_name,",
"= ['system: authenticated'] return builder.get_certificate_signing_request(subject, key) class ControllerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, controller_url, broker_url,",
"def add_token(self, token): self._tokens.add(token) def add_account(self, account): self._accounts[account.token] = account def AccountState(self, request,",
"incorrect') def add_token(self, token): self._tokens.add(token) def add_account(self, account): self._accounts[account.token] = account def AccountState(self,",
"controllables so that we can control them etc. self._controllables[token] = controllable # send",
"master IP... builder = crt.CertificateSigningRequestBuilder() builder.name = 'controller' builder.usages = ['digital signature','key encipherment',",
"'''encapsulates utilities for remotely controlling a strategy.''' def __init__(self, name, controllable_channel): self._name =",
"subject.common_name = 'controller' subject.alternative_names = [self._url] # TODO: how do pod ip's,services etc",
"that we can control them etc. self._controllables[token] = controllable # send the generated",
"_add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc, server) class Controllable(object): '''encapsulates utilities for remotely controlling a strategy.'''",
"from pluto.coms.utils import conversions as cv from pluto.utils import files class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates",
"token): self._tokens.add(token) def add_account(self, account): self._accounts[account.token] = account def AccountState(self, request, context): #",
"and store clients data... token = str(uuid.uuid4()) self._config.store({client_name: {'url': client_url, 'token': token}}) return",
"request, context): self._check_metadata(context) for order in self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order) def _get_dict_values(self, dict_): return",
"BrokerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, broker_url, broker, key=None, certificate=None): super(BrokerMainServer, self).__init__(broker_url, key, certificate) self._acc",
"clients return ctl.RegisterReply(url=self._account_url, token=token) def _load_config(self, name): try: return next(self._config.load())[name] except FileNotFoundError: raise",
"elif req_style == br_msg.OrderParams.STOP_LIMIT_ORDER: style = StopLimitOrder(request.limit_price, request.stop_price) if style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount,",
"in self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, broker_url, broker, key=None, certificate=None):",
"KeyError def _create_token(self, client_name, client_url): '''creates a url and maps it to the",
"= bundle_factory self._key = key self._cert = certificate self._ca = ca self._config =",
"from protos import controller_service_pb2 as ctl, controllable_service_pb2_grpc as cbl_rpc, \\ controllable_service_pb2 as cbl,",
"store the url permanently so that the client can be id-ed beyond run",
"in self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order) def _get_dict_values(self, dict_): return dict_.values() def BatchOrder(self, request_iterator, context):",
"__init__(self, name, controllable_channel): self._name = name self._capital = 0.0 # reference to the",
"port... # one client account per server. @property def capital(self): return self._capital @capital.setter",
"TODO: store the url permanently so that the client can be id-ed beyond",
"Controllable( client_name, self._create_channel(controllable_url) ) #todo: when and how should we run the controllables?",
"['system: authenticated'] return builder.get_certificate_signing_request(subject, key) class ControllerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, controller_url, broker_url, key=None,",
"from pluto.utils import files class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available services per-client''' # todo: must",
"else: raise ValueError('No data frequency of type {} is supported'.format(data_frequency)) for perf in",
"check the metadata... def __init__(self, broker, bundle_factory): # the bundle factory is aggregated,",
"the specified 'domains' and sends the bundle as a stream of bytes.''' #",
"for remotely controlling a strategy.''' def __init__(self, name, controllable_channel): self._name = name self._capital",
"raise ValueError('No data frequency of type {} is supported'.format(data_frequency)) for perf in self._ctr.Run(",
"BrokerMainServer(bundle_factory, broker_url, key, certificate) # TODO: finish this function (registration of the controllable)",
"context): self._check_metadata(context) for trx in self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx) def SingleOrder(self, request, context): self._check_metadata(context)",
"class Controllable(object): '''encapsulates utilities for remotely controlling a strategy.''' def __init__(self, name, controllable_channel):",
"style = None if req_style == br_msg.OrderParams.MARKET_ORDER: style = MarketOrder() elif req_style ==",
"BrokerServicer(bundle_factory, broker) def add_token(self, token): self._acc.add_token(token) def _add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc, server) class Controllable(object):",
"a secure channel). The client communicate with the # account through this channel.",
"server_utils as srv from pluto.coms.utils import certification as crt from pluto.coms.utils import conversions",
"def _load_config(self, name): try: return next(self._config.load())[name] except FileNotFoundError: raise KeyError def _create_token(self, client_name,",
"client_name, client_url): '''creates a url and maps it to the client url (which",
"url): super(ControllerCertificateFactory, self).__init__() self._url = url def _create_certificate(self, root_path, cert_name, key, subject): '''creates",
"note: returns data by chunks of 1KB by default. self._check_metadata(context) for chunk in",
"account per server. @property def capital(self): return self._capital @capital.setter def capital(self, value): self._capital",
"yield cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates the controller service. This class manages a",
"def PortfolioState(self, request, context): raise NotImplementedError def Orders(self, request, context): self._check_metadata(context) for order",
"returns a certificate if one exists...''' # create the subject of the certificate",
"import MarketOrder, StopLimitOrder, StopOrder, LimitOrder from protos import controller_service_pb2 as ctl, controllable_service_pb2_grpc as",
"if data_frequency == 'daily': df = cbl.RunParams.DAY elif data_frequency == 'minutely': df =",
"self._bdf = bundle_factory self._key = key self._cert = certificate self._blt = broker_url def",
"by chunks of 1KB by default. self._check_metadata(context) for chunk in self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk)",
"run the controllables? => should we schedule periodic back-testings? # keep track of",
"request.amount, style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order style argument') def GetDataBundle(self, request, context): '''creates",
"creating data bundles.''' super(ControllerMainServer, self).__init__(controller_url, key, certificate) self._bdf = bundle_factory self._key = key",
"\\ controllable_service_pb2 as cbl, broker_pb2_grpc as broker_rpc, broker_pb2 as br_msg, \\ controller_service_pb2_grpc as",
"# additional addresses: pod ip, pod dns, master IP... builder = crt.CertificateSigningRequestBuilder() builder.name",
"context): '''the controllable calls this function to be registered''' # TODO: store the",
"self._capital = value def run(self, start, end, max_leverage, data_frequency='daily', metrics_set='default', live=False): '''this function",
"= certificate self._blt = broker_url def _add_servicer_to_server(self, server): ctl_rpc.add_ControllerServicer_to_server(ControllerServicer( self._bdf, self._blt, self._key, self._cert),",
"a server that listens to some generated port... # one client account per",
"# account through this channel. # the client must store this url permanently,",
"BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available services per-client''' # todo: must check the metadata... def __init__(self,",
"metadata = dict(context.invocation_metadata()) token = metadata['Token'] if not token in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The",
"0.0 # reference to the controllable so that we can remotely control it",
"live=live, maximum_leverage=max_leverage )): yield cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates the controller service. This",
"id-ed beyond run lifetime. #the controllable sends its url controllable_url = request.url client_name",
"StopOrder(request.stop_price) elif req_style == br_msg.OrderParams.STOP_LIMIT_ORDER: style = StopLimitOrder(request.limit_price, request.stop_price) if style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset),",
"'''this function is an iterable (generator) ''' if data_frequency == 'daily': df =",
"cbl.RunParams.MINUTE else: raise ValueError('No data frequency of type {} is supported'.format(data_frequency)) for perf",
"tests routines, assigns capital etc.''' # TODO: upon termination, we need to save",
"this function (registration of the controllable) def Register(self, request, context): '''the controllable calls",
"['digital signature','key encipherment', 'data encipherment','server auth'] builder.groups = ['system: authenticated'] return builder.get_certificate_signing_request(subject, key)",
"bundle_factory is an abstraction for creating data bundles.''' super(ControllerMainServer, self).__init__(controller_url, key, certificate) self._bdf",
"controllable_service_pb2_grpc as cbl_rpc, \\ controllable_service_pb2 as cbl, broker_pb2_grpc as broker_rpc, broker_pb2 as br_msg,",
"FileNotFoundError: raise KeyError def _create_token(self, client_name, client_url): '''creates a url and maps it",
"stream of bytes.''' # note: returns data by chunks of 1KB by default.",
"permanently so that the client can be id-ed beyond run lifetime. #the controllable",
"for perf in self._ctr.Run( cbl.RunParams( capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live, maximum_leverage=max_leverage )):",
"= [self._url] # TODO: how do pod ip's,services etc work? # additional addresses:",
"context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order style argument') def GetDataBundle(self, request, context): '''creates a bundle based",
"of strategies (performs tests routines, assigns capital etc.''' # TODO: upon termination, we",
"__init__(self, bundle_factory, broker_url, broker, key=None, certificate=None): super(BrokerMainServer, self).__init__(broker_url, key, certificate) self._acc = BrokerServicer(bundle_factory,",
"def capital(self): return self._capital @capital.setter def capital(self, value): self._capital = value def run(self,",
"the url permanently so that the client can be id-ed beyond run lifetime.",
"self._client_account = BrokerMainServer(bundle_factory, broker_url, key, certificate) # TODO: finish this function (registration of",
"server. @property def capital(self): return self._capital @capital.setter def capital(self, value): self._capital = value",
"{} self._broker = broker def _check_metadata(self, context): metadata = dict(context.invocation_metadata()) token = metadata['Token']",
"== br_msg.OrderParams.LIMIT_ORDER: style = LimitOrder(request.limit_price) elif req_style == br_msg.OrderParams.STOP_ORDER: style = StopOrder(request.stop_price) elif",
"assigns capital etc.''' # TODO: upon termination, we need to save the generated",
"# TODO: finish this function (registration of the controllable) def Register(self, request, context):",
"broker_url, key=None, certificate=None): '''the bundle_factory is an abstraction for creating data bundles.''' super(ControllerMainServer,",
"AccountState(self, request, context): # todo: these methods aren't necessary raise NotImplementedError def PortfolioState(self,",
"== br_msg.OrderParams.MARKET_ORDER: style = MarketOrder() elif req_style == br_msg.OrderParams.LIMIT_ORDER: style = LimitOrder(request.limit_price) elif",
"available services per-client''' # todo: must check the metadata... def __init__(self, broker, bundle_factory):",
"@property def capital(self): return self._capital @capital.setter def capital(self, value): self._capital = value def",
"a certificate request or returns a certificate if one exists...''' # create the",
"it can recognise clients return ctl.RegisterReply(url=self._account_url, token=token) def _load_config(self, name): try: return next(self._config.load())[name]",
"(through a secure channel). The client communicate with the # account through this",
"token = self._create_token(client_name, controllable_url) controllable = Controllable( client_name, self._create_channel(controllable_url) ) #todo: when and",
"as br_msg, \\ controller_service_pb2_grpc as ctl_rpc, data_bundle_pb2 as dtb from pluto.coms.utils import server_utils",
"order style argument') def GetDataBundle(self, request, context): '''creates a bundle based on the",
"context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided token is incorrect') def add_token(self, token): self._tokens.add(token) def add_account(self, account):",
"return builder.get_certificate_signing_request(subject, key) class ControllerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, controller_url, broker_url, key=None, certificate=None): '''the",
"as ctl_rpc, data_bundle_pb2 as dtb from pluto.coms.utils import server_utils as srv from pluto.coms.utils",
"is supported'.format(data_frequency)) for perf in self._ctr.Run( cbl.RunParams( capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live,",
"generated urls, and relaunch the services # that server on those urls. def",
"self._ca = ca self._config = files.JsonFile('controller/config') self._account_url = broker_url self._client_account = BrokerMainServer(bundle_factory, broker_url,",
"token is generated token = self._create_token(client_name, controllable_url) controllable = Controllable( client_name, self._create_channel(controllable_url) )",
"request subject.common_name = 'controller' subject.alternative_names = [self._url] # TODO: how do pod ip's,services",
"= url def _create_certificate(self, root_path, cert_name, key, subject): '''creates a certificate request or",
"# reference to the controllable so that we can remotely control it self._ctr",
"server on those urls. def __init__(self, bundle_factory, broker_url, key=None, certificate=None, ca=None): # list",
"= StopOrder(request.stop_price) elif req_style == br_msg.OrderParams.STOP_LIMIT_ORDER: style = StopLimitOrder(request.limit_price, request.stop_price) if style: return",
"controllable sends its url controllable_url = request.url client_name = request.name #a token is",
"the certificate request subject.common_name = 'controller' subject.alternative_names = [self._url] # TODO: how do",
"return conf['token'] except KeyError: #create a token and store clients data... token =",
"raise NotImplementedError def PortfolioState(self, request, context): raise NotImplementedError def Orders(self, request, context): self._check_metadata(context)",
"client_url): '''creates a url and maps it to the client url (which is",
"cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order style argument') def GetDataBundle(self, request, context):",
"the client must store this url permanently, so that it can be identified",
"bundle_factory, controller_url, broker_url, key=None, certificate=None): '''the bundle_factory is an abstraction for creating data",
"'''creates a certificate request or returns a certificate if one exists...''' # create",
"pod ip, pod dns, master IP... builder = crt.CertificateSigningRequestBuilder() builder.name = 'controller' builder.usages",
"import grpc from zipline.finance.execution import MarketOrder, StopLimitOrder, StopOrder, LimitOrder from protos import controller_service_pb2",
"routines, assigns capital etc.''' # TODO: upon termination, we need to save the",
"#a token is generated token = self._create_token(client_name, controllable_url) controllable = Controllable( client_name, self._create_channel(controllable_url)",
"else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order style argument') def GetDataBundle(self, request, context): '''creates a bundle",
"remotely controlling a strategy.''' def __init__(self, name, controllable_channel): self._name = name self._capital =",
"context): metadata = dict(context.invocation_metadata()) token = metadata['Token'] if not token in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED,",
"try: return next(self._config.load())[name] except FileNotFoundError: raise KeyError def _create_token(self, client_name, client_url): '''creates a",
"subject): '''creates a certificate request or returns a certificate if one exists...''' #",
"NotImplementedError def Transactions(self, request, context): self._check_metadata(context) for trx in self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx) def",
"through this channel. # the client must store this url permanently, so that",
"= bundle_factory self._tokens = set() self._accounts = {} self._broker = broker def _check_metadata(self,",
"communicate with the # account through this channel. # the client must store",
"client_name, self._create_channel(controllable_url) ) #todo: when and how should we run the controllables? =>",
"data... token = str(uuid.uuid4()) self._config.store({client_name: {'url': client_url, 'token': token}}) return token def _create_channel(self,",
"broker_url, broker, key=None, certificate=None): super(BrokerMainServer, self).__init__(broker_url, key, certificate) self._acc = BrokerServicer(bundle_factory, broker) def",
"def GetDataBundle(self, request, context): '''creates a bundle based on the specified 'domains' and",
"yield cv.to_proto_order(order) def _get_dict_values(self, dict_): return dict_.values() def BatchOrder(self, request_iterator, context): raise NotImplementedError",
"def _create_certificate(self, root_path, cert_name, key, subject): '''creates a certificate request or returns a",
"== 'daily': df = cbl.RunParams.DAY elif data_frequency == 'minutely': df = cbl.RunParams.MINUTE else:",
"KeyError: #create a token and store clients data... token = str(uuid.uuid4()) self._config.store({client_name: {'url':",
"__init__(self, url): super(ControllerCertificateFactory, self).__init__() self._url = url def _create_certificate(self, root_path, cert_name, key, subject):",
"on the specified 'domains' and sends the bundle as a stream of bytes.'''",
"= 'controller' builder.usages = ['digital signature','key encipherment', 'data encipherment','server auth'] builder.groups = ['system:",
"utilities for remotely controlling a strategy.''' def __init__(self, name, controllable_channel): self._name = name",
"todo: must check the metadata... def __init__(self, broker, bundle_factory): # the bundle factory",
"def __init__(self, bundle_factory, controller_url, broker_url, key=None, certificate=None): '''the bundle_factory is an abstraction for",
"channel. # the client must store this url permanently, so that it can",
"a bundle based on the specified 'domains' and sends the bundle as a",
"function is an iterable (generator) ''' if data_frequency == 'daily': df = cbl.RunParams.DAY",
"elif data_frequency == 'minutely': df = cbl.RunParams.MINUTE else: raise ValueError('No data frequency of",
"how should we run the controllables? => should we schedule periodic back-testings? #",
"try: conf = self._load_config(client_name) return conf['token'] except KeyError: #create a token and store",
"builder.groups = ['system: authenticated'] return builder.get_certificate_signing_request(subject, key) class ControllerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, controller_url,",
"token in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided token is incorrect') def add_token(self, token): self._tokens.add(token)",
"provided token is incorrect') def add_token(self, token): self._tokens.add(token) def add_account(self, account): self._accounts[account.token] =",
"def BatchOrder(self, request_iterator, context): raise NotImplementedError def CancelAllOrdersForAsset(self, request, context): raise NotImplementedError def",
"certification as crt from pluto.coms.utils import conversions as cv from pluto.utils import files",
"strategy controller has a server that listens to some generated port... # one",
"self._create_channel(controllable_url) ) #todo: when and how should we run the controllables? => should",
"periodic back-testings? # keep track of controllables so that we can control them",
"of type {} is supported'.format(data_frequency)) for perf in self._ctr.Run( cbl.RunParams( capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start),",
"data by chunks of 1KB by default. self._check_metadata(context) for chunk in self._bundle_factory.get_bundle(request.country_code): yield",
"the bundle as a stream of bytes.''' # note: returns data by chunks",
"metrics_set=metrics_set, live=live, maximum_leverage=max_leverage )): yield cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates the controller service.",
"and maps it to the client url (which is the key)''' try: conf",
"def _add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc, server) class Controllable(object): '''encapsulates utilities for remotely controlling a",
"function to be registered''' # TODO: store the url permanently so that the",
"return srv.create_channel(url, self._ca) def start(self): self._client_account.start() def stop(self, grace=None): self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory): def",
"= {} self._bundle_factory = bundle_factory self._key = key self._cert = certificate self._ca =",
"access url to the client (through a secure channel). The client communicate with",
"files class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available services per-client''' # todo: must check the metadata...",
"urls. def __init__(self, bundle_factory, broker_url, key=None, certificate=None, ca=None): # list of controllables (strategies)",
"conf = self._load_config(client_name) return conf['token'] except KeyError: #create a token and store clients",
"client_name = request.name #a token is generated token = self._create_token(client_name, controllable_url) controllable =",
"[self._url] # TODO: how do pod ip's,services etc work? # additional addresses: pod",
"capital(self): return self._capital @capital.setter def capital(self, value): self._capital = value def run(self, start,",
"function (registration of the controllable) def Register(self, request, context): '''the controllable calls this",
"'''the controllable calls this function to be registered''' # TODO: store the url",
"the bundle factory is aggregated, for caching purposes. self._bundle_factory = bundle_factory self._tokens =",
"capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live, maximum_leverage=max_leverage )): yield cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer):",
"work? # additional addresses: pod ip, pod dns, master IP... builder = crt.CertificateSigningRequestBuilder()",
"client must store this url permanently, so that it can be identified #",
"'controller' subject.alternative_names = [self._url] # TODO: how do pod ip's,services etc work? #",
"zipline.finance.execution import MarketOrder, StopLimitOrder, StopOrder, LimitOrder from protos import controller_service_pb2 as ctl, controllable_service_pb2_grpc",
"account def AccountState(self, request, context): # todo: these methods aren't necessary raise NotImplementedError",
"it self._ctr = cbl_rpc.ControllableStub(controllable_channel) # each strategy controller has a server that listens",
"must check the metadata... def __init__(self, broker, bundle_factory): # the bundle factory is",
"of the controllable) def Register(self, request, context): '''the controllable calls this function to",
"controllable # send the generated access url to the client (through a secure",
"abstraction for creating data bundles.''' super(ControllerMainServer, self).__init__(controller_url, key, certificate) self._bdf = bundle_factory self._key",
"= key self._cert = certificate self._ca = ca self._config = files.JsonFile('controller/config') self._account_url =",
"a url and maps it to the client url (which is the key)'''",
"caching purposes. self._bundle_factory = bundle_factory self._tokens = set() self._accounts = {} self._broker =",
"bundle as a stream of bytes.''' # note: returns data by chunks of",
"self._ca) def start(self): self._client_account.start() def stop(self, grace=None): self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory): def __init__(self, url):",
"broker_rpc, broker_pb2 as br_msg, \\ controller_service_pb2_grpc as ctl_rpc, data_bundle_pb2 as dtb from pluto.coms.utils",
"those urls. def __init__(self, bundle_factory, broker_url, key=None, certificate=None, ca=None): # list of controllables",
"upon termination, we need to save the generated urls, and relaunch the services",
"necessary raise NotImplementedError def PortfolioState(self, request, context): raise NotImplementedError def Orders(self, request, context):",
"broker_url, key, certificate) # TODO: finish this function (registration of the controllable) def",
"self._config.store({client_name: {'url': client_url, 'token': token}}) return token def _create_channel(self, url): return srv.create_channel(url, self._ca)",
"class ControllerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, controller_url, broker_url, key=None, certificate=None): '''the bundle_factory is an",
"we can remotely control it self._ctr = cbl_rpc.ControllableStub(controllable_channel) # each strategy controller has",
"= broker_url self._client_account = BrokerMainServer(bundle_factory, broker_url, key, certificate) # TODO: finish this function",
"metadata['Token'] if not token in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided token is incorrect') def",
"class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available services per-client''' # todo: must check the metadata... def",
"request, context): raise NotImplementedError def Transactions(self, request, context): self._check_metadata(context) for trx in self._get_dict_values(self._broker.transactions()):",
"chunk in self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, broker_url, broker, key=None,",
"style = MarketOrder() elif req_style == br_msg.OrderParams.LIMIT_ORDER: style = LimitOrder(request.limit_price) elif req_style ==",
"broker def _check_metadata(self, context): metadata = dict(context.invocation_metadata()) token = metadata['Token'] if not token",
"bundle_factory, broker_url, key=None, certificate=None, ca=None): # list of controllables (strategies) self._controllables = {}",
"should we run the controllables? => should we schedule periodic back-testings? # keep",
"capital(self, value): self._capital = value def run(self, start, end, max_leverage, data_frequency='daily', metrics_set='default', live=False):",
"we can control them etc. self._controllables[token] = controllable # send the generated access",
"client_url, 'token': token}}) return token def _create_channel(self, url): return srv.create_channel(url, self._ca) def start(self):",
"self._check_metadata(context) for trx in self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx) def SingleOrder(self, request, context): self._check_metadata(context) req_style",
"is an abstraction for creating data bundles.''' super(ControllerMainServer, self).__init__(controller_url, key, certificate) self._bdf =",
"TODO: finish this function (registration of the controllable) def Register(self, request, context): '''the",
"add_token(self, token): self._acc.add_token(token) def _add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc, server) class Controllable(object): '''encapsulates utilities for",
"max_leverage, data_frequency='daily', metrics_set='default', live=False): '''this function is an iterable (generator) ''' if data_frequency",
"(performs tests routines, assigns capital etc.''' # TODO: upon termination, we need to",
"in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided token is incorrect') def add_token(self, token): self._tokens.add(token) def",
"# list of controllables (strategies) self._controllables = {} self._bundle_factory = bundle_factory self._key =",
"to the client so that it can recognise clients return ctl.RegisterReply(url=self._account_url, token=token) def",
"request, context): self._check_metadata(context) req_style = request.style style = None if req_style == br_msg.OrderParams.MARKET_ORDER:",
"should we schedule periodic back-testings? # keep track of controllables so that we",
"can control them etc. self._controllables[token] = controllable # send the generated access url",
"return self._capital @capital.setter def capital(self, value): self._capital = value def run(self, start, end,",
"request.stop_price) if style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order style argument')",
"bundle_factory self._key = key self._cert = certificate self._ca = ca self._config = files.JsonFile('controller/config')",
"import uuid import grpc from zipline.finance.execution import MarketOrder, StopLimitOrder, StopOrder, LimitOrder from protos",
"based on the specified 'domains' and sends the bundle as a stream of",
"(strategies) self._controllables = {} self._bundle_factory = bundle_factory self._key = key self._cert = certificate",
"a strategy.''' def __init__(self, name, controllable_channel): self._name = name self._capital = 0.0 #",
"(registration of the controllable) def Register(self, request, context): '''the controllable calls this function",
"_create_token(self, client_name, client_url): '''creates a url and maps it to the client url",
"generated access url to the client (through a secure channel). The client communicate",
"PositionsState(self, request, context): raise NotImplementedError def Transactions(self, request, context): self._check_metadata(context) for trx in",
"style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order style argument') def GetDataBundle(self,",
"is generated token = self._create_token(client_name, controllable_url) controllable = Controllable( client_name, self._create_channel(controllable_url) ) #todo:",
"{} is supported'.format(data_frequency)) for perf in self._ctr.Run( cbl.RunParams( capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set,",
"cv.to_proto_transaction(trx) def SingleOrder(self, request, context): self._check_metadata(context) req_style = request.style style = None if",
"builder.get_certificate_signing_request(subject, key) class ControllerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, controller_url, broker_url, key=None, certificate=None): '''the bundle_factory",
"for creating data bundles.''' super(ControllerMainServer, self).__init__(controller_url, key, certificate) self._bdf = bundle_factory self._key =",
"req_style == br_msg.OrderParams.STOP_LIMIT_ORDER: style = StopLimitOrder(request.limit_price, request.stop_price) if style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style))",
"crt.CertificateSigningRequestBuilder() builder.name = 'controller' builder.usages = ['digital signature','key encipherment', 'data encipherment','server auth'] builder.groups",
"style = StopLimitOrder(request.limit_price, request.stop_price) if style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported",
"urls, and relaunch the services # that server on those urls. def __init__(self,",
"iterable (generator) ''' if data_frequency == 'daily': df = cbl.RunParams.DAY elif data_frequency ==",
"certificate self._blt = broker_url def _add_servicer_to_server(self, server): ctl_rpc.add_ControllerServicer_to_server(ControllerServicer( self._bdf, self._blt, self._key, self._cert), server)",
"= BrokerServicer(bundle_factory, broker) def add_token(self, token): self._acc.add_token(token) def _add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc, server) class",
"'minutely': df = cbl.RunParams.MINUTE else: raise ValueError('No data frequency of type {} is",
"this url permanently, so that it can be identified # add token to",
"NotImplementedError def PositionsState(self, request, context): raise NotImplementedError def Transactions(self, request, context): self._check_metadata(context) for",
"df = cbl.RunParams.MINUTE else: raise ValueError('No data frequency of type {} is supported'.format(data_frequency))",
"can be id-ed beyond run lifetime. #the controllable sends its url controllable_url =",
"return next(self._config.load())[name] except FileNotFoundError: raise KeyError def _create_token(self, client_name, client_url): '''creates a url",
"== br_msg.OrderParams.STOP_ORDER: style = StopOrder(request.stop_price) elif req_style == br_msg.OrderParams.STOP_LIMIT_ORDER: style = StopLimitOrder(request.limit_price, request.stop_price)",
"key, certificate) self._bdf = bundle_factory self._key = key self._cert = certificate self._blt =",
"url controllable_url = request.url client_name = request.name #a token is generated token =",
"# TODO: how do pod ip's,services etc work? # additional addresses: pod ip,",
"certificate) self._bdf = bundle_factory self._key = key self._cert = certificate self._blt = broker_url",
"url permanently, so that it can be identified # add token to the",
"calls this function to be registered''' # TODO: store the url permanently so",
"certificate) self._acc = BrokerServicer(bundle_factory, broker) def add_token(self, token): self._acc.add_token(token) def _add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc,",
"self._name = name self._capital = 0.0 # reference to the controllable so that",
"key=None, certificate=None): super(BrokerMainServer, self).__init__(broker_url, key, certificate) self._acc = BrokerServicer(bundle_factory, broker) def add_token(self, token):",
"def Transactions(self, request, context): self._check_metadata(context) for trx in self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx) def SingleOrder(self,",
"self._bundle_factory = bundle_factory self._tokens = set() self._accounts = {} self._broker = broker def",
"as cbl, broker_pb2_grpc as broker_rpc, broker_pb2 as br_msg, \\ controller_service_pb2_grpc as ctl_rpc, data_bundle_pb2",
"from pluto.coms.utils import certification as crt from pluto.coms.utils import conversions as cv from",
"broker, bundle_factory): # the bundle factory is aggregated, for caching purposes. self._bundle_factory =",
"list of controllables (strategies) self._controllables = {} self._bundle_factory = bundle_factory self._key = key",
"beyond run lifetime. #the controllable sends its url controllable_url = request.url client_name =",
"bundle_factory, broker_url, broker, key=None, certificate=None): super(BrokerMainServer, self).__init__(broker_url, key, certificate) self._acc = BrokerServicer(bundle_factory, broker)",
"token = metadata['Token'] if not token in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided token is",
"= None if req_style == br_msg.OrderParams.MARKET_ORDER: style = MarketOrder() elif req_style == br_msg.OrderParams.LIMIT_ORDER:",
"NotImplementedError def PortfolioState(self, request, context): raise NotImplementedError def Orders(self, request, context): self._check_metadata(context) for",
"certificate) # TODO: finish this function (registration of the controllable) def Register(self, request,",
"be registered''' # TODO: store the url permanently so that the client can",
"def __init__(self, bundle_factory, broker_url, broker, key=None, certificate=None): super(BrokerMainServer, self).__init__(broker_url, key, certificate) self._acc =",
"as a stream of bytes.''' # note: returns data by chunks of 1KB",
"certificate=None): '''the bundle_factory is an abstraction for creating data bundles.''' super(ControllerMainServer, self).__init__(controller_url, key,",
"self._broker = broker def _check_metadata(self, context): metadata = dict(context.invocation_metadata()) token = metadata['Token'] if",
"NotImplementedError def Orders(self, request, context): self._check_metadata(context) for order in self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order) def",
"req_style == br_msg.OrderParams.LIMIT_ORDER: style = LimitOrder(request.limit_price) elif req_style == br_msg.OrderParams.STOP_ORDER: style = StopOrder(request.stop_price)",
"bytes.''' # note: returns data by chunks of 1KB by default. self._check_metadata(context) for",
"to some generated port... # one client account per server. @property def capital(self):",
"def add_token(self, token): self._acc.add_token(token) def _add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc, server) class Controllable(object): '''encapsulates utilities",
"the services # that server on those urls. def __init__(self, bundle_factory, broker_url, key=None,",
"controllable_url) controllable = Controllable( client_name, self._create_channel(controllable_url) ) #todo: when and how should we",
"data_frequency == 'daily': df = cbl.RunParams.DAY elif data_frequency == 'minutely': df = cbl.RunParams.MINUTE",
"self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory): def __init__(self, url): super(ControllerCertificateFactory, self).__init__() self._url = url def _create_certificate(self,",
"self._key = key self._cert = certificate self._blt = broker_url def _add_servicer_to_server(self, server): ctl_rpc.add_ControllerServicer_to_server(ControllerServicer(",
"broker_rpc.add_BrokerServicer_to_server(self._acc, server) class Controllable(object): '''encapsulates utilities for remotely controlling a strategy.''' def __init__(self,",
"back-testings? # keep track of controllables so that we can control them etc.",
"the controllables? => should we schedule periodic back-testings? # keep track of controllables",
"value): self._capital = value def run(self, start, end, max_leverage, data_frequency='daily', metrics_set='default', live=False): '''this",
"and sends the bundle as a stream of bytes.''' # note: returns data",
"controllable) def Register(self, request, context): '''the controllable calls this function to be registered'''",
"br_msg.OrderParams.LIMIT_ORDER: style = LimitOrder(request.limit_price) elif req_style == br_msg.OrderParams.STOP_ORDER: style = StopOrder(request.stop_price) elif req_style",
"controllable_channel): self._name = name self._capital = 0.0 # reference to the controllable so",
"ctl.RegisterReply(url=self._account_url, token=token) def _load_config(self, name): try: return next(self._config.load())[name] except FileNotFoundError: raise KeyError def",
"remotely control it self._ctr = cbl_rpc.ControllableStub(controllable_channel) # each strategy controller has a server",
"= controllable # send the generated access url to the client (through a",
"def __init__(self, name, controllable_channel): self._name = name self._capital = 0.0 # reference to",
"def add_account(self, account): self._accounts[account.token] = account def AccountState(self, request, context): # todo: these",
"elif req_style == br_msg.OrderParams.STOP_ORDER: style = StopOrder(request.stop_price) elif req_style == br_msg.OrderParams.STOP_LIMIT_ORDER: style =",
"server) class Controllable(object): '''encapsulates utilities for remotely controlling a strategy.''' def __init__(self, name,",
"key=None, certificate=None, ca=None): # list of controllables (strategies) self._controllables = {} self._bundle_factory =",
"can remotely control it self._ctr = cbl_rpc.ControllableStub(controllable_channel) # each strategy controller has a",
"cbl, broker_pb2_grpc as broker_rpc, broker_pb2 as br_msg, \\ controller_service_pb2_grpc as ctl_rpc, data_bundle_pb2 as",
"lifetime. #the controllable sends its url controllable_url = request.url client_name = request.name #a",
"dict_): return dict_.values() def BatchOrder(self, request_iterator, context): raise NotImplementedError def CancelAllOrdersForAsset(self, request, context):",
"run lifetime. #the controllable sends its url controllable_url = request.url client_name = request.name",
"builder.usages = ['digital signature','key encipherment', 'data encipherment','server auth'] builder.groups = ['system: authenticated'] return",
"srv.create_channel(url, self._ca) def start(self): self._client_account.start() def stop(self, grace=None): self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory): def __init__(self,",
"additional addresses: pod ip, pod dns, master IP... builder = crt.CertificateSigningRequestBuilder() builder.name =",
"= metadata['Token'] if not token in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided token is incorrect')",
"import conversions as cv from pluto.utils import files class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available services",
"if style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'unsupported order style argument') def",
"key self._cert = certificate self._blt = broker_url def _add_servicer_to_server(self, server): ctl_rpc.add_ControllerServicer_to_server(ControllerServicer( self._bdf, self._blt,",
"it can be identified # add token to the client so that it",
"client so that it can recognise clients return ctl.RegisterReply(url=self._account_url, token=token) def _load_config(self, name):",
"br_msg.OrderParams.STOP_LIMIT_ORDER: style = StopLimitOrder(request.limit_price, request.stop_price) if style: return cv.to_proto_order(self._broker.order(cv.to_zp_asset(request.asset), request.amount, style)) else: context.abort(grpc.StatusCode.INVALID_ARGUMENT,",
"'''the bundle_factory is an abstraction for creating data bundles.''' super(ControllerMainServer, self).__init__(controller_url, key, certificate)",
"= request.url client_name = request.name #a token is generated token = self._create_token(client_name, controllable_url)",
"this channel. # the client must store this url permanently, so that it",
"the client url (which is the key)''' try: conf = self._load_config(client_name) return conf['token']",
"registered''' # TODO: store the url permanently so that the client can be",
"account): self._accounts[account.token] = account def AccountState(self, request, context): # todo: these methods aren't",
"controllable_service_pb2 as cbl, broker_pb2_grpc as broker_rpc, broker_pb2 as br_msg, \\ controller_service_pb2_grpc as ctl_rpc,",
"add_account(self, account): self._accounts[account.token] = account def AccountState(self, request, context): # todo: these methods",
"permanently, so that it can be identified # add token to the client",
"auth'] builder.groups = ['system: authenticated'] return builder.get_certificate_signing_request(subject, key) class ControllerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory,",
"'''creates a bundle based on the specified 'domains' and sends the bundle as",
"that it can recognise clients return ctl.RegisterReply(url=self._account_url, token=token) def _load_config(self, name): try: return",
"default. self._check_metadata(context) for chunk in self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory,",
"for chunk in self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, broker_url, broker,",
"subject.alternative_names = [self._url] # TODO: how do pod ip's,services etc work? # additional",
"def stop(self, grace=None): self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory): def __init__(self, url): super(ControllerCertificateFactory, self).__init__() self._url =",
"ValueError('No data frequency of type {} is supported'.format(data_frequency)) for perf in self._ctr.Run( cbl.RunParams(",
"token=token) def _load_config(self, name): try: return next(self._config.load())[name] except FileNotFoundError: raise KeyError def _create_token(self,",
"so that the client can be id-ed beyond run lifetime. #the controllable sends",
"'data encipherment','server auth'] builder.groups = ['system: authenticated'] return builder.get_certificate_signing_request(subject, key) class ControllerMainServer(srv.MainServerFactory): def",
"def SingleOrder(self, request, context): self._check_metadata(context) req_style = request.style style = None if req_style",
"def capital(self, value): self._capital = value def run(self, start, end, max_leverage, data_frequency='daily', metrics_set='default',",
") #todo: when and how should we run the controllables? => should we",
"that server on those urls. def __init__(self, bundle_factory, broker_url, key=None, certificate=None, ca=None): #",
"per server. @property def capital(self): return self._capital @capital.setter def capital(self, value): self._capital =",
"dtb from pluto.coms.utils import server_utils as srv from pluto.coms.utils import certification as crt",
"token}}) return token def _create_channel(self, url): return srv.create_channel(url, self._ca) def start(self): self._client_account.start() def",
"= request.name #a token is generated token = self._create_token(client_name, controllable_url) controllable = Controllable(",
"= key self._cert = certificate self._blt = broker_url def _add_servicer_to_server(self, server): ctl_rpc.add_ControllerServicer_to_server(ControllerServicer( self._bdf,",
"self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, broker_url, broker, key=None, certificate=None): super(BrokerMainServer,",
"request, context): # todo: these methods aren't necessary raise NotImplementedError def PortfolioState(self, request,",
"value def run(self, start, end, max_leverage, data_frequency='daily', metrics_set='default', live=False): '''this function is an",
"the client (through a secure channel). The client communicate with the # account",
"_create_certificate(self, root_path, cert_name, key, subject): '''creates a certificate request or returns a certificate",
"the controllable) def Register(self, request, context): '''the controllable calls this function to be",
"ca=None): # list of controllables (strategies) self._controllables = {} self._bundle_factory = bundle_factory self._key",
"termination, we need to save the generated urls, and relaunch the services #",
"= set() self._accounts = {} self._broker = broker def _check_metadata(self, context): metadata =",
"token and store clients data... token = str(uuid.uuid4()) self._config.store({client_name: {'url': client_url, 'token': token}})",
"# TODO: upon termination, we need to save the generated urls, and relaunch",
"except KeyError: #create a token and store clients data... token = str(uuid.uuid4()) self._config.store({client_name:",
"'''encapsulates available services per-client''' # todo: must check the metadata... def __init__(self, broker,",
"broker_pb2_grpc as broker_rpc, broker_pb2 as br_msg, \\ controller_service_pb2_grpc as ctl_rpc, data_bundle_pb2 as dtb",
"__init__(self, broker, bundle_factory): # the bundle factory is aggregated, for caching purposes. self._bundle_factory",
"context): raise NotImplementedError def PositionsState(self, request, context): raise NotImplementedError def Transactions(self, request, context):",
"in self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx) def SingleOrder(self, request, context): self._check_metadata(context) req_style = request.style style",
"services # that server on those urls. def __init__(self, bundle_factory, broker_url, key=None, certificate=None,",
"and relaunch the services # that server on those urls. def __init__(self, bundle_factory,",
"bundle factory is aggregated, for caching purposes. self._bundle_factory = bundle_factory self._tokens = set()",
"raise NotImplementedError def PositionsState(self, request, context): raise NotImplementedError def Transactions(self, request, context): self._check_metadata(context)",
"crt from pluto.coms.utils import conversions as cv from pluto.utils import files class BrokerServicer(broker_rpc.BrokerServicer):",
"= broker def _check_metadata(self, context): metadata = dict(context.invocation_metadata()) token = metadata['Token'] if not",
"dict(context.invocation_metadata()) token = metadata['Token'] if not token in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided token",
"self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx) def SingleOrder(self, request, context): self._check_metadata(context) req_style = request.style style =",
"= str(uuid.uuid4()) self._config.store({client_name: {'url': client_url, 'token': token}}) return token def _create_channel(self, url): return",
"we need to save the generated urls, and relaunch the services # that",
"PortfolioState(self, request, context): raise NotImplementedError def Orders(self, request, context): self._check_metadata(context) for order in",
"str(uuid.uuid4()) self._config.store({client_name: {'url': client_url, 'token': token}}) return token def _create_channel(self, url): return srv.create_channel(url,",
"metadata... def __init__(self, broker, bundle_factory): # the bundle factory is aggregated, for caching",
"chunks of 1KB by default. self._check_metadata(context) for chunk in self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk) class",
"each strategy controller has a server that listens to some generated port... #",
"generated port... # one client account per server. @property def capital(self): return self._capital",
"certificate=None): super(BrokerMainServer, self).__init__(broker_url, key, certificate) self._acc = BrokerServicer(bundle_factory, broker) def add_token(self, token): self._acc.add_token(token)",
"key, certificate) # TODO: finish this function (registration of the controllable) def Register(self,",
"dict_.values() def BatchOrder(self, request_iterator, context): raise NotImplementedError def CancelAllOrdersForAsset(self, request, context): raise NotImplementedError",
"request.url client_name = request.name #a token is generated token = self._create_token(client_name, controllable_url) controllable",
"controllables? => should we schedule periodic back-testings? # keep track of controllables so",
"some generated port... # one client account per server. @property def capital(self): return",
"the key)''' try: conf = self._load_config(client_name) return conf['token'] except KeyError: #create a token",
"yield cv.to_proto_transaction(trx) def SingleOrder(self, request, context): self._check_metadata(context) req_style = request.style style = None",
"as cv from pluto.utils import files class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available services per-client''' #",
"sends its url controllable_url = request.url client_name = request.name #a token is generated",
"protos import controller_service_pb2 as ctl, controllable_service_pb2_grpc as cbl_rpc, \\ controllable_service_pb2 as cbl, broker_pb2_grpc",
"key, certificate) self._acc = BrokerServicer(bundle_factory, broker) def add_token(self, token): self._acc.add_token(token) def _add_servicer_to_server(self, server):",
"we schedule periodic back-testings? # keep track of controllables so that we can",
"context): self._check_metadata(context) for order in self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order) def _get_dict_values(self, dict_): return dict_.values()",
"_create_channel(self, url): return srv.create_channel(url, self._ca) def start(self): self._client_account.start() def stop(self, grace=None): self._client_account.stop(grace) class",
"class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates the controller service. This class manages a portfolio of",
"not token in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided token is incorrect') def add_token(self, token):",
"channel). The client communicate with the # account through this channel. # the",
"from pluto.coms.utils import server_utils as srv from pluto.coms.utils import certification as crt from",
"control them etc. self._controllables[token] = controllable # send the generated access url to",
"of the certificate request subject.common_name = 'controller' subject.alternative_names = [self._url] # TODO: how",
"as ctl, controllable_service_pb2_grpc as cbl_rpc, \\ controllable_service_pb2 as cbl, broker_pb2_grpc as broker_rpc, broker_pb2",
"service. This class manages a portfolio of strategies (performs tests routines, assigns capital",
"to be registered''' # TODO: store the url permanently so that the client",
"# one client account per server. @property def capital(self): return self._capital @capital.setter def",
"track of controllables so that we can control them etc. self._controllables[token] = controllable",
"= dict(context.invocation_metadata()) token = metadata['Token'] if not token in self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided",
"key) class ControllerMainServer(srv.MainServerFactory): def __init__(self, bundle_factory, controller_url, broker_url, key=None, certificate=None): '''the bundle_factory is",
"controller_service_pb2 as ctl, controllable_service_pb2_grpc as cbl_rpc, \\ controllable_service_pb2 as cbl, broker_pb2_grpc as broker_rpc,",
"import server_utils as srv from pluto.coms.utils import certification as crt from pluto.coms.utils import",
"ctl, controllable_service_pb2_grpc as cbl_rpc, \\ controllable_service_pb2 as cbl, broker_pb2_grpc as broker_rpc, broker_pb2 as",
"todo: these methods aren't necessary raise NotImplementedError def PortfolioState(self, request, context): raise NotImplementedError",
"controller_url, broker_url, key=None, certificate=None): '''the bundle_factory is an abstraction for creating data bundles.'''",
"token to the client so that it can recognise clients return ctl.RegisterReply(url=self._account_url, token=token)",
"controllable calls this function to be registered''' # TODO: store the url permanently",
"CancelAllOrdersForAsset(self, request, context): raise NotImplementedError def PositionsState(self, request, context): raise NotImplementedError def Transactions(self,",
"client (through a secure channel). The client communicate with the # account through",
"self._acc.add_token(token) def _add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc, server) class Controllable(object): '''encapsulates utilities for remotely controlling",
"on those urls. def __init__(self, bundle_factory, broker_url, key=None, certificate=None, ca=None): # list of",
"Register(self, request, context): '''the controllable calls this function to be registered''' # TODO:",
"self._url = url def _create_certificate(self, root_path, cert_name, key, subject): '''creates a certificate request",
"context): raise NotImplementedError def CancelAllOrdersForAsset(self, request, context): raise NotImplementedError def PositionsState(self, request, context):",
"class manages a portfolio of strategies (performs tests routines, assigns capital etc.''' #",
"= ca self._config = files.JsonFile('controller/config') self._account_url = broker_url self._client_account = BrokerMainServer(bundle_factory, broker_url, key,",
"except FileNotFoundError: raise KeyError def _create_token(self, client_name, client_url): '''creates a url and maps",
"files.JsonFile('controller/config') self._account_url = broker_url self._client_account = BrokerMainServer(bundle_factory, broker_url, key, certificate) # TODO: finish",
"bundle_factory self._tokens = set() self._accounts = {} self._broker = broker def _check_metadata(self, context):",
"'daily': df = cbl.RunParams.DAY elif data_frequency == 'minutely': df = cbl.RunParams.MINUTE else: raise",
"{'url': client_url, 'token': token}}) return token def _create_channel(self, url): return srv.create_channel(url, self._ca) def",
"self._capital @capital.setter def capital(self, value): self._capital = value def run(self, start, end, max_leverage,",
"metrics_set='default', live=False): '''this function is an iterable (generator) ''' if data_frequency == 'daily':",
"ip, pod dns, master IP... builder = crt.CertificateSigningRequestBuilder() builder.name = 'controller' builder.usages =",
"self._accounts[account.token] = account def AccountState(self, request, context): # todo: these methods aren't necessary",
"for order in self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order) def _get_dict_values(self, dict_): return dict_.values() def BatchOrder(self,",
"pod ip's,services etc work? # additional addresses: pod ip, pod dns, master IP...",
"as cbl_rpc, \\ controllable_service_pb2 as cbl, broker_pb2_grpc as broker_rpc, broker_pb2 as br_msg, \\",
"this function to be registered''' # TODO: store the url permanently so that",
"raise NotImplementedError def Orders(self, request, context): self._check_metadata(context) for order in self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order)",
"name self._capital = 0.0 # reference to the controllable so that we can",
"''' if data_frequency == 'daily': df = cbl.RunParams.DAY elif data_frequency == 'minutely': df",
"key=None, certificate=None): '''the bundle_factory is an abstraction for creating data bundles.''' super(ControllerMainServer, self).__init__(controller_url,",
"'''creates a url and maps it to the client url (which is the",
"def _create_channel(self, url): return srv.create_channel(url, self._ca) def start(self): self._client_account.start() def stop(self, grace=None): self._client_account.stop(grace)",
"services per-client''' # todo: must check the metadata... def __init__(self, broker, bundle_factory): #",
"must store this url permanently, so that it can be identified # add",
"one exists...''' # create the subject of the certificate request subject.common_name = 'controller'",
"broker, key=None, certificate=None): super(BrokerMainServer, self).__init__(broker_url, key, certificate) self._acc = BrokerServicer(bundle_factory, broker) def add_token(self,",
"# TODO: store the url permanently so that the client can be id-ed",
"need to save the generated urls, and relaunch the services # that server",
"certificate if one exists...''' # create the subject of the certificate request subject.common_name",
"<reponame>chalant/pluto import uuid import grpc from zipline.finance.execution import MarketOrder, StopLimitOrder, StopOrder, LimitOrder from",
"srv.IServer): '''Encapsulates the controller service. This class manages a portfolio of strategies (performs",
"relaunch the services # that server on those urls. def __init__(self, bundle_factory, broker_url,",
"# todo: these methods aren't necessary raise NotImplementedError def PortfolioState(self, request, context): raise",
"when and how should we run the controllables? => should we schedule periodic",
"self._config = files.JsonFile('controller/config') self._account_url = broker_url self._client_account = BrokerMainServer(bundle_factory, broker_url, key, certificate) #",
"uuid import grpc from zipline.finance.execution import MarketOrder, StopLimitOrder, StopOrder, LimitOrder from protos import",
"# the bundle factory is aggregated, for caching purposes. self._bundle_factory = bundle_factory self._tokens",
"self._check_metadata(context) for order in self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order) def _get_dict_values(self, dict_): return dict_.values() def",
"for trx in self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx) def SingleOrder(self, request, context): self._check_metadata(context) req_style =",
"self._tokens: context.abort(grpc.StatusCode.PERMISSION_DENIED, 'The provided token is incorrect') def add_token(self, token): self._tokens.add(token) def add_account(self,",
"def Orders(self, request, context): self._check_metadata(context) for order in self._get_dict_values(self._broker.orders()): yield cv.to_proto_order(order) def _get_dict_values(self,",
"NotImplementedError def CancelAllOrdersForAsset(self, request, context): raise NotImplementedError def PositionsState(self, request, context): raise NotImplementedError",
"SingleOrder(self, request, context): self._check_metadata(context) req_style = request.style style = None if req_style ==",
"= Controllable( client_name, self._create_channel(controllable_url) ) #todo: when and how should we run the",
"1KB by default. self._check_metadata(context) for chunk in self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory): def",
"controller_service_pb2_grpc as ctl_rpc, data_bundle_pb2 as dtb from pluto.coms.utils import server_utils as srv from",
"req_style == br_msg.OrderParams.STOP_ORDER: style = StopOrder(request.stop_price) elif req_style == br_msg.OrderParams.STOP_LIMIT_ORDER: style = StopLimitOrder(request.limit_price,",
"can recognise clients return ctl.RegisterReply(url=self._account_url, token=token) def _load_config(self, name): try: return next(self._config.load())[name] except",
"save the generated urls, and relaunch the services # that server on those",
"self._tokens.add(token) def add_account(self, account): self._accounts[account.token] = account def AccountState(self, request, context): # todo:",
"strategies (performs tests routines, assigns capital etc.''' # TODO: upon termination, we need",
"end, max_leverage, data_frequency='daily', metrics_set='default', live=False): '''this function is an iterable (generator) ''' if",
"request, context): '''the controllable calls this function to be registered''' # TODO: store",
"cv from pluto.utils import files class BrokerServicer(broker_rpc.BrokerServicer): '''encapsulates available services per-client''' # todo:",
"= request.style style = None if req_style == br_msg.OrderParams.MARKET_ORDER: style = MarketOrder() elif",
"df = cbl.RunParams.DAY elif data_frequency == 'minutely': df = cbl.RunParams.MINUTE else: raise ValueError('No",
"'The provided token is incorrect') def add_token(self, token): self._tokens.add(token) def add_account(self, account): self._accounts[account.token]",
"pluto.coms.utils import certification as crt from pluto.coms.utils import conversions as cv from pluto.utils",
"'domains' and sends the bundle as a stream of bytes.''' # note: returns",
"of controllables so that we can control them etc. self._controllables[token] = controllable #",
"pod dns, master IP... builder = crt.CertificateSigningRequestBuilder() builder.name = 'controller' builder.usages = ['digital",
"controller service. This class manages a portfolio of strategies (performs tests routines, assigns",
"of 1KB by default. self._check_metadata(context) for chunk in self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory):",
"dns, master IP... builder = crt.CertificateSigningRequestBuilder() builder.name = 'controller' builder.usages = ['digital signature','key",
"self._acc = BrokerServicer(bundle_factory, broker) def add_token(self, token): self._acc.add_token(token) def _add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc, server)",
"IP... builder = crt.CertificateSigningRequestBuilder() builder.name = 'controller' builder.usages = ['digital signature','key encipherment', 'data",
"style = StopOrder(request.stop_price) elif req_style == br_msg.OrderParams.STOP_LIMIT_ORDER: style = StopLimitOrder(request.limit_price, request.stop_price) if style:",
"request.name #a token is generated token = self._create_token(client_name, controllable_url) controllable = Controllable( client_name,",
"these methods aren't necessary raise NotImplementedError def PortfolioState(self, request, context): raise NotImplementedError def",
"super(ControllerCertificateFactory, self).__init__() self._url = url def _create_certificate(self, root_path, cert_name, key, subject): '''creates a",
"controllable = Controllable( client_name, self._create_channel(controllable_url) ) #todo: when and how should we run",
"its url controllable_url = request.url client_name = request.name #a token is generated token",
"url def _create_certificate(self, root_path, cert_name, key, subject): '''creates a certificate request or returns",
"for caching purposes. self._bundle_factory = bundle_factory self._tokens = set() self._accounts = {} self._broker",
"store this url permanently, so that it can be identified # add token",
"is the key)''' try: conf = self._load_config(client_name) return conf['token'] except KeyError: #create a",
"has a server that listens to some generated port... # one client account",
"def __init__(self, bundle_factory, broker_url, key=None, certificate=None, ca=None): # list of controllables (strategies) self._controllables",
"broker) def add_token(self, token): self._acc.add_token(token) def _add_servicer_to_server(self, server): broker_rpc.add_BrokerServicer_to_server(self._acc, server) class Controllable(object): '''encapsulates",
"(which is the key)''' try: conf = self._load_config(client_name) return conf['token'] except KeyError: #create",
"self._load_config(client_name) return conf['token'] except KeyError: #create a token and store clients data... token",
"_load_config(self, name): try: return next(self._config.load())[name] except FileNotFoundError: raise KeyError def _create_token(self, client_name, client_url):",
"set() self._accounts = {} self._broker = broker def _check_metadata(self, context): metadata = dict(context.invocation_metadata())",
"cbl.RunParams( capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live, maximum_leverage=max_leverage )): yield cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer,",
"encipherment','server auth'] builder.groups = ['system: authenticated'] return builder.get_certificate_signing_request(subject, key) class ControllerMainServer(srv.MainServerFactory): def __init__(self,",
"self._ctr.Run( cbl.RunParams( capital_base=self._capital, data_frequency=df, start_session=cv.to_datetime(start), end_session=cv.to_datetime(end), metrics_set=metrics_set, live=live, maximum_leverage=max_leverage )): yield cv.from_proto_performance_packet(perf) class",
"_get_dict_values(self, dict_): return dict_.values() def BatchOrder(self, request_iterator, context): raise NotImplementedError def CancelAllOrdersForAsset(self, request,",
"(generator) ''' if data_frequency == 'daily': df = cbl.RunParams.DAY elif data_frequency == 'minutely':",
"that listens to some generated port... # one client account per server. @property",
"maximum_leverage=max_leverage )): yield cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates the controller service. This class",
"builder = crt.CertificateSigningRequestBuilder() builder.name = 'controller' builder.usages = ['digital signature','key encipherment', 'data encipherment','server",
"data frequency of type {} is supported'.format(data_frequency)) for perf in self._ctr.Run( cbl.RunParams( capital_base=self._capital,",
"=> should we schedule periodic back-testings? # keep track of controllables so that",
"def _create_token(self, client_name, client_url): '''creates a url and maps it to the client",
"factory is aggregated, for caching purposes. self._bundle_factory = bundle_factory self._tokens = set() self._accounts",
"= ['digital signature','key encipherment', 'data encipherment','server auth'] builder.groups = ['system: authenticated'] return builder.get_certificate_signing_request(subject,",
"self._capital = 0.0 # reference to the controllable so that we can remotely",
"self).__init__(broker_url, key, certificate) self._acc = BrokerServicer(bundle_factory, broker) def add_token(self, token): self._acc.add_token(token) def _add_servicer_to_server(self,",
"etc.''' # TODO: upon termination, we need to save the generated urls, and",
"data_frequency='daily', metrics_set='default', live=False): '''this function is an iterable (generator) ''' if data_frequency ==",
"= name self._capital = 0.0 # reference to the controllable so that we",
"controllables (strategies) self._controllables = {} self._bundle_factory = bundle_factory self._key = key self._cert =",
"cbl_rpc.ControllableStub(controllable_channel) # each strategy controller has a server that listens to some generated",
"style argument') def GetDataBundle(self, request, context): '''creates a bundle based on the specified",
"generated token = self._create_token(client_name, controllable_url) controllable = Controllable( client_name, self._create_channel(controllable_url) ) #todo: when",
"# create the subject of the certificate request subject.common_name = 'controller' subject.alternative_names =",
"we run the controllables? => should we schedule periodic back-testings? # keep track",
"cert_name, key, subject): '''creates a certificate request or returns a certificate if one",
"certificate request subject.common_name = 'controller' subject.alternative_names = [self._url] # TODO: how do pod",
"def start(self): self._client_account.start() def stop(self, grace=None): self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory): def __init__(self, url): super(ControllerCertificateFactory,",
"# send the generated access url to the client (through a secure channel).",
"the controllable so that we can remotely control it self._ctr = cbl_rpc.ControllableStub(controllable_channel) #",
"self._cert = certificate self._ca = ca self._config = files.JsonFile('controller/config') self._account_url = broker_url self._client_account",
"etc. self._controllables[token] = controllable # send the generated access url to the client",
"'unsupported order style argument') def GetDataBundle(self, request, context): '''creates a bundle based on",
"stop(self, grace=None): self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory): def __init__(self, url): super(ControllerCertificateFactory, self).__init__() self._url = url",
"token def _create_channel(self, url): return srv.create_channel(url, self._ca) def start(self): self._client_account.start() def stop(self, grace=None):",
"as crt from pluto.coms.utils import conversions as cv from pluto.utils import files class",
"create the subject of the certificate request subject.common_name = 'controller' subject.alternative_names = [self._url]",
"add token to the client so that it can recognise clients return ctl.RegisterReply(url=self._account_url,",
"by default. self._check_metadata(context) for chunk in self._bundle_factory.get_bundle(request.country_code): yield dtb.Bundle(data=chunk) class BrokerMainServer(srv.MainServerFactory): def __init__(self,",
"conf['token'] except KeyError: #create a token and store clients data... token = str(uuid.uuid4())",
"= bundle_factory self._key = key self._cert = certificate self._blt = broker_url def _add_servicer_to_server(self,",
"that the client can be id-ed beyond run lifetime. #the controllable sends its",
"recognise clients return ctl.RegisterReply(url=self._account_url, token=token) def _load_config(self, name): try: return next(self._config.load())[name] except FileNotFoundError:",
"context): raise NotImplementedError def Orders(self, request, context): self._check_metadata(context) for order in self._get_dict_values(self._broker.orders()): yield",
"Controllable(object): '''encapsulates utilities for remotely controlling a strategy.''' def __init__(self, name, controllable_channel): self._name",
"of controllables (strategies) self._controllables = {} self._bundle_factory = bundle_factory self._key = key self._cert",
"# note: returns data by chunks of 1KB by default. self._check_metadata(context) for chunk",
"cv.from_proto_performance_packet(perf) class ControllerServicer(ctl_rpc.ControllerServicer, srv.IServer): '''Encapsulates the controller service. This class manages a portfolio",
"# that server on those urls. def __init__(self, bundle_factory, broker_url, key=None, certificate=None, ca=None):",
"ip's,services etc work? # additional addresses: pod ip, pod dns, master IP... builder",
"context): # todo: these methods aren't necessary raise NotImplementedError def PortfolioState(self, request, context):",
"if req_style == br_msg.OrderParams.MARKET_ORDER: style = MarketOrder() elif req_style == br_msg.OrderParams.LIMIT_ORDER: style =",
"self._accounts = {} self._broker = broker def _check_metadata(self, context): metadata = dict(context.invocation_metadata()) token",
"bundles.''' super(ControllerMainServer, self).__init__(controller_url, key, certificate) self._bdf = bundle_factory self._key = key self._cert =",
"reference to the controllable so that we can remotely control it self._ctr =",
"client url (which is the key)''' try: conf = self._load_config(client_name) return conf['token'] except",
"= certificate self._ca = ca self._config = files.JsonFile('controller/config') self._account_url = broker_url self._client_account =",
"start(self): self._client_account.start() def stop(self, grace=None): self._client_account.stop(grace) class ControllerCertificateFactory(crt.CertificateFactory): def __init__(self, url): super(ControllerCertificateFactory, self).__init__()",
"key self._cert = certificate self._ca = ca self._config = files.JsonFile('controller/config') self._account_url = broker_url",
"builder.name = 'controller' builder.usages = ['digital signature','key encipherment', 'data encipherment','server auth'] builder.groups =",
"= self._load_config(client_name) return conf['token'] except KeyError: #create a token and store clients data...",
"to the controllable so that we can remotely control it self._ctr = cbl_rpc.ControllableStub(controllable_channel)",
"context): raise NotImplementedError def Transactions(self, request, context): self._check_metadata(context) for trx in self._get_dict_values(self._broker.transactions()): yield",
"Transactions(self, request, context): self._check_metadata(context) for trx in self._get_dict_values(self._broker.transactions()): yield cv.to_proto_transaction(trx) def SingleOrder(self, request,",
"is an iterable (generator) ''' if data_frequency == 'daily': df = cbl.RunParams.DAY elif",
"maps it to the client url (which is the key)''' try: conf =",
"add_token(self, token): self._tokens.add(token) def add_account(self, account): self._accounts[account.token] = account def AccountState(self, request, context):",
"elif req_style == br_msg.OrderParams.LIMIT_ORDER: style = LimitOrder(request.limit_price) elif req_style == br_msg.OrderParams.STOP_ORDER: style =",
"GetDataBundle(self, request, context): '''creates a bundle based on the specified 'domains' and sends",
"= 0.0 # reference to the controllable so that we can remotely control",
"controllable so that we can remotely control it self._ctr = cbl_rpc.ControllableStub(controllable_channel) # each",
"url permanently so that the client can be id-ed beyond run lifetime. #the",
"them etc. self._controllables[token] = controllable # send the generated access url to the",
"# todo: must check the metadata... def __init__(self, broker, bundle_factory): # the bundle",
"the controller service. This class manages a portfolio of strategies (performs tests routines,",
"exists...''' # create the subject of the certificate request subject.common_name = 'controller' subject.alternative_names",
"sends the bundle as a stream of bytes.''' # note: returns data by"
] |
[
"/ train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"] = math.ceil( ( train_config.len // train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"] )",
"= ( train_config.len / train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"] = math.ceil( ( train_config.len // train_config.train_args[\"gradient_accumulation_steps\"]",
"TrainingArguments(**train_config.train_args) trainer = Trainer( model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), ) trainer.train() trainer.save_model() if __name__",
"json from sgnlp.models.emotion_entailment import train from sgnlp.models.emotion_entailment.utils import parse_args_and_load_config config = parse_args_and_load_config('config/emotion_entailment_config.json') train(config)",
"train_args = TrainingArguments(**train_config.train_args) trainer = Trainer( model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), ) trainer.train() trainer.save_model()",
"tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df = pd.read_csv(train_config.x_train_path) val_df = pd.read_csv(train_config.x_valid_path)",
"( RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config, ) def train_model(train_config: RecconEmotionEntailmentArguments): \"\"\" Method for training RecconEmotionEntailmentModel.",
") train_args = TrainingArguments(**train_config.train_args) trainer = Trainer( model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), ) trainer.train()",
"RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df = pd.read_csv(train_config.x_train_path) val_df = pd.read_csv(train_config.x_valid_path) train_dataset =",
"as pd from transformers import Trainer, TrainingArguments from .config import RecconEmotionEntailmentConfig from .data_class",
"* train_config.train_args[\"num_train_epochs\"] ) * train_config.train_args[\"warmup_ratio\"] ) train_args = TrainingArguments(**train_config.train_args) trainer = Trainer( model=model,",
"RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df = pd.read_csv(train_config.x_train_path) val_df = pd.read_csv(train_config.x_valid_path) train_dataset = convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length,",
"= RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df = pd.read_csv(train_config.x_train_path) val_df",
"RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df = pd.read_csv(train_config.x_train_path) val_df =",
"* train_config.train_args[\"warmup_ratio\"] ) train_args = TrainingArguments(**train_config.train_args) trainer = Trainer( model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset),",
") train_config.len = len(train_df) train_config.train_args[\"eval_steps\"] = ( train_config.len / train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"] =",
"Trainer( model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), ) trainer.train() trainer.save_model() if __name__ == \"__main__\": cfg",
"(:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config load from config file. Example:: import json from sgnlp.models.emotion_entailment import",
"train(config) \"\"\" config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df",
"math.ceil( ( train_config.len // train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"] ) * train_config.train_args[\"warmup_ratio\"] ) train_args =",
"= convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) train_config.len = len(train_df) train_config.train_args[\"eval_steps\"] = ( train_config.len",
"train_config.train_args[\"num_train_epochs\"] ) * train_config.train_args[\"warmup_ratio\"] ) train_args = TrainingArguments(**train_config.train_args) trainer = Trainer( model=model, args=train_args,",
"train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"] = math.ceil( ( train_config.len // train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"] ) *",
") def train_model(train_config: RecconEmotionEntailmentArguments): \"\"\" Method for training RecconEmotionEntailmentModel. Args: train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments",
"\"\"\" config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df =",
"config load from config file. Example:: import json from sgnlp.models.emotion_entailment import train from",
"tokenizer=tokenizer ) val_dataset = convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) train_config.len = len(train_df) train_config.train_args[\"eval_steps\"]",
"training RecconEmotionEntailmentModel. Args: train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config load from config file. Example:: import",
"// train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"] ) * train_config.train_args[\"warmup_ratio\"] ) train_args = TrainingArguments(**train_config.train_args) trainer =",
"trainer = Trainer( model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), ) trainer.train() trainer.save_model() if __name__ ==",
"import parse_args_and_load_config config = parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\" config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name)",
"def train_model(train_config: RecconEmotionEntailmentArguments): \"\"\" Method for training RecconEmotionEntailmentModel. Args: train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config",
"transformers import Trainer, TrainingArguments from .config import RecconEmotionEntailmentConfig from .data_class import RecconEmotionEntailmentArguments from",
"= math.ceil( ( train_config.len // train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"] ) * train_config.train_args[\"warmup_ratio\"] ) train_args",
"from transformers import Trainer, TrainingArguments from .config import RecconEmotionEntailmentConfig from .data_class import RecconEmotionEntailmentArguments",
"from .data_class import RecconEmotionEntailmentArguments from .modeling import RecconEmotionEntailmentModel from .tokenization import RecconEmotionEntailmentTokenizer from",
"RecconEmotionEntailmentConfig from .data_class import RecconEmotionEntailmentArguments from .modeling import RecconEmotionEntailmentModel from .tokenization import RecconEmotionEntailmentTokenizer",
"import train from sgnlp.models.emotion_entailment.utils import parse_args_and_load_config config = parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\" config =",
"import json from sgnlp.models.emotion_entailment import train from sgnlp.models.emotion_entailment.utils import parse_args_and_load_config config = parse_args_and_load_config('config/emotion_entailment_config.json')",
"for training RecconEmotionEntailmentModel. Args: train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config load from config file. Example::",
"RecconEmotionEntailmentArguments from .modeling import RecconEmotionEntailmentModel from .tokenization import RecconEmotionEntailmentTokenizer from .utils import (",
"parse_args_and_load_config, ) def train_model(train_config: RecconEmotionEntailmentArguments): \"\"\" Method for training RecconEmotionEntailmentModel. Args: train_config (:obj:`RecconEmotionEntailmentArguments`):",
"model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df = pd.read_csv(train_config.x_train_path) val_df = pd.read_csv(train_config.x_valid_path) train_dataset = convert_df_to_dataset(",
"import pandas as pd from transformers import Trainer, TrainingArguments from .config import RecconEmotionEntailmentConfig",
"convert_df_to_dataset, parse_args_and_load_config, ) def train_model(train_config: RecconEmotionEntailmentArguments): \"\"\" Method for training RecconEmotionEntailmentModel. Args: train_config",
"train_config.train_args[\"eval_steps\"] = ( train_config.len / train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"] = math.ceil( ( train_config.len //",
"train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), ) trainer.train() trainer.save_model() if __name__ == \"__main__\": cfg = parse_args_and_load_config() train_model(cfg)",
"math import pandas as pd from transformers import Trainer, TrainingArguments from .config import",
"RecconEmotionEntailmentModel. Args: train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config load from config file. Example:: import json",
"= RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df = pd.read_csv(train_config.x_train_path) val_df = pd.read_csv(train_config.x_valid_path) train_dataset",
"= pd.read_csv(train_config.x_valid_path) train_dataset = convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) val_dataset = convert_df_to_dataset( df=val_df,",
"import RecconEmotionEntailmentTokenizer from .utils import ( RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config, ) def train_model(train_config: RecconEmotionEntailmentArguments):",
"from .tokenization import RecconEmotionEntailmentTokenizer from .utils import ( RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config, ) def",
"= TrainingArguments(**train_config.train_args) trainer = Trainer( model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), ) trainer.train() trainer.save_model() if",
"import math import pandas as pd from transformers import Trainer, TrainingArguments from .config",
"Method for training RecconEmotionEntailmentModel. Args: train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config load from config file.",
"= convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) val_dataset = convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer )",
"max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) val_dataset = convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) train_config.len = len(train_df)",
"load from config file. Example:: import json from sgnlp.models.emotion_entailment import train from sgnlp.models.emotion_entailment.utils",
"file. Example:: import json from sgnlp.models.emotion_entailment import train from sgnlp.models.emotion_entailment.utils import parse_args_and_load_config config",
"Trainer, TrainingArguments from .config import RecconEmotionEntailmentConfig from .data_class import RecconEmotionEntailmentArguments from .modeling import",
"train_config.len / train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"] = math.ceil( ( train_config.len // train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"]",
"df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) train_config.len = len(train_df) train_config.train_args[\"eval_steps\"] = ( train_config.len / train_config.train_args[\"per_device_train_batch_size\"]",
"import RecconEmotionEntailmentArguments from .modeling import RecconEmotionEntailmentModel from .tokenization import RecconEmotionEntailmentTokenizer from .utils import",
"RecconEmotionEntailmentTokenizer from .utils import ( RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config, ) def train_model(train_config: RecconEmotionEntailmentArguments): \"\"\"",
"train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"] ) * train_config.train_args[\"warmup_ratio\"] ) train_args = TrainingArguments(**train_config.train_args) trainer = Trainer(",
"sgnlp.models.emotion_entailment.utils import parse_args_and_load_config config = parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\" config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer =",
"pd from transformers import Trainer, TrainingArguments from .config import RecconEmotionEntailmentConfig from .data_class import",
"import RecconEmotionEntailmentConfig from .data_class import RecconEmotionEntailmentArguments from .modeling import RecconEmotionEntailmentModel from .tokenization import",
".tokenization import RecconEmotionEntailmentTokenizer from .utils import ( RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config, ) def train_model(train_config:",
"\"\"\" Method for training RecconEmotionEntailmentModel. Args: train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config load from config",
"RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config, ) def train_model(train_config: RecconEmotionEntailmentArguments): \"\"\" Method for training RecconEmotionEntailmentModel. Args:",
"from sgnlp.models.emotion_entailment import train from sgnlp.models.emotion_entailment.utils import parse_args_and_load_config config = parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\"",
"import RecconEmotionEntailmentModel from .tokenization import RecconEmotionEntailmentTokenizer from .utils import ( RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config,",
".modeling import RecconEmotionEntailmentModel from .tokenization import RecconEmotionEntailmentTokenizer from .utils import ( RecconEmotionEntailmentData, convert_df_to_dataset,",
"RecconEmotionEntailmentModel from .tokenization import RecconEmotionEntailmentTokenizer from .utils import ( RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config, )",
") train_config.train_args[\"warmup_steps\"] = math.ceil( ( train_config.len // train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"] ) * train_config.train_args[\"warmup_ratio\"]",
"parse_args_and_load_config config = parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\" config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model",
"model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), ) trainer.train() trainer.save_model() if __name__ == \"__main__\": cfg =",
"parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\" config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config)",
"Example:: import json from sgnlp.models.emotion_entailment import train from sgnlp.models.emotion_entailment.utils import parse_args_and_load_config config =",
") * train_config.train_args[\"warmup_ratio\"] ) train_args = TrainingArguments(**train_config.train_args) trainer = Trainer( model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset),",
"pd.read_csv(train_config.x_train_path) val_df = pd.read_csv(train_config.x_valid_path) train_dataset = convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) val_dataset =",
"config file. Example:: import json from sgnlp.models.emotion_entailment import train from sgnlp.models.emotion_entailment.utils import parse_args_and_load_config",
"= pd.read_csv(train_config.x_train_path) val_df = pd.read_csv(train_config.x_valid_path) train_dataset = convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) val_dataset",
"max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) train_config.len = len(train_df) train_config.train_args[\"eval_steps\"] = ( train_config.len / train_config.train_args[\"per_device_train_batch_size\"] )",
"convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) train_config.len = len(train_df) train_config.train_args[\"eval_steps\"] = ( train_config.len /",
".data_class import RecconEmotionEntailmentArguments from .modeling import RecconEmotionEntailmentModel from .tokenization import RecconEmotionEntailmentTokenizer from .utils",
".config import RecconEmotionEntailmentConfig from .data_class import RecconEmotionEntailmentArguments from .modeling import RecconEmotionEntailmentModel from .tokenization",
"convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) val_dataset = convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) train_config.len",
"= parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\" config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name,",
"sgnlp.models.emotion_entailment import train from sgnlp.models.emotion_entailment.utils import parse_args_and_load_config config = parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\" config",
"train_config.len // train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"] ) * train_config.train_args[\"warmup_ratio\"] ) train_args = TrainingArguments(**train_config.train_args) trainer",
"train_df = pd.read_csv(train_config.x_train_path) val_df = pd.read_csv(train_config.x_valid_path) train_dataset = convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer )",
"( train_config.len // train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"] ) * train_config.train_args[\"warmup_ratio\"] ) train_args = TrainingArguments(**train_config.train_args)",
"train from sgnlp.models.emotion_entailment.utils import parse_args_and_load_config config = parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\" config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name)",
"from .utils import ( RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config, ) def train_model(train_config: RecconEmotionEntailmentArguments): \"\"\" Method",
".utils import ( RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config, ) def train_model(train_config: RecconEmotionEntailmentArguments): \"\"\" Method for",
"from .config import RecconEmotionEntailmentConfig from .data_class import RecconEmotionEntailmentArguments from .modeling import RecconEmotionEntailmentModel from",
"config=config) train_df = pd.read_csv(train_config.x_train_path) val_df = pd.read_csv(train_config.x_valid_path) train_dataset = convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer",
"from .modeling import RecconEmotionEntailmentModel from .tokenization import RecconEmotionEntailmentTokenizer from .utils import ( RecconEmotionEntailmentData,",
") val_dataset = convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) train_config.len = len(train_df) train_config.train_args[\"eval_steps\"] =",
"train_config.train_args[\"warmup_steps\"] = math.ceil( ( train_config.len // train_config.train_args[\"gradient_accumulation_steps\"] * train_config.train_args[\"num_train_epochs\"] ) * train_config.train_args[\"warmup_ratio\"] )",
"len(train_df) train_config.train_args[\"eval_steps\"] = ( train_config.len / train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"] = math.ceil( ( train_config.len",
"val_df = pd.read_csv(train_config.x_valid_path) train_dataset = convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) val_dataset = convert_df_to_dataset(",
"train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config load from config file. Example:: import json from sgnlp.models.emotion_entailment",
"pd.read_csv(train_config.x_valid_path) train_dataset = convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) val_dataset = convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length,",
"tokenizer=tokenizer ) train_config.len = len(train_df) train_config.train_args[\"eval_steps\"] = ( train_config.len / train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"]",
"config = parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\" config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model =",
"TrainingArguments from .config import RecconEmotionEntailmentConfig from .data_class import RecconEmotionEntailmentArguments from .modeling import RecconEmotionEntailmentModel",
"Args: train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config load from config file. Example:: import json from",
"train_config.len = len(train_df) train_config.train_args[\"eval_steps\"] = ( train_config.len / train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"] = math.ceil(",
"import Trainer, TrainingArguments from .config import RecconEmotionEntailmentConfig from .data_class import RecconEmotionEntailmentArguments from .modeling",
"from sgnlp.models.emotion_entailment.utils import parse_args_and_load_config config = parse_args_and_load_config('config/emotion_entailment_config.json') train(config) \"\"\" config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer",
"train_config.train_args[\"warmup_ratio\"] ) train_args = TrainingArguments(**train_config.train_args) trainer = Trainer( model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), )",
"= Trainer( model=model, args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), ) trainer.train() trainer.save_model() if __name__ == \"__main__\":",
"val_dataset = convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) train_config.len = len(train_df) train_config.train_args[\"eval_steps\"] = (",
"from config file. Example:: import json from sgnlp.models.emotion_entailment import train from sgnlp.models.emotion_entailment.utils import",
"( train_config.len / train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"] = math.ceil( ( train_config.len // train_config.train_args[\"gradient_accumulation_steps\"] *",
"args=train_args, train_dataset=RecconEmotionEntailmentData(train_dataset), eval_dataset=RecconEmotionEntailmentData(val_dataset), ) trainer.train() trainer.save_model() if __name__ == \"__main__\": cfg = parse_args_and_load_config()",
"RecconEmotionEntailmentArguments config load from config file. Example:: import json from sgnlp.models.emotion_entailment import train",
"import ( RecconEmotionEntailmentData, convert_df_to_dataset, parse_args_and_load_config, ) def train_model(train_config: RecconEmotionEntailmentArguments): \"\"\" Method for training",
"pandas as pd from transformers import Trainer, TrainingArguments from .config import RecconEmotionEntailmentConfig from",
"config = RecconEmotionEntailmentConfig.from_pretrained(train_config.model_name) tokenizer = RecconEmotionEntailmentTokenizer.from_pretrained(train_config.model_name) model = RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df = pd.read_csv(train_config.x_train_path)",
"= RecconEmotionEntailmentModel.from_pretrained(train_config.model_name, config=config) train_df = pd.read_csv(train_config.x_train_path) val_df = pd.read_csv(train_config.x_valid_path) train_dataset = convert_df_to_dataset( df=train_df,",
"train_model(train_config: RecconEmotionEntailmentArguments): \"\"\" Method for training RecconEmotionEntailmentModel. Args: train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config load",
"RecconEmotionEntailmentArguments): \"\"\" Method for training RecconEmotionEntailmentModel. Args: train_config (:obj:`RecconEmotionEntailmentArguments`): RecconEmotionEntailmentArguments config load from",
"train_dataset = convert_df_to_dataset( df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) val_dataset = convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer",
"= len(train_df) train_config.train_args[\"eval_steps\"] = ( train_config.len / train_config.train_args[\"per_device_train_batch_size\"] ) train_config.train_args[\"warmup_steps\"] = math.ceil( (",
"df=train_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) val_dataset = convert_df_to_dataset( df=val_df, max_seq_length=train_config.max_seq_length, tokenizer=tokenizer ) train_config.len ="
] |
[
"dateutil.relativedelta import relativedelta save_loc = '~/Desktop/hu' redownload = True if redownload: f1 =",
"plot_cols = ['M2SL'] mpl.rcParams['font.family'] = 'Helvetica Neue' fig, axes = plt.subplots(1,1, figsize=(12,6), sharex=True)",
"### import pandas as pd import pandas_datareader.data as web import matplotlib as mpl",
"= 'USREC' # recession data from FRED f2 = 'M2SL' # M2 from",
"1 in the data recs = data.query('USREC==1') plot_cols = ['M2SL'] mpl.rcParams['font.family'] = 'Helvetica",
"' \\nRecessions Shaded Gray', fontsize=14, fontweight='demi') # add axis labels ax.set_ylabel('% change\\n(Annualized)', fontsize=12,",
"color='k', linestyle='-', linewidth=1) # add titles ax.set_title('Monthly ' + 'M2 percentage change' +",
"fontweight='demi') ax.set_xlabel('Date', fontsize=12, fontweight='demi') # upgrade axis tick labels yticks = ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks))",
"in the data recs = data.query('USREC==1') plot_cols = ['M2SL'] mpl.rcParams['font.family'] = 'Helvetica Neue'",
"'USREC' # recession data from FRED f2 = 'M2SL' # M2 from FRED",
"Neue' fig, axes = plt.subplots(1,1, figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True, ax=axes, marker='o', ms=3) col =",
"fig, axes = plt.subplots(1,1, figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True, ax=axes, marker='o', ms=3) col = plot_cols",
"recs = data.query('USREC==1') plot_cols = ['M2SL'] mpl.rcParams['font.family'] = 'Helvetica Neue' fig, axes =",
"M2 from FRED start = pd.to_datetime('1959-12-01') end = pd.to_datetime('2020-12-31') M2 = web.DataReader([f2], 'fred',",
"M2 = web.DataReader([f2], 'fred', start, end) data_line = M2.pct_change() data_line = data_line.apply(lambda x:",
"f1 = 'USREC' # recession data from FRED f2 = 'M2SL' # M2",
"lines ax.axhline(0, color='k', linestyle='-', linewidth=1) # add titles ax.set_title('Monthly ' + 'M2 percentage",
"= True if redownload: f1 = 'USREC' # recession data from FRED f2",
"data.index[-1], freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz in dates_rng], rotation=45) # bold up tick",
"\"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta import relativedelta save_loc = '~/Desktop/hu' redownload = True if",
"yticks = ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x in yticks]); dates_rng = pd.date_range(data.index[0], data.index[-1],",
"dtz in dates_rng], rotation=45) # bold up tick axes ax.tick_params(axis='both', which='major', labelsize=11) #",
"pd.read_pickle(save_loc + r'/M2SL.pkl') # recessions are marked as 1 in the data recs",
"tick labels yticks = ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x in yticks]); dates_rng =",
"16 18:49:46 2021 @author: wanderer \"\"\" ### Housekeeping ### import pandas as pd",
"2, \"ytick.major.size\": 2}) flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from",
"ax.set_title('Monthly ' + 'M2 percentage change' + ' \\nRecessions Shaded Gray', fontsize=14, fontweight='demi')",
"fontweight='demi') # upgrade axis tick labels yticks = ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x",
"data_line = data_line.apply(lambda x: 12*x) data_shade = web.DataReader([f1], 'fred', start, end) data =",
"\"\"\" ### Housekeeping ### import pandas as pd import pandas_datareader.data as web import",
"fontsize=12, fontweight='demi') # upgrade axis tick labels yticks = ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for",
"recessions are marked as 1 in the data recs = data.query('USREC==1') plot_cols =",
"sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta import relativedelta save_loc = '~/Desktop/hu' redownload = True if redownload:",
"matplotlib.ticker as mticker import seaborn as sns sns.set_style('white', {\"xtick.major.size\": 2, \"ytick.major.size\": 2}) flatui",
"\"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta import relativedelta save_loc = '~/Desktop/hu' redownload",
"data.to_pickle(save_loc + r'/M2SL.pkl') data = pd.read_pickle(save_loc + r'/M2SL.pkl') # recessions are marked as",
"FRED f2 = 'M2SL' # M2 from FRED start = pd.to_datetime('1959-12-01') end =",
"ax=axes, marker='o', ms=3) col = plot_cols ax = axes for month in recs.index:",
"= data.query('USREC==1') plot_cols = ['M2SL'] mpl.rcParams['font.family'] = 'Helvetica Neue' fig, axes = plt.subplots(1,1,",
"if redownload: f1 = 'USREC' # recession data from FRED f2 = 'M2SL'",
"rotation=45) # bold up tick axes ax.tick_params(axis='both', which='major', labelsize=11) # add cool legend",
"python3 # -*- coding: utf-8 -*- \"\"\" Created on Tue Mar 16 18:49:46",
"percentage change' + ' \\nRecessions Shaded Gray', fontsize=14, fontweight='demi') # add axis labels",
"data.query('USREC==1') plot_cols = ['M2SL'] mpl.rcParams['font.family'] = 'Helvetica Neue' fig, axes = plt.subplots(1,1, figsize=(12,6),",
"color=sns.xkcd_rgb['grey'], alpha=0.5) # lets add horizontal zero lines ax.axhline(0, color='k', linestyle='-', linewidth=1) #",
"matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.ticker as mticker import seaborn",
"add axis labels ax.set_ylabel('% change\\n(Annualized)', fontsize=12, fontweight='demi') ax.set_xlabel('Date', fontsize=12, fontweight='demi') # upgrade axis",
"as mticker import seaborn as sns sns.set_style('white', {\"xtick.major.size\": 2, \"ytick.major.size\": 2}) flatui =",
"= web.DataReader([f2], 'fred', start, end) data_line = M2.pct_change() data_line = data_line.apply(lambda x: 12*x)",
"+ r'/M2SL.pkl') data = pd.read_pickle(save_loc + r'/M2SL.pkl') # recessions are marked as 1",
"import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.ticker as mticker import",
"axis labels ax.set_ylabel('% change\\n(Annualized)', fontsize=12, fontweight='demi') ax.set_xlabel('Date', fontsize=12, fontweight='demi') # upgrade axis tick",
"redownload = True if redownload: f1 = 'USREC' # recession data from FRED",
"mticker import seaborn as sns sns.set_style('white', {\"xtick.major.size\": 2, \"ytick.major.size\": 2}) flatui = [\"#9b59b6\",",
"freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz in dates_rng], rotation=45) # bold up tick axes",
"= ['M2SL'] mpl.rcParams['font.family'] = 'Helvetica Neue' fig, axes = plt.subplots(1,1, figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True,",
"\"\"\" Created on Tue Mar 16 18:49:46 2021 @author: wanderer \"\"\" ### Housekeeping",
"= axes for month in recs.index: ax.axvspan(month, month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5) # lets",
"month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5) # lets add horizontal zero lines ax.axhline(0, color='k', linestyle='-',",
"labels yticks = ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x in yticks]); dates_rng = pd.date_range(data.index[0],",
"= pd.to_datetime('1959-12-01') end = pd.to_datetime('2020-12-31') M2 = web.DataReader([f2], 'fred', start, end) data_line =",
"bold up tick axes ax.tick_params(axis='both', which='major', labelsize=11) # add cool legend ax.legend(loc='upper left',",
"'fred', start, end) data_line = M2.pct_change() data_line = data_line.apply(lambda x: 12*x) data_shade =",
"add titles ax.set_title('Monthly ' + 'M2 percentage change' + ' \\nRecessions Shaded Gray',",
"= [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta import relativedelta save_loc",
"= 'Helvetica Neue' fig, axes = plt.subplots(1,1, figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True, ax=axes, marker='o', ms=3)",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on Tue Mar 16",
"\"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta import relativedelta save_loc = '~/Desktop/hu' redownload =",
"data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc + r'/M2SL.pkl') data = pd.read_pickle(save_loc + r'/M2SL.pkl') # recessions are",
"r'/M2SL.pkl') data = pd.read_pickle(save_loc + r'/M2SL.pkl') # recessions are marked as 1 in",
"are marked as 1 in the data recs = data.query('USREC==1') plot_cols = ['M2SL']",
"# -*- coding: utf-8 -*- \"\"\" Created on Tue Mar 16 18:49:46 2021",
"seaborn as sns sns.set_style('white', {\"xtick.major.size\": 2, \"ytick.major.size\": 2}) flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\",",
"= plot_cols ax = axes for month in recs.index: ax.axvspan(month, month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'],",
"plt import matplotlib.ticker as mticker import seaborn as sns sns.set_style('white', {\"xtick.major.size\": 2, \"ytick.major.size\":",
"Gray', fontsize=14, fontweight='demi') # add axis labels ax.set_ylabel('% change\\n(Annualized)', fontsize=12, fontweight='demi') ax.set_xlabel('Date', fontsize=12,",
"ax.tick_params(axis='both', which='major', labelsize=11) # add cool legend ax.legend(loc='upper left', fontsize=11, labels=['M2'], frameon=True).get_frame().set_edgecolor('blue') plt.savefig('M2SL_recession.png',",
"import matplotlib.ticker as mticker import seaborn as sns sns.set_style('white', {\"xtick.major.size\": 2, \"ytick.major.size\": 2})",
"labels ax.set_ylabel('% change\\n(Annualized)', fontsize=12, fontweight='demi') ax.set_xlabel('Date', fontsize=12, fontweight='demi') # upgrade axis tick labels",
"plot_cols ax = axes for month in recs.index: ax.axvspan(month, month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5)",
"ax.set_ylabel('% change\\n(Annualized)', fontsize=12, fontweight='demi') ax.set_xlabel('Date', fontsize=12, fontweight='demi') # upgrade axis tick labels yticks",
"as pd import pandas_datareader.data as web import matplotlib as mpl import matplotlib.pyplot as",
"' + 'M2 percentage change' + ' \\nRecessions Shaded Gray', fontsize=14, fontweight='demi') #",
"fontweight='demi') # add axis labels ax.set_ylabel('% change\\n(Annualized)', fontsize=12, fontweight='demi') ax.set_xlabel('Date', fontsize=12, fontweight='demi') #",
"utf-8 -*- \"\"\" Created on Tue Mar 16 18:49:46 2021 @author: wanderer \"\"\"",
"wanderer \"\"\" ### Housekeeping ### import pandas as pd import pandas_datareader.data as web",
"# add titles ax.set_title('Monthly ' + 'M2 percentage change' + ' \\nRecessions Shaded",
"# recession data from FRED f2 = 'M2SL' # M2 from FRED start",
"data_line.apply(lambda x: 12*x) data_shade = web.DataReader([f1], 'fred', start, end) data = data_shade.join(data_line, how='outer').dropna()",
"# recessions are marked as 1 in the data recs = data.query('USREC==1') plot_cols",
"as sns sns.set_style('white', {\"xtick.major.size\": 2, \"ytick.major.size\": 2}) flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\",",
"as mpl import matplotlib.pyplot as plt import matplotlib.ticker as mticker import seaborn as",
"web.DataReader([f1], 'fred', start, end) data = data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc + r'/M2SL.pkl') data =",
"axes for month in recs.index: ax.axvspan(month, month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5) # lets add",
"data = data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc + r'/M2SL.pkl') data = pd.read_pickle(save_loc + r'/M2SL.pkl') #",
"from dateutil.relativedelta import relativedelta save_loc = '~/Desktop/hu' redownload = True if redownload: f1",
"ax.set_xlabel('Date', fontsize=12, fontweight='demi') # upgrade axis tick labels yticks = ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100)",
"ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x in yticks]); dates_rng = pd.date_range(data.index[0], data.index[-1], freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for",
"end) data = data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc + r'/M2SL.pkl') data = pd.read_pickle(save_loc + r'/M2SL.pkl')",
"alpha=0.5) # lets add horizontal zero lines ax.axhline(0, color='k', linestyle='-', linewidth=1) # add",
"+ 'M2 percentage change' + ' \\nRecessions Shaded Gray', fontsize=14, fontweight='demi') # add",
"data_shade = web.DataReader([f1], 'fred', start, end) data = data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc + r'/M2SL.pkl')",
"for dtz in dates_rng], rotation=45) # bold up tick axes ax.tick_params(axis='both', which='major', labelsize=11)",
"# lets add horizontal zero lines ax.axhline(0, color='k', linestyle='-', linewidth=1) # add titles",
"= data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc + r'/M2SL.pkl') data = pd.read_pickle(save_loc + r'/M2SL.pkl') # recessions",
"recs.index: ax.axvspan(month, month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5) # lets add horizontal zero lines ax.axhline(0,",
"ms=3) col = plot_cols ax = axes for month in recs.index: ax.axvspan(month, month+",
"x: 12*x) data_shade = web.DataReader([f1], 'fred', start, end) data = data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc",
"\"ytick.major.size\": 2}) flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta",
"end) data_line = M2.pct_change() data_line = data_line.apply(lambda x: 12*x) data_shade = web.DataReader([f1], 'fred',",
"in yticks]); dates_rng = pd.date_range(data.index[0], data.index[-1], freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz in dates_rng],",
"Housekeeping ### import pandas as pd import pandas_datareader.data as web import matplotlib as",
"add horizontal zero lines ax.axhline(0, color='k', linestyle='-', linewidth=1) # add titles ax.set_title('Monthly '",
"matplotlib.pyplot as plt import matplotlib.ticker as mticker import seaborn as sns sns.set_style('white', {\"xtick.major.size\":",
"import pandas_datareader.data as web import matplotlib as mpl import matplotlib.pyplot as plt import",
"axes ax.tick_params(axis='both', which='major', labelsize=11) # add cool legend ax.legend(loc='upper left', fontsize=11, labels=['M2'], frameon=True).get_frame().set_edgecolor('blue')",
"pd.to_datetime('2020-12-31') M2 = web.DataReader([f2], 'fred', start, end) data_line = M2.pct_change() data_line = data_line.apply(lambda",
"= '~/Desktop/hu' redownload = True if redownload: f1 = 'USREC' # recession data",
"+ r'/M2SL.pkl') # recessions are marked as 1 in the data recs =",
"[\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta import relativedelta save_loc =",
"# bold up tick axes ax.tick_params(axis='both', which='major', labelsize=11) # add cool legend ax.legend(loc='upper",
"pandas as pd import pandas_datareader.data as web import matplotlib as mpl import matplotlib.pyplot",
"= ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x in yticks]); dates_rng = pd.date_range(data.index[0], data.index[-1], freq='24M')",
"the data recs = data.query('USREC==1') plot_cols = ['M2SL'] mpl.rcParams['font.family'] = 'Helvetica Neue' fig,",
"### Housekeeping ### import pandas as pd import pandas_datareader.data as web import matplotlib",
"2021 @author: wanderer \"\"\" ### Housekeeping ### import pandas as pd import pandas_datareader.data",
"12*x) data_shade = web.DataReader([f1], 'fred', start, end) data = data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc +",
"pd import pandas_datareader.data as web import matplotlib as mpl import matplotlib.pyplot as plt",
"= M2.pct_change() data_line = data_line.apply(lambda x: 12*x) data_shade = web.DataReader([f1], 'fred', start, end)",
"# M2 from FRED start = pd.to_datetime('1959-12-01') end = pd.to_datetime('2020-12-31') M2 = web.DataReader([f2],",
"axes = plt.subplots(1,1, figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True, ax=axes, marker='o', ms=3) col = plot_cols ax",
"dates_rng = pd.date_range(data.index[0], data.index[-1], freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz in dates_rng], rotation=45) #",
"on Tue Mar 16 18:49:46 2021 @author: wanderer \"\"\" ### Housekeeping ### import",
"= plt.subplots(1,1, figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True, ax=axes, marker='o', ms=3) col = plot_cols ax =",
"linestyle='-', linewidth=1) # add titles ax.set_title('Monthly ' + 'M2 percentage change' + '",
"up tick axes ax.tick_params(axis='both', which='major', labelsize=11) # add cool legend ax.legend(loc='upper left', fontsize=11,",
"as web import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.ticker as",
"marker='o', ms=3) col = plot_cols ax = axes for month in recs.index: ax.axvspan(month,",
"fontsize=12, fontweight='demi') ax.set_xlabel('Date', fontsize=12, fontweight='demi') # upgrade axis tick labels yticks = ax.get_yticks()",
"= 'M2SL' # M2 from FRED start = pd.to_datetime('1959-12-01') end = pd.to_datetime('2020-12-31') M2",
"in recs.index: ax.axvspan(month, month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5) # lets add horizontal zero lines",
"web.DataReader([f2], 'fred', start, end) data_line = M2.pct_change() data_line = data_line.apply(lambda x: 12*x) data_shade",
"Shaded Gray', fontsize=14, fontweight='demi') # add axis labels ax.set_ylabel('% change\\n(Annualized)', fontsize=12, fontweight='demi') ax.set_xlabel('Date',",
"for x in yticks]); dates_rng = pd.date_range(data.index[0], data.index[-1], freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz",
"Tue Mar 16 18:49:46 2021 @author: wanderer \"\"\" ### Housekeeping ### import pandas",
"data_line = M2.pct_change() data_line = data_line.apply(lambda x: 12*x) data_shade = web.DataReader([f1], 'fred', start,",
"sharex=True) data[plot_cols].plot(subplots=True, ax=axes, marker='o', ms=3) col = plot_cols ax = axes for month",
"data recs = data.query('USREC==1') plot_cols = ['M2SL'] mpl.rcParams['font.family'] = 'Helvetica Neue' fig, axes",
"pandas_datareader.data as web import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.ticker",
"yticks]); dates_rng = pd.date_range(data.index[0], data.index[-1], freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz in dates_rng], rotation=45)",
"as plt import matplotlib.ticker as mticker import seaborn as sns sns.set_style('white', {\"xtick.major.size\": 2,",
"relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5) # lets add horizontal zero lines ax.axhline(0, color='k', linestyle='-', linewidth=1)",
"True if redownload: f1 = 'USREC' # recession data from FRED f2 =",
"sns sns.set_style('white', {\"xtick.major.size\": 2, \"ytick.major.size\": 2}) flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\",",
"save_loc = '~/Desktop/hu' redownload = True if redownload: f1 = 'USREC' # recession",
"mpl import matplotlib.pyplot as plt import matplotlib.ticker as mticker import seaborn as sns",
"f2 = 'M2SL' # M2 from FRED start = pd.to_datetime('1959-12-01') end = pd.to_datetime('2020-12-31')",
"change' + ' \\nRecessions Shaded Gray', fontsize=14, fontweight='demi') # add axis labels ax.set_ylabel('%",
"pd.date_range(data.index[0], data.index[-1], freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz in dates_rng], rotation=45) # bold up",
"import seaborn as sns sns.set_style('white', {\"xtick.major.size\": 2, \"ytick.major.size\": 2}) flatui = [\"#9b59b6\", \"#3498db\",",
"as 1 in the data recs = data.query('USREC==1') plot_cols = ['M2SL'] mpl.rcParams['font.family'] =",
"# upgrade axis tick labels yticks = ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x in",
"= pd.to_datetime('2020-12-31') M2 = web.DataReader([f2], 'fred', start, end) data_line = M2.pct_change() data_line =",
"month in recs.index: ax.axvspan(month, month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5) # lets add horizontal zero",
"import pandas as pd import pandas_datareader.data as web import matplotlib as mpl import",
"'~/Desktop/hu' redownload = True if redownload: f1 = 'USREC' # recession data from",
"from FRED start = pd.to_datetime('1959-12-01') end = pd.to_datetime('2020-12-31') M2 = web.DataReader([f2], 'fred', start,",
"{\"xtick.major.size\": 2, \"ytick.major.size\": 2}) flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7))",
"which='major', labelsize=11) # add cool legend ax.legend(loc='upper left', fontsize=11, labels=['M2'], frameon=True).get_frame().set_edgecolor('blue') plt.savefig('M2SL_recession.png', dpi=300)",
"import matplotlib.pyplot as plt import matplotlib.ticker as mticker import seaborn as sns sns.set_style('white',",
"start, end) data = data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc + r'/M2SL.pkl') data = pd.read_pickle(save_loc +",
"ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x in yticks]); dates_rng = pd.date_range(data.index[0], data.index[-1], freq='24M') plt.xticks(dates_rng,",
"Mar 16 18:49:46 2021 @author: wanderer \"\"\" ### Housekeeping ### import pandas as",
"coding: utf-8 -*- \"\"\" Created on Tue Mar 16 18:49:46 2021 @author: wanderer",
"Created on Tue Mar 16 18:49:46 2021 @author: wanderer \"\"\" ### Housekeeping ###",
"@author: wanderer \"\"\" ### Housekeeping ### import pandas as pd import pandas_datareader.data as",
"\"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta import relativedelta save_loc = '~/Desktop/hu'",
"upgrade axis tick labels yticks = ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x in yticks]);",
"axis tick labels yticks = ax.get_yticks() ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x in yticks]); dates_rng",
"linewidth=1) # add titles ax.set_title('Monthly ' + 'M2 percentage change' + ' \\nRecessions",
"data = pd.read_pickle(save_loc + r'/M2SL.pkl') # recessions are marked as 1 in the",
"plt.subplots(1,1, figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True, ax=axes, marker='o', ms=3) col = plot_cols ax = axes",
"= pd.read_pickle(save_loc + r'/M2SL.pkl') # recessions are marked as 1 in the data",
"'fred', start, end) data = data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc + r'/M2SL.pkl') data = pd.read_pickle(save_loc",
"in dates_rng], rotation=45) # bold up tick axes ax.tick_params(axis='both', which='major', labelsize=11) # add",
"'Helvetica Neue' fig, axes = plt.subplots(1,1, figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True, ax=axes, marker='o', ms=3) col",
"figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True, ax=axes, marker='o', ms=3) col = plot_cols ax = axes for",
"dates_rng], rotation=45) # bold up tick axes ax.tick_params(axis='both', which='major', labelsize=11) # add cool",
"change\\n(Annualized)', fontsize=12, fontweight='demi') ax.set_xlabel('Date', fontsize=12, fontweight='demi') # upgrade axis tick labels yticks =",
"-*- coding: utf-8 -*- \"\"\" Created on Tue Mar 16 18:49:46 2021 @author:",
"['M2SL'] mpl.rcParams['font.family'] = 'Helvetica Neue' fig, axes = plt.subplots(1,1, figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True, ax=axes,",
"\"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta import relativedelta save_loc = '~/Desktop/hu' redownload = True",
"start, end) data_line = M2.pct_change() data_line = data_line.apply(lambda x: 12*x) data_shade = web.DataReader([f1],",
"pd.to_datetime('1959-12-01') end = pd.to_datetime('2020-12-31') M2 = web.DataReader([f2], 'fred', start, end) data_line = M2.pct_change()",
"[dtz.strftime('%Y-%m') for dtz in dates_rng], rotation=45) # bold up tick axes ax.tick_params(axis='both', which='major',",
"2}) flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta import",
"end = pd.to_datetime('2020-12-31') M2 = web.DataReader([f2], 'fred', start, end) data_line = M2.pct_change() data_line",
"start = pd.to_datetime('1959-12-01') end = pd.to_datetime('2020-12-31') M2 = web.DataReader([f2], 'fred', start, end) data_line",
"data from FRED f2 = 'M2SL' # M2 from FRED start = pd.to_datetime('1959-12-01')",
"how='outer').dropna() data.to_pickle(save_loc + r'/M2SL.pkl') data = pd.read_pickle(save_loc + r'/M2SL.pkl') # recessions are marked",
"r'/M2SL.pkl') # recessions are marked as 1 in the data recs = data.query('USREC==1')",
"lets add horizontal zero lines ax.axhline(0, color='k', linestyle='-', linewidth=1) # add titles ax.set_title('Monthly",
"ax.yaxis.set_major_locator(mticker.FixedLocator(yticks)) ax.set_yticklabels(['{:3.1f}%'.format(x*100) for x in yticks]); dates_rng = pd.date_range(data.index[0], data.index[-1], freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m')",
"flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"] sns.set_palette(sns.color_palette(flatui,7)) from dateutil.relativedelta import relativedelta",
"marked as 1 in the data recs = data.query('USREC==1') plot_cols = ['M2SL'] mpl.rcParams['font.family']",
"sns.set_style('white', {\"xtick.major.size\": 2, \"ytick.major.size\": 2}) flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\",\"#f4cae4\"]",
"import relativedelta save_loc = '~/Desktop/hu' redownload = True if redownload: f1 = 'USREC'",
"\\nRecessions Shaded Gray', fontsize=14, fontweight='demi') # add axis labels ax.set_ylabel('% change\\n(Annualized)', fontsize=12, fontweight='demi')",
"fontsize=14, fontweight='demi') # add axis labels ax.set_ylabel('% change\\n(Annualized)', fontsize=12, fontweight='demi') ax.set_xlabel('Date', fontsize=12, fontweight='demi')",
"web import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.ticker as mticker",
"for month in recs.index: ax.axvspan(month, month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5) # lets add horizontal",
"M2.pct_change() data_line = data_line.apply(lambda x: 12*x) data_shade = web.DataReader([f1], 'fred', start, end) data",
"FRED start = pd.to_datetime('1959-12-01') end = pd.to_datetime('2020-12-31') M2 = web.DataReader([f2], 'fred', start, end)",
"= pd.date_range(data.index[0], data.index[-1], freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz in dates_rng], rotation=45) # bold",
"'M2SL' # M2 from FRED start = pd.to_datetime('1959-12-01') end = pd.to_datetime('2020-12-31') M2 =",
"plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz in dates_rng], rotation=45) # bold up tick axes ax.tick_params(axis='both',",
"recession data from FRED f2 = 'M2SL' # M2 from FRED start =",
"= web.DataReader([f1], 'fred', start, end) data = data_shade.join(data_line, how='outer').dropna() data.to_pickle(save_loc + r'/M2SL.pkl') data",
"-*- \"\"\" Created on Tue Mar 16 18:49:46 2021 @author: wanderer \"\"\" ###",
"tick axes ax.tick_params(axis='both', which='major', labelsize=11) # add cool legend ax.legend(loc='upper left', fontsize=11, labels=['M2'],",
"+ ' \\nRecessions Shaded Gray', fontsize=14, fontweight='demi') # add axis labels ax.set_ylabel('% change\\n(Annualized)',",
"x in yticks]); dates_rng = pd.date_range(data.index[0], data.index[-1], freq='24M') plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz in",
"# add axis labels ax.set_ylabel('% change\\n(Annualized)', fontsize=12, fontweight='demi') ax.set_xlabel('Date', fontsize=12, fontweight='demi') # upgrade",
"from FRED f2 = 'M2SL' # M2 from FRED start = pd.to_datetime('1959-12-01') end",
"horizontal zero lines ax.axhline(0, color='k', linestyle='-', linewidth=1) # add titles ax.set_title('Monthly ' +",
"ax = axes for month in recs.index: ax.axvspan(month, month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5) #",
"ax.axvspan(month, month+ relativedelta(months=+1), color=sns.xkcd_rgb['grey'], alpha=0.5) # lets add horizontal zero lines ax.axhline(0, color='k',",
"redownload: f1 = 'USREC' # recession data from FRED f2 = 'M2SL' #",
"data[plot_cols].plot(subplots=True, ax=axes, marker='o', ms=3) col = plot_cols ax = axes for month in",
"relativedelta save_loc = '~/Desktop/hu' redownload = True if redownload: f1 = 'USREC' #",
"ax.axhline(0, color='k', linestyle='-', linewidth=1) # add titles ax.set_title('Monthly ' + 'M2 percentage change'",
"= data_line.apply(lambda x: 12*x) data_shade = web.DataReader([f1], 'fred', start, end) data = data_shade.join(data_line,",
"col = plot_cols ax = axes for month in recs.index: ax.axvspan(month, month+ relativedelta(months=+1),",
"mpl.rcParams['font.family'] = 'Helvetica Neue' fig, axes = plt.subplots(1,1, figsize=(12,6), sharex=True) data[plot_cols].plot(subplots=True, ax=axes, marker='o',",
"titles ax.set_title('Monthly ' + 'M2 percentage change' + ' \\nRecessions Shaded Gray', fontsize=14,",
"'M2 percentage change' + ' \\nRecessions Shaded Gray', fontsize=14, fontweight='demi') # add axis",
"zero lines ax.axhline(0, color='k', linestyle='-', linewidth=1) # add titles ax.set_title('Monthly ' + 'M2",
"18:49:46 2021 @author: wanderer \"\"\" ### Housekeeping ### import pandas as pd import"
] |
[
"print('\\nSending message \"%s\" to channel %s' % (text,channel)) except: print('Failed to get channel/text",
"KafkaError import json import time import os,sys token = os.environ.get('SLACK_API_TOKEN') if token is",
"email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s` just left a bad review :disappointed:\\n> %s\\n\\n_Please contact them",
"them immediately and see if we can fix the issue *right here, right",
"message \"%s\" to channel %s' % (text,channel)) except: print('Failed to get channel/text from",
"% sc_response['error']) except Exception as e: print(type(e)) print(dir(e)) elif msg.error().code() == KafkaError._PARTITION_EOF: print('End",
"True: msg = c.poll(0.1) time.sleep(5) if msg is None: continue elif not msg.error():",
"except Exception as e: print(type(e)) print(dir(e)) elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition",
"*right here, right now*_' % (email, message)) print('\\nSending message \"%s\" to channel %s'",
"'smallest' if you want to consume all messages # from the beginning of",
"environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc = SlackClient(token) # Set 'auto.offset.reset': 'smallest' if you want",
"from the beginning of the topic settings = { 'bootstrap.servers': 'localhost:9092', 'group.id': 'python_kafka_notify.py',",
"SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc = SlackClient(token) # Set 'auto.offset.reset': 'smallest' if you",
"rmoff / 13 Jun 2018 from slackclient import SlackClient from confluent_kafka import Consumer,",
"{0}'.format(msg.value())) if msg.value() is None: continue try: app_msg = json.loads(msg.value().decode()) except: app_msg =",
"to get channel/text from message') channel='general' text=msg.value() try: sc_response = sc.api_call('chat.postMessage', channel=channel, text=text,",
"try: email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s` just left a bad review :disappointed:\\n> %s\\n\\n_Please contact",
"to consume all messages # from the beginning of the topic settings =",
"immediately and see if we can fix the issue *right here, right now*_'",
"# from the beginning of the topic settings = { 'bootstrap.servers': 'localhost:9092', 'group.id':",
"import Consumer, KafkaError import json import time import os,sys token = os.environ.get('SLACK_API_TOKEN') if",
"topic settings = { 'bootstrap.servers': 'localhost:9092', 'group.id': 'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset': 'largest'} } c",
"{ 'bootstrap.servers': 'localhost:9092', 'group.id': 'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset': 'largest'} } c = Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS'])",
"Slack API token in the SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc = SlackClient(token) #",
"'group.id': 'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset': 'largest'} } c = Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while True:",
"review :disappointed:\\n> %s\\n\\n_Please contact them immediately and see if we can fix the",
"sc_response = sc.api_call('chat.postMessage', channel=channel, text=text, username='KSQL Notifications', icon_emoji=':rocket:') if not sc_response['ok']: print('\\t** FAILED:",
"= SlackClient(token) # Set 'auto.offset.reset': 'smallest' if you want to consume all messages",
"None: continue try: app_msg = json.loads(msg.value().decode()) except: app_msg = json.loads(msg.value()) try: email=app_msg['EMAIL'] message=app_msg['MESSAGE']",
"except: app_msg = json.loads(msg.value()) try: email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s` just left a bad",
"c = Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while True: msg = c.poll(0.1) time.sleep(5) if msg",
"'auto.offset.reset': 'smallest' if you want to consume all messages # from the beginning",
"sc_response['error']) except Exception as e: print(type(e)) print(dir(e)) elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of",
"msg = c.poll(0.1) time.sleep(5) if msg is None: continue elif not msg.error(): print('Received",
"continue elif not msg.error(): print('Received message: {0}'.format(msg.value())) if msg.value() is None: continue try:",
"if msg.value() is None: continue try: app_msg = json.loads(msg.value().decode()) except: app_msg = json.loads(msg.value())",
"msg is None: continue elif not msg.error(): print('Received message: {0}'.format(msg.value())) if msg.value() is",
"set your Slack API token in the SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc =",
"if token is None: print('\\n\\n*******\\nYou need to set your Slack API token in",
"sys.exit(1) sc = SlackClient(token) # Set 'auto.offset.reset': 'smallest' if you want to consume",
"if we can fix the issue *right here, right now*_' % (email, message))",
":disappointed:\\n> %s\\n\\n_Please contact them immediately and see if we can fix the issue",
"SlackClient from confluent_kafka import Consumer, KafkaError import json import time import os,sys token",
"elif not msg.error(): print('Received message: {0}'.format(msg.value())) if msg.value() is None: continue try: app_msg",
"username='KSQL Notifications', icon_emoji=':rocket:') if not sc_response['ok']: print('\\t** FAILED: %s' % sc_response['error']) except Exception",
".format(msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str())) except Exception as e: print(type(e)) print(dir(e)) finally:",
"import os,sys token = os.environ.get('SLACK_API_TOKEN') if token is None: print('\\n\\n*******\\nYou need to set",
"print(type(e)) print(dir(e)) elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}' .format(msg.topic(), msg.partition()))",
"message)) print('\\nSending message \"%s\" to channel %s' % (text,channel)) except: print('Failed to get",
"/ 13 Jun 2018 from slackclient import SlackClient from confluent_kafka import Consumer, KafkaError",
"messages # from the beginning of the topic settings = { 'bootstrap.servers': 'localhost:9092',",
"(email, message)) print('\\nSending message \"%s\" to channel %s' % (text,channel)) except: print('Failed to",
"\"%s\" to channel %s' % (text,channel)) except: print('Failed to get channel/text from message')",
"channel %s' % (text,channel)) except: print('Failed to get channel/text from message') channel='general' text=msg.value()",
"app_msg = json.loads(msg.value()) try: email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s` just left a bad review",
"channel='general' text=msg.value() try: sc_response = sc.api_call('chat.postMessage', channel=channel, text=text, username='KSQL Notifications', icon_emoji=':rocket:') if not",
"msg.partition())) else: print('Error occured: {0}'.format(msg.error().str())) except Exception as e: print(type(e)) print(dir(e)) finally: c.close()",
"need to set your Slack API token in the SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1)",
"message: {0}'.format(msg.value())) if msg.value() is None: continue try: app_msg = json.loads(msg.value().decode()) except: app_msg",
"None: print('\\n\\n*******\\nYou need to set your Slack API token in the SLACK_API_TOKEN environment",
"can fix the issue *right here, right now*_' % (email, message)) print('\\nSending message",
"fix the issue *right here, right now*_' % (email, message)) print('\\nSending message \"%s\"",
"time.sleep(5) if msg is None: continue elif not msg.error(): print('Received message: {0}'.format(msg.value())) if",
"%s' % (text,channel)) except: print('Failed to get channel/text from message') channel='general' text=msg.value() try:",
"try: app_msg = json.loads(msg.value().decode()) except: app_msg = json.loads(msg.value()) try: email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s`",
"from confluent_kafka import Consumer, KafkaError import json import time import os,sys token =",
"= c.poll(0.1) time.sleep(5) if msg is None: continue elif not msg.error(): print('Received message:",
"we can fix the issue *right here, right now*_' % (email, message)) print('\\nSending",
"confluent_kafka import Consumer, KafkaError import json import time import os,sys token = os.environ.get('SLACK_API_TOKEN')",
"you want to consume all messages # from the beginning of the topic",
"%s\\n\\n_Please contact them immediately and see if we can fix the issue *right",
"the SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc = SlackClient(token) # Set 'auto.offset.reset': 'smallest' if",
"see if we can fix the issue *right here, right now*_' % (email,",
"if not sc_response['ok']: print('\\t** FAILED: %s' % sc_response['error']) except Exception as e: print(type(e))",
"now*_' % (email, message)) print('\\nSending message \"%s\" to channel %s' % (text,channel)) except:",
"%s' % sc_response['error']) except Exception as e: print(type(e)) print(dir(e)) elif msg.error().code() == KafkaError._PARTITION_EOF:",
"= json.loads(msg.value()) try: email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s` just left a bad review :disappointed:\\n>",
"# Set 'auto.offset.reset': 'smallest' if you want to consume all messages # from",
"get channel/text from message') channel='general' text=msg.value() try: sc_response = sc.api_call('chat.postMessage', channel=channel, text=text, username='KSQL",
"of the topic settings = { 'bootstrap.servers': 'localhost:9092', 'group.id': 'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset': 'largest'}",
"try: sc_response = sc.api_call('chat.postMessage', channel=channel, text=text, username='KSQL Notifications', icon_emoji=':rocket:') if not sc_response['ok']: print('\\t**",
"sc_response['ok']: print('\\t** FAILED: %s' % sc_response['error']) except Exception as e: print(type(e)) print(dir(e)) elif",
"from slackclient import SlackClient from confluent_kafka import Consumer, KafkaError import json import time",
"continue try: app_msg = json.loads(msg.value().decode()) except: app_msg = json.loads(msg.value()) try: email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers'",
"channel='unhappy-customers' text=('`%s` just left a bad review :disappointed:\\n> %s\\n\\n_Please contact them immediately and",
"and see if we can fix the issue *right here, right now*_' %",
"token in the SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc = SlackClient(token) # Set 'auto.offset.reset':",
"= json.loads(msg.value().decode()) except: app_msg = json.loads(msg.value()) try: email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s` just left",
"'default.topic.config': {'auto.offset.reset': 'largest'} } c = Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while True: msg =",
"Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while True: msg = c.poll(0.1) time.sleep(5) if msg is None:",
"msg.error(): print('Received message: {0}'.format(msg.value())) if msg.value() is None: continue try: app_msg = json.loads(msg.value().decode())",
"just left a bad review :disappointed:\\n> %s\\n\\n_Please contact them immediately and see if",
"'largest'} } c = Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while True: msg = c.poll(0.1) time.sleep(5)",
"the beginning of the topic settings = { 'bootstrap.servers': 'localhost:9092', 'group.id': 'python_kafka_notify.py', 'default.topic.config':",
"token = os.environ.get('SLACK_API_TOKEN') if token is None: print('\\n\\n*******\\nYou need to set your Slack",
"'bootstrap.servers': 'localhost:9092', 'group.id': 'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset': 'largest'} } c = Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try:",
"% (text,channel)) except: print('Failed to get channel/text from message') channel='general' text=msg.value() try: sc_response",
"from message') channel='general' text=msg.value() try: sc_response = sc.api_call('chat.postMessage', channel=channel, text=text, username='KSQL Notifications', icon_emoji=':rocket:')",
"as e: print(type(e)) print(dir(e)) elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}'",
"os.environ.get('SLACK_API_TOKEN') if token is None: print('\\n\\n*******\\nYou need to set your Slack API token",
"partition reached {0}/{1}' .format(msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str())) except Exception as e:",
"msg.value() is None: continue try: app_msg = json.loads(msg.value().decode()) except: app_msg = json.loads(msg.value()) try:",
"c.poll(0.1) time.sleep(5) if msg is None: continue elif not msg.error(): print('Received message: {0}'.format(msg.value()))",
"Notifications', icon_emoji=':rocket:') if not sc_response['ok']: print('\\t** FAILED: %s' % sc_response['error']) except Exception as",
"None: continue elif not msg.error(): print('Received message: {0}'.format(msg.value())) if msg.value() is None: continue",
"json.loads(msg.value().decode()) except: app_msg = json.loads(msg.value()) try: email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s` just left a",
"{0}/{1}' .format(msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str())) except Exception as e: print(type(e)) print(dir(e))",
"icon_emoji=':rocket:') if not sc_response['ok']: print('\\t** FAILED: %s' % sc_response['error']) except Exception as e:",
"msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}' .format(msg.topic(), msg.partition())) else: print('Error occured:",
"= Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while True: msg = c.poll(0.1) time.sleep(5) if msg is",
"{'auto.offset.reset': 'largest'} } c = Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while True: msg = c.poll(0.1)",
"left a bad review :disappointed:\\n> %s\\n\\n_Please contact them immediately and see if we",
"2018 from slackclient import SlackClient from confluent_kafka import Consumer, KafkaError import json import",
"not msg.error(): print('Received message: {0}'.format(msg.value())) if msg.value() is None: continue try: app_msg =",
"reached {0}/{1}' .format(msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str())) except Exception as e: print(type(e))",
"settings = { 'bootstrap.servers': 'localhost:9092', 'group.id': 'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset': 'largest'} } c =",
"} c = Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while True: msg = c.poll(0.1) time.sleep(5) if",
"try: while True: msg = c.poll(0.1) time.sleep(5) if msg is None: continue elif",
"message') channel='general' text=msg.value() try: sc_response = sc.api_call('chat.postMessage', channel=channel, text=text, username='KSQL Notifications', icon_emoji=':rocket:') if",
"json import time import os,sys token = os.environ.get('SLACK_API_TOKEN') if token is None: print('\\n\\n*******\\nYou",
"is None: print('\\n\\n*******\\nYou need to set your Slack API token in the SLACK_API_TOKEN",
"message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s` just left a bad review :disappointed:\\n> %s\\n\\n_Please contact them immediately",
"13 Jun 2018 from slackclient import SlackClient from confluent_kafka import Consumer, KafkaError import",
"Consumer, KafkaError import json import time import os,sys token = os.environ.get('SLACK_API_TOKEN') if token",
"% (email, message)) print('\\nSending message \"%s\" to channel %s' % (text,channel)) except: print('Failed",
"print('Failed to get channel/text from message') channel='general' text=msg.value() try: sc_response = sc.api_call('chat.postMessage', channel=channel,",
"= sc.api_call('chat.postMessage', channel=channel, text=text, username='KSQL Notifications', icon_emoji=':rocket:') if not sc_response['ok']: print('\\t** FAILED: %s'",
"text=('`%s` just left a bad review :disappointed:\\n> %s\\n\\n_Please contact them immediately and see",
"variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc = SlackClient(token) # Set 'auto.offset.reset': 'smallest' if you want to",
"<reponame>alonsoir/examples-2<gh_stars>1000+ # rmoff / 13 Jun 2018 from slackclient import SlackClient from confluent_kafka",
"consume all messages # from the beginning of the topic settings = {",
"import time import os,sys token = os.environ.get('SLACK_API_TOKEN') if token is None: print('\\n\\n*******\\nYou need",
"os,sys token = os.environ.get('SLACK_API_TOKEN') if token is None: print('\\n\\n*******\\nYou need to set your",
"not sc_response['ok']: print('\\t** FAILED: %s' % sc_response['error']) except Exception as e: print(type(e)) print(dir(e))",
"while True: msg = c.poll(0.1) time.sleep(5) if msg is None: continue elif not",
"print('\\t** FAILED: %s' % sc_response['error']) except Exception as e: print(type(e)) print(dir(e)) elif msg.error().code()",
"of partition reached {0}/{1}' .format(msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str())) except Exception as",
"sc = SlackClient(token) # Set 'auto.offset.reset': 'smallest' if you want to consume all",
"bad review :disappointed:\\n> %s\\n\\n_Please contact them immediately and see if we can fix",
"c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while True: msg = c.poll(0.1) time.sleep(5) if msg is None: continue",
"channel=channel, text=text, username='KSQL Notifications', icon_emoji=':rocket:') if not sc_response['ok']: print('\\t** FAILED: %s' % sc_response['error'])",
"print(dir(e)) elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}' .format(msg.topic(), msg.partition())) else:",
"print('End of partition reached {0}/{1}' .format(msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str())) except Exception",
"beginning of the topic settings = { 'bootstrap.servers': 'localhost:9092', 'group.id': 'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset':",
"import json import time import os,sys token = os.environ.get('SLACK_API_TOKEN') if token is None:",
"time import os,sys token = os.environ.get('SLACK_API_TOKEN') if token is None: print('\\n\\n*******\\nYou need to",
"= os.environ.get('SLACK_API_TOKEN') if token is None: print('\\n\\n*******\\nYou need to set your Slack API",
"if you want to consume all messages # from the beginning of the",
"app_msg = json.loads(msg.value().decode()) except: app_msg = json.loads(msg.value()) try: email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s` just",
"KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}' .format(msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str())) except",
"the topic settings = { 'bootstrap.servers': 'localhost:9092', 'group.id': 'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset': 'largest'} }",
"== KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}' .format(msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str()))",
"(text,channel)) except: print('Failed to get channel/text from message') channel='general' text=msg.value() try: sc_response =",
"to set your Slack API token in the SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc",
"# rmoff / 13 Jun 2018 from slackclient import SlackClient from confluent_kafka import",
"Jun 2018 from slackclient import SlackClient from confluent_kafka import Consumer, KafkaError import json",
"a bad review :disappointed:\\n> %s\\n\\n_Please contact them immediately and see if we can",
"text=msg.value() try: sc_response = sc.api_call('chat.postMessage', channel=channel, text=text, username='KSQL Notifications', icon_emoji=':rocket:') if not sc_response['ok']:",
"the issue *right here, right now*_' % (email, message)) print('\\nSending message \"%s\" to",
"channel/text from message') channel='general' text=msg.value() try: sc_response = sc.api_call('chat.postMessage', channel=channel, text=text, username='KSQL Notifications',",
"'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset': 'largest'} } c = Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while True: msg",
"text=text, username='KSQL Notifications', icon_emoji=':rocket:') if not sc_response['ok']: print('\\t** FAILED: %s' % sc_response['error']) except",
"API token in the SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc = SlackClient(token) # Set",
"e: print(type(e)) print(dir(e)) elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}' .format(msg.topic(),",
"FAILED: %s' % sc_response['error']) except Exception as e: print(type(e)) print(dir(e)) elif msg.error().code() ==",
"if msg is None: continue elif not msg.error(): print('Received message: {0}'.format(msg.value())) if msg.value()",
"to channel %s' % (text,channel)) except: print('Failed to get channel/text from message') channel='general'",
"in the SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc = SlackClient(token) # Set 'auto.offset.reset': 'smallest'",
"here, right now*_' % (email, message)) print('\\nSending message \"%s\" to channel %s' %",
"is None: continue elif not msg.error(): print('Received message: {0}'.format(msg.value())) if msg.value() is None:",
"elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}' .format(msg.topic(), msg.partition())) else: print('Error",
"your Slack API token in the SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n') sys.exit(1) sc = SlackClient(token)",
"all messages # from the beginning of the topic settings = { 'bootstrap.servers':",
"want to consume all messages # from the beginning of the topic settings",
"json.loads(msg.value()) try: email=app_msg['EMAIL'] message=app_msg['MESSAGE'] channel='unhappy-customers' text=('`%s` just left a bad review :disappointed:\\n> %s\\n\\n_Please",
"Exception as e: print(type(e)) print(dir(e)) elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached",
"print('Received message: {0}'.format(msg.value())) if msg.value() is None: continue try: app_msg = json.loads(msg.value().decode()) except:",
"issue *right here, right now*_' % (email, message)) print('\\nSending message \"%s\" to channel",
"sc.api_call('chat.postMessage', channel=channel, text=text, username='KSQL Notifications', icon_emoji=':rocket:') if not sc_response['ok']: print('\\t** FAILED: %s' %",
"right now*_' % (email, message)) print('\\nSending message \"%s\" to channel %s' % (text,channel))",
"contact them immediately and see if we can fix the issue *right here,",
"print('\\n\\n*******\\nYou need to set your Slack API token in the SLACK_API_TOKEN environment variable\\n\\nExiting.\\n\\n*******\\n')",
"'localhost:9092', 'group.id': 'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset': 'largest'} } c = Consumer(settings) c.subscribe(['UNHAPPY_PLATINUM_CUSTOMERS']) try: while",
"token is None: print('\\n\\n*******\\nYou need to set your Slack API token in the",
"except: print('Failed to get channel/text from message') channel='general' text=msg.value() try: sc_response = sc.api_call('chat.postMessage',",
"Set 'auto.offset.reset': 'smallest' if you want to consume all messages # from the",
"SlackClient(token) # Set 'auto.offset.reset': 'smallest' if you want to consume all messages #",
"is None: continue try: app_msg = json.loads(msg.value().decode()) except: app_msg = json.loads(msg.value()) try: email=app_msg['EMAIL']",
"import SlackClient from confluent_kafka import Consumer, KafkaError import json import time import os,sys",
"= { 'bootstrap.servers': 'localhost:9092', 'group.id': 'python_kafka_notify.py', 'default.topic.config': {'auto.offset.reset': 'largest'} } c = Consumer(settings)",
"slackclient import SlackClient from confluent_kafka import Consumer, KafkaError import json import time import"
] |
[
"d in fe[a:]: temp += int(FE[d]) print(d) final.append(temp) temp = 0 for d",
"{'o': 100, 'e': 10, 'g': 1, 'a': 0, 'b': -1, 'i': -10, 'u':",
"for d in fe[a:]: temp += int(FE[d]) print(d) final.append(temp) temp = 0 for",
"-10, 'u': -100} final=[] count=len(fe) for a in range(0,count): temp = 0 for",
"in range(0,count): temp = 0 for d in fe[a:]: temp += int(FE[d]) print(d)",
"fe[a:]: temp += int(FE[d]) print(d) final.append(temp) temp = 0 for d in fe[:a]:",
"final.append(temp) temp = 0 for d in fe[:a]: temp += int(FE[d]) print(d) final.append(temp)",
"10, 'g': 1, 'a': 0, 'b': -1, 'i': -10, 'u': -100} final=[] count=len(fe)",
"temp += int(FE[d]) print(d) final.append(temp) temp = 0 for d in fe[:a]: temp",
"'g': 1, 'a': 0, 'b': -1, 'i': -10, 'u': -100} final=[] count=len(fe) for",
"'a': 0, 'b': -1, 'i': -10, 'u': -100} final=[] count=len(fe) for a in",
"print(d) final.append(temp) temp = 0 for d in fe[:a]: temp += int(FE[d]) print(d)",
"'b': -1, 'i': -10, 'u': -100} final=[] count=len(fe) for a in range(0,count): temp",
"'u': -100} final=[] count=len(fe) for a in range(0,count): temp = 0 for d",
"in fe[a:]: temp += int(FE[d]) print(d) final.append(temp) temp = 0 for d in",
"for d in fe[:a]: temp += int(FE[d]) print(d) final.append(temp) print(a) return max(final) maxScore('aabg')",
"+= int(FE[d]) print(d) final.append(temp) temp = 0 for d in fe[:a]: temp +=",
"for a in range(0,count): temp = 0 for d in fe[a:]: temp +=",
"0 for d in fe[:a]: temp += int(FE[d]) print(d) final.append(temp) print(a) return max(final)",
"count=len(fe) for a in range(0,count): temp = 0 for d in fe[a:]: temp",
"FE = {'o': 100, 'e': 10, 'g': 1, 'a': 0, 'b': -1, 'i':",
"-1, 'i': -10, 'u': -100} final=[] count=len(fe) for a in range(0,count): temp =",
"final=[] count=len(fe) for a in range(0,count): temp = 0 for d in fe[a:]:",
"'i': -10, 'u': -100} final=[] count=len(fe) for a in range(0,count): temp = 0",
"= 0 for d in fe[a:]: temp += int(FE[d]) print(d) final.append(temp) temp =",
"temp = 0 for d in fe[:a]: temp += int(FE[d]) print(d) final.append(temp) print(a)",
"= 0 for d in fe[:a]: temp += int(FE[d]) print(d) final.append(temp) print(a) return",
"maxScore(fe): FE = {'o': 100, 'e': 10, 'g': 1, 'a': 0, 'b': -1,",
"temp = 0 for d in fe[a:]: temp += int(FE[d]) print(d) final.append(temp) temp",
"def maxScore(fe): FE = {'o': 100, 'e': 10, 'g': 1, 'a': 0, 'b':",
"1, 'a': 0, 'b': -1, 'i': -10, 'u': -100} final=[] count=len(fe) for a",
"a in range(0,count): temp = 0 for d in fe[a:]: temp += int(FE[d])",
"int(FE[d]) print(d) final.append(temp) temp = 0 for d in fe[:a]: temp += int(FE[d])",
"-100} final=[] count=len(fe) for a in range(0,count): temp = 0 for d in",
"0 for d in fe[a:]: temp += int(FE[d]) print(d) final.append(temp) temp = 0",
"0, 'b': -1, 'i': -10, 'u': -100} final=[] count=len(fe) for a in range(0,count):",
"100, 'e': 10, 'g': 1, 'a': 0, 'b': -1, 'i': -10, 'u': -100}",
"= {'o': 100, 'e': 10, 'g': 1, 'a': 0, 'b': -1, 'i': -10,",
"range(0,count): temp = 0 for d in fe[a:]: temp += int(FE[d]) print(d) final.append(temp)",
"'e': 10, 'g': 1, 'a': 0, 'b': -1, 'i': -10, 'u': -100} final=[]"
] |
[
"# -*- coding: utf-8 -*- # File name: __init__.py # Description: Basic format",
"coding: utf-8 -*- # File name: __init__.py # Description: Basic format for Python",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- # File name: __init__.py # Description:",
"utf-8 -*- # File name: __init__.py # Description: Basic format for Python scripts",
"# File name: __init__.py # Description: Basic format for Python scripts # Author:",
"File name: __init__.py # Description: Basic format for Python scripts # Author: irreq",
"__init__.py # Description: Basic format for Python scripts # Author: irreq (<EMAIL>) #",
"Description: Basic format for Python scripts # Author: irreq (<EMAIL>) # Date: 17/12/2021",
"name: __init__.py # Description: Basic format for Python scripts # Author: irreq (<EMAIL>)",
"# Description: Basic format for Python scripts # Author: irreq (<EMAIL>) # Date:",
"-*- coding: utf-8 -*- # File name: __init__.py # Description: Basic format for",
"python3 # -*- coding: utf-8 -*- # File name: __init__.py # Description: Basic",
"-*- # File name: __init__.py # Description: Basic format for Python scripts #",
"Basic format for Python scripts # Author: irreq (<EMAIL>) # Date: 17/12/2021 \"\"\"Documentation\"\"\""
] |
[
"a rendered image''' rounded_score = int(round(self.stats.score, -1)) score_str = \"Score: {:,}\".format((rounded_score)) self.score_image =",
"the high score into a rendered image''' high_score = int(round(self.stats.high_score, -1)) high_score_str =",
"(30, 30, 30) self.font = pygame.font.SysFont(None, 48) #prepare the initial score image self.prep_score()",
"self.prep_level() self.prep_ships() def prep_score(self): '''turn the score into a rendered image''' rounded_score =",
"score at the top right of the screen self.score_rect = self.score_image.get_rect() self.score_rect.right =",
"pygame.font.SysFont(None, 48) #prepare the initial score image self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self):",
"def show_score(self): '''draw scores and level to the screen''' self.screen.blit(self.score_image, self.score_rect) self.screen.blit(self.high_score_image, self.high_score_rect)",
"self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) #display the score at the top right",
"'''turn the level into a rendered image''' level_str = \"{}\".format(self.stats.level) self.level_image = self.font.render(level_str,",
"= self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def prep_ships(self): '''show how many ships",
"Scoreboard(): '''a class to report scoring information''' def __init__(self, ai_settings, screen, stats): '''initialize",
"'''initialize scorekeeping attributes''' self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats",
"import Ship class Scoreboard(): '''a class to report scoring information''' def __init__(self, ai_settings,",
"high score into a rendered image''' high_score = int(round(self.stats.high_score, -1)) high_score_str = \"High",
"self.ships.add(ship) def show_score(self): '''draw scores and level to the screen''' self.screen.blit(self.score_image, self.score_rect) self.screen.blit(self.high_score_image,",
"= self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top = self.score_rect.top def prep_level(self): '''turn the level",
"10 + ship_number * ship.rect.width ship.rect.y = 10 self.ships.add(ship) def show_score(self): '''draw scores",
"self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 20 def prep_high_score(self): '''turn the high",
"= self.score_rect.top def prep_level(self): '''turn the level into a rendered image''' level_str =",
"are left''' self.ships = Group() for ship_number in range(self.stats.ships_left): ship = Ship(self.ai_settings, self.screen)",
"self.score_rect.bottom + 10 def prep_ships(self): '''show how many ships are left''' self.ships =",
"self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self): '''turn the score into a rendered image''' rounded_score",
"left''' self.ships = Group() for ship_number in range(self.stats.ships_left): ship = Ship(self.ai_settings, self.screen) ship.rect.x",
"= 10 self.ships.add(ship) def show_score(self): '''draw scores and level to the screen''' self.screen.blit(self.score_image,",
"ai_settings self.stats = stats #font settings for scoring information self.text_color = (30, 30,",
"ai_settings, screen, stats): '''initialize scorekeeping attributes''' self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings",
"self.ai_settings = ai_settings self.stats = stats #font settings for scoring information self.text_color =",
"self.ai_settings.bg_color) #center the high score at the top of the screen self.high_score_rect =",
"many ships are left''' self.ships = Group() for ship_number in range(self.stats.ships_left): ship =",
"= 10 + ship_number * ship.rect.width ship.rect.y = 10 self.ships.add(ship) def show_score(self): '''draw",
"at the top right of the screen self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right",
"to report scoring information''' def __init__(self, ai_settings, screen, stats): '''initialize scorekeeping attributes''' self.screen",
"high score at the top of the screen self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx =",
"'''a class to report scoring information''' def __init__(self, ai_settings, screen, stats): '''initialize scorekeeping",
"self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self): '''turn the score into a rendered image'''",
"= self.screen_rect.right - 20 self.score_rect.top = 20 def prep_high_score(self): '''turn the high score",
"self.ai_settings.bg_color) #position the level below the score self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right",
"report scoring information''' def __init__(self, ai_settings, screen, stats): '''initialize scorekeeping attributes''' self.screen =",
"pygame.sprite import Group from ship import Ship class Scoreboard(): '''a class to report",
"image''' high_score = int(round(self.stats.high_score, -1)) high_score_str = \"High Score: {:,}\".format((high_score)) self.high_score_image = self.font.render(high_score_str,",
"= \"{}\".format(self.stats.level) self.level_image = self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color) #position the level below the",
"self.font = pygame.font.SysFont(None, 48) #prepare the initial score image self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships()",
"show_score(self): '''draw scores and level to the screen''' self.screen.blit(self.score_image, self.score_rect) self.screen.blit(self.high_score_image, self.high_score_rect) self.screen.blit(self.level_image,",
"def prep_score(self): '''turn the score into a rendered image''' rounded_score = int(round(self.stats.score, -1))",
"the top right of the screen self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right -",
"self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top = self.score_rect.top def prep_level(self): '''turn the",
"def prep_ships(self): '''show how many ships are left''' self.ships = Group() for ship_number",
"= stats #font settings for scoring information self.text_color = (30, 30, 30) self.font",
"{:,}\".format((high_score)) self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) #center the high score at the",
"30, 30) self.font = pygame.font.SysFont(None, 48) #prepare the initial score image self.prep_score() self.prep_high_score()",
"= self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) #display the score at the top right of",
"= screen.get_rect() self.ai_settings = ai_settings self.stats = stats #font settings for scoring information",
"+ 10 def prep_ships(self): '''show how many ships are left''' self.ships = Group()",
"pygame.font from pygame.sprite import Group from ship import Ship class Scoreboard(): '''a class",
"Group from ship import Ship class Scoreboard(): '''a class to report scoring information'''",
"self.screen_rect.centerx self.high_score_rect.top = self.score_rect.top def prep_level(self): '''turn the level into a rendered image'''",
"= Ship(self.ai_settings, self.screen) ship.rect.x = 10 + ship_number * ship.rect.width ship.rect.y = 10",
"= pygame.font.SysFont(None, 48) #prepare the initial score image self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def",
"<filename>scoreboard.py import pygame.font from pygame.sprite import Group from ship import Ship class Scoreboard():",
"how many ships are left''' self.ships = Group() for ship_number in range(self.stats.ships_left): ship",
"'''show how many ships are left''' self.ships = Group() for ship_number in range(self.stats.ships_left):",
"the level below the score self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top =",
"ships are left''' self.ships = Group() for ship_number in range(self.stats.ships_left): ship = Ship(self.ai_settings,",
"level into a rendered image''' level_str = \"{}\".format(self.stats.level) self.level_image = self.font.render(level_str, True, self.text_color,",
"of the screen self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top =",
"score into a rendered image''' rounded_score = int(round(self.stats.score, -1)) score_str = \"Score: {:,}\".format((rounded_score))",
"screen self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 20 def",
"= \"High Score: {:,}\".format((high_score)) self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) #center the high",
"def __init__(self, ai_settings, screen, stats): '''initialize scorekeeping attributes''' self.screen = screen self.screen_rect =",
"- 20 self.score_rect.top = 20 def prep_high_score(self): '''turn the high score into a",
"'''turn the high score into a rendered image''' high_score = int(round(self.stats.high_score, -1)) high_score_str",
"= self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) #center the high score at the top of",
"rounded_score = int(round(self.stats.score, -1)) score_str = \"Score: {:,}\".format((rounded_score)) self.score_image = self.font.render(score_str, True, self.text_color,",
"self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top = self.score_rect.top def prep_level(self): '''turn the level into a",
"the level into a rendered image''' level_str = \"{}\".format(self.stats.level) self.level_image = self.font.render(level_str, True,",
"#font settings for scoring information self.text_color = (30, 30, 30) self.font = pygame.font.SysFont(None,",
"self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def prep_ships(self): '''show how",
"the score at the top right of the screen self.score_rect = self.score_image.get_rect() self.score_rect.right",
"= self.score_rect.bottom + 10 def prep_ships(self): '''show how many ships are left''' self.ships",
"'''draw scores and level to the screen''' self.screen.blit(self.score_image, self.score_rect) self.screen.blit(self.high_score_image, self.high_score_rect) self.screen.blit(self.level_image, self.level_rect)",
"= \"Score: {:,}\".format((rounded_score)) self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) #display the score at",
"self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) #center the high score at the top",
"20 self.score_rect.top = 20 def prep_high_score(self): '''turn the high score into a rendered",
"self.score_rect.top def prep_level(self): '''turn the level into a rendered image''' level_str = \"{}\".format(self.stats.level)",
"attributes''' self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats",
"class to report scoring information''' def __init__(self, ai_settings, screen, stats): '''initialize scorekeeping attributes'''",
"scorekeeping attributes''' self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats =",
"ship.rect.y = 10 self.ships.add(ship) def show_score(self): '''draw scores and level to the screen'''",
"prep_ships(self): '''show how many ships are left''' self.ships = Group() for ship_number in",
"self.screen) ship.rect.x = 10 + ship_number * ship.rect.width ship.rect.y = 10 self.ships.add(ship) def",
"stats): '''initialize scorekeeping attributes''' self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings",
"score_str = \"Score: {:,}\".format((rounded_score)) self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) #display the score",
"into a rendered image''' level_str = \"{}\".format(self.stats.level) self.level_image = self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color)",
"self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def prep_ships(self): '''show how many ships are",
"information''' def __init__(self, ai_settings, screen, stats): '''initialize scorekeeping attributes''' self.screen = screen self.screen_rect",
"top of the screen self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top = self.score_rect.top",
"image''' level_str = \"{}\".format(self.stats.level) self.level_image = self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color) #position the level",
"self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def prep_ships(self):",
"self.text_color, self.ai_settings.bg_color) #position the level below the score self.level_rect = self.level_image.get_rect() self.level_rect.right =",
"prep_level(self): '''turn the level into a rendered image''' level_str = \"{}\".format(self.stats.level) self.level_image =",
"self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top = self.score_rect.top def prep_level(self): '''turn the level into",
"= int(round(self.stats.high_score, -1)) high_score_str = \"High Score: {:,}\".format((high_score)) self.high_score_image = self.font.render(high_score_str, True, self.text_color,",
"-1)) high_score_str = \"High Score: {:,}\".format((high_score)) self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) #center",
"self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def prep_ships(self): '''show how many",
"class Scoreboard(): '''a class to report scoring information''' def __init__(self, ai_settings, screen, stats):",
"= (30, 30, 30) self.font = pygame.font.SysFont(None, 48) #prepare the initial score image",
"the top of the screen self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top =",
"for scoring information self.text_color = (30, 30, 30) self.font = pygame.font.SysFont(None, 48) #prepare",
"= 20 def prep_high_score(self): '''turn the high score into a rendered image''' high_score",
"self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 20 def prep_high_score(self): '''turn the",
"score self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def",
"prep_score(self): '''turn the score into a rendered image''' rounded_score = int(round(self.stats.score, -1)) score_str",
"{:,}\".format((rounded_score)) self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) #display the score at the top",
"self.screen_rect.right - 20 self.score_rect.top = 20 def prep_high_score(self): '''turn the high score into",
"prep_high_score(self): '''turn the high score into a rendered image''' high_score = int(round(self.stats.high_score, -1))",
"of the screen self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top = self.score_rect.top def",
"the screen self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 20",
"True, self.text_color, self.ai_settings.bg_color) #position the level below the score self.level_rect = self.level_image.get_rect() self.level_rect.right",
"ship import Ship class Scoreboard(): '''a class to report scoring information''' def __init__(self,",
"20 def prep_high_score(self): '''turn the high score into a rendered image''' high_score =",
"high_score_str = \"High Score: {:,}\".format((high_score)) self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) #center the",
"high_score = int(round(self.stats.high_score, -1)) high_score_str = \"High Score: {:,}\".format((high_score)) self.high_score_image = self.font.render(high_score_str, True,",
"level below the score self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom",
"screen.get_rect() self.ai_settings = ai_settings self.stats = stats #font settings for scoring information self.text_color",
"= Group() for ship_number in range(self.stats.ships_left): ship = Ship(self.ai_settings, self.screen) ship.rect.x = 10",
"Ship(self.ai_settings, self.screen) ship.rect.x = 10 + ship_number * ship.rect.width ship.rect.y = 10 self.ships.add(ship)",
"+ ship_number * ship.rect.width ship.rect.y = 10 self.ships.add(ship) def show_score(self): '''draw scores and",
"-1)) score_str = \"Score: {:,}\".format((rounded_score)) self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) #display the",
"ship_number * ship.rect.width ship.rect.y = 10 self.ships.add(ship) def show_score(self): '''draw scores and level",
"import pygame.font from pygame.sprite import Group from ship import Ship class Scoreboard(): '''a",
"self.text_color, self.ai_settings.bg_color) #center the high score at the top of the screen self.high_score_rect",
"rendered image''' rounded_score = int(round(self.stats.score, -1)) score_str = \"Score: {:,}\".format((rounded_score)) self.score_image = self.font.render(score_str,",
"\"High Score: {:,}\".format((high_score)) self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) #center the high score",
"a rendered image''' level_str = \"{}\".format(self.stats.level) self.level_image = self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color) #position",
"initial score image self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self): '''turn the score into",
"= self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color) #position the level below the score self.level_rect =",
"from ship import Ship class Scoreboard(): '''a class to report scoring information''' def",
"information self.text_color = (30, 30, 30) self.font = pygame.font.SysFont(None, 48) #prepare the initial",
"int(round(self.stats.high_score, -1)) high_score_str = \"High Score: {:,}\".format((high_score)) self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color)",
"#center the high score at the top of the screen self.high_score_rect = self.high_score_image.get_rect()",
"48) #prepare the initial score image self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self): '''turn",
"screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats #font settings for",
"self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats #font settings for scoring",
"scores and level to the screen''' self.screen.blit(self.score_image, self.score_rect) self.screen.blit(self.high_score_image, self.high_score_rect) self.screen.blit(self.level_image, self.level_rect) self.ships.draw(self.screen)",
"the score self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10",
"image self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self): '''turn the score into a rendered",
"10 def prep_ships(self): '''show how many ships are left''' self.ships = Group() for",
"'''turn the score into a rendered image''' rounded_score = int(round(self.stats.score, -1)) score_str =",
"True, self.text_color, self.ai_settings.bg_color) #center the high score at the top of the screen",
"self.ai_settings.bg_color) #display the score at the top right of the screen self.score_rect =",
"rendered image''' level_str = \"{}\".format(self.stats.level) self.level_image = self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color) #position the",
"below the score self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom +",
"ship.rect.x = 10 + ship_number * ship.rect.width ship.rect.y = 10 self.ships.add(ship) def show_score(self):",
"range(self.stats.ships_left): ship = Ship(self.ai_settings, self.screen) ship.rect.x = 10 + ship_number * ship.rect.width ship.rect.y",
"#prepare the initial score image self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self): '''turn the",
"right of the screen self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top",
"Score: {:,}\".format((high_score)) self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) #center the high score at",
"screen self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top = self.score_rect.top def prep_level(self): '''turn",
"ship.rect.width ship.rect.y = 10 self.ships.add(ship) def show_score(self): '''draw scores and level to the",
"True, self.text_color, self.ai_settings.bg_color) #display the score at the top right of the screen",
"self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) #display the score at the top right of the",
"= self.screen_rect.centerx self.high_score_rect.top = self.score_rect.top def prep_level(self): '''turn the level into a rendered",
"self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 20 def prep_high_score(self):",
"stats #font settings for scoring information self.text_color = (30, 30, 30) self.font =",
"\"Score: {:,}\".format((rounded_score)) self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) #display the score at the",
"top right of the screen self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20",
"\"{}\".format(self.stats.level) self.level_image = self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color) #position the level below the score",
"scoring information self.text_color = (30, 30, 30) self.font = pygame.font.SysFont(None, 48) #prepare the",
"= screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats #font settings",
"#position the level below the score self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top",
"scoring information''' def __init__(self, ai_settings, screen, stats): '''initialize scorekeeping attributes''' self.screen = screen",
"score image self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self): '''turn the score into a",
"the score into a rendered image''' rounded_score = int(round(self.stats.score, -1)) score_str = \"Score:",
"the high score at the top of the screen self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx",
"rendered image''' high_score = int(round(self.stats.high_score, -1)) high_score_str = \"High Score: {:,}\".format((high_score)) self.high_score_image =",
"score at the top of the screen self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx",
"screen, stats): '''initialize scorekeeping attributes''' self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings =",
"the screen self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top = self.score_rect.top def prep_level(self):",
"= ai_settings self.stats = stats #font settings for scoring information self.text_color = (30,",
"at the top of the screen self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top",
"a rendered image''' high_score = int(round(self.stats.high_score, -1)) high_score_str = \"High Score: {:,}\".format((high_score)) self.high_score_image",
"self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) #center the high score at the top of the",
"self.level_rect.top = self.score_rect.bottom + 10 def prep_ships(self): '''show how many ships are left'''",
"from pygame.sprite import Group from ship import Ship class Scoreboard(): '''a class to",
"self.stats = stats #font settings for scoring information self.text_color = (30, 30, 30)",
"import Group from ship import Ship class Scoreboard(): '''a class to report scoring",
"settings for scoring information self.text_color = (30, 30, 30) self.font = pygame.font.SysFont(None, 48)",
"ship = Ship(self.ai_settings, self.screen) ship.rect.x = 10 + ship_number * ship.rect.width ship.rect.y =",
"= self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 20 def prep_high_score(self): '''turn",
"self.ships = Group() for ship_number in range(self.stats.ships_left): ship = Ship(self.ai_settings, self.screen) ship.rect.x =",
"= int(round(self.stats.score, -1)) score_str = \"Score: {:,}\".format((rounded_score)) self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color)",
"Ship class Scoreboard(): '''a class to report scoring information''' def __init__(self, ai_settings, screen,",
"in range(self.stats.ships_left): ship = Ship(self.ai_settings, self.screen) ship.rect.x = 10 + ship_number * ship.rect.width",
"def prep_high_score(self): '''turn the high score into a rendered image''' high_score = int(round(self.stats.high_score,",
"self.prep_ships() def prep_score(self): '''turn the score into a rendered image''' rounded_score = int(round(self.stats.score,",
"__init__(self, ai_settings, screen, stats): '''initialize scorekeeping attributes''' self.screen = screen self.screen_rect = screen.get_rect()",
"the initial score image self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self): '''turn the score",
"self.text_color = (30, 30, 30) self.font = pygame.font.SysFont(None, 48) #prepare the initial score",
"into a rendered image''' high_score = int(round(self.stats.high_score, -1)) high_score_str = \"High Score: {:,}\".format((high_score))",
"= self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def prep_ships(self): '''show",
"10 self.ships.add(ship) def show_score(self): '''draw scores and level to the screen''' self.screen.blit(self.score_image, self.score_rect)",
"#display the score at the top right of the screen self.score_rect = self.score_image.get_rect()",
"score into a rendered image''' high_score = int(round(self.stats.high_score, -1)) high_score_str = \"High Score:",
"image''' rounded_score = int(round(self.stats.score, -1)) score_str = \"Score: {:,}\".format((rounded_score)) self.score_image = self.font.render(score_str, True,",
"30) self.font = pygame.font.SysFont(None, 48) #prepare the initial score image self.prep_score() self.prep_high_score() self.prep_level()",
"level_str = \"{}\".format(self.stats.level) self.level_image = self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color) #position the level below",
"self.text_color, self.ai_settings.bg_color) #display the score at the top right of the screen self.score_rect",
"for ship_number in range(self.stats.ships_left): ship = Ship(self.ai_settings, self.screen) ship.rect.x = 10 + ship_number",
"Group() for ship_number in range(self.stats.ships_left): ship = Ship(self.ai_settings, self.screen) ship.rect.x = 10 +",
"self.high_score_rect.top = self.score_rect.top def prep_level(self): '''turn the level into a rendered image''' level_str",
"int(round(self.stats.score, -1)) score_str = \"Score: {:,}\".format((rounded_score)) self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) #display",
"into a rendered image''' rounded_score = int(round(self.stats.score, -1)) score_str = \"Score: {:,}\".format((rounded_score)) self.score_image",
"self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color) #position the level below the score self.level_rect = self.level_image.get_rect()",
"self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats #font",
"def prep_level(self): '''turn the level into a rendered image''' level_str = \"{}\".format(self.stats.level) self.level_image",
"ship_number in range(self.stats.ships_left): ship = Ship(self.ai_settings, self.screen) ship.rect.x = 10 + ship_number *",
"* ship.rect.width ship.rect.y = 10 self.ships.add(ship) def show_score(self): '''draw scores and level to",
"self.level_image = self.font.render(level_str, True, self.text_color, self.ai_settings.bg_color) #position the level below the score self.level_rect",
"self.score_rect.top = 20 def prep_high_score(self): '''turn the high score into a rendered image'''"
] |
[
"step size is returned, when back_tol is not met. \"\"\" np.random.seed(32964) n =",
"= est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check, 5) == np.round(opt_t, 5))) def test_14(): \"\"\" Test for",
"def test_8(): \"\"\" Test for compute_backward - check that when flag=False, original track",
"beta, step, const_back, back_tol, const_forward, forward_tol, f, func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals)",
"matrix = np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001) step = 1 forward_tol",
"func_args = (minimizer, matrix, 0, 0.0000001) step = 0.5 forward_tol = 1.5 beta",
"0, 5) t = 1 back_tol = 1 beta = np.array([200, 200]) f_old",
"matrix, 0, 1000) t = 17001.993794080016 back_tol = 1 no_vars = m region",
"f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta, *func_args) assert(f_old > f_new)",
"for compute_backward - check that when flag=True, track is updated. \"\"\" np.random.seed(90) m",
"step = 1 forward_tol = 100000 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point),",
"test_5(): \"\"\" Test for forward_tracking - forward_tol not met initially, f_new < track[-2][1]",
"int) assert(func_val < f_old) def test_18(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100],",
"def test_11(): \"\"\" Test for backward_tracking - back tol is not met and",
"for backward_tracking - back_tol is met. \"\"\" np.random.seed(32964) m = 2 f =",
"== np.array([100, 90, 110]))) assert(np.all(track_t == np.array([0, 0.25, 0.5]))) def test_21(): \"\"\"Test for",
"(minimizer, matrix, 0, 5) t = 97.688932389756 back_tol = 0.000000001 no_vars = m",
"> f_new) assert(flag == False) assert(count_func_evals > 0) for j in range(len(test_track)): assert(test_track[j,",
"beta, *func_args) assert(f_old < f_new) track, total_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new,",
"assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val == f_old) def test_17(): \"\"\"",
"< track[j-1][1]) else: assert(track[j][1] > track[j-1][1]) def test_8(): \"\"\" Test for compute_backward -",
"j in range(1, len(track)): assert(track[j-1][1] > track[j][1]) def test_6(): \"\"\" Test for forward_tracking",
"returned. \"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer",
"\"\"\" Test for backward_tracking - back tol is not initially met, f_new <",
"assert(flag == False) for j in range(1, len(track)): assert(track[j-1][1] > track[j][1]) def test_6():",
"- t * beta, *func_args) assert(f_old < f_new) track, total_func_evals = (est_dir.backward_tracking (centre_point,",
"= est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 10, (m,)) centre_point = np.random.uniform(0,",
"const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, )) matrix = est_dir.quad_func_params(1,",
"- check that correct step size is returned when forward_tol is met. \"\"\"",
"== np.round(t, 3)) assert(total_func_evals > 0) for j in range(1, len(track)): assert(np.round(track[j][0], 4)",
"f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag == False) assert(track[2][1] < track[1][1] <",
"= 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 1, (m,",
"(centre_point, t, f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0,",
"(1 / const_back) minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix = est_dir.quad_func_params(1,",
"3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) for",
"\"\"\" Test for forward_tracking - forward_tol not met and f_new < track[-2][1]. \"\"\"",
"\"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward =",
"region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region) assert(func_evals",
"(minimizer, matrix, 0, 1000) t = 17001.993794080016 back_tol = 0.000000001 no_vars = m",
"- step * beta, *func_args) assert(f_old > f_new) track = np.array([[0, 100], [1,",
"0, 0.0000001) step = 1 forward_tol = 100000 beta = np.array([0.0001, 0.0001]) f_old",
"if j < len(track) - 1: assert(track[j][1] < track[j - 1][1]) else: assert(track[j][1]",
"f(np.copy(centre_point) - step * beta, *func_args) assert(f_old > f_new) track = np.array([[0, 100],",
"10, m) func_args = (minimizer, matrix, 0, 1000) t = 17001.993794080016 back_tol =",
"step = 1 forward_tol = 100000 back_tol = 0.0000001 beta = np.array([0.0001, 0.0001])",
"updated. \"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer",
"matrix, 0, 10) t = 0.005 forward_tol = 10 beta = np.array([1, 1])",
"assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:, 1][0])",
"5) step = 0.05 forward_tol = 1000000 no_vars = 10 region = 1",
"func_args = (minimizer, matrix, 0, 10) t = 0.005 forward_tol = 10 beta",
"f, func_args)) assert(track.shape == (2, m)) assert(track[0][0] == 0) assert(track[1][0] == t) assert(track[1][0]",
"80]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 80,",
"- check that correct step size is returned, when forward_tol is not met.",
"assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point,",
"assert(track[1][0] < track[1][1]) assert(count_func_evals == 0) def test_10(): \"\"\" Test for backward_tracking -",
"\"\"\" Test for combine_tracking - check that correct step size is returned when",
"arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2, 70], [4, 90]]) track_method =",
"track_y[1].\"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise minimizer = np.ones((m,)) centre_point =",
"forward_tol = 10000 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new =",
"- check that when flag=True, track is updated. \"\"\" np.random.seed(90) m = 100",
"returned, when forward_tol is not met. \"\"\" np.random.seed(3291) m = 2 f =",
"np.array([[0, 100], [1, 120], [0.5, 110], [0.25, 90]]) track_method = 'Backward' track_y, track_t",
"20 m = 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0,",
"j in range(len(test_track)): assert(test_track[j, 0] < forward_tol) if j >= 1: assert(test_track[j, 1]",
"assert(len(track) - 1 == total_func_evals) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) ==",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step = 0.05",
"back_tol, f, func_args)) assert(track.shape == (2, m)) assert(track[0][0] == 0) assert(track[1][0] == t)",
"f_old], [step, f_new]]) track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point,",
"test_track[j - 1, 1]) assert(test_track[j, 0] * const_forward > forward_tol) def test_3(): \"\"\"",
"10000 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) -",
"- 1: assert(track[j][1] < track[j - 1][1]) else: assert(track[j][1] > track[j - 1][1])",
"1 beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) -",
"track_method) assert(np.all(track_y == np.array([100, 90, 110]))) assert(np.all(track_t == np.array([0, 0.25, 0.5]))) def test_21():",
"160], [2, 40], [4, 90]]) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track,",
"= (minimizer, matrix, 0, 5) t = 1 back_tol = 1 beta =",
"np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old,",
"< track[-2][1]. \"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise const_back = 0.5",
"const_back) minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10, m)",
"func_args = (minimizer, matrix, 0, 5) t = 1 back_tol = 1 beta",
"size is returned, when forward_tol is not met. \"\"\" np.random.seed(3291) m = 2",
"1000) t = 17001.993794080016 back_tol = 1 no_vars = m region = 1",
"in range(1, len(track)): assert(track[j-1][1] > track[j][1]) def test_6(): \"\"\" Test for forward_tracking -",
"40) def test_23(): \"\"\"Test for check_func_val_coeffs when func_val <= track_y[1].\"\"\" np.random.seed(91) m =",
"beta, f, func_args)) assert(f_old > f_new) assert(count_func_evals == len(track) - 2) assert(flag ==",
"compute_backward - check that when flag=True, track is updated. \"\"\" np.random.seed(90) m =",
"20]) matrix = np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001) step = 1",
"assert(flag == True) assert(track[0][0] == 0) for j in range(1, len(track)): assert(track[j][0] ==",
"forward_tol is met. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back =",
"assert(track[j][1] > track[j-1][1]) else: assert(track[j-1][1] > track[j][1]) def test_5(): \"\"\" Test for forward_tracking",
"assert(count_func_evals == len(track) - 2) assert(flag == True) assert(track[0][0] == 0) for j",
"f_new >= track[-2][1] \"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise const_back =",
"0, 0.1) step = 0.1 back_tol = 0.075 no_vars = 10 region =",
"= (minimizer, matrix, 0, 0.0000001) step = 1 forward_tol = 100000 beta =",
"is not met and f_new < track[-2][1] \"\"\" np.random.seed(329998) n = 20 m",
"10, m) func_args = (minimizer, matrix, 0, 5) step = 1 back_tol =",
"t = 17001.993794080016 back_tol = 1 no_vars = m region = 1 beta,",
"3)) assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_13(): \"\"\"Test for",
"t, f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(track.shape == (2, m)) assert(track[0][0]",
"= (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(len(track) -",
"check = -OLS[1] / (2 * OLS[2]) opt_t = est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check, 5)",
"range(1, len(track)): if j == (len(track) - 1): assert(track[j][1] > track[j-1][1]) else: assert(track[j-1][1]",
"= 0.0000001 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals",
"1]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta,",
"met and f_new > track[-2][1]. \"\"\" np.random.seed(32964) n = 6 m = 2",
"0) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f,",
"f(np.copy(centre_point) - t * beta, *func_args) assert(f_old < f_new) track, count_func_evals = (est_dir.backward_tracking",
"check that correct step size is returned, when back_tol is met. \"\"\" np.random.seed(32964)",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 1000) t = 17001.993794080016 back_tol",
"= t / 2 assert(np.min(track[:, 1]) < track[1][0]) def test_11(): \"\"\" Test for",
"- check that when flag=False, track is returned. \"\"\" np.random.seed(90) m = 2",
"== np.round(t, 3)) assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_13():",
"= 0.0000001 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals",
"def test_21(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5, 80]])",
"m) func_args = (minimizer, matrix, 0, 0.1) step = 0.1 back_tol = 0.075",
"test_12(): \"\"\" Test for backward_tracking - back tol is not initially met, f_new",
"16]))) def test_19(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2,",
"est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 70, 90]))) assert(np.all(track_t == np.array([0, 2, 4]))) def",
"assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(flag == True) for j",
"flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag",
"def test_12(): \"\"\" Test for backward_tracking - back tol is not initially met,",
"for j in range(1, len(track)): assert(np.round(track[j][0], 4) == np.round(t, 4)) t = t",
"== len(track) - 2) assert(flag == True) assert(track[0][0] == 0) for j in",
"step = 0.005 forward_tol = 10000 back_tol = 0.0000001 beta = np.array([1, 1])",
"n) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta,",
"func_args = (minimizer, matrix, 0, 5) t = 97.688932389756 back_tol = 0.000000001 no_vars",
"assert(np.all(design_matrix_step[2, :] == np.array([100, 0.5, 0.25]))) OLS = (np.linalg.inv(design_matrix_step.T @ design_matrix_step) @ design_matrix_step.T",
"10, m) func_args = (minimizer, matrix, 0, 5) step = 0.005 forward_tol =",
"assert(flag == False) assert(total_func_evals == 0) def test_9(): \"\"\" Test for backward_tracking -",
"n = 6 m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward",
"t / 2 assert(np.min(track[:, 1]) < track[1][0]) def test_11(): \"\"\" Test for backward_tracking",
"< track[:, 1][0]) def test_13(): \"\"\"Test for compute_coeffs\"\"\" track_y = np.array([100, 200, 50])",
"Test for backward_tracking - back tol is not met and f_new > track[-2][1].",
"== np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(step, 3)) assert(flag == True) for j",
"m = 10 f = est_dir.quad_f_noise minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20,",
"= (minimizer, matrix, 0, 5) t = 97.688932389756 back_tol = 0.000000001 no_vars =",
"OLS[2]) opt_t = est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check, 5) == np.round(opt_t, 5))) def test_14(): \"\"\"",
"int) assert(func_val < f_old) def test_16(): \"\"\" Test for combine_tracking - check that",
"1]))) def test_22(): \"\"\"Test for check_func_val_coeffs when func_val > track_y[1].\"\"\" np.random.seed(90) m =",
"assert(flag == True) for j in range(2, len(track)): step = step * 2",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 10) t = 0.005 forward_tol",
"= f(np.copy(centre_point) - t * beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag",
"func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals >",
"flag=False, original track is returned. \"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise",
"0.0000001) step = 1 forward_tol = 100000 back_tol = 0.0000001 beta = np.array([0.0001,",
"= (minimizer, matrix, 0, 1000) t = 17001.993794080016 back_tol = 0.000000001 no_vars =",
"track[-2][1] and eventually forward_tol is met. \"\"\" np.random.seed(25) m = 2 f =",
"*func_args) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol,",
"= np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t *",
"= 97.688932389756 back_tol = 0.000000001 no_vars = m region = 1 beta, func_evals",
"def test_2(): \"\"\" Test for compute_forward() - check that when flag=False, track is",
"forward_tol = 100000 back_tol = 0.0000001 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point),",
"= np.array([[0, 100], [1, 80], [2, 70], [4, 90]]) track_method = 'Forward' track_y,",
"step) step = step * const_back if j < len(track) - 1: assert(track[j][1]",
")) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_18(): \"\"\"Test for arrange_track_y_t\"\"\" track",
"back_tol = 0.000001 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m,",
"for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2, 70], [4, 90]]) track_method",
"(track, track_method, centre_point, beta, f, func_args)) assert(upd_point.shape == (m, )) assert(func_val == 40)",
"range(2, len(track)): step = step * 2 assert(np.round(track[j][0], 3) == step) if j",
"that correct step size is returned, when back_tol is not met. \"\"\" np.random.seed(32964)",
"track[:, 1][0]) def test_13(): \"\"\"Test for compute_coeffs\"\"\" track_y = np.array([100, 200, 50]) track_t",
"def test_7(): \"\"\" Test for compute_backward - check that when flag=True, track is",
"- back_tol is met. \"\"\" np.random.seed(32964) m = 2 f = est_dir.quad_f_noise const_back",
"track is updated. \"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise const_back =",
"- forward_tol met. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back =",
"func_args = (minimizer, matrix, 0, 5) step = 0.01 forward_tol = 1000000 no_vars",
"110]))) assert(np.all(track_t == np.array([0, 0.25, 0.5]))) def test_21(): \"\"\"Test for arrange_track_y_t\"\"\" track =",
"0, 10) t = 0.005 forward_tol = 10 beta = np.array([1, 1]) f_old",
"back_tol = 0.075 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m,",
"check that correct step size is returned, when forward_tol is not met. \"\"\"",
"back_tol = 1 beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) f_new =",
":] == np.array([100, 0, 0]))) assert(np.all(design_matrix_step[1, :] == np.array([100, 1, 1]))) assert(np.all(design_matrix_step[2, :]",
"matrix, 0, 0.1) step = 0.1 back_tol = 0.075 no_vars = 10 region",
"is returned, when forward_tol is not met. \"\"\" np.random.seed(3291) m = 2 f",
"\"\"\" np.random.seed(329998) n = 20 m = 100 f = est_dir.quad_f_noise const_back =",
"*func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) track, total_func_evals, flag =",
"= 10 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point)",
"== True) assert(track[0][0] == 0) for j in range(1, len(track)): assert(track[j][0] == step)",
"< test_track[j - 1, 1]) assert(test_track[j, 0] * const_forward > forward_tol) def test_3():",
"[1, 160], [2, 40], [4, 90]]) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs",
"- check that correct step size is returned, when back_tol is not met.",
"f_new]]) track_new, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f,",
"1]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta, *func_args)",
"= 0.1 back_tol = 0.075 no_vars = 10 region = 1 beta, func_evals",
"const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.array([20, 20]) matrix",
"- 1: assert(track[j][1] < track[j-1][1]) else: assert(track[j][1] > track[j-1][1]) def test_8(): \"\"\" Test",
"back_tol = 0.0000001 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val,",
"[4, 90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100,",
"f_old], [step, f_new]]) test_track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point,",
"0.5 minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10, m)",
"Test for backward_tracking - back tol is not initially met, f_new < track[-2][1]",
"1, (m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0,",
"assert(np.all(track_t == np.array([0, 0.5, 1]))) def test_22(): \"\"\"Test for check_func_val_coeffs when func_val >",
"func_val > track_y[1].\"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise minimizer = np.ones((m,))",
"> f_new) track = np.array([[0, f_old], [step, f_new]]) track_new, total_func_evals, flag = (est_dir.compute_backward",
"= np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point,",
"\"\"\" Test for compute_backward - check that when flag=False, original track is returned.",
"m = 2 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,)) centre_point",
"m) func_args = (minimizer, matrix, 0, 5) t = 1 back_tol = 1",
"False) assert(total_func_evals == 0) def test_9(): \"\"\" Test for backward_tracking - back_tol is",
"< f_new) track, total_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol,",
"n = 6 m = 2 f = est_dir.quad_f_noise const_back = 0.5 minimizer",
"= (minimizer, matrix, 0, 10) t = 0.005 forward_tol = 10000 beta =",
"\"\"\"Test for check_func_val_coeffs when func_val > track_y[1].\"\"\" np.random.seed(90) m = 10 f =",
"track_method) assert(np.all(track_y == np.array([100, 80, 120]))) assert(np.all(track_t == np.array([0, 0.5, 1]))) def test_22():",
"== np.round(t, 3)) assert(total_func_evals > 0) assert(flag == False) for j in range(1,",
"90]]) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f,",
"no_vars = 10 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region) assert(func_evals",
"f_new) track, count_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol, f,",
"check_func_val_coeffs when func_val > track_y[1].\"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise minimizer",
"= f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta, *func_args) assert(f_old <",
"track, centre_point, beta, f, func_args)) assert(np.all(track == track_new)) assert(flag == False) assert(total_func_evals ==",
"func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region) assert(func_evals == 16) f_old =",
"track = np.array([[0, 100], [1, 80], [2, 70], [4, 90]]) track_method = 'Forward'",
"test_10(): \"\"\" Test for backward_tracking - back tol is not met and f_new",
"def test_17(): \"\"\" Test for combine_tracking - check that correct step size is",
"[step, f_new]]) test_track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta,",
"np.round(t, 3)) assert(total_func_evals > 0) assert(flag == False) for j in range(1, len(track)):",
"= 1000000 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point,",
"const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m,",
"* beta, *func_args) assert(f_old > f_new) track = np.array([[0, 100], [1, 160], [2,",
"not met initially, f_new < track[-2][1] and eventually forward_tol is met. \"\"\" np.random.seed(25)",
"= np.ones((m,)) centre_point = np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10, m) func_args =",
"0, 0.0000001) step = 1 forward_tol = 100000 back_tol = 0.0000001 beta =",
"0) for j in range(1, len(track)): assert(track[j][0] == step) step = step *",
"(len(track) - 1): assert(track[j][1] > track[j-1][1]) else: assert(track[j-1][1] > track[j][1]) def test_5(): \"\"\"",
"= np.array([20, 20]) matrix = np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001) step",
"beta, *func_args) assert(f_old > f_new) track = np.array([[0, f_old], [step, f_new]]) track_new, total_func_evals,",
"= (est_dir.combine_tracking (centre_point, f_old, beta, step, const_back, back_tol, const_forward, forward_tol, f, func_args)) assert(upd_point.shape",
"[1, 120], [0.5, 110], [0.25, 90]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track,",
"total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args))",
"matrix, 0, 5) region = 1 step = 0.17741338024633116 forward_tol = 1000000 no_vars",
"3)) assert(total_func_evals > 0) assert(flag == False) for j in range(1, len(track)): assert(track[j-1][1]",
"10, m) func_args = (minimizer, matrix, 0, 0.1) step = 0.1 back_tol =",
"0.17741338024633116 forward_tol = 1000000 no_vars = 10 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f,",
"10, m) func_args = (minimizer, matrix, 0, 60) step = 1.8251102718712913 no_vars =",
"'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 70, 90]))) assert(np.all(track_t ==",
"func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val == f_old) def test_17():",
"test_19(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2, 70], [4,",
"10 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1 / const_back) minimizer",
"*func_args) assert(f_old > f_new) track = np.array([[0, f_old], [step, f_new]]) track_new, total_func_evals, flag",
"check that correct step size is returned when forward_tol is met. \"\"\" np.random.seed(90)",
"f_new = f(np.copy(centre_point) - step * beta, *func_args) assert(f_old > f_new) track =",
"const_back = 0.5 const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point =",
"= est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region) assert(func_evals == 16) f_old = f(np.copy(centre_point),",
"(m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_18(): \"\"\"Test for arrange_track_y_t\"\"\"",
"= (minimizer, matrix, 0, 5) region = 1 step = 0.17741338024633116 forward_tol =",
")) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step",
"est_dir.quad_f_noise const_back = 0.5 const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point",
"forward_tol = 1000000 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m,",
"< len(track) - 1: assert(track[j][1] < track[j-1][1]) else: assert(track[j][1] > track[j-1][1]) def test_8():",
"> track[j-1][1]) def test_8(): \"\"\" Test for compute_backward - check that when flag=False,",
"** 2)).T assert(np.all(design_matrix_step[0, :] == np.array([100, 0, 0]))) assert(np.all(design_matrix_step[1, :] == np.array([100, 1,",
"track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 90, 110]))) assert(np.all(track_t == np.array([0, 0.25,",
"(2, m)) assert(track[0][0] == 0) assert(track[1][0] == t) assert(track[1][0] < track[1][1]) assert(count_func_evals ==",
"j in range(1, len(track)): assert(np.round(track[j][0], 4) == np.round(t, 4)) t = t /",
"1 forward_tol = 100000 beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) upd_point,",
"f_new < track[-2][1] and eventually forward_tol is met. \"\"\" np.random.seed(25) m = 2",
"returned, when back_tol is met. \"\"\" np.random.seed(32964) m = 2 f = est_dir.quad_f_noise",
"= np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001) step = 1 forward_tol =",
"that when flag=False, original track is returned. \"\"\" np.random.seed(90) m = 100 f",
"no_vars = m region = 1 beta, func_evals = est_dir.compute_direction_XY(n, m, centre_point, f,",
"(est_dir.forward_tracking (centre_point, t, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(np.round(track[0][0], 3) ==",
"1.8251102718712913 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f,",
"== step) step = step * const_forward if j < len(track) - 1:",
"f, func_args)) assert(np.all(track == track_new)) assert(flag == False) assert(total_func_evals == 0) def test_9():",
"test_1(): \"\"\" Test for compute_forward() - check for flag=True. \"\"\" np.random.seed(90) m =",
"len(track)): assert(track[j-1][1] > track[j][1]) def test_6(): \"\"\" Test for forward_tracking - forward_tol met.",
"\"\"\" Test for backward_tracking - back_tol is met. \"\"\" np.random.seed(32964) m = 2",
"j == (len(track) - 1): assert(track[j][1] > track[j - 1][1]) else: assert(track[j -",
"track, centre_point, beta, f, func_args)) assert(f_old > f_new) assert(flag == False) assert(count_func_evals >",
"= np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, )) matrix = est_dir.quad_func_params(1, 10, m)",
"back tol is met. \"\"\" np.random.seed(329998) n = 20 m = 100 f",
"np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0,",
"combine_tracking - check that correct step size is returned, when back_tol is met.",
"func_args)) assert(flag == True) assert(total_func_evals > 0) track_method = 'Forward' upd_point, func_val =",
"back_tol, const_forward, forward_tol, f, func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val",
"test_17(): \"\"\" Test for combine_tracking - check that correct step size is returned,",
"= est_dir.compute_direction_XY(n, m, centre_point, f, func_args, no_vars, region) assert(func_evals == n) f_old =",
"10000 back_tol = 0.0000001 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) upd_point,",
"test_20(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5, 110], [0.25,",
"= 1000000 no_vars = 10 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars,",
"* OLS[2]) opt_t = est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check, 5) == np.round(opt_t, 5))) def test_14():",
"step * beta, *func_args) track = np.array([[0, f_old], [step, f_new]]) track, count_func_evals, flag",
"step, const_back, back_tol, const_forward, forward_tol, f, func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is",
"*func_args) f_new = f(np.copy(centre_point) - t * beta, *func_args) assert(f_old > f_new) track,",
"\"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise const_back = 0.5 const_forward =",
"centre_point = np.random.uniform(0, 20, (m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args =",
"opt_t = est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check, 5) == np.round(opt_t, 5))) def test_14(): \"\"\" Test",
"assert(flag == False) assert(count_func_evals > 0) for j in range(len(test_track)): assert(test_track[j, 0] <",
"*func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) assert(f_old > f_new) track,",
"m) func_args = (minimizer, matrix, 0, 0.1) step = 0.001 back_tol = 0.000001",
"1][1]) else: assert(track[j - 1][1] > track[j][1]) def test_4(): \"\"\" Test for forward_tracking",
"for compute_forward() - check for flag=True. \"\"\" np.random.seed(90) m = 10 f =",
"10) t = 0.005 forward_tol = 10 beta = np.array([1, 1]) f_old =",
"t = 97.688932389756 back_tol = 0.000000001 no_vars = m region = 1 beta,",
"np.random.uniform(0, 20, (m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix,",
"f(np.copy(centre_point) - step * beta, *func_args) track = np.array([[0, f_old], [step, f_new]]) test_track,",
"8, 16]))) def test_19(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80],",
"== (m, )) assert(func_val == 40) def test_23(): \"\"\"Test for check_func_val_coeffs when func_val",
"10, m) func_args = (minimizer, matrix, 0, 5) region = 1 step =",
"f_new, beta, const_back, back_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3)",
"np.array([100, 1, 1]))) assert(np.all(design_matrix_step[2, :] == np.array([100, 0.5, 0.25]))) OLS = (np.linalg.inv(design_matrix_step.T @",
"1 no_vars = m region = 1 beta, func_evals = est_dir.compute_direction_XY(n, m, centre_point,",
"const_back = 0.5 minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix =",
"original track is returned. \"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise const_back",
"met. \"\"\" np.random.seed(32964) n = 6 m = 2 f = est_dir.quad_f_noise const_back",
"0.5, 1]))) def test_22(): \"\"\"Test for check_func_val_coeffs when func_val > track_y[1].\"\"\" np.random.seed(90) m",
"track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 80, 120]))) assert(np.all(track_t == np.array([0,",
"step = step * const_back if j < len(track) - 1: assert(track[j][1] <",
"3) == np.round(t, 3)) assert(total_func_evals > 0) assert(flag == True) for j in",
"n = 20 m = 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer",
"correct step size is returned, when back_tol is met. \"\"\" np.random.seed(32964) m =",
"0, 1000) t = 17001.993794080016 back_tol = 1 no_vars = m region =",
"arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5, 110], [0.25, 90]]) track_method =",
"func_args = (minimizer, matrix, 0, 0.0000001) step = 1 forward_tol = 100000 back_tol",
"= (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f, func_args)) assert(upd_point.shape == (m, )) assert(func_val",
"f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag == False) assert(track[2][1] < track[1][1]",
"func_args = (minimizer, matrix, 0, 0.1) step = 0.1 back_tol = 0.075 no_vars",
"step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag == False) assert(track[2][1] <",
"< track[:, 1][0]) def test_12(): \"\"\" Test for backward_tracking - back tol is",
"f_new < track[-2][1] and eventaully back tol is met. \"\"\" np.random.seed(329998) n =",
"f, func_args, no_vars, region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) f_new =",
"assert(np.all(track_t == np.array([0, 2, 4]))) def test_20(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0,",
"= (minimizer, matrix, 0, 5) step = 1 back_tol = 1 forward_tol =",
"est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix =",
"back_tol = 1 forward_tol = 100000 beta = np.array([200, 200]) f_old = f(np.copy(centre_point),",
"forward_tol, track, centre_point, beta, f, func_args)) assert(f_old > f_new) assert(count_func_evals == len(track) -",
"for backward_tracking - back tol is not met and f_new < track[-2][1] \"\"\"",
"- 1 == total_func_evals) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(step,",
"assert(np.round(track[1][0], 3) == np.round(step, 3)) assert(flag == True) for j in range(2, len(track)):",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 0.1) step = 0.001 back_tol",
"region) assert(func_evals == 16) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step",
"step = 0.001 back_tol = 0.000001 no_vars = 10 region = 1 beta,",
"track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 80, 120]))) assert(np.all(track_t == np.array([0, 0.5,",
"= 10 f = est_dir.quad_f_noise minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m,",
"matrix, 0, 0.0000001) step = 1 forward_tol = 100000 beta = np.array([0.0001, 0.0001])",
"assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_16(): \"\"\"",
"func_args)) assert(flag == False) assert(track[2][1] < track[1][1] < track[0][1]) assert(total_func_evals == 1) def",
"'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 90, 110]))) assert(np.all(track_t ==",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step = 0.005 forward_tol",
"beta, f, func_args)) assert(f_old > f_new) assert(flag == False) assert(count_func_evals > 0) for",
"np.random.seed(32964) n = 6 m = 2 f = est_dir.quad_f_noise const_back = 0.5",
"= 17001.993794080016 back_tol = 1 no_vars = m region = 1 beta, func_evals",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 0.1) step = 0.1",
"10, m) func_args = (minimizer, matrix, 0, 5) step = 10 forward_tol =",
"True) assert(total_func_evals > 0) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method,",
"beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking",
"np.round(step, 3)) assert(flag == True) for j in range(2, len(track)): step = step",
"beta, func_evals = est_dir.compute_direction_XY(n, m, centre_point, f, func_args, no_vars, region) assert(func_evals == n)",
"forward_tol not met initially, f_new < track[-2][1] and eventually forward_tol is met. \"\"\"",
"'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 20, 90]))) assert(np.all(track_t ==",
"track[-2][1]. \"\"\" np.random.seed(32964) n = 6 m = 2 f = est_dir.quad_f_noise const_back",
"1 forward_tol = 100000 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new",
"for combine_tracking - check that correct step size is returned, when back_tol is",
"assert(np.all(design_matrix_step[1, :] == np.array([100, 1, 1]))) assert(np.all(design_matrix_step[2, :] == np.array([100, 0.5, 0.25]))) OLS",
"func_args)) assert(f_old > f_new) assert(flag == False) assert(count_func_evals > 0) for j in",
"120], [0.5, 80]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y ==",
"200]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta, *func_args)",
"[1, 120], [0.5, 80]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y",
"2 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,)) centre_point = np.array([25,",
"track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 20, 90])))",
"np.round(t, 3)) assert(total_func_evals > 0) for j in range(1, len(track)): assert(np.round(track[j][0], 4) ==",
"beta, *func_args) assert(f_old > f_new) track = np.array([[0, 100], [1, 160], [2, 40],",
"assert(test_track[j, 1] < test_track[j - 1, 1]) assert(test_track[j, 0] * const_forward > forward_tol)",
"matrix, 0, 1000) t = 17001.993794080016 back_tol = 0.000000001 no_vars = m region",
"100000 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) -",
"assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_13(): \"\"\"Test for compute_coeffs\"\"\"",
"track_t) assert(np.all(np.round(check, 5) == np.round(opt_t, 5))) def test_14(): \"\"\" Test for combine_tracking -",
"= np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t *",
"is not met. \"\"\" np.random.seed(3291) m = 2 f = est_dir.quad_f_noise const_back =",
"func_args)) assert(total_func_evals == len(track) - 2) assert(flag == True) assert(track[0][0] == 0) for",
"met and f_new < track[-2][1]. \"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise",
"6 m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1",
"= 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1 / const_back)",
"else: assert(track[j][1] > track[j-1][1]) def test_8(): \"\"\" Test for compute_backward - check that",
"0.0000001 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals =",
"np.round(t, 4)) t = t / 2 assert(np.min(track[:, 1]) < track[1][0]) def test_11():",
"const_forward, forward_tol, f, func_args)) assert(flag == False) assert(track[2][1] < track[1][1] < track[0][1]) assert(total_func_evals",
"[0.5, 80]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100,",
"track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 20, 90]))) assert(np.all(track_t == np.array([0,",
"(est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(np.round(track[0][0], 3) ==",
"track[j][1]) def test_4(): \"\"\" Test for forward_tracking - forward_tol not met and f_new",
"const_forward, forward_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t,",
"\"\"\" Test for forward_tracking - flag=True and f_new >= track[-2][1] \"\"\" np.random.seed(90) m",
"def test_18(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2, 160],",
"1000000 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f,",
"25]) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 10) t",
"True) for j in range(1, len(track)): if j == (len(track) - 1): assert(track[j][1]",
"== np.array([100, 0, 0]))) assert(np.all(design_matrix_step[1, :] == np.array([100, 1, 1]))) assert(np.all(design_matrix_step[2, :] ==",
"4)) t = t / 2 assert(np.min(track[:, 1]) < track[1][0]) def test_11(): \"\"\"",
"0.1 back_tol = 0.075 no_vars = 10 region = 1 beta, func_evals =",
"assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, t, f_old, f_new, beta,",
"track_y = np.array([100, 200, 50]) track_t = np.array([0, 1, 0.5]) design_matrix_step = np.vstack((np.repeat(track_y[0],",
"matrix, 0, 10) t = 0.005 forward_tol = 10000 beta = np.array([1, 1])",
"3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(np.min(track[:,",
"flag=False, track is returned. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back",
"back tol is not met and f_new < track[-2][1] \"\"\" np.random.seed(329998) n =",
"== np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) for j",
"assert(total_func_evals == 0) def test_9(): \"\"\" Test for backward_tracking - back_tol is met.",
"track_t = np.array([0, 1, 0.5]) design_matrix_step = np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t), np.array(track_t) ** 2)).T",
"2, 4]))) def test_20(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120],",
"test_21(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5, 80]]) track_method",
"m = 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 1,",
"np.array([100, 0, 0]))) assert(np.all(design_matrix_step[1, :] == np.array([100, 1, 1]))) assert(np.all(design_matrix_step[2, :] == np.array([100,",
"*func_args) track = np.array([[0, f_old], [step, f_new]]) test_track, count_func_evals, flag = (est_dir.compute_forward (step,",
"0, 5) region = 1 step = 0.17741338024633116 forward_tol = 1000000 no_vars =",
"= 0.005 forward_tol = 10000 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args)",
"len(track_t)), np.array(track_t), np.array(track_t) ** 2)).T assert(np.all(design_matrix_step[0, :] == np.array([100, 0, 0]))) assert(np.all(design_matrix_step[1, :]",
"= 1000000 back_tol = 0.000000001 no_vars = m region = 1 beta, func_evals",
"0.000001 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f,",
"== step) if j == (len(track) - 1): assert(track[j][1] > track[j - 1][1])",
"== False) assert(count_func_evals > 0) for j in range(len(test_track)): assert(test_track[j, 0] < forward_tol)",
"np.array([[0, 100], [1, 80], [2, 160], [4, 40], [8, 20], [16, 90]]) track_method",
"= 1 no_vars = m region = 1 beta, func_evals = est_dir.compute_direction_XY(n, m,",
"f, func_args)) assert(flag == False) assert(track[2][1] < track[1][1] < track[0][1]) assert(total_func_evals == 1)",
"(est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f, func_args)) assert(np.all(track == track_new)) assert(flag",
"= m region = 1 beta, func_evals = est_dir.compute_direction_XY(n, m, centre_point, f, func_args,",
"track[1][0]) def test_11(): \"\"\" Test for backward_tracking - back tol is not met",
"np.array([[0, f_old], [step, f_new]]) track, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track,",
"0, 5) step = 0.005 forward_tol = 10000 back_tol = 0.0000001 beta =",
"== track_new)) assert(flag == False) assert(total_func_evals == 0) def test_9(): \"\"\" Test for",
"4) == np.round(t, 4)) t = t / 2 assert(np.min(track[:, 1]) < track[1][0])",
"for j in range(1, len(track)): assert(track[j][0] == step) step = step * const_forward",
"func_args = (minimizer, matrix, 0, 0.0000001) step = 1 forward_tol = 100000 beta",
"0.25]))) OLS = (np.linalg.inv(design_matrix_step.T @ design_matrix_step) @ design_matrix_step.T @ track_y) check = -OLS[1]",
"< track[1][1]) assert(count_func_evals == 0) def test_10(): \"\"\" Test for backward_tracking - back",
"m)) assert(track[0][0] == 0) assert(track[1][0] == t) assert(track[1][0] < track[1][1]) assert(count_func_evals == 0)",
"* beta, *func_args) assert(f_old > f_new) track = np.array([[0, f_old], [step, f_new]]) track,",
"len(track) - 1: assert(track[j][1] < track[j-1][1]) else: assert(track[j][1] > track[j-1][1]) def test_8(): \"\"\"",
"est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 10, (m,)) centre_point = np.random.uniform(0, 10,",
"est_dir def test_1(): \"\"\" Test for compute_forward() - check for flag=True. \"\"\" np.random.seed(90)",
"count_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(track.shape",
"f(np.copy(centre_point) - t * beta, *func_args) assert(f_old < f_new) track, total_func_evals = (est_dir.backward_tracking",
"== False) for j in range(1, len(track)): assert(track[j-1][1] > track[j][1]) def test_6(): \"\"\"",
"for j in range(1, len(track)): if j == (len(track) - 1): assert(track[j][1] >",
"/ const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, )) matrix =",
"assert(track[j-1][1] > track[j][1]) def test_6(): \"\"\" Test for forward_tracking - forward_tol met. \"\"\"",
"100 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 10, (m,)) centre_point",
"f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,)) centre_point = np.array([25, 25])",
"np.array([20, 20]) matrix = np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001) step =",
"*func_args) f_new = f(np.copy(centre_point) - t * beta, *func_args) assert(f_old < f_new) track,",
"else: assert(track[j][1] > track[j - 1][1]) def test_2(): \"\"\" Test for compute_forward() -",
"0.005 forward_tol = 10 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new",
"80], [2, 160], [4, 40], [8, 20], [16, 90]]) track_method = 'Forward' track_y,",
"0.5]))) def test_21(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5,",
"0) assert(flag == True) for j in range(1, len(track)): if j == (len(track)",
"track is returned. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back =",
"track, centre_point, beta, f, func_args)) assert(f_old > f_new) assert(count_func_evals == len(track) - 2)",
"= f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) assert(f_old >",
"is met. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back = 0.5",
"= 0.5 const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.array([25,",
"== np.round(t, 3)) assert(total_func_evals > 0) assert(flag == True) for j in range(1,",
"f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 1, (m, )) centre_point",
":] == np.array([100, 0.5, 0.25]))) OLS = (np.linalg.inv(design_matrix_step.T @ design_matrix_step) @ design_matrix_step.T @",
"that correct step size is returned, when back_tol is met. \"\"\" np.random.seed(32964) m",
"- back tol is not initially met, f_new < track[-2][1] and eventaully back",
"np.array(track_t), np.array(track_t) ** 2)).T assert(np.all(design_matrix_step[0, :] == np.array([100, 0, 0]))) assert(np.all(design_matrix_step[1, :] ==",
"minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10, m) func_args",
"1 back_tol = 1 beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) f_new",
"0, 5) step = 1 back_tol = 1 forward_tol = 100000 beta =",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) t = 1 back_tol",
"def test_1(): \"\"\" Test for compute_forward() - check for flag=True. \"\"\" np.random.seed(90) m",
"= np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args",
"17001.993794080016 back_tol = 0.000000001 no_vars = m region = 1 beta, func_evals =",
"for backward_tracking - back tol is not initially met, f_new < track[-2][1] and",
"== t) assert(track[1][0] < track[1][1]) assert(count_func_evals == 0) def test_10(): \"\"\" Test for",
"check for flag=True. \"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise const_back =",
"1]))) assert(np.all(design_matrix_step[2, :] == np.array([100, 0.5, 0.25]))) OLS = (np.linalg.inv(design_matrix_step.T @ design_matrix_step) @",
"2 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1 / const_back) minimizer",
"= 1 forward_tol = 100000 back_tol = 0.0000001 beta = np.array([0.0001, 0.0001]) f_old",
"np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old,",
"backward_tracking - back tol is not met and f_new > track[-2][1]. \"\"\" np.random.seed(32964)",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) region = 1 step",
"matrix, 0, 0.0000001) step = 0.5 forward_tol = 1.5 beta = np.array([0.0001, 0.0001])",
"(minimizer, matrix, 0, 5) step = 0.05 forward_tol = 1000000 no_vars = 10",
"= 6 m = 2 f = est_dir.quad_f_noise const_back = 0.5 minimizer =",
")) centre_point = np.random.uniform(0, 1, (m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args",
"= np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point,",
"= 1 back_tol = 1 forward_tol = 100000 beta = np.array([200, 200]) f_old",
"assert(track[j - 1][1] > track[j][1]) def test_4(): \"\"\" Test for forward_tracking - forward_tol",
"= 0.075 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point,",
"> 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_12(): \"\"\" Test for backward_tracking",
"assert(func_evals == 16) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step *",
"(m, )) assert(func_val == 40) def test_23(): \"\"\"Test for check_func_val_coeffs when func_val <=",
"= 0.5 minimizer = np.random.uniform(0, 10, (m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix",
"for combine_tracking - check that correct step size is returned, when forward_tol is",
"assert(flag == False) assert(track[2][1] < track[1][1] < track[0][1]) assert(total_func_evals == 1) def test_7():",
"back_tol is not met. \"\"\" np.random.seed(32964) n = 6 m = 2 f",
"f_new = f(np.copy(centre_point) - t * beta, *func_args) assert(f_old < f_new) track, total_func_evals",
"< track[1][0]) def test_11(): \"\"\" Test for backward_tracking - back tol is not",
"combine_tracking - check that correct step size is returned, when back_tol is not",
"when func_val <= track_y[1].\"\"\" np.random.seed(91) m = 10 f = est_dir.quad_f_noise const_back =",
"(m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_16(): \"\"\" Test for",
"np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5)",
"Test for compute_forward() - check for flag=True. \"\"\" np.random.seed(90) m = 10 f",
"func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_16():",
"\"\"\" Test for backward_tracking - back tol is not met and f_new <",
"3)) assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_12(): \"\"\" Test",
"(len(track) - 1): assert(track[j][1] > track[j - 1][1]) else: assert(track[j - 1][1] >",
"= np.random.uniform(0, 1, (m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer,",
"@ design_matrix_step.T @ track_y) check = -OLS[1] / (2 * OLS[2]) opt_t =",
"assert(np.all(track_y == np.array([100, 20, 90]))) assert(np.all(track_t == np.array([0, 8, 16]))) def test_19(): \"\"\"Test",
"func_args)) assert(upd_point.shape == (m, )) assert(func_val == 40) def test_23(): \"\"\"Test for check_func_val_coeffs",
"* const_forward if j < len(track) - 1: assert(track[j][1] < track[j - 1][1])",
"= (minimizer, matrix, 0, 5) step = 10 forward_tol = 1000000 back_tol =",
"track_new, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f, func_args))",
"Test for combine_tracking - check that correct step size is returned, when forward_tol",
"1): assert(track[j][1] > track[j - 1][1]) else: assert(track[j - 1][1] > track[j][1]) def",
"0.075 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f,",
"test_9(): \"\"\" Test for backward_tracking - back_tol is met. \"\"\" np.random.seed(32964) m =",
"met initially, f_new < track[-2][1] and eventually forward_tol is met. \"\"\" np.random.seed(25) m",
"assert(f_old > f_new) assert(count_func_evals == len(track) - 2) assert(flag == True) assert(track[0][0] ==",
"beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking",
"(minimizer, matrix, 0, 0.1) step = 0.001 back_tol = 0.000001 no_vars = 10",
"(minimizer, matrix, 0, 5) step = 1 back_tol = 1 forward_tol = 100000",
"= 0.5 const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0,",
"f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10,",
"50]) track_t = np.array([0, 1, 0.5]) design_matrix_step = np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t), np.array(track_t) **",
"centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer,",
"> 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_13(): \"\"\"Test for compute_coeffs\"\"\" track_y",
"forward_tol not met and f_new < track[-2][1]. \"\"\" np.random.seed(25) m = 2 f",
"const_back, back_tol, const_forward, forward_tol, f, func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int)",
"(est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(len(track) - 1",
"Test for backward_tracking - back_tol is met. \"\"\" np.random.seed(32964) m = 2 f",
"[2, 70], [4, 90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y",
"const_back) minimizer = np.ones((m,)) centre_point = np.array([20, 20]) matrix = np.identity(m) func_args =",
"== np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(flag ==",
"flag=True and f_new >= track[-2][1] \"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise",
"(m, )) centre_point = np.random.uniform(0, 1, (m, )) matrix = est_dir.quad_func_params(1, 10, m)",
"> f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward,",
"97.688932389756 back_tol = 0.000000001 no_vars = m region = 1 beta, func_evals =",
"= 10000 back_tol = 0.0000001 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args)",
"= 1 step = 0.17741338024633116 forward_tol = 1000000 no_vars = 10 beta, func_evals",
"<= track_y[1].\"\"\" np.random.seed(91) m = 10 f = est_dir.quad_f_noise const_back = 0.5 const_forward",
"track_method) assert(np.all(track_y == np.array([100, 70, 90]))) assert(np.all(track_t == np.array([0, 2, 4]))) def test_20():",
"f_new) track = np.array([[0, f_old], [step, f_new]]) track, total_func_evals, flag = (est_dir.compute_backward (step,",
"forward_tracking - flag=True and f_new >= track[-2][1] \"\"\" np.random.seed(90) m = 10 f",
"== 0) for j in range(1, len(track)): assert(track[j][0] == step) step = step",
"\"\"\" np.random.seed(32964) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward =",
"(centre_point, f_old, beta, step, const_back, back_tol, const_forward, forward_tol, f, func_args)) assert(upd_point.shape == (m,",
"step * beta, *func_args) assert(f_old > f_new) track = np.array([[0, f_old], [step, f_new]])",
"beta, *func_args) track = np.array([[0, f_old], [step, f_new]]) test_track, count_func_evals, flag = (est_dir.compute_forward",
"20, 90]))) assert(np.all(track_t == np.array([0, 8, 16]))) def test_19(): \"\"\"Test for arrange_track_y_t\"\"\" track",
"= step * const_forward if j < len(track) - 1: assert(track[j][1] < track[j",
"step * beta, *func_args) track = np.array([[0, f_old], [step, f_new]]) test_track, count_func_evals, flag",
"forward_tol, f, func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val == f_old)",
"design_matrix_step = np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t), np.array(track_t) ** 2)).T assert(np.all(design_matrix_step[0, :] == np.array([100, 0,",
"step = 10 forward_tol = 1000000 back_tol = 0.000000001 no_vars = m region",
"(minimizer, matrix, 0, 0.0000001) step = 1 forward_tol = 100000 beta = np.array([0.0001,",
"Test for forward_tracking - flag=True and f_new >= track[-2][1] \"\"\" np.random.seed(90) m =",
"1000000 back_tol = 0.000000001 no_vars = m region = 1 beta, func_evals =",
"0.0000001) step = 0.5 forward_tol = 1.5 beta = np.array([0.0001, 0.0001]) f_old =",
"= est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 70, 90]))) assert(np.all(track_t == np.array([0, 2, 4])))",
"est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 90, 110]))) assert(np.all(track_t == np.array([0, 0.25, 0.5]))) def",
"= f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) track =",
"centre_point, beta, f, func_args)) assert(upd_point.shape == (m, )) assert(func_val == 40) def test_23():",
"(m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) t",
"* 2 assert(np.round(track[j][0], 3) == step) if j == (len(track) - 1): assert(track[j][1]",
"(est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f, func_args)) assert(total_func_evals == len(track) -",
"5))) def test_14(): \"\"\" Test for combine_tracking - check that correct step size",
"back tol is not met and f_new > track[-2][1]. \"\"\" np.random.seed(32964) n =",
"back_tol = 0.0000001 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val,",
"np.random.seed(32964) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1",
"\"\"\"Test for check_func_val_coeffs when func_val <= track_y[1].\"\"\" np.random.seed(91) m = 10 f =",
"upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f, func_args)) assert(upd_point.shape == (m,",
"back_tol, track, centre_point, beta, f, func_args)) assert(total_func_evals == len(track) - 2) assert(flag ==",
"step size is returned, when forward_tol is not met. \"\"\" np.random.seed(3291) m =",
"f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) assert(f_old",
"f_new) track, total_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol, f,",
"1 beta, func_evals = est_dir.compute_direction_XY(n, m, centre_point, f, func_args, no_vars, region) assert(func_evals ==",
"that correct step size is returned when forward_tol is met. \"\"\" np.random.seed(90) m",
"np.array([[0, f_old], [step, f_new]]) track_new, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track,",
"3)) assert(total_func_evals > 0) for j in range(1, len(track)): assert(np.round(track[j][0], 4) == np.round(t,",
"arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5, 80]]) track_method = 'Backward' track_y,",
"*func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) track = np.array([[0, f_old],",
"*func_args) assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new,",
"m) func_args = (minimizer, matrix, 0, 5) t = 97.688932389756 back_tol = 0.000000001",
"step) if j == (len(track) - 1): assert(track[j][1] > track[j - 1][1]) else:",
"[2, 40], [4, 90]]) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method,",
"f(np.copy(centre_point) - step * beta, *func_args) assert(f_old > f_new) track = np.array([[0, f_old],",
"5) region = 1 step = 0.17741338024633116 forward_tol = 1000000 no_vars = 10",
"t) assert(track[1][0] < track[1][1]) assert(count_func_evals == 0) def test_10(): \"\"\" Test for backward_tracking",
"= est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 80, 120]))) assert(np.all(track_t == np.array([0, 0.5, 1])))",
"back_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3))",
"= (minimizer, matrix, 0, 60) step = 1.8251102718712913 no_vars = 10 region =",
"tol is not initially met, f_new < track[-2][1] and eventaully back tol is",
"numpy as np import est_dir def test_1(): \"\"\" Test for compute_forward() - check",
"centre_point, beta, f, func_args)) assert(f_old > f_new) assert(count_func_evals == len(track) - 2) assert(flag",
"10, (m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 1000)",
"step = 1 back_tol = 1 forward_tol = 100000 beta = np.array([200, 200])",
"is returned. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back = 0.5",
"0] < forward_tol) if j >= 1: assert(test_track[j, 1] < test_track[j - 1,",
"forward_tracking - forward_tol not met initially, f_new < track[-2][1] and eventually forward_tol is",
"= (1 / const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix",
"func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_18():",
"track[1][1] < track[0][1]) assert(total_func_evals == 1) def test_7(): \"\"\" Test for compute_backward -",
"range(1, len(track)): assert(track[j-1][1] > track[j][1]) def test_6(): \"\"\" Test for forward_tracking - forward_tol",
"beta, const_forward, forward_tol, f, func_args)) assert(flag == False) assert(track[2][1] < track[1][1] < track[0][1])",
"False) assert(track[2][1] < track[1][1] < track[0][1]) assert(total_func_evals == 1) def test_7(): \"\"\" Test",
"import est_dir def test_1(): \"\"\" Test for compute_forward() - check for flag=True. \"\"\"",
"forward_tol = 10 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new =",
"track, centre_point, beta, f, func_args)) assert(total_func_evals == len(track) - 2) assert(flag == True)",
"design_matrix_step.T @ track_y) check = -OLS[1] / (2 * OLS[2]) opt_t = est_dir.compute_coeffs(track_y,",
"assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_15(): \"\"\"",
"compute_forward() - check for flag=True. \"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise",
"not initially met, f_new < track[-2][1] and eventaully back tol is met. \"\"\"",
"func_args)) assert(len(track) - 1 == total_func_evals) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3)",
"total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta, step, const_back, back_tol, const_forward, forward_tol, f, func_args))",
"test_15(): \"\"\" Test for combine_tracking - check that correct step size is returned,",
"[16, 90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100,",
"step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag == True) assert(total_func_evals >",
"1][1] > track[j][1]) def test_4(): \"\"\" Test for forward_tracking - forward_tol not met",
"flag=True. \"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise const_back = 0.5 const_forward",
"10, m) func_args = (minimizer, matrix, 0, 5) step = 0.05 forward_tol =",
"t = 0.005 forward_tol = 10000 beta = np.array([1, 1]) f_old = f(np.copy(centre_point),",
"check that correct step size is returned, when back_tol is not met. \"\"\"",
"func_args = (minimizer, matrix, 0, 10) t = 0.005 forward_tol = 10000 beta",
"= np.array([[0, f_old], [step, f_new]]) test_track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol,",
"func_args, no_vars, region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals",
"0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_12(): \"\"\" Test for backward_tracking -",
"j < len(track) - 1: assert(track[j][1] < track[j-1][1]) else: assert(track[j][1] > track[j-1][1]) def",
"/ const_back) minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10,",
"== False) assert(track[2][1] < track[1][1] < track[0][1]) assert(total_func_evals == 1) def test_7(): \"\"\"",
"that correct step size is returned, when forward_tol is not met. \"\"\" np.random.seed(3291)",
"check that when flag=False, original track is returned. \"\"\" np.random.seed(90) m = 100",
"def test_15(): \"\"\" Test for combine_tracking - check that correct step size is",
"back_tol is met. \"\"\" np.random.seed(32964) m = 2 f = est_dir.quad_f_noise const_back =",
"5) step = 1 back_tol = 1 forward_tol = 100000 beta = np.array([200,",
"= 17001.993794080016 back_tol = 0.000000001 no_vars = m region = 1 beta, func_evals",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step = 10 forward_tol",
"track[j - 1][1]) else: assert(track[j - 1][1] > track[j][1]) def test_4(): \"\"\" Test",
"f_new = f(np.copy(centre_point) - step * beta, *func_args) track, total_func_evals, flag = (est_dir.forward_tracking",
"f_old) def test_17(): \"\"\" Test for combine_tracking - check that correct step size",
"track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 70, 90])))",
"'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f, func_args)) assert(upd_point.shape ==",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step = 0.05 forward_tol",
"> f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, t, f_old, f_new, beta, const_forward,",
"f_new, beta, const_forward, forward_tol, f, func_args)) assert(len(track) - 1 == total_func_evals) assert(np.round(track[0][0], 3)",
"0.005 forward_tol = 10000 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new",
"120], [0.5, 110], [0.25, 90]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method)",
"check_func_val_coeffs when func_val <= track_y[1].\"\"\" np.random.seed(91) m = 10 f = est_dir.quad_f_noise const_back",
"assert(func_val < f_old) def test_15(): \"\"\" Test for combine_tracking - check that correct",
"np.random.uniform(0, 1, (m, )) centre_point = np.random.uniform(0, 1, (m, )) matrix = est_dir.quad_func_params(1,",
"func_args = (minimizer, matrix, 0, 1000) t = 17001.993794080016 back_tol = 1 no_vars",
"step * const_back if j < len(track) - 1: assert(track[j][1] < track[j-1][1]) else:",
"func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_15():",
"beta, const_forward, forward_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) ==",
"step * 2 assert(np.round(track[j][0], 3) == step) if j == (len(track) - 1):",
"step) step = step * const_forward if j < len(track) - 1: assert(track[j][1]",
"test_7(): \"\"\" Test for compute_backward - check that when flag=True, track is updated.",
"16) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args)",
"3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(flag == False) for",
"in range(2, len(track)): step = step * 2 assert(np.round(track[j][0], 3) == step) if",
"total_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(np.round(track[0][0],",
"step = 1.8251102718712913 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m,",
"beta, f, func_args)) assert(np.all(track == track_new)) assert(flag == False) assert(total_func_evals == 0) def",
"[2, 160], [4, 40], [8, 20], [16, 90]]) track_method = 'Forward' track_y, track_t",
"matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 0.1) step =",
"track = np.array([[0, 100], [1, 120], [0.5, 80]]) track_method = 'Backward' track_y, track_t",
"0.5]) design_matrix_step = np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t), np.array(track_t) ** 2)).T assert(np.all(design_matrix_step[0, :] == np.array([100,",
"== np.array([0, 0.25, 0.5]))) def test_21(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100],",
")) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) region",
"tol is met. \"\"\" np.random.seed(329998) n = 20 m = 100 f =",
"assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(step, 3)) assert(flag == True)",
"np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t), np.array(track_t) ** 2)).T assert(np.all(design_matrix_step[0, :] == np.array([100, 0, 0]))) assert(np.all(design_matrix_step[1,",
"for compute_backward - check that when flag=False, original track is returned. \"\"\" np.random.seed(90)",
"size is returned, when back_tol is not met. \"\"\" np.random.seed(32964) n = 6",
"for j in range(2, len(track)): step = step * 2 assert(np.round(track[j][0], 3) ==",
"not met and f_new < track[-2][1] \"\"\" np.random.seed(329998) n = 20 m =",
"0) def test_9(): \"\"\" Test for backward_tracking - back_tol is met. \"\"\" np.random.seed(32964)",
"assert(track[1][0] == t) assert(track[1][0] < track[1][1]) assert(count_func_evals == 0) def test_10(): \"\"\" Test",
"< track[0][1]) assert(total_func_evals == 1) def test_7(): \"\"\" Test for compute_backward - check",
"2 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,)) centre_point = np.random.uniform(0,",
"backward_tracking - back tol is not met and f_new < track[-2][1] \"\"\" np.random.seed(329998)",
"const_back if j < len(track) - 1: assert(track[j][1] < track[j-1][1]) else: assert(track[j][1] >",
"0.0001]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta,",
"centre_point, f, func_args, no_vars, region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) f_new",
"t = 1 back_tol = 1 beta = np.array([200, 200]) f_old = f(np.copy(centre_point),",
"< track[-2][1] and eventually forward_tol is met. \"\"\" np.random.seed(25) m = 2 f",
"for forward_tracking - forward_tol not met initially, f_new < track[-2][1] and eventually forward_tol",
"test_14(): \"\"\" Test for combine_tracking - check that correct step size is returned",
"0.5 const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.array([25, 25])",
"assert(np.all(track_t == np.array([0, 8, 16]))) def test_19(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0,",
"= 0.05 forward_tol = 1000000 no_vars = 10 region = 1 beta, func_evals",
"correct step size is returned, when forward_tol is not met. \"\"\" np.random.seed(3291) m",
"< f_old) def test_15(): \"\"\" Test for combine_tracking - check that correct step",
"track_method, centre_point, beta, f, func_args)) assert(upd_point.shape == (m, )) assert(func_val == 40) def",
"< forward_tol) if j >= 1: assert(test_track[j, 1] < test_track[j - 1, 1])",
"0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_13(): \"\"\"Test for compute_coeffs\"\"\" track_y =",
"10 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region) assert(func_evals == 16)",
"-OLS[1] / (2 * OLS[2]) opt_t = est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check, 5) == np.round(opt_t,",
"func_args, no_vars, region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point)",
"- step * beta, *func_args) track = np.array([[0, f_old], [step, f_new]]) track, count_func_evals,",
"returned. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward",
"is updated. \"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise const_back = 0.5",
"1 step = 0.17741338024633116 forward_tol = 1000000 no_vars = 10 beta, func_evals =",
"track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta, f, func_args))",
"(est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag == True)",
"m) func_args = (minimizer, matrix, 0, 1000) t = 17001.993794080016 back_tol = 0.000000001",
"= f(np.copy(centre_point) - step * beta, *func_args) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point,",
"count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta, f, func_args)) assert(f_old",
"True) for j in range(2, len(track)): step = step * 2 assert(np.round(track[j][0], 3)",
"1: assert(test_track[j, 1] < test_track[j - 1, 1]) assert(test_track[j, 0] * const_forward >",
"3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(flag",
"in range(1, len(track)): assert(track[j][0] == step) step = step * const_back if j",
"assert(track[2][1] < track[1][1] < track[0][1]) assert(total_func_evals == 1) def test_7(): \"\"\" Test for",
"np.array([[0, 100], [1, 120], [0.5, 80]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track,",
"def test_22(): \"\"\"Test for check_func_val_coeffs when func_val > track_y[1].\"\"\" np.random.seed(90) m = 10",
"* beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, t,",
"range(1, len(track)): assert(track[j][0] == step) step = step * const_back if j <",
"assert(f_old < f_new) track, count_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back,",
"f_new) assert(count_func_evals == len(track) - 2) assert(flag == True) assert(track[0][0] == 0) for",
"forward_tol = 10000 back_tol = 0.0000001 beta = np.array([1, 1]) f_old = f(np.copy(centre_point),",
"= (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f, func_args)) assert(total_func_evals == len(track)",
"0, 0]))) assert(np.all(design_matrix_step[1, :] == np.array([100, 1, 1]))) assert(np.all(design_matrix_step[2, :] == np.array([100, 0.5,",
"= 1 forward_tol = 100000 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args)",
"3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(step, 3)) assert(flag == True) for",
"check that when flag=False, track is returned. \"\"\" np.random.seed(90) m = 2 f",
"= 1 forward_tol = 100000 beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args)",
"(m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step",
":] == np.array([100, 1, 1]))) assert(np.all(design_matrix_step[2, :] == np.array([100, 0.5, 0.25]))) OLS =",
"f_new = f(np.copy(centre_point) - t * beta, *func_args) assert(f_old > f_new) track, total_func_evals,",
"1, 1]) assert(test_track[j, 0] * const_forward > forward_tol) def test_3(): \"\"\" Test for",
"= 0.000000001 no_vars = m region = 1 beta, func_evals = est_dir.compute_direction_XY(n, m,",
"forward_tol, f, func_args)) assert(flag == False) assert(track[2][1] < track[1][1] < track[0][1]) assert(total_func_evals ==",
"met. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward",
"step = 0.05 forward_tol = 1000000 no_vars = 10 region = 1 beta,",
"assert(track[j-1][1] > track[j][1]) def test_5(): \"\"\" Test for forward_tracking - forward_tol not met",
"0.5 forward_tol = 1.5 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new",
"assert(f_old < f_new) track, total_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back,",
"np.round(opt_t, 5))) def test_14(): \"\"\" Test for combine_tracking - check that correct step",
"np.random.seed(90) m = 10 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1",
"\"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5, 80]]) track_method =",
"1]) < track[:, 1][0]) def test_12(): \"\"\" Test for backward_tracking - back tol",
"= 100000 back_tol = 0.0000001 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args)",
"= np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001) step = 0.5 forward_tol =",
"test_11(): \"\"\" Test for backward_tracking - back tol is not met and f_new",
"(1 / const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, )) matrix",
"np.round(t, 3)) assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_12(): \"\"\"",
"back tol is not initially met, f_new < track[-2][1] and eventaully back tol",
"track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 90, 110]))) assert(np.all(track_t == np.array([0,",
"= est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 1, (m, )) centre_point =",
"5) step = 0.005 forward_tol = 10000 back_tol = 0.0000001 beta = np.array([1,",
"region = 1 beta, func_evals = est_dir.compute_direction_XY(n, m, centre_point, f, func_args, no_vars, region)",
"/ const_back) minimizer = np.ones((m,)) centre_point = np.array([20, 20]) matrix = np.identity(m) func_args",
"np.array([100, 0.5, 0.25]))) OLS = (np.linalg.inv(design_matrix_step.T @ design_matrix_step) @ design_matrix_step.T @ track_y) check",
"\"\"\" np.random.seed(32964) m = 2 f = est_dir.quad_f_noise const_back = 0.5 minimizer =",
"size is returned when forward_tol is met. \"\"\" np.random.seed(90) m = 2 f",
"f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag == True) assert(total_func_evals > 0) track_method",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) t = 1",
"assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta,",
"forward_tol is met. \"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise const_back =",
"test_2(): \"\"\" Test for compute_forward() - check that when flag=False, track is returned.",
"when func_val > track_y[1].\"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise minimizer =",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 60) step = 1.8251102718712913 no_vars",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step = 1",
"\"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5, 110], [0.25, 90]])",
"= 0.17741338024633116 forward_tol = 1000000 no_vars = 10 beta, func_evals = est_dir.compute_direction_LS(m, centre_point,",
"*func_args) assert(f_old > f_new) track = np.array([[0, 100], [1, 160], [2, 40], [4,",
"func_args = (minimizer, matrix, 0, 5) region = 1 step = 0.17741338024633116 forward_tol",
"assert(track[j][1] > track[j-1][1]) def test_8(): \"\"\" Test for compute_backward - check that when",
"= 1 back_tol = 1 beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args)",
"matrix, 0, 0.0000001) step = 1 forward_tol = 100000 back_tol = 0.0000001 beta",
"when forward_tol is met. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back",
"= 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars,",
"10, m) func_args = (minimizer, matrix, 0, 0.1) step = 0.001 back_tol =",
"f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(track.shape == (2, m)) assert(track[0][0] ==",
"f, func_args)) assert(flag == True) assert(total_func_evals > 0) track_method = 'Forward' upd_point, func_val",
"= np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix,",
"0, 1000) t = 17001.993794080016 back_tol = 0.000000001 no_vars = m region =",
"f, func_args, no_vars, region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val,",
"(minimizer, matrix, 0, 5) step = 10 forward_tol = 1000000 back_tol = 0.000000001",
"= np.random.uniform(0, 20, (m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer,",
"track is returned. \"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise const_back =",
"200]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta,",
"track_y[1].\"\"\" np.random.seed(91) m = 10 f = est_dir.quad_f_noise const_back = 0.5 const_forward =",
"[4, 90]]) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta,",
"track[-2][1] \"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise const_back = 0.5 const_forward",
"100 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 1, (m, ))",
"[8, 20], [16, 90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y",
"j >= 1: assert(test_track[j, 1] < test_track[j - 1, 1]) assert(test_track[j, 0] *",
"total_func_evals) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(step, 3)) assert(flag ==",
"80, 120]))) assert(np.all(track_t == np.array([0, 0.5, 1]))) def test_22(): \"\"\"Test for check_func_val_coeffs when",
"0.000000001 no_vars = m region = 1 beta, func_evals = est_dir.compute_direction_XY(n, m, centre_point,",
"= (minimizer, matrix, 0, 0.1) step = 0.1 back_tol = 0.075 no_vars =",
"forward_tol = 100000 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new =",
"= 0.5 minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10,",
"f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(len(track) - 1 == total_func_evals) assert(np.round(track[0][0],",
">= track[-2][1] \"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise const_back = 0.5",
"* const_forward > forward_tol) def test_3(): \"\"\" Test for forward_tracking - flag=True and",
"centre_point, beta, f, func_args)) assert(np.all(track == track_new)) assert(flag == False) assert(total_func_evals == 0)",
"np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args =",
"(minimizer, matrix, 0, 5) step = 0.01 forward_tol = 1000000 no_vars = 10",
"f_new, beta, const_forward, forward_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3)",
"1: assert(track[j][1] < track[j-1][1]) else: assert(track[j][1] > track[j-1][1]) def test_8(): \"\"\" Test for",
"beta, const_forward, forward_tol, f, func_args)) assert(len(track) - 1 == total_func_evals) assert(np.round(track[0][0], 3) ==",
"= np.array([0, 1, 0.5]) design_matrix_step = np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t), np.array(track_t) ** 2)).T assert(np.all(design_matrix_step[0,",
"= 1 beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point)",
"assert(total_func_evals == len(track) - 2) assert(flag == True) assert(track[0][0] == 0) for j",
"f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta, step, const_back, back_tol,",
"assert(track[j][1] > track[j - 1][1]) def test_2(): \"\"\" Test for compute_forward() - check",
"assert(func_val == 40) def test_23(): \"\"\"Test for check_func_val_coeffs when func_val <= track_y[1].\"\"\" np.random.seed(91)",
"is met. \"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise const_back = 0.5",
"= 10 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1 / const_back)",
"(centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(len(track) - 1 ==",
"test_13(): \"\"\"Test for compute_coeffs\"\"\" track_y = np.array([100, 200, 50]) track_t = np.array([0, 1,",
"t * beta, *func_args) assert(f_old < f_new) track, count_func_evals = (est_dir.backward_tracking (centre_point, t,",
"j in range(1, len(track)): if j == (len(track) - 1): assert(track[j][1] > track[j-1][1])",
"== np.array([100, 0.5, 0.25]))) OLS = (np.linalg.inv(design_matrix_step.T @ design_matrix_step) @ design_matrix_step.T @ track_y)",
"assert(np.all(track == track_new)) assert(flag == False) assert(total_func_evals == 0) def test_9(): \"\"\" Test",
"track, count_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol, f, func_args))",
"- 1][1]) else: assert(track[j][1] > track[j - 1][1]) def test_2(): \"\"\" Test for",
"\"\"\" Test for compute_forward() - check that when flag=False, track is returned. \"\"\"",
"is int) assert(func_val < f_old) def test_15(): \"\"\" Test for combine_tracking - check",
"def test_3(): \"\"\" Test for forward_tracking - flag=True and f_new >= track[-2][1] \"\"\"",
"assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(flag == False) for j",
"np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(step, 3)) assert(flag == True) for j in",
"for combine_tracking - check that correct step size is returned when forward_tol is",
"backward_tracking - back_tol is met. \"\"\" np.random.seed(32964) m = 2 f = est_dir.quad_f_noise",
"track = np.array([[0, f_old], [step, f_new]]) track_new, total_func_evals, flag = (est_dir.compute_backward (step, const_back,",
"(m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 60)",
"track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 70, 90]))) assert(np.all(track_t == np.array([0, 2,",
"0] * const_forward > forward_tol) def test_3(): \"\"\" Test for forward_tracking - flag=True",
"assert(func_val < f_old) def test_16(): \"\"\" Test for combine_tracking - check that correct",
"= (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(np.round(track[0][0], 3)",
"t, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3))",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step = 0.005",
"tol is not met and f_new < track[-2][1] \"\"\" np.random.seed(329998) n = 20",
"back_tol = 0.000000001 no_vars = m region = 1 beta, func_evals = est_dir.compute_direction_XY(n,",
"\"\"\" Test for compute_backward - check that when flag=True, track is updated. \"\"\"",
"for j in range(len(test_track)): assert(test_track[j, 0] < forward_tol) if j >= 1: assert(test_track[j,",
"not met and f_new > track[-2][1]. \"\"\" np.random.seed(32964) n = 6 m =",
"== n) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta,",
"j in range(2, len(track)): step = step * 2 assert(np.round(track[j][0], 3) == step)",
"is met. \"\"\" np.random.seed(32964) m = 2 f = est_dir.quad_f_noise const_back = 0.5",
"design_matrix_step) @ design_matrix_step.T @ track_y) check = -OLS[1] / (2 * OLS[2]) opt_t",
"assert(np.all(track_y == np.array([100, 90, 110]))) assert(np.all(track_t == np.array([0, 0.25, 0.5]))) def test_21(): \"\"\"Test",
"np.ones((m,)) centre_point = np.array([20, 20]) matrix = np.identity(m) func_args = (minimizer, matrix, 0,",
"beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, t, f_old,",
"- back tol is not met and f_new < track[-2][1] \"\"\" np.random.seed(329998) n",
"- forward_tol not met and f_new < track[-2][1]. \"\"\" np.random.seed(25) m = 2",
"minimizer = np.random.uniform(0, 1, (m, )) centre_point = np.random.uniform(0, 1, (m, )) matrix",
"eventually forward_tol is met. \"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise const_back",
"= -OLS[1] / (2 * OLS[2]) opt_t = est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check, 5) ==",
"assert(np.round(track[j][0], 4) == np.round(t, 4)) t = t / 2 assert(np.min(track[:, 1]) <",
"f_old], [step, f_new]]) track, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point,",
"assert(type(total_func_evals) is int) assert(func_val < f_old) def test_15(): \"\"\" Test for combine_tracking -",
"m) func_args = (minimizer, matrix, 0, 5) step = 0.05 forward_tol = 1000000",
"as np import est_dir def test_1(): \"\"\" Test for compute_forward() - check for",
"10, m) func_args = (minimizer, matrix, 0, 5) step = 0.01 forward_tol =",
"is returned, when back_tol is met. \"\"\" np.random.seed(32964) m = 2 f =",
"len(track)): assert(track[j][0] == step) step = step * const_forward if j < len(track)",
"const_forward, forward_tol, f, func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val ==",
"track[j][1]) def test_5(): \"\"\" Test for forward_tracking - forward_tol not met initially, f_new",
"== 0) def test_9(): \"\"\" Test for backward_tracking - back_tol is met. \"\"\"",
"< track[-2][1] \"\"\" np.random.seed(329998) n = 20 m = 100 f = est_dir.quad_f_noise",
"100000 back_tol = 0.0000001 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) upd_point,",
")) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_16(): \"\"\" Test for combine_tracking",
"= f(np.copy(centre_point) - step * beta, *func_args) assert(f_old > f_new) track = np.array([[0,",
"(minimizer, matrix, 0, 60) step = 1.8251102718712913 no_vars = 10 region = 1",
"step = 0.5 forward_tol = 1.5 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point),",
"= (minimizer, matrix, 0, 5) step = 0.05 forward_tol = 1000000 no_vars =",
"np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta,",
"= np.array([[0, f_old], [step, f_new]]) track, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol,",
"forward_tol = 1.5 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new =",
")) assert(type(total_func_evals) is int) assert(func_val == f_old) def test_17(): \"\"\" Test for combine_tracking",
"compute_forward() - check that when flag=False, track is returned. \"\"\" np.random.seed(90) m =",
"(minimizer, matrix, 0, 5) region = 1 step = 0.17741338024633116 forward_tol = 1000000",
"const_forward, forward_tol, f, func_args)) assert(len(track) - 1 == total_func_evals) assert(np.round(track[0][0], 3) == np.round(0,",
"matrix, 0, 60) step = 1.8251102718712913 no_vars = 10 region = 1 beta,",
"1, 0.5]) design_matrix_step = np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t), np.array(track_t) ** 2)).T assert(np.all(design_matrix_step[0, :] ==",
"Test for compute_backward - check that when flag=True, track is updated. \"\"\" np.random.seed(90)",
"track[j-1][1]) def test_8(): \"\"\" Test for compute_backward - check that when flag=False, original",
"that when flag=True, track is updated. \"\"\" np.random.seed(90) m = 100 f =",
"[step, f_new]]) track_new, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta,",
"len(track) - 2) assert(flag == True) assert(track[0][0] == 0) for j in range(1,",
"(m, )) assert(type(total_func_evals) is int) assert(func_val == f_old) def test_17(): \"\"\" Test for",
"(est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f, func_args)) assert(upd_point.shape == (m, )) assert(func_val ==",
"if j == (len(track) - 1): assert(track[j][1] > track[j-1][1]) else: assert(track[j-1][1] > track[j][1])",
"f_old) def test_18(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2,",
"np.array([0, 8, 16]))) def test_19(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1,",
"0.5 minimizer = np.random.uniform(0, 1, (m, )) centre_point = np.random.uniform(0, 1, (m, ))",
"f, func_args)) assert(f_old > f_new) assert(count_func_evals == len(track) - 2) assert(flag == True)",
"= (minimizer, matrix, 0, 5) step = 0.005 forward_tol = 10000 back_tol =",
"= 6 m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward =",
"m) func_args = (minimizer, matrix, 0, 10) t = 0.005 forward_tol = 10000",
"backward_tracking - back tol is not initially met, f_new < track[-2][1] and eventaully",
"np.random.seed(90) m = 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0,",
"track[j][1]) def test_6(): \"\"\" Test for forward_tracking - forward_tol met. \"\"\" np.random.seed(90) m",
"minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10, m)",
"0, 60) step = 1.8251102718712913 no_vars = 10 region = 1 beta, func_evals",
"np.array([0, 0.5, 1]))) def test_22(): \"\"\"Test for check_func_val_coeffs when func_val > track_y[1].\"\"\" np.random.seed(90)",
"track[j - 1][1]) def test_2(): \"\"\" Test for compute_forward() - check that when",
"(step, const_back, back_tol, track, centre_point, beta, f, func_args)) assert(np.all(track == track_new)) assert(flag ==",
"110], [0.25, 90]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y ==",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step = 10",
"= (minimizer, matrix, 0, 5) step = 0.01 forward_tol = 1000000 no_vars =",
"f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag == True) assert(total_func_evals > 0)",
"1 forward_tol = 100000 back_tol = 0.0000001 beta = np.array([0.0001, 0.0001]) f_old =",
"np.array([[0, 100], [1, 80], [2, 70], [4, 90]]) track_method = 'Forward' track_y, track_t",
"90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 70,",
"beta, *func_args) track = np.array([[0, f_old], [step, f_new]]) track, count_func_evals, flag = (est_dir.compute_forward",
"assert(track.shape == (2, m)) assert(track[0][0] == 0) assert(track[1][0] == t) assert(track[1][0] < track[1][1])",
"def test_6(): \"\"\" Test for forward_tracking - forward_tol met. \"\"\" np.random.seed(90) m =",
"track = np.array([[0, f_old], [step, f_new]]) track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward,",
"import numpy as np import est_dir def test_1(): \"\"\" Test for compute_forward() -",
"= 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 80, 120]))) assert(np.all(track_t",
"> 0) assert(flag == False) for j in range(1, len(track)): assert(track[j-1][1] > track[j][1])",
"f(np.copy(centre_point) - step * beta, *func_args) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step,",
"f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) track, total_func_evals, flag",
"step = 0.01 forward_tol = 1000000 no_vars = 10 region = 1 beta,",
"== np.array([100, 80, 120]))) assert(np.all(track_t == np.array([0, 0.5, 1]))) def test_22(): \"\"\"Test for",
"f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta, *func_args) assert(f_old < f_new)",
"== 16) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta,",
"step size is returned when forward_tol is met. \"\"\" np.random.seed(90) m = 2",
"matrix, 0, 5) t = 97.688932389756 back_tol = 0.000000001 no_vars = m region",
"\"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2, 160], [4, 40],",
"(np.linalg.inv(design_matrix_step.T @ design_matrix_step) @ design_matrix_step.T @ track_y) check = -OLS[1] / (2 *",
"- t * beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking",
"1 == total_func_evals) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(step, 3))",
"np.random.seed(25) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1",
"\"\"\" np.random.seed(3291) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward =",
"np.random.seed(3291) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1",
"np.array([0, 2, 4]))) def test_20(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1,",
"f_new]]) test_track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta, f,",
"f_new]]) track, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f,",
"beta, *func_args) assert(f_old > f_new) track = np.array([[0, f_old], [step, f_new]]) track, total_func_evals,",
"(1 / const_back) minimizer = np.ones((m,)) centre_point = np.array([20, 20]) matrix = np.identity(m)",
"func_args = (minimizer, matrix, 0, 5) step = 10 forward_tol = 1000000 back_tol",
"np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old,",
"test_23(): \"\"\"Test for check_func_val_coeffs when func_val <= track_y[1].\"\"\" np.random.seed(91) m = 10 f",
"2)).T assert(np.all(design_matrix_step[0, :] == np.array([100, 0, 0]))) assert(np.all(design_matrix_step[1, :] == np.array([100, 1, 1])))",
"5) step = 10 forward_tol = 1000000 back_tol = 0.000000001 no_vars = m",
"- step * beta, *func_args) track = np.array([[0, f_old], [step, f_new]]) test_track, count_func_evals,",
"func_evals = est_dir.compute_direction_XY(n, m, centre_point, f, func_args, no_vars, region) assert(func_evals == n) f_old",
"== np.round(t, 3)) assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_12():",
"== n) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old,",
"0, 5) step = 0.05 forward_tol = 1000000 no_vars = 10 region =",
"> 0) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta,",
"f_new = f(np.copy(centre_point) - t * beta, *func_args) assert(f_old < f_new) track, count_func_evals",
"beta, f, func_args)) assert(upd_point.shape == (m, )) assert(func_val == 40) def test_23(): \"\"\"Test",
"10, (m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args",
"m) func_args = (minimizer, matrix, 0, 1000) t = 17001.993794080016 back_tol = 1",
"in range(1, len(track)): assert(np.round(track[j][0], 4) == np.round(t, 4)) t = t / 2",
"= 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region) assert(func_evals ==",
"flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f, func_args)) assert(np.all(track ==",
"= 1 beta, func_evals = est_dir.compute_direction_XY(n, m, centre_point, f, func_args, no_vars, region) assert(func_evals",
"f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) assert(f_old > f_new)",
"3) == step) if j == (len(track) - 1): assert(track[j][1] > track[j -",
"f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1 / const_back) minimizer =",
"track = np.array([[0, 100], [1, 120], [0.5, 110], [0.25, 90]]) track_method = 'Backward'",
"= np.random.uniform(0, 10, (m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10,",
"False) assert(count_func_evals > 0) for j in range(len(test_track)): assert(test_track[j, 0] < forward_tol) if",
"= np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point,",
"= 10000 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point)",
"for forward_tracking - forward_tol met. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise",
"100], [1, 80], [2, 160], [4, 40], [8, 20], [16, 90]]) track_method =",
"= 0.01 forward_tol = 1000000 no_vars = 10 region = 1 beta, func_evals",
"assert(func_val < f_old) def test_18(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1,",
"= 2 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,)) centre_point =",
"17001.993794080016 back_tol = 1 no_vars = m region = 1 beta, func_evals =",
"= (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f, func_args)) assert(np.all(track == track_new))",
"is int) assert(func_val < f_old) def test_18(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0,",
"m) func_args = (minimizer, matrix, 0, 60) step = 1.8251102718712913 no_vars = 10",
"- forward_tol not met initially, f_new < track[-2][1] and eventually forward_tol is met.",
"= (minimizer, matrix, 0, 0.0000001) step = 1 forward_tol = 100000 back_tol =",
"const_back, back_tol, track, centre_point, beta, f, func_args)) assert(total_func_evals == len(track) - 2) assert(flag",
"t = 17001.993794080016 back_tol = 0.000000001 no_vars = m region = 1 beta,",
"- 1): assert(track[j][1] > track[j-1][1]) else: assert(track[j-1][1] > track[j][1]) def test_5(): \"\"\" Test",
"when flag=False, track is returned. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise",
"when back_tol is met. \"\"\" np.random.seed(32964) m = 2 f = est_dir.quad_f_noise const_back",
"track[j-1][1]) else: assert(track[j-1][1] > track[j][1]) def test_5(): \"\"\" Test for forward_tracking - forward_tol",
"160], [4, 40], [8, 20], [16, 90]]) track_method = 'Forward' track_y, track_t =",
"1][0]) def test_12(): \"\"\" Test for backward_tracking - back tol is not initially",
"== 1) def test_7(): \"\"\" Test for compute_backward - check that when flag=True,",
"@ track_y) check = -OLS[1] / (2 * OLS[2]) opt_t = est_dir.compute_coeffs(track_y, track_t)",
"> track[j][1]) def test_6(): \"\"\" Test for forward_tracking - forward_tol met. \"\"\" np.random.seed(90)",
"np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(np.min(track[:, 1]) <",
"Test for forward_tracking - forward_tol not met initially, f_new < track[-2][1] and eventually",
"track, total_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol, f, func_args))",
"np.ones((m,)) centre_point = np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer,",
"for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2, 160], [4, 40], [8,",
"\"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2, 70], [4, 90]])",
"(minimizer, matrix, 0, 0.0000001) step = 0.5 forward_tol = 1.5 beta = np.array([0.0001,",
"else: assert(track[j-1][1] > track[j][1]) def test_5(): \"\"\" Test for forward_tracking - forward_tol not",
"est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region) assert(func_evals == 16) f_old = f(np.copy(centre_point), *func_args)",
"flag = (est_dir.forward_tracking (centre_point, t, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(np.round(track[0][0],",
"= 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 90, 110]))) assert(np.all(track_t",
"= f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta, step, const_back,",
"= est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 20, 90]))) assert(np.all(track_t == np.array([0, 8, 16])))",
"> track[j - 1][1]) else: assert(track[j - 1][1] > track[j][1]) def test_4(): \"\"\"",
"is returned. \"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise const_back = 0.5",
"when flag=True, track is updated. \"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise",
"minimizer = np.random.uniform(0, 10, (m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1,",
"10) t = 0.005 forward_tol = 10000 beta = np.array([1, 1]) f_old =",
"f_new < track[-2][1] \"\"\" np.random.seed(329998) n = 20 m = 100 f =",
"False) for j in range(1, len(track)): assert(track[j-1][1] > track[j][1]) def test_6(): \"\"\" Test",
"test_6(): \"\"\" Test for forward_tracking - forward_tol met. \"\"\" np.random.seed(90) m = 2",
"0) for j in range(len(test_track)): assert(test_track[j, 0] < forward_tol) if j >= 1:",
"func_args)) assert(np.all(track == track_new)) assert(flag == False) assert(total_func_evals == 0) def test_9(): \"\"\"",
"6 m = 2 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,))",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) t = 97.688932389756",
"f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0],",
"Test for forward_tracking - forward_tol met. \"\"\" np.random.seed(90) m = 2 f =",
"const_back = 0.5 minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix = est_dir.quad_func_params(1,",
"est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 80, 120]))) assert(np.all(track_t == np.array([0, 0.5, 1]))) def",
"np.array([100, 70, 90]))) assert(np.all(track_t == np.array([0, 2, 4]))) def test_20(): \"\"\"Test for arrange_track_y_t\"\"\"",
"90]))) assert(np.all(track_t == np.array([0, 8, 16]))) def test_19(): \"\"\"Test for arrange_track_y_t\"\"\" track =",
"track[j - 1][1]) else: assert(track[j][1] > track[j - 1][1]) def test_2(): \"\"\" Test",
"np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001) step = 1 forward_tol = 100000",
"def test_14(): \"\"\" Test for combine_tracking - check that correct step size is",
"* beta, *func_args) track = np.array([[0, f_old], [step, f_new]]) track, count_func_evals, flag =",
"= 0.5 minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1,",
"step = 0.1 back_tol = 0.075 no_vars = 10 region = 1 beta,",
"matrix, 0, 5) step = 1 back_tol = 1 forward_tol = 100000 beta",
"0.5 const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.array([20, 20])",
"and f_new >= track[-2][1] \"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise const_back",
"0.01 forward_tol = 1000000 no_vars = 10 region = 1 beta, func_evals =",
"centre_point, f, func_args, no_vars, region) assert(func_evals == 16) f_old = f(np.copy(centre_point), *func_args) f_new",
"(m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args =",
"* beta, *func_args) assert(f_old < f_new) track, count_func_evals = (est_dir.backward_tracking (centre_point, t, f_old,",
"= np.array([[0, 100], [1, 120], [0.5, 80]]) track_method = 'Backward' track_y, track_t =",
"np.array([100, 200, 50]) track_t = np.array([0, 1, 0.5]) design_matrix_step = np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t),",
"* beta, *func_args) assert(f_old > f_new) track = np.array([[0, f_old], [step, f_new]]) track_new,",
"- 1, 1]) assert(test_track[j, 0] * const_forward > forward_tol) def test_3(): \"\"\" Test",
"np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 10)",
"matrix, 0, 0.1) step = 0.001 back_tol = 0.000001 no_vars = 10 region",
"Test for backward_tracking - back tol is not met and f_new < track[-2][1]",
"0.0000001 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals =",
"= (minimizer, matrix, 0, 1000) t = 17001.993794080016 back_tol = 1 no_vars =",
"100], [1, 120], [0.5, 80]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method)",
"3) == np.round(t, 3)) assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def",
"- back tol is not met and f_new > track[-2][1]. \"\"\" np.random.seed(32964) n",
"10, m) func_args = (minimizer, matrix, 0, 5) t = 1 back_tol =",
"- 1][1]) else: assert(track[j - 1][1] > track[j][1]) def test_4(): \"\"\" Test for",
"f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) track",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step = 0.01",
"(minimizer, matrix, 0, 0.1) step = 0.1 back_tol = 0.075 no_vars = 10",
"120]))) assert(np.all(track_t == np.array([0, 0.5, 1]))) def test_22(): \"\"\"Test for check_func_val_coeffs when func_val",
"= 0.5 const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.array([20,",
"assert(f_old > f_new) assert(flag == False) assert(count_func_evals > 0) for j in range(len(test_track)):",
"for forward_tracking - forward_tol not met and f_new < track[-2][1]. \"\"\" np.random.seed(25) m",
"= (minimizer, matrix, 0, 0.1) step = 0.001 back_tol = 0.000001 no_vars =",
"[0.25, 90]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100,",
"= est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix",
"est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check, 5) == np.round(opt_t, 5))) def test_14(): \"\"\" Test for combine_tracking",
"(est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(track.shape == (2,",
"returned, when back_tol is not met. \"\"\" np.random.seed(32964) n = 6 m =",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 60) step = 1.8251102718712913",
"def test_23(): \"\"\"Test for check_func_val_coeffs when func_val <= track_y[1].\"\"\" np.random.seed(91) m = 10",
"20], [16, 90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y ==",
"== (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_18(): \"\"\"Test for",
"for check_func_val_coeffs when func_val > track_y[1].\"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise",
"initially, f_new < track[-2][1] and eventually forward_tol is met. \"\"\" np.random.seed(25) m =",
"func_args = (minimizer, matrix, 0, 1000) t = 17001.993794080016 back_tol = 0.000000001 no_vars",
"and f_new < track[-2][1] \"\"\" np.random.seed(329998) n = 20 m = 100 f",
"and f_new < track[-2][1]. \"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise const_back",
"assert(total_func_evals > 0) assert(flag == True) for j in range(1, len(track)): if j",
"met. \"\"\" np.random.seed(3291) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward",
"0, 0.1) step = 0.001 back_tol = 0.000001 no_vars = 10 region =",
"def test_13(): \"\"\"Test for compute_coeffs\"\"\" track_y = np.array([100, 200, 50]) track_t = np.array([0,",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step = 1 back_tol",
"f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta, step,",
"assert(flag == True) for j in range(1, len(track)): if j == (len(track) -",
"0, 5) t = 97.688932389756 back_tol = 0.000000001 no_vars = m region =",
"= est_dir.quad_f_noise minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, )) matrix =",
"*func_args) assert(f_old > f_new) track = np.array([[0, f_old], [step, f_new]]) track, total_func_evals, flag",
"90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 20,",
"= np.array([100, 200, 50]) track_t = np.array([0, 1, 0.5]) design_matrix_step = np.vstack((np.repeat(track_y[0], len(track_t)),",
"1]) assert(test_track[j, 0] * const_forward > forward_tol) def test_3(): \"\"\" Test for forward_tracking",
"const_forward, forward_tol, f, func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val <",
"(1 / const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix =",
"range(1, len(track)): assert(np.round(track[j][0], 4) == np.round(t, 4)) t = t / 2 assert(np.min(track[:,",
"assert(track[j][1] > track[j - 1][1]) else: assert(track[j - 1][1] > track[j][1]) def test_4():",
"/ 2 assert(np.min(track[:, 1]) < track[1][0]) def test_11(): \"\"\" Test for backward_tracking -",
"region = 1 step = 0.17741338024633116 forward_tol = 1000000 no_vars = 10 beta,",
"const_back = 0.5 minimizer = np.random.uniform(0, 1, (m, )) centre_point = np.random.uniform(0, 1,",
"0.001 back_tol = 0.000001 no_vars = 10 region = 1 beta, func_evals =",
"const_forward, forward_tol, track, centre_point, beta, f, func_args)) assert(f_old > f_new) assert(count_func_evals == len(track)",
"is not initially met, f_new < track[-2][1] and eventaully back tol is met.",
"track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 80, 120])))",
"test_16(): \"\"\" Test for combine_tracking - check that correct step size is returned,",
"Test for forward_tracking - forward_tol not met and f_new < track[-2][1]. \"\"\" np.random.seed(25)",
"(step, const_back, back_tol, track, centre_point, beta, f, func_args)) assert(total_func_evals == len(track) - 2)",
"assert(count_func_evals > 0) for j in range(len(test_track)): assert(test_track[j, 0] < forward_tol) if j",
"t, f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3))",
"= (minimizer, matrix, 0, 10) t = 0.005 forward_tol = 10 beta =",
"track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 70, 90]))) assert(np.all(track_t == np.array([0,",
"25]) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step",
"m region = 1 beta, func_evals = est_dir.compute_direction_XY(n, m, centre_point, f, func_args, no_vars,",
"track = np.array([[0, f_old], [step, f_new]]) test_track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward,",
"70, 90]))) assert(np.all(track_t == np.array([0, 2, 4]))) def test_20(): \"\"\"Test for arrange_track_y_t\"\"\" track",
"assert(test_track[j, 0] * const_forward > forward_tol) def test_3(): \"\"\" Test for forward_tracking -",
"1): assert(track[j][1] > track[j-1][1]) else: assert(track[j-1][1] > track[j][1]) def test_5(): \"\"\" Test for",
"track[1][1]) assert(count_func_evals == 0) def test_10(): \"\"\" Test for backward_tracking - back tol",
"200, 50]) track_t = np.array([0, 1, 0.5]) design_matrix_step = np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t), np.array(track_t)",
"f_old) def test_15(): \"\"\" Test for combine_tracking - check that correct step size",
"is not met and f_new > track[-2][1]. \"\"\" np.random.seed(32964) n = 6 m",
"centre_point = np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix,",
"(centre_point, t, f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(track.shape == (2, m))",
"forward_tol) if j >= 1: assert(test_track[j, 1] < test_track[j - 1, 1]) assert(test_track[j,",
"in range(len(test_track)): assert(test_track[j, 0] < forward_tol) if j >= 1: assert(test_track[j, 1] <",
"== (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_16(): \"\"\" Test",
"f_new < track[-2][1]. \"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise const_back =",
"minimizer = np.ones((m,)) centre_point = np.array([20, 20]) matrix = np.identity(m) func_args = (minimizer,",
"(minimizer, matrix, 0, 10) t = 0.005 forward_tol = 10 beta = np.array([1,",
"(est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta, f, func_args)) assert(f_old > f_new) assert(count_func_evals",
"(minimizer, matrix, 0, 0.0000001) step = 1 forward_tol = 100000 back_tol = 0.0000001",
"not met. \"\"\" np.random.seed(32964) n = 6 m = 2 f = est_dir.quad_f_noise",
"for compute_forward() - check that when flag=False, track is returned. \"\"\" np.random.seed(90) m",
"90]))) assert(np.all(track_t == np.array([0, 2, 4]))) def test_20(): \"\"\"Test for arrange_track_y_t\"\"\" track =",
"(m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 0.1)",
"== np.array([0, 8, 16]))) def test_19(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100],",
"step = step * const_forward if j < len(track) - 1: assert(track[j][1] <",
"100], [1, 120], [0.5, 110], [0.25, 90]]) track_method = 'Backward' track_y, track_t =",
"1] < test_track[j - 1, 1]) assert(test_track[j, 0] * const_forward > forward_tol) def",
"(m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_15(): \"\"\" Test for",
"0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args)",
"= np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t), np.array(track_t) ** 2)).T assert(np.all(design_matrix_step[0, :] == np.array([100, 0, 0])))",
"1 back_tol = 1 forward_tol = 100000 beta = np.array([200, 200]) f_old =",
"2 assert(np.round(track[j][0], 3) == step) if j == (len(track) - 1): assert(track[j][1] >",
")) assert(func_val == 40) def test_23(): \"\"\"Test for check_func_val_coeffs when func_val <= track_y[1].\"\"\"",
"(step, const_forward, forward_tol, track, centre_point, beta, f, func_args)) assert(f_old > f_new) assert(flag ==",
"matrix, 0, 5) t = 1 back_tol = 1 beta = np.array([200, 200])",
"f, func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val == f_old) def",
"* beta, *func_args) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta,",
"if j < len(track) - 1: assert(track[j][1] < track[j-1][1]) else: assert(track[j][1] > track[j-1][1])",
"== True) assert(total_func_evals > 0) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track,",
"(centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag == False) assert(track[2][1]",
"0.5 const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10,",
"forward_tol, track, centre_point, beta, f, func_args)) assert(f_old > f_new) assert(flag == False) assert(count_func_evals",
"matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 1000) t =",
"[0.5, 110], [0.25, 90]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y",
"1]) < track[:, 1][0]) def test_13(): \"\"\"Test for compute_coeffs\"\"\" track_y = np.array([100, 200,",
"matrix, 0, 5) step = 0.05 forward_tol = 1000000 no_vars = 10 region",
"> 0) for j in range(1, len(track)): assert(np.round(track[j][0], 4) == np.round(t, 4)) t",
"Test for combine_tracking - check that correct step size is returned, when back_tol",
"3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(flag == True) for",
"= (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag ==",
"= 10 forward_tol = 1000000 back_tol = 0.000000001 no_vars = m region =",
"0.5 minimizer = np.random.uniform(0, 10, (m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix =",
"in range(1, len(track)): assert(track[j][0] == step) step = step * const_forward if j",
"= 1.5 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point)",
"func_args = (minimizer, matrix, 0, 5) step = 0.05 forward_tol = 1000000 no_vars",
"beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking",
"assert(np.round(track[j][0], 3) == step) if j == (len(track) - 1): assert(track[j][1] > track[j",
"matrix = np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001) step = 0.5 forward_tol",
"*func_args) assert(f_old < f_new) track, total_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta,",
"*func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) assert(f_old > f_new) track",
"no_vars, region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals =",
"3)) assert(total_func_evals > 0) assert(flag == True) for j in range(1, len(track)): if",
"matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) region =",
"matrix, 0, 5) step = 0.005 forward_tol = 10000 back_tol = 0.0000001 beta",
"m) func_args = (minimizer, matrix, 0, 5) step = 0.005 forward_tol = 10000",
"0) def test_10(): \"\"\" Test for backward_tracking - back tol is not met",
"= f(np.copy(centre_point) - t * beta, *func_args) assert(f_old < f_new) track, count_func_evals =",
"compute_backward - check that when flag=False, original track is returned. \"\"\" np.random.seed(90) m",
"= f(np.copy(centre_point) - step * beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag",
"= f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) track, total_func_evals,",
"1][1]) def test_2(): \"\"\" Test for compute_forward() - check that when flag=False, track",
"beta, *func_args) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward,",
"def test_4(): \"\"\" Test for forward_tracking - forward_tol not met and f_new <",
"== (m, )) assert(type(total_func_evals) is int) assert(func_val == f_old) def test_17(): \"\"\" Test",
"@ design_matrix_step) @ design_matrix_step.T @ track_y) check = -OLS[1] / (2 * OLS[2])",
"beta, f, func_args)) assert(total_func_evals == len(track) - 2) assert(flag == True) assert(track[0][0] ==",
"1][1]) else: assert(track[j][1] > track[j - 1][1]) def test_2(): \"\"\" Test for compute_forward()",
"track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f, func_args))",
"== (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_15(): \"\"\" Test",
"1) def test_7(): \"\"\" Test for compute_backward - check that when flag=True, track",
"== True) for j in range(1, len(track)): if j == (len(track) - 1):",
"not met. \"\"\" np.random.seed(3291) m = 2 f = est_dir.quad_f_noise const_back = 0.5",
"minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, )) matrix = est_dir.quad_func_params(1, 10,",
"step * beta, *func_args) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new,",
"f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, t, f_old, f_new, beta, const_forward, forward_tol,",
"assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t *",
"met. \"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward",
"upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta, step, const_back, back_tol, const_forward, forward_tol,",
"1000000 no_vars = 10 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region)",
"= f(np.copy(centre_point) - t * beta, *func_args) assert(f_old < f_new) track, total_func_evals =",
"*func_args) assert(f_old < f_new) track, count_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta,",
"< f_new) track, count_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol,",
"centre_point, f, func_args, no_vars, region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) upd_point,",
"3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) for j in range(1,",
"\"\"\" Test for compute_forward() - check for flag=True. \"\"\" np.random.seed(90) m = 10",
"np.random.seed(329998) n = 20 m = 100 f = est_dir.quad_f_noise const_back = 0.5",
"func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta, step, const_back, back_tol, const_forward, forward_tol, f,",
"(centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag == True) assert(total_func_evals",
"forward_tol, f, func_args)) assert(flag == True) assert(total_func_evals > 0) track_method = 'Forward' upd_point,",
"- 1): assert(track[j][1] > track[j - 1][1]) else: assert(track[j - 1][1] > track[j][1])",
"f_new]]) track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta, f,",
"0, 0.0000001) step = 0.5 forward_tol = 1.5 beta = np.array([0.0001, 0.0001]) f_old",
"np.array([[0, 100], [1, 160], [2, 40], [4, 90]]) track_method = 'Forward' upd_point, func_val",
"const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,))",
"= (est_dir.backward_tracking (centre_point, t, f_old, f_new, beta, const_back, back_tol, f, func_args)) assert(track.shape ==",
"f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta, *func_args) assert(f_old",
"check that when flag=True, track is updated. \"\"\" np.random.seed(90) m = 100 f",
"when flag=False, original track is returned. \"\"\" np.random.seed(90) m = 100 f =",
"np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(flag == True)",
"f, func_args)) assert(f_old > f_new) assert(flag == False) assert(count_func_evals > 0) for j",
"10, m) func_args = (minimizer, matrix, 0, 10) t = 0.005 forward_tol =",
"1, (m, )) centre_point = np.random.uniform(0, 1, (m, )) matrix = est_dir.quad_func_params(1, 10,",
"f = est_dir.quad_f_noise minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, )) matrix",
"beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t",
"len(track)): if j == (len(track) - 1): assert(track[j][1] > track[j-1][1]) else: assert(track[j-1][1] >",
"and eventaully back tol is met. \"\"\" np.random.seed(329998) n = 20 m =",
"80], [2, 70], [4, 90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method)",
"np.random.uniform(0, 10, (m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10, m)",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step = 0.01 forward_tol",
"beta, const_back, back_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) ==",
"= f(np.copy(centre_point) - step * beta, *func_args) track = np.array([[0, f_old], [step, f_new]])",
"1, 1]))) assert(np.all(design_matrix_step[2, :] == np.array([100, 0.5, 0.25]))) OLS = (np.linalg.inv(design_matrix_step.T @ design_matrix_step)",
")) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 60) step",
"60) step = 1.8251102718712913 no_vars = 10 region = 1 beta, func_evals =",
"- 1][1]) def test_2(): \"\"\" Test for compute_forward() - check that when flag=False,",
"1]) < track[1][0]) def test_11(): \"\"\" Test for backward_tracking - back tol is",
"np.random.seed(91) m = 10 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1",
"5) == np.round(opt_t, 5))) def test_14(): \"\"\" Test for combine_tracking - check that",
"np.round(t, 3)) assert(total_func_evals > 0) assert(flag == True) for j in range(1, len(track)):",
"for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5, 110], [0.25, 90]]) track_method",
"forward_tracking - forward_tol met. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back",
"beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step",
"- check that when flag=False, original track is returned. \"\"\" np.random.seed(90) m =",
"= 1.8251102718712913 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point,",
"= 100000 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point)",
"np.array([0, 1, 0.5]) design_matrix_step = np.vstack((np.repeat(track_y[0], len(track_t)), np.array(track_t), np.array(track_t) ** 2)).T assert(np.all(design_matrix_step[0, :]",
"5) t = 97.688932389756 back_tol = 0.000000001 no_vars = m region = 1",
"f_new, beta, const_back, back_tol, f, func_args)) assert(track.shape == (2, m)) assert(track[0][0] == 0)",
"= est_dir.quad_f_noise const_back = 0.5 const_forward = (1 / const_back) minimizer = np.ones((m,))",
"np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args",
"step * const_forward if j < len(track) - 1: assert(track[j][1] < track[j -",
"assert(flag == True) assert(total_func_evals > 0) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs",
"0) assert(track[1][0] == t) assert(track[1][0] < track[1][1]) assert(count_func_evals == 0) def test_10(): \"\"\"",
"assert(np.all(np.round(check, 5) == np.round(opt_t, 5))) def test_14(): \"\"\" Test for combine_tracking - check",
"0) for j in range(1, len(track)): assert(np.round(track[j][0], 4) == np.round(t, 4)) t =",
"j < len(track) - 1: assert(track[j][1] < track[j - 1][1]) else: assert(track[j][1] >",
"range(len(test_track)): assert(test_track[j, 0] < forward_tol) if j >= 1: assert(test_track[j, 1] < test_track[j",
"est_dir.compute_direction_XY(n, m, centre_point, f, func_args, no_vars, region) assert(func_evals == n) f_old = f(np.copy(centre_point),",
"assert(np.all(design_matrix_step[0, :] == np.array([100, 0, 0]))) assert(np.all(design_matrix_step[1, :] == np.array([100, 1, 1]))) assert(np.all(design_matrix_step[2,",
"- step * beta, *func_args) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old,",
"for j in range(1, len(track)): assert(track[j-1][1] > track[j][1]) def test_6(): \"\"\" Test for",
"= f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta, *func_args) assert(f_old >",
"90]]) track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 90,",
"func_args)) assert(f_old > f_new) assert(count_func_evals == len(track) - 2) assert(flag == True) assert(track[0][0]",
"step = step * 2 assert(np.round(track[j][0], 3) == step) if j == (len(track)",
"90, 110]))) assert(np.all(track_t == np.array([0, 0.25, 0.5]))) def test_21(): \"\"\"Test for arrange_track_y_t\"\"\" track",
"> track[j][1]) def test_5(): \"\"\" Test for forward_tracking - forward_tol not met initially,",
"track_method) assert(np.all(track_y == np.array([100, 20, 90]))) assert(np.all(track_t == np.array([0, 8, 16]))) def test_19():",
"(est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(flag == False)",
"== 40) def test_23(): \"\"\"Test for check_func_val_coeffs when func_val <= track_y[1].\"\"\" np.random.seed(91) m",
"OLS = (np.linalg.inv(design_matrix_step.T @ design_matrix_step) @ design_matrix_step.T @ track_y) check = -OLS[1] /",
"< track[-2][1] and eventaully back tol is met. \"\"\" np.random.seed(329998) n = 20",
"3)) assert(np.round(track[1][0], 3) == np.round(step, 3)) assert(flag == True) for j in range(2,",
"for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5, 80]]) track_method = 'Backward'",
"0.25, 0.5]))) def test_21(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120],",
"assert(total_func_evals == 1) def test_7(): \"\"\" Test for compute_backward - check that when",
"len(track)): assert(track[j][0] == step) step = step * const_back if j < len(track)",
"track[-2][1] and eventaully back tol is met. \"\"\" np.random.seed(329998) n = 20 m",
"that when flag=False, track is returned. \"\"\" np.random.seed(90) m = 2 f =",
"3) == np.round(t, 3)) assert(total_func_evals > 0) assert(flag == False) for j in",
"total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f, func_args)) assert(total_func_evals",
"* beta, *func_args) track = np.array([[0, f_old], [step, f_new]]) test_track, count_func_evals, flag =",
"= 0.005 forward_tol = 10000 back_tol = 0.0000001 beta = np.array([1, 1]) f_old",
"total_func_evals, flag = (est_dir.forward_tracking (centre_point, t, f_old, f_new, beta, const_forward, forward_tol, f, func_args))",
"== np.array([100, 20, 90]))) assert(np.all(track_t == np.array([0, 8, 16]))) def test_19(): \"\"\"Test for",
"== np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(np.min(track[:, 1])",
"= np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step *",
"const_back, back_tol, track, centre_point, beta, f, func_args)) assert(np.all(track == track_new)) assert(flag == False)",
"> track[-2][1]. \"\"\" np.random.seed(32964) n = 6 m = 2 f = est_dir.quad_f_noise",
"< f_old) def test_16(): \"\"\" Test for combine_tracking - check that correct step",
"f, func_args)) assert(total_func_evals == len(track) - 2) assert(flag == True) assert(track[0][0] == 0)",
"back_tol, track, centre_point, beta, f, func_args)) assert(np.all(track == track_new)) assert(flag == False) assert(total_func_evals",
"range(1, len(track)): assert(track[j][0] == step) step = step * const_forward if j <",
"40], [8, 20], [16, 90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method)",
"40], [4, 90]]) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point,",
"f_new = f(np.copy(centre_point) - step * beta, *func_args) track = np.array([[0, f_old], [step,",
"m) func_args = (minimizer, matrix, 0, 5) region = 1 step = 0.17741338024633116",
"m = 10 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1 /",
"== True) for j in range(2, len(track)): step = step * 2 assert(np.round(track[j][0],",
"when back_tol is not met. \"\"\" np.random.seed(32964) n = 6 m = 2",
"1.5 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) -",
"assert(type(total_func_evals) is int) assert(func_val < f_old) def test_18(): \"\"\"Test for arrange_track_y_t\"\"\" track =",
"'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 80, 120]))) assert(np.all(track_t ==",
"not met and f_new < track[-2][1]. \"\"\" np.random.seed(25) m = 2 f =",
"== total_func_evals) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(step, 3)) assert(flag",
"flag = (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta, f, func_args)) assert(f_old >",
"met. \"\"\" np.random.seed(329998) n = 20 m = 100 f = est_dir.quad_f_noise const_back",
"= 20 m = 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer =",
"size is returned, when back_tol is met. \"\"\" np.random.seed(32964) m = 2 f",
"0, 5) step = 0.01 forward_tol = 1000000 no_vars = 10 region =",
"test_22(): \"\"\"Test for check_func_val_coeffs when func_val > track_y[1].\"\"\" np.random.seed(90) m = 10 f",
"20]) matrix = np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001) step = 0.5",
"flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f, func_args)) assert(total_func_evals ==",
"matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) step =",
"f_old], [step, f_new]]) track_new, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point,",
"> 0) assert(flag == True) for j in range(1, len(track)): if j ==",
"f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) track = np.array([[0,",
"step * beta, *func_args) assert(f_old > f_new) track = np.array([[0, 100], [1, 160],",
"> f_new) track = np.array([[0, f_old], [step, f_new]]) track, total_func_evals, flag = (est_dir.compute_backward",
"= np.array([[0, 100], [1, 160], [2, 40], [4, 90]]) track_method = 'Forward' upd_point,",
"est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix",
"np import est_dir def test_1(): \"\"\" Test for compute_forward() - check for flag=True.",
"assert(track[j][1] < track[j - 1][1]) else: assert(track[j][1] > track[j - 1][1]) def test_2():",
"== np.array([100, 1, 1]))) assert(np.all(design_matrix_step[2, :] == np.array([100, 0.5, 0.25]))) OLS = (np.linalg.inv(design_matrix_step.T",
"matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 10) t =",
"assert(total_func_evals > 0) for j in range(1, len(track)): assert(np.round(track[j][0], 4) == np.round(t, 4))",
"= np.array([[0, f_old], [step, f_new]]) track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol,",
"= 0.000001 no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point,",
"int) assert(func_val == f_old) def test_17(): \"\"\" Test for combine_tracking - check that",
"f_new) track = np.array([[0, f_old], [step, f_new]]) track_new, total_func_evals, flag = (est_dir.compute_backward (step,",
"* beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step,",
"const_back, back_tol, f, func_args)) assert(track.shape == (2, m)) assert(track[0][0] == 0) assert(track[1][0] ==",
"== np.array([100, 70, 90]))) assert(np.all(track_t == np.array([0, 2, 4]))) def test_20(): \"\"\"Test for",
"centre_point = np.random.uniform(0, 1, (m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args =",
"Test for compute_forward() - check that when flag=False, track is returned. \"\"\" np.random.seed(90)",
"10 forward_tol = 1000000 back_tol = 0.000000001 no_vars = m region = 1",
"track[:, 1][0]) def test_12(): \"\"\" Test for backward_tracking - back tol is not",
"< track[j - 1][1]) else: assert(track[j][1] > track[j - 1][1]) def test_2(): \"\"\"",
"0, 10) t = 0.005 forward_tol = 10000 beta = np.array([1, 1]) f_old",
"assert(np.all(track_y == np.array([100, 70, 90]))) assert(np.all(track_t == np.array([0, 2, 4]))) def test_20(): \"\"\"Test",
"== (len(track) - 1): assert(track[j][1] > track[j-1][1]) else: assert(track[j-1][1] > track[j][1]) def test_5():",
"0, 5) step = 10 forward_tol = 1000000 back_tol = 0.000000001 no_vars =",
"f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0],",
"no_vars, region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) -",
"beta, *func_args) assert(f_old < f_new) track, count_func_evals = (est_dir.backward_tracking (centre_point, t, f_old, f_new,",
"0.5, 0.25]))) OLS = (np.linalg.inv(design_matrix_step.T @ design_matrix_step) @ design_matrix_step.T @ track_y) check =",
"track = np.array([[0, 100], [1, 160], [2, 40], [4, 90]]) track_method = 'Forward'",
"= step * 2 assert(np.round(track[j][0], 3) == step) if j == (len(track) -",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 1000) t = 17001.993794080016",
"assert(type(total_func_evals) is int) assert(func_val < f_old) def test_16(): \"\"\" Test for combine_tracking -",
"f_new = f(np.copy(centre_point) - step * beta, *func_args) assert(f_old > f_new) track, total_func_evals,",
"= 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 20, 90]))) assert(np.all(track_t",
"70], [4, 90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y ==",
"track[-2][1] \"\"\" np.random.seed(329998) n = 20 m = 100 f = est_dir.quad_f_noise const_back",
"test_18(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2, 160], [4,",
"\"\"\"Test for compute_coeffs\"\"\" track_y = np.array([100, 200, 50]) track_t = np.array([0, 1, 0.5])",
"assert(track[0][0] == 0) for j in range(1, len(track)): assert(track[j][0] == step) step =",
"assert(track[j][0] == step) step = step * const_back if j < len(track) -",
"0.5 minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10,",
"is returned when forward_tol is met. \"\"\" np.random.seed(90) m = 2 f =",
"- flag=True and f_new >= track[-2][1] \"\"\" np.random.seed(90) m = 10 f =",
"= 100000 beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals",
"eventaully back tol is met. \"\"\" np.random.seed(329998) n = 20 m = 100",
"* const_back if j < len(track) - 1: assert(track[j][1] < track[j-1][1]) else: assert(track[j][1]",
"no_vars, region) assert(func_evals == 16) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) -",
"== (2, m)) assert(track[0][0] == 0) assert(track[1][0] == t) assert(track[1][0] < track[1][1]) assert(count_func_evals",
"- t * beta, *func_args) assert(f_old < f_new) track, count_func_evals = (est_dir.backward_tracking (centre_point,",
"matrix, 0, 5) step = 0.01 forward_tol = 1000000 no_vars = 10 region",
"[1, 80], [2, 160], [4, 40], [8, 20], [16, 90]]) track_method = 'Forward'",
"est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 20, 90]))) assert(np.all(track_t == np.array([0, 8, 16]))) def",
"(est_dir.combine_tracking (centre_point, f_old, beta, step, const_back, back_tol, const_forward, forward_tol, f, func_args)) assert(upd_point.shape ==",
"Test for combine_tracking - check that correct step size is returned when forward_tol",
"const_back = 0.5 minimizer = np.random.uniform(0, 10, (m,)) centre_point = np.random.uniform(0, 10, (m,))",
"== False) assert(total_func_evals == 0) def test_9(): \"\"\" Test for backward_tracking - back_tol",
"20, (m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0,",
"> 0) for j in range(len(test_track)): assert(test_track[j, 0] < forward_tol) if j >=",
"np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta,",
"centre_point = np.array([20, 20]) matrix = np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001)",
"(minimizer, matrix, 0, 10) t = 0.005 forward_tol = 10000 beta = np.array([1,",
"track = np.array([[0, f_old], [step, f_new]]) track, total_func_evals, flag = (est_dir.compute_backward (step, const_back,",
"func_val <= track_y[1].\"\"\" np.random.seed(91) m = 10 f = est_dir.quad_f_noise const_back = 0.5",
"== np.round(opt_t, 5))) def test_14(): \"\"\" Test for combine_tracking - check that correct",
"assert(np.all(track_t == np.array([0, 0.25, 0.5]))) def test_21(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0,",
"= (minimizer, matrix, 0, 0.0000001) step = 0.5 forward_tol = 1.5 beta =",
"/ const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1,",
"region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking",
"f, func_args)) assert(len(track) - 1 == total_func_evals) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0],",
"3)) assert(flag == True) for j in range(2, len(track)): step = step *",
"f(np.copy(centre_point) - step * beta, *func_args) track = np.array([[0, f_old], [step, f_new]]) track,",
"> track[j][1]) def test_4(): \"\"\" Test for forward_tracking - forward_tol not met and",
"10, m) func_args = (minimizer, matrix, 0, 5) t = 97.688932389756 back_tol =",
"assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) for j in range(1, len(track)):",
"assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_12(): \"\"\" Test for",
"assert(type(total_func_evals) is int) assert(func_val == f_old) def test_17(): \"\"\" Test for combine_tracking -",
"int) assert(func_val < f_old) def test_15(): \"\"\" Test for combine_tracking - check that",
"== 0) assert(track[1][0] == t) assert(track[1][0] < track[1][1]) assert(count_func_evals == 0) def test_10():",
"(m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5)",
"5) t = 1 back_tol = 1 beta = np.array([200, 200]) f_old =",
"def test_19(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2, 70],",
"track, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f, func_args))",
"test_track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta, f, func_args))",
"(centre_point, t, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0,",
"if j >= 1: assert(test_track[j, 1] < test_track[j - 1, 1]) assert(test_track[j, 0]",
"initially met, f_new < track[-2][1] and eventaully back tol is met. \"\"\" np.random.seed(329998)",
"forward_tol is not met. \"\"\" np.random.seed(3291) m = 2 f = est_dir.quad_f_noise const_back",
"*func_args) track = np.array([[0, f_old], [step, f_new]]) track, count_func_evals, flag = (est_dir.compute_forward (step,",
"f_old, beta, step, const_back, back_tol, const_forward, forward_tol, f, func_args)) assert(upd_point.shape == (m, ))",
"< track[1][1] < track[0][1]) assert(total_func_evals == 1) def test_7(): \"\"\" Test for compute_backward",
"*func_args) upd_point, func_val, total_func_evals = (est_dir.combine_tracking (centre_point, f_old, beta, step, const_back, back_tol, const_forward,",
"10, (m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5)",
"2 assert(np.min(track[:, 1]) < track[1][0]) def test_11(): \"\"\" Test for backward_tracking - back",
"0) assert(flag == False) for j in range(1, len(track)): assert(track[j-1][1] > track[j][1]) def",
"*func_args) assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, t, f_old, f_new,",
"arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80], [2, 160], [4, 40], [8, 20],",
"def test_5(): \"\"\" Test for forward_tracking - forward_tol not met initially, f_new <",
"track_method = 'Backward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 90, 110])))",
"assert(f_old > f_new) track = np.array([[0, f_old], [step, f_new]]) track_new, total_func_evals, flag =",
"100000 beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val, total_func_evals =",
"1][0]) def test_13(): \"\"\"Test for compute_coeffs\"\"\" track_y = np.array([100, 200, 50]) track_t =",
"assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0)",
"assert(np.min(track[:, 1]) < track[:, 1][0]) def test_13(): \"\"\"Test for compute_coeffs\"\"\" track_y = np.array([100,",
"np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta,",
"beta, const_forward, forward_tol, f, func_args)) assert(flag == True) assert(total_func_evals > 0) track_method =",
"= est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 90, 110]))) assert(np.all(track_t == np.array([0, 0.25, 0.5])))",
"== f_old) def test_17(): \"\"\" Test for combine_tracking - check that correct step",
"f, func_args, no_vars, region) assert(func_evals == 16) f_old = f(np.copy(centre_point), *func_args) f_new =",
"flag=True, track is updated. \"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise const_back",
"= 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 70, 90]))) assert(np.all(track_t",
"> track[j-1][1]) else: assert(track[j-1][1] > track[j][1]) def test_5(): \"\"\" Test for forward_tracking -",
"\"\"\" np.random.seed(90) m = 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer =",
"total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta, f, func_args)) assert(np.all(track",
"f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol,",
"m) func_args = (minimizer, matrix, 0, 5) step = 10 forward_tol = 1000000",
">= 1: assert(test_track[j, 1] < test_track[j - 1, 1]) assert(test_track[j, 0] * const_forward",
"compute_coeffs\"\"\" track_y = np.array([100, 200, 50]) track_t = np.array([0, 1, 0.5]) design_matrix_step =",
"(minimizer, matrix, 0, 5) t = 1 back_tol = 1 beta = np.array([200,",
"= (1 / const_back) minimizer = np.ones((m,)) centre_point = np.array([20, 20]) matrix =",
"== np.array([0, 0.5, 1]))) def test_22(): \"\"\"Test for check_func_val_coeffs when func_val > track_y[1].\"\"\"",
"func_args, no_vars, region) assert(func_evals == 16) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point)",
"3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:,",
"def test_20(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5, 110],",
"np.array([[0, f_old], [step, f_new]]) test_track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track,",
"= (1 / const_back) minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix =",
"np.array([100, 90, 110]))) assert(np.all(track_t == np.array([0, 0.25, 0.5]))) def test_21(): \"\"\"Test for arrange_track_y_t\"\"\"",
"forward_tol = 1000000 back_tol = 0.000000001 no_vars = m region = 1 beta,",
"est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 1, (m, )) centre_point = np.random.uniform(0,",
"and f_new > track[-2][1]. \"\"\" np.random.seed(32964) n = 6 m = 2 f",
"is int) assert(func_val < f_old) def test_16(): \"\"\" Test for combine_tracking - check",
"== np.array([0, 2, 4]))) def test_20(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100],",
"for compute_coeffs\"\"\" track_y = np.array([100, 200, 50]) track_t = np.array([0, 1, 0.5]) design_matrix_step",
"test_8(): \"\"\" Test for compute_backward - check that when flag=False, original track is",
"else: assert(track[j - 1][1] > track[j][1]) def test_4(): \"\"\" Test for forward_tracking -",
"> f_new) assert(count_func_evals == len(track) - 2) assert(flag == True) assert(track[0][0] == 0)",
"assert(test_track[j, 0] < forward_tol) if j >= 1: assert(test_track[j, 1] < test_track[j -",
"assert(np.min(track[:, 1]) < track[1][0]) def test_11(): \"\"\" Test for backward_tracking - back tol",
"matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 60) step =",
"1000) t = 17001.993794080016 back_tol = 0.000000001 no_vars = m region = 1",
"len(track)): assert(np.round(track[j][0], 4) == np.round(t, 4)) t = t / 2 assert(np.min(track[:, 1])",
"beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old,",
"100], [1, 160], [2, 40], [4, 90]]) track_method = 'Forward' upd_point, func_val =",
"forward_tol, f, func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old)",
"[1, 80], [2, 70], [4, 90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track,",
"np.array([100, 20, 90]))) assert(np.all(track_t == np.array([0, 8, 16]))) def test_19(): \"\"\"Test for arrange_track_y_t\"\"\"",
"0.0000001) step = 1 forward_tol = 100000 beta = np.array([0.0001, 0.0001]) f_old =",
"= np.random.uniform(0, 1, (m, )) centre_point = np.random.uniform(0, 1, (m, )) matrix =",
"assert(total_func_evals > 0) assert(flag == False) for j in range(1, len(track)): assert(track[j-1][1] >",
"returned when forward_tol is met. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise",
"region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t",
"* beta, *func_args) assert(f_old < f_new) track, total_func_evals = (est_dir.backward_tracking (centre_point, t, f_old,",
"func_args)) assert(track.shape == (2, m)) assert(track[0][0] == 0) assert(track[1][0] == t) assert(track[1][0] <",
"0]))) assert(np.all(design_matrix_step[1, :] == np.array([100, 1, 1]))) assert(np.all(design_matrix_step[2, :] == np.array([100, 0.5, 0.25])))",
"track_method, centre_point, beta, f, func_args)) assert(upd_point.shape == (m, )) assert(np.all(func_val <= track[:, 1]))",
"(m,)) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 1000) t",
"10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region)",
"t * beta, *func_args) assert(f_old < f_new) track, total_func_evals = (est_dir.backward_tracking (centre_point, t,",
"func_args = (minimizer, matrix, 0, 5) step = 0.005 forward_tol = 10000 back_tol",
"m, centre_point, f, func_args, no_vars, region) assert(func_evals == n) f_old = f(np.copy(centre_point), *func_args)",
"= 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 10, (m,))",
"t = 0.005 forward_tol = 10 beta = np.array([1, 1]) f_old = f(np.copy(centre_point),",
"np.identity(m) func_args = (minimizer, matrix, 0, 0.0000001) step = 0.5 forward_tol = 1.5",
"m) func_args = (minimizer, matrix, 0, 5) step = 1 back_tol = 1",
"3) == np.round(t, 3)) assert(total_func_evals > 0) for j in range(1, len(track)): assert(np.round(track[j][0],",
"combine_tracking - check that correct step size is returned, when forward_tol is not",
"in range(1, len(track)): if j == (len(track) - 1): assert(track[j][1] > track[j-1][1]) else:",
"for backward_tracking - back tol is not met and f_new > track[-2][1]. \"\"\"",
"< len(track) - 1: assert(track[j][1] < track[j - 1][1]) else: assert(track[j][1] > track[j",
"const_forward if j < len(track) - 1: assert(track[j][1] < track[j - 1][1]) else:",
"(est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f, func_args)) assert(upd_point.shape == (m, )) assert(np.all(func_val <=",
"forward_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3))",
"const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,)) matrix = est_dir.quad_func_params(1, 10,",
"- 1][1] > track[j][1]) def test_4(): \"\"\" Test for forward_tracking - forward_tol not",
"track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f,",
"const_forward > forward_tol) def test_3(): \"\"\" Test for forward_tracking - flag=True and f_new",
"(step, const_forward, forward_tol, track, centre_point, beta, f, func_args)) assert(f_old > f_new) assert(count_func_evals ==",
"forward_tol = 1000000 no_vars = 10 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args,",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 10) t = 0.005",
"np.array([[0, f_old], [step, f_new]]) track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track,",
"track[0][1]) assert(total_func_evals == 1) def test_7(): \"\"\" Test for compute_backward - check that",
"step size is returned, when back_tol is met. \"\"\" np.random.seed(32964) m = 2",
"- 2) assert(flag == True) assert(track[0][0] == 0) for j in range(1, len(track)):",
"matrix, 0, 5) step = 10 forward_tol = 1000000 back_tol = 0.000000001 no_vars",
"for check_func_val_coeffs when func_val <= track_y[1].\"\"\" np.random.seed(91) m = 10 f = est_dir.quad_f_noise",
"(minimizer, matrix, 0, 1000) t = 17001.993794080016 back_tol = 1 no_vars = m",
"tol is not met and f_new > track[-2][1]. \"\"\" np.random.seed(32964) n = 6",
"back_tol = 1 no_vars = m region = 1 beta, func_evals = est_dir.compute_direction_XY(n,",
"\"\"\" np.random.seed(32964) n = 6 m = 2 f = est_dir.quad_f_noise const_back =",
"== np.round(step, 3)) assert(flag == True) for j in range(2, len(track)): step =",
"len(track)): step = step * 2 assert(np.round(track[j][0], 3) == step) if j ==",
"assert(f_old > f_new) track = np.array([[0, f_old], [step, f_new]]) track, total_func_evals, flag =",
"= 0.005 forward_tol = 10 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args)",
"track[-2][1]. \"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward",
"- step * beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking",
"def test_10(): \"\"\" Test for backward_tracking - back tol is not met and",
"= (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta, f, func_args)) assert(f_old > f_new)",
"np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1",
"= (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f, func_args)) assert(upd_point.shape == (m, )) assert(np.all(func_val",
"forward_tol) def test_3(): \"\"\" Test for forward_tracking - flag=True and f_new >= track[-2][1]",
"np.random.uniform(0, 1, (m, )) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix,",
"centre_point, beta, f, func_args)) assert(total_func_evals == len(track) - 2) assert(flag == True) assert(track[0][0]",
"track_new)) assert(flag == False) assert(total_func_evals == 0) def test_9(): \"\"\" Test for backward_tracking",
"[step, f_new]]) track, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol, track, centre_point, beta,",
"track_t = est_dir.arrange_track_y_t(track, track_method) assert(np.all(track_y == np.array([100, 20, 90]))) assert(np.all(track_t == np.array([0, 8,",
"f_new > track[-2][1]. \"\"\" np.random.seed(32964) n = 6 m = 2 f =",
"forward_tracking - forward_tol not met and f_new < track[-2][1]. \"\"\" np.random.seed(25) m =",
"f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 10, (m,)) centre_point =",
"no_vars = 10 region = 1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args,",
"< f_old) def test_18(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 80],",
"f_new) assert(flag == False) assert(count_func_evals > 0) for j in range(len(test_track)): assert(test_track[j, 0]",
"track_y) check = -OLS[1] / (2 * OLS[2]) opt_t = est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check,",
"np.round(t, 3)) assert(total_func_evals > 0) assert(np.min(track[:, 1]) < track[:, 1][0]) def test_13(): \"\"\"Test",
"= 0.001 back_tol = 0.000001 no_vars = 10 region = 1 beta, func_evals",
"- check for flag=True. \"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise const_back",
"assert(track[0][0] == 0) assert(track[1][0] == t) assert(track[1][0] < track[1][1]) assert(count_func_evals == 0) def",
"f_new) track = np.array([[0, 100], [1, 160], [2, 40], [4, 90]]) track_method =",
"and eventually forward_tol is met. \"\"\" np.random.seed(25) m = 2 f = est_dir.quad_f_noise",
"m) func_args = (minimizer, matrix, 0, 5) step = 0.01 forward_tol = 1000000",
"assert(track[j][1] < track[j-1][1]) else: assert(track[j][1] > track[j-1][1]) def test_8(): \"\"\" Test for compute_backward",
"assert(f_old > f_new) track = np.array([[0, 100], [1, 160], [2, 40], [4, 90]])",
"np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) for j in",
"assert(total_func_evals > 0) track_method = 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point,",
"\"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward =",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 0.1) step = 0.001",
"np.array([0, 0.25, 0.5]))) def test_21(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1,",
"> f_new) track = np.array([[0, 100], [1, 160], [2, 40], [4, 90]]) track_method",
"t * beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point,",
"assert(np.all(track_y == np.array([100, 80, 120]))) assert(np.all(track_t == np.array([0, 0.5, 1]))) def test_22(): \"\"\"Test",
"const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.array([25, 25]) matrix",
"assert(np.min(track[:, 1]) < track[:, 1][0]) def test_12(): \"\"\" Test for backward_tracking - back",
"0.05 forward_tol = 1000000 no_vars = 10 region = 1 beta, func_evals =",
"\"\"\" Test for combine_tracking - check that correct step size is returned, when",
"[4, 40], [8, 20], [16, 90]]) track_method = 'Forward' track_y, track_t = est_dir.arrange_track_y_t(track,",
"combine_tracking - check that correct step size is returned when forward_tol is met.",
"> forward_tol) def test_3(): \"\"\" Test for forward_tracking - flag=True and f_new >=",
"test_3(): \"\"\" Test for forward_tracking - flag=True and f_new >= track[-2][1] \"\"\" np.random.seed(90)",
"j in range(1, len(track)): assert(track[j][0] == step) step = step * const_forward if",
"for j in range(1, len(track)): assert(track[j][0] == step) step = step * const_back",
"= np.array([[0, 100], [1, 80], [2, 160], [4, 40], [8, 20], [16, 90]])",
"forward_tol = 100000 beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) upd_point, func_val,",
"- step * beta, *func_args) assert(f_old > f_new) track = np.array([[0, f_old], [step,",
"const_forward, forward_tol, f, func_args)) assert(flag == True) assert(total_func_evals > 0) track_method = 'Forward'",
"np.array([100, 80, 120]))) assert(np.all(track_t == np.array([0, 0.5, 1]))) def test_22(): \"\"\"Test for check_func_val_coeffs",
"0.1) step = 0.001 back_tol = 0.000001 no_vars = 10 region = 1",
"for forward_tracking - flag=True and f_new >= track[-2][1] \"\"\" np.random.seed(90) m = 10",
"assert(count_func_evals == 0) def test_10(): \"\"\" Test for backward_tracking - back tol is",
"is met. \"\"\" np.random.seed(329998) n = 20 m = 100 f = est_dir.quad_f_noise",
"beta, const_back, back_tol, f, func_args)) assert(track.shape == (2, m)) assert(track[0][0] == 0) assert(track[1][0]",
"met. \"\"\" np.random.seed(32964) m = 2 f = est_dir.quad_f_noise const_back = 0.5 minimizer",
"met, f_new < track[-2][1] and eventaully back tol is met. \"\"\" np.random.seed(329998) n",
"[step, f_new]]) track, count_func_evals, flag = (est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta,",
"const_back, back_tol, f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t,",
"= 0.5 minimizer = np.random.uniform(0, 1, (m, )) centre_point = np.random.uniform(0, 1, (m,",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) t = 97.688932389756 back_tol",
"- check that correct step size is returned, when back_tol is met. \"\"\"",
"= (1 / const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, ))",
"f(np.copy(centre_point) - t * beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag =",
"0.005 forward_tol = 10000 back_tol = 0.0000001 beta = np.array([1, 1]) f_old =",
"Test for compute_backward - check that when flag=False, original track is returned. \"\"\"",
"assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_18(): \"\"\"Test",
"f, func_args)) assert(upd_point.shape == (m, )) assert(type(total_func_evals) is int) assert(func_val < f_old) def",
"(est_dir.compute_forward (step, const_forward, forward_tol, track, centre_point, beta, f, func_args)) assert(f_old > f_new) assert(flag",
"= np.array([25, 25]) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0,",
"const_forward, forward_tol, track, centre_point, beta, f, func_args)) assert(f_old > f_new) assert(flag == False)",
"f_old) def test_16(): \"\"\" Test for combine_tracking - check that correct step size",
"assert(upd_point.shape == (m, )) assert(func_val == 40) def test_23(): \"\"\"Test for check_func_val_coeffs when",
"t = t / 2 assert(np.min(track[:, 1]) < track[1][0]) def test_11(): \"\"\" Test",
"is not met. \"\"\" np.random.seed(32964) n = 6 m = 2 f =",
"= 10 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region) assert(func_evals ==",
"j in range(1, len(track)): assert(track[j][0] == step) step = step * const_back if",
")) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 0.1) step",
"for flag=True. \"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise const_back = 0.5",
"m = 100 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.random.uniform(0, 10,",
"forward_tol met. \"\"\" np.random.seed(90) m = 2 f = est_dir.quad_f_noise const_back = 0.5",
"np.random.seed(90) m = 10 f = est_dir.quad_f_noise minimizer = np.ones((m,)) centre_point = np.random.uniform(0,",
"= est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) region = 1",
"f, func_args)) assert(np.round(track[0][0], 3) == np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals",
"25]) matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) t",
"= (est_dir.forward_tracking (centre_point, t, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(np.round(track[0][0], 3)",
"f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - step * beta, *func_args) track,",
"np.round(0, 3)) assert(np.round(track[1][0], 3) == np.round(t, 3)) assert(total_func_evals > 0) assert(flag == False)",
"> track_y[1].\"\"\" np.random.seed(90) m = 10 f = est_dir.quad_f_noise minimizer = np.ones((m,)) centre_point",
"def test_9(): \"\"\" Test for backward_tracking - back_tol is met. \"\"\" np.random.seed(32964) m",
"= (np.linalg.inv(design_matrix_step.T @ design_matrix_step) @ design_matrix_step.T @ track_y) check = -OLS[1] / (2",
"matrix = est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 5) t =",
"centre_point, beta, f, func_args)) assert(f_old > f_new) assert(flag == False) assert(count_func_evals > 0)",
"\"\"\" Test for forward_tracking - forward_tol not met initially, f_new < track[-2][1] and",
"100], [1, 80], [2, 70], [4, 90]]) track_method = 'Forward' track_y, track_t =",
"if j == (len(track) - 1): assert(track[j][1] > track[j - 1][1]) else: assert(track[j",
"== 0) def test_10(): \"\"\" Test for backward_tracking - back tol is not",
"0.1) step = 0.1 back_tol = 0.075 no_vars = 10 region = 1",
"\"\"\" Test for forward_tracking - forward_tol met. \"\"\" np.random.seed(90) m = 2 f",
"/ (2 * OLS[2]) opt_t = est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check, 5) == np.round(opt_t, 5)))",
"= est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 10, (m,))",
"beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region) assert(func_evals == 16) f_old",
"func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f, func_args)) assert(upd_point.shape == (m, ))",
"n) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t * beta, *func_args)",
"= np.array([[0, f_old], [step, f_new]]) track_new, total_func_evals, flag = (est_dir.compute_backward (step, const_back, back_tol,",
"is returned, when back_tol is not met. \"\"\" np.random.seed(32964) n = 6 m",
"track[j-1][1]) else: assert(track[j][1] > track[j-1][1]) def test_8(): \"\"\" Test for compute_backward - check",
"= np.array([[0, 100], [1, 120], [0.5, 110], [0.25, 90]]) track_method = 'Backward' track_y,",
"beta = np.array([200, 200]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) - t",
"func_args = (minimizer, matrix, 0, 60) step = 1.8251102718712913 no_vars = 10 region",
"m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward = (1 /",
"== (len(track) - 1): assert(track[j][1] > track[j - 1][1]) else: assert(track[j - 1][1]",
"4]))) def test_20(): \"\"\"Test for arrange_track_y_t\"\"\" track = np.array([[0, 100], [1, 120], [0.5,",
"np.random.seed(32964) m = 2 f = est_dir.quad_f_noise const_back = 0.5 minimizer = np.ones((m,))",
"step * beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag = (est_dir.forward_tracking (centre_point,",
"(2 * OLS[2]) opt_t = est_dir.compute_coeffs(track_y, track_t) assert(np.all(np.round(check, 5) == np.round(opt_t, 5))) def",
"> track[j - 1][1]) def test_2(): \"\"\" Test for compute_forward() - check that",
"1: assert(track[j][1] < track[j - 1][1]) else: assert(track[j][1] > track[j - 1][1]) def",
"= 'Forward' upd_point, func_val = (est_dir.check_func_val_coeffs (track, track_method, centre_point, beta, f, func_args)) assert(upd_point.shape",
"1 beta, func_evals = est_dir.compute_direction_LS(m, centre_point, f, func_args, no_vars, region) assert(func_evals == 16)",
"0.5 const_forward = (1 / const_back) minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20,",
"10 beta = np.array([1, 1]) f_old = f(np.copy(centre_point), *func_args) f_new = f(np.copy(centre_point) -",
")) assert(type(total_func_evals) is int) assert(func_val < f_old) def test_15(): \"\"\" Test for combine_tracking",
"10 f = est_dir.quad_f_noise minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, ))",
"func_args = (minimizer, matrix, 0, 5) step = 1 back_tol = 1 forward_tol",
"(minimizer, matrix, 0, 5) step = 0.005 forward_tol = 10000 back_tol = 0.0000001",
"f(np.copy(centre_point) - step * beta, *func_args) assert(f_old > f_new) track, total_func_evals, flag =",
"step = 0.17741338024633116 forward_tol = 1000000 no_vars = 10 beta, func_evals = est_dir.compute_direction_LS(m,",
"(track, track_method, centre_point, beta, f, func_args)) assert(upd_point.shape == (m, )) assert(np.all(func_val <= track[:,",
"== np.round(t, 4)) t = t / 2 assert(np.min(track[:, 1]) < track[1][0]) def",
"assert(track[j][0] == step) step = step * const_forward if j < len(track) -",
"flag = (est_dir.forward_tracking (centre_point, step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(len(track)",
"= 0.5 forward_tol = 1.5 beta = np.array([0.0001, 0.0001]) f_old = f(np.copy(centre_point), *func_args)",
"is int) assert(func_val == f_old) def test_17(): \"\"\" Test for combine_tracking - check",
"correct step size is returned, when back_tol is not met. \"\"\" np.random.seed(32964) n",
"forward_tol, f, func_args)) assert(len(track) - 1 == total_func_evals) assert(np.round(track[0][0], 3) == np.round(0, 3))",
"3) == np.round(step, 3)) assert(flag == True) for j in range(2, len(track)): step",
"track = np.array([[0, 100], [1, 80], [2, 160], [4, 40], [8, 20], [16,",
"def test_16(): \"\"\" Test for combine_tracking - check that correct step size is",
"5) step = 0.01 forward_tol = 1000000 no_vars = 10 region = 1",
"= np.ones((m,)) centre_point = np.array([20, 20]) matrix = np.identity(m) func_args = (minimizer, matrix,",
"= step * const_back if j < len(track) - 1: assert(track[j][1] < track[j-1][1])",
"met. \"\"\" np.random.seed(32964) m = 2 f = est_dir.quad_f_noise const_back = 0.5 const_forward",
"np.array(track_t) ** 2)).T assert(np.all(design_matrix_step[0, :] == np.array([100, 0, 0]))) assert(np.all(design_matrix_step[1, :] == np.array([100,",
"m) func_args = (minimizer, matrix, 0, 10) t = 0.005 forward_tol = 10",
"j == (len(track) - 1): assert(track[j][1] > track[j-1][1]) else: assert(track[j-1][1] > track[j][1]) def",
"\"\"\" Test for backward_tracking - back tol is not met and f_new >",
"2) assert(flag == True) assert(track[0][0] == 0) for j in range(1, len(track)): assert(track[j][0]",
"est_dir.quad_func_params(1, 10, m) func_args = (minimizer, matrix, 0, 0.1) step = 0.1 back_tol",
"True) assert(track[0][0] == 0) for j in range(1, len(track)): assert(track[j][0] == step) step",
"== step) step = step * const_back if j < len(track) - 1:",
"track, total_func_evals, flag = (est_dir.forward_tracking (centre_point, t, f_old, f_new, beta, const_forward, forward_tol, f,",
"met and f_new < track[-2][1] \"\"\" np.random.seed(329998) n = 20 m = 100",
"f, func_args)) assert(upd_point.shape == (m, )) assert(func_val == 40) def test_23(): \"\"\"Test for",
"func_args = (minimizer, matrix, 0, 0.1) step = 0.001 back_tol = 0.000001 no_vars",
"correct step size is returned when forward_tol is met. \"\"\" np.random.seed(90) m =",
"len(track) - 1: assert(track[j][1] < track[j - 1][1]) else: assert(track[j][1] > track[j -",
"assert(func_val == f_old) def test_17(): \"\"\" Test for combine_tracking - check that correct",
"est_dir.quad_f_noise minimizer = np.ones((m,)) centre_point = np.random.uniform(0, 20, (m, )) matrix = est_dir.quad_func_params(1,",
"when forward_tol is not met. \"\"\" np.random.seed(3291) m = 2 f = est_dir.quad_f_noise",
"step, f_old, f_new, beta, const_forward, forward_tol, f, func_args)) assert(len(track) - 1 == total_func_evals)",
"test_4(): \"\"\" Test for forward_tracking - forward_tol not met and f_new < track[-2][1]."
] |
[] |
[
"self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def extend_dropdown(self): data = self.data.container.data() if self.data and self.data.container else None",
"= MALE if self.radioMale.isChecked() else gender gender = FEMALE if self.radioFemale.isChecked() else gender",
"data or \"gender.json\" not in data: return gender_data = data[\"gender.json\"] self.list_gender.clear() for _species,",
"species) self.setattr(self.data.gender, \"gender\", gender) def context_menu(self, pos): context = QtWidgets.QMenu() delete_action = context.addAction(\"delete\")",
"context.exec_(self.list_gender.mapToGlobal(pos)) if action == delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self, widget_item): species_name = widget_item.text() button_reply",
"creator.child_views import list_view GENDERLESS = 0 MALE = 1 FEMALE = 2 class",
"list_view GENDERLESS = 0 MALE = 1 FEMALE = 2 class GenderTab(QtWidgets.QWidget, shared.Tab):",
"2 class GenderTab(QtWidgets.QWidget, shared.Tab): def __init__(self, data): super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui', self)",
"= util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def extend_dropdown(self): data = self.data.container.data() if self.data and",
"self.setattr(self.data.gender, \"gender\", gender) def context_menu(self, pos): context = QtWidgets.QMenu() delete_action = context.addAction(\"delete\") action",
"= self.data.container.data() if self.data and self.data.container else None if data and not self.extended:",
"{}\".format(species_name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if button_reply == QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited",
"GENDERLESS = 0 MALE = 1 FEMALE = 2 class GenderTab(QtWidgets.QWidget, shared.Tab): def",
"/ 'GenderTab.ui', self) self.data = data self.extended = False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list =",
"self) self.data = data self.extended = False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list = util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list)",
"self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name)) def update_custom_list(self): data = self.data.container.data() if self.data.container else None if",
"self).__init__() uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui', self) self.data = data self.extended = False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu)",
"self.pkmn_list = util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def extend_dropdown(self): data = self.data.container.data() if self.data",
"and not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended = True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def add(self): species =",
"not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended = True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def add(self): species = self.speciesDropdown.currentText()",
"= self.speciesDropdown.currentText() gender = GENDERLESS if self.radioNoGender.isChecked() else None gender = MALE if",
"delete_gender(self, widget_item): species_name = widget_item.text() button_reply = QtWidgets.QMessageBox.question(None, 'Delete', \"Would you like to",
"| QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if button_reply == QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited = True",
"extend_dropdown(self): data = self.data.container.data() if self.data and self.data.container else None if data and",
"remove {}\".format(species_name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if button_reply == QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow())",
"= QtWidgets.QMessageBox.question(None, 'Delete', \"Would you like to remove {}\".format(species_name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel)",
"= 1 FEMALE = 2 class GenderTab(QtWidgets.QWidget, shared.Tab): def __init__(self, data): super(GenderTab, self).__init__()",
"uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui', self) self.data = data self.extended = False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list",
"from PyQt5.QtCore import Qt from creator.utils import util from creator.child_views import shared from",
"species_name == self.data.gender.species: self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name)) def update_custom_list(self): data = self.data.container.data() if",
"\"gender.json\" not in data: return gender_data = data[\"gender.json\"] self.list_gender.clear() for _species, _ in",
"self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self, widget_item): species_name = widget_item.text() button_reply = QtWidgets.QMessageBox.question(None, 'Delete', \"Would you",
"from creator.child_views import shared from creator.child_views import list_view GENDERLESS = 0 MALE =",
"FEMALE = 2 class GenderTab(QtWidgets.QWidget, shared.Tab): def __init__(self, data): super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI /",
"1 FEMALE = 2 class GenderTab(QtWidgets.QWidget, shared.Tab): def __init__(self, data): super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI",
"\"Would you like to remove {}\".format(species_name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if button_reply ==",
"action == delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self, widget_item): species_name = widget_item.text() button_reply = QtWidgets.QMessageBox.question(None,",
"= self.data.container.data() if self.data.container else None if not data or \"gender.json\" not in",
"= GENDERLESS if self.radioNoGender.isChecked() else None gender = MALE if self.radioMale.isChecked() else gender",
"= FEMALE if self.radioFemale.isChecked() else gender self.setattr(self.data.gender, \"species\", species) self.setattr(self.data.gender, \"gender\", gender) def",
"add(self): species = self.speciesDropdown.currentText() gender = GENDERLESS if self.radioNoGender.isChecked() else None gender =",
"shared.Tab): def __init__(self, data): super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui', self) self.data = data",
"MALE = 1 FEMALE = 2 class GenderTab(QtWidgets.QWidget, shared.Tab): def __init__(self, data): super(GenderTab,",
"species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited = True if species_name == self.data.gender.species: self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name))",
"= 2 class GenderTab(QtWidgets.QWidget, shared.Tab): def __init__(self, data): super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui',",
"self.radioNoGender.isChecked() else None gender = MALE if self.radioMale.isChecked() else gender gender = FEMALE",
"button_reply == QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited = True if species_name == self.data.gender.species:",
"import Qt from creator.utils import util from creator.child_views import shared from creator.child_views import",
"= QtWidgets.QMenu() delete_action = context.addAction(\"delete\") action = context.exec_(self.list_gender.mapToGlobal(pos)) if action == delete_action: self.delete_gender(self.list_gender.selectedItems()[0])",
"log.info(\"Deleted {}\".format(species_name)) def update_custom_list(self): data = self.data.container.data() if self.data.container else None if not",
"data self.extended = False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list = util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def",
"QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited = True if species_name == self.data.gender.species: self.data.gender.new() self.update_list_signal.emit()",
"delete_action = context.addAction(\"delete\") action = context.exec_(self.list_gender.mapToGlobal(pos)) if action == delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self,",
"self.setattr(self.data.gender, \"species\", species) self.setattr(self.data.gender, \"gender\", gender) def context_menu(self, pos): context = QtWidgets.QMenu() delete_action",
"update_custom_list(self): data = self.data.container.data() if self.data.container else None if not data or \"gender.json\"",
"if self.radioNoGender.isChecked() else None gender = MALE if self.radioMale.isChecked() else gender gender =",
"uic from PyQt5.QtCore import Qt from creator.utils import util from creator.child_views import shared",
"= True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def add(self): species = self.speciesDropdown.currentText() gender = GENDERLESS if",
"None gender = MALE if self.radioMale.isChecked() else gender gender = FEMALE if self.radioFemale.isChecked()",
"self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name)) def update_custom_list(self): data = self.data.container.data() if self.data.container else None",
"QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if button_reply == QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited = True if",
"PyQt5 import QtWidgets, uic from PyQt5.QtCore import Qt from creator.utils import util from",
"== QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited = True if species_name == self.data.gender.species: self.data.gender.new()",
"else None gender = MALE if self.radioMale.isChecked() else gender gender = FEMALE if",
"gender = MALE if self.radioMale.isChecked() else gender gender = FEMALE if self.radioFemale.isChecked() else",
"\"gender\", gender) def context_menu(self, pos): context = QtWidgets.QMenu() delete_action = context.addAction(\"delete\") action =",
"def add(self): species = self.speciesDropdown.currentText() gender = GENDERLESS if self.radioNoGender.isChecked() else None gender",
"pos): context = QtWidgets.QMenu() delete_action = context.addAction(\"delete\") action = context.exec_(self.list_gender.mapToGlobal(pos)) if action ==",
"QtWidgets, uic from PyQt5.QtCore import Qt from creator.utils import util from creator.child_views import",
"gender self.setattr(self.data.gender, \"species\", species) self.setattr(self.data.gender, \"gender\", gender) def context_menu(self, pos): context = QtWidgets.QMenu()",
"creator.utils import util from creator.child_views import shared from creator.child_views import list_view GENDERLESS =",
"self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list = util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def extend_dropdown(self): data = self.data.container.data() if",
"to remove {}\".format(species_name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if button_reply == QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name)",
"action = context.exec_(self.list_gender.mapToGlobal(pos)) if action == delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self, widget_item): species_name =",
"or \"gender.json\" not in data: return gender_data = data[\"gender.json\"] self.list_gender.clear() for _species, _",
"else None if not data or \"gender.json\" not in data: return gender_data =",
"GenderTab(QtWidgets.QWidget, shared.Tab): def __init__(self, data): super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui', self) self.data =",
"self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended = True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def add(self): species = self.speciesDropdown.currentText() gender",
"if button_reply == QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited = True if species_name ==",
"== self.data.gender.species: self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name)) def update_custom_list(self): data = self.data.container.data() if self.data.container",
"in data: return gender_data = data[\"gender.json\"] self.list_gender.clear() for _species, _ in gender_data.items(): self.list_gender.addItem(_species)",
"self.speciesDropdown.currentText() gender = GENDERLESS if self.radioNoGender.isChecked() else None gender = MALE if self.radioMale.isChecked()",
"shared from creator.child_views import list_view GENDERLESS = 0 MALE = 1 FEMALE =",
"data): super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui', self) self.data = data self.extended = False",
"self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list = util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def extend_dropdown(self): data = self.data.container.data()",
"if self.radioFemale.isChecked() else gender self.setattr(self.data.gender, \"species\", species) self.setattr(self.data.gender, \"gender\", gender) def context_menu(self, pos):",
"widget_item): species_name = widget_item.text() button_reply = QtWidgets.QMessageBox.question(None, 'Delete', \"Would you like to remove",
"util from creator.child_views import shared from creator.child_views import list_view GENDERLESS = 0 MALE",
"self.data.container.data() if self.data.container else None if not data or \"gender.json\" not in data:",
"gender gender = FEMALE if self.radioFemale.isChecked() else gender self.setattr(self.data.gender, \"species\", species) self.setattr(self.data.gender, \"gender\",",
"gender = FEMALE if self.radioFemale.isChecked() else gender self.setattr(self.data.gender, \"species\", species) self.setattr(self.data.gender, \"gender\", gender)",
"Qt from creator.utils import util from creator.child_views import shared from creator.child_views import list_view",
"self.radioMale.isChecked() else gender gender = FEMALE if self.radioFemale.isChecked() else gender self.setattr(self.data.gender, \"species\", species)",
"def delete_gender(self, widget_item): species_name = widget_item.text() button_reply = QtWidgets.QMessageBox.question(None, 'Delete', \"Would you like",
"GENDERLESS if self.radioNoGender.isChecked() else None gender = MALE if self.radioMale.isChecked() else gender gender",
"self.extended = False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list = util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def extend_dropdown(self):",
"self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited = True if species_name == self.data.gender.species: self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted",
"data = self.data.container.data() if self.data.container else None if not data or \"gender.json\" not",
"from creator.child_views import list_view GENDERLESS = 0 MALE = 1 FEMALE = 2",
"log from PyQt5 import QtWidgets, uic from PyQt5.QtCore import Qt from creator.utils import",
"species_name = widget_item.text() button_reply = QtWidgets.QMessageBox.question(None, 'Delete', \"Would you like to remove {}\".format(species_name),",
"def __init__(self, data): super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui', self) self.data = data self.extended",
"if not data or \"gender.json\" not in data: return gender_data = data[\"gender.json\"] self.list_gender.clear()",
"if self.data.container else None if not data or \"gender.json\" not in data: return",
"self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def extend_dropdown(self): data = self.data.container.data() if self.data and self.data.container else",
"import list_view GENDERLESS = 0 MALE = 1 FEMALE = 2 class GenderTab(QtWidgets.QWidget,",
"= 0 MALE = 1 FEMALE = 2 class GenderTab(QtWidgets.QWidget, shared.Tab): def __init__(self,",
"def update_custom_list(self): data = self.data.container.data() if self.data.container else None if not data or",
"import util from creator.child_views import shared from creator.child_views import list_view GENDERLESS = 0",
"self.speciesDropdown.addItems(self.pkmn_list) def add(self): species = self.speciesDropdown.currentText() gender = GENDERLESS if self.radioNoGender.isChecked() else None",
"= False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list = util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def extend_dropdown(self): data",
"class GenderTab(QtWidgets.QWidget, shared.Tab): def __init__(self, data): super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui', self) self.data",
"if self.data and self.data.container else None if data and not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended",
"delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self, widget_item): species_name = widget_item.text() button_reply = QtWidgets.QMessageBox.question(None, 'Delete', \"Would",
"you like to remove {}\".format(species_name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if button_reply == QtWidgets.QMessageBox.Yes:",
"False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list = util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def extend_dropdown(self): data =",
"from PyQt5 import QtWidgets, uic from PyQt5.QtCore import Qt from creator.utils import util",
"self.extended = True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def add(self): species = self.speciesDropdown.currentText() gender = GENDERLESS",
"context.addAction(\"delete\") action = context.exec_(self.list_gender.mapToGlobal(pos)) if action == delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self, widget_item): species_name",
"super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui', self) self.data = data self.extended = False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu)",
"creator.child_views import shared from creator.child_views import list_view GENDERLESS = 0 MALE = 1",
"if action == delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self, widget_item): species_name = widget_item.text() button_reply =",
"self.data.container.data() if self.data and self.data.container else None if data and not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"])",
"self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited = True if species_name == self.data.gender.species: self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name)) def",
"import shared from creator.child_views import list_view GENDERLESS = 0 MALE = 1 FEMALE",
"PyQt5.QtCore import Qt from creator.utils import util from creator.child_views import shared from creator.child_views",
"self.data.container else None if data and not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended = True self.speciesDropdown.clear()",
"as log from PyQt5 import QtWidgets, uic from PyQt5.QtCore import Qt from creator.utils",
"self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def add(self): species = self.speciesDropdown.currentText() gender = GENDERLESS if self.radioNoGender.isChecked() else",
"gender = GENDERLESS if self.radioNoGender.isChecked() else None gender = MALE if self.radioMale.isChecked() else",
"else None if data and not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended = True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list)",
"0 MALE = 1 FEMALE = 2 class GenderTab(QtWidgets.QWidget, shared.Tab): def __init__(self, data):",
"__init__(self, data): super(GenderTab, self).__init__() uic.loadUi(util.RESOURCE_UI / 'GenderTab.ui', self) self.data = data self.extended =",
"context = QtWidgets.QMenu() delete_action = context.addAction(\"delete\") action = context.exec_(self.list_gender.mapToGlobal(pos)) if action == delete_action:",
"== delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self, widget_item): species_name = widget_item.text() button_reply = QtWidgets.QMessageBox.question(None, 'Delete',",
"import QtWidgets, uic from PyQt5.QtCore import Qt from creator.utils import util from creator.child_views",
"import logging as log from PyQt5 import QtWidgets, uic from PyQt5.QtCore import Qt",
"self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended = True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def add(self): species = self.speciesDropdown.currentText() gender =",
"QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if button_reply == QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited =",
"self.data.gender.species: self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name)) def update_custom_list(self): data = self.data.container.data() if self.data.container else",
"{}\".format(species_name)) def update_custom_list(self): data = self.data.container.data() if self.data.container else None if not data",
"None if data and not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended = True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def",
"gender) def context_menu(self, pos): context = QtWidgets.QMenu() delete_action = context.addAction(\"delete\") action = context.exec_(self.list_gender.mapToGlobal(pos))",
"= context.exec_(self.list_gender.mapToGlobal(pos)) if action == delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self, widget_item): species_name = widget_item.text()",
"FEMALE if self.radioFemale.isChecked() else gender self.setattr(self.data.gender, \"species\", species) self.setattr(self.data.gender, \"gender\", gender) def context_menu(self,",
"not in data: return gender_data = data[\"gender.json\"] self.list_gender.clear() for _species, _ in gender_data.items():",
"data = self.data.container.data() if self.data and self.data.container else None if data and not",
"not data or \"gender.json\" not in data: return gender_data = data[\"gender.json\"] self.list_gender.clear() for",
"like to remove {}\".format(species_name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if button_reply == QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\",",
"if self.radioMale.isChecked() else gender gender = FEMALE if self.radioFemale.isChecked() else gender self.setattr(self.data.gender, \"species\",",
"util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add) def extend_dropdown(self): data = self.data.container.data() if self.data and self.data.container",
"from creator.utils import util from creator.child_views import shared from creator.child_views import list_view GENDERLESS",
"MALE if self.radioMale.isChecked() else gender gender = FEMALE if self.radioFemale.isChecked() else gender self.setattr(self.data.gender,",
"if data and not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended = True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def add(self):",
"self.data._edited = True if species_name == self.data.gender.species: self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name)) def update_custom_list(self):",
"= widget_item.text() button_reply = QtWidgets.QMessageBox.question(None, 'Delete', \"Would you like to remove {}\".format(species_name), QtWidgets.QMessageBox.Yes",
"'GenderTab.ui', self) self.data = data self.extended = False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list = util.pokemon_list()",
"self.data and self.data.container else None if data and not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended =",
"QtWidgets.QMenu() delete_action = context.addAction(\"delete\") action = context.exec_(self.list_gender.mapToGlobal(pos)) if action == delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def",
"QtWidgets.QMessageBox.question(None, 'Delete', \"Would you like to remove {}\".format(species_name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if",
"self.add_button.clicked.connect(self.add) def extend_dropdown(self): data = self.data.container.data() if self.data and self.data.container else None if",
"data and not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended = True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def add(self): species",
"widget_item.text() button_reply = QtWidgets.QMessageBox.question(None, 'Delete', \"Would you like to remove {}\".format(species_name), QtWidgets.QMessageBox.Yes |",
"QtWidgets.QMessageBox.Cancel) if button_reply == QtWidgets.QMessageBox.Yes: self.data.container.delete_entry(\"gender.json\", species_name) self.list_gender.takeItem(self.list_gender.currentRow()) self.data._edited = True if species_name",
"= data self.extended = False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list = util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown) self.add_button.clicked.connect(self.add)",
"def context_menu(self, pos): context = QtWidgets.QMenu() delete_action = context.addAction(\"delete\") action = context.exec_(self.list_gender.mapToGlobal(pos)) if",
"and self.data.container else None if data and not self.extended: self.pkmn_list.extend(data[\"pokemon.json\"]) self.extended = True",
"None if not data or \"gender.json\" not in data: return gender_data = data[\"gender.json\"]",
"species = self.speciesDropdown.currentText() gender = GENDERLESS if self.radioNoGender.isChecked() else None gender = MALE",
"True self.speciesDropdown.clear() self.speciesDropdown.addItems(self.pkmn_list) def add(self): species = self.speciesDropdown.currentText() gender = GENDERLESS if self.radioNoGender.isChecked()",
"button_reply = QtWidgets.QMessageBox.question(None, 'Delete', \"Would you like to remove {}\".format(species_name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel,",
"= context.addAction(\"delete\") action = context.exec_(self.list_gender.mapToGlobal(pos)) if action == delete_action: self.delete_gender(self.list_gender.selectedItems()[0]) def delete_gender(self, widget_item):",
"'Delete', \"Would you like to remove {}\".format(species_name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) if button_reply",
"logging as log from PyQt5 import QtWidgets, uic from PyQt5.QtCore import Qt from",
"self.radioFemale.isChecked() else gender self.setattr(self.data.gender, \"species\", species) self.setattr(self.data.gender, \"gender\", gender) def context_menu(self, pos): context",
"\"species\", species) self.setattr(self.data.gender, \"gender\", gender) def context_menu(self, pos): context = QtWidgets.QMenu() delete_action =",
"= True if species_name == self.data.gender.species: self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name)) def update_custom_list(self): data",
"True if species_name == self.data.gender.species: self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name)) def update_custom_list(self): data =",
"else gender self.setattr(self.data.gender, \"species\", species) self.setattr(self.data.gender, \"gender\", gender) def context_menu(self, pos): context =",
"context_menu(self, pos): context = QtWidgets.QMenu() delete_action = context.addAction(\"delete\") action = context.exec_(self.list_gender.mapToGlobal(pos)) if action",
"self.data = data self.extended = False self.list_gender.setContextMenuPolicy(Qt.CustomContextMenu) self.list_gender.customContextMenuRequested.connect(self.context_menu) self.pkmn_list = util.pokemon_list() self.speciesDropdown.addItems(self.pkmn_list) self.speciesDropdown.activated.connect(self.extend_dropdown)",
"self.data.container else None if not data or \"gender.json\" not in data: return gender_data",
"if species_name == self.data.gender.species: self.data.gender.new() self.update_list_signal.emit() log.info(\"Deleted {}\".format(species_name)) def update_custom_list(self): data = self.data.container.data()",
"else gender gender = FEMALE if self.radioFemale.isChecked() else gender self.setattr(self.data.gender, \"species\", species) self.setattr(self.data.gender,",
"def extend_dropdown(self): data = self.data.container.data() if self.data and self.data.container else None if data"
] |
[
"(m/s)', 'Wind Direction (°)', 'Humidity (%)']] for a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return barChartData",
"get_LineChartData(date_time,actualPower): lineChartData = [] for i,j in zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData # This",
"to plot in Bar Chart ... def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData = [['Date-Time ', 'Wind",
"barChartData.append(list((a,b,c,d))) return barChartData def get_TableData(date_time,actualPower,wind_speed): tableData = [] for p,q,r in zip(date_time,actualPower,wind_speed): tableData.append(list((p,q,r)))",
"in zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData # This Function formating the data to plot",
"lineChartData.append(list((i,j))) return lineChartData # This Function formating the data to plot in Bar",
"... def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData = [['Date-Time ', 'Wind Speed (m/s)', 'Wind Direction (°)',",
"lineChartData # This Function formating the data to plot in Bar Chart ...",
"= [['Date-Time ', 'Wind Speed (m/s)', 'Wind Direction (°)', 'Humidity (%)']] for a,b,c,d",
"(%)']] for a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return barChartData def get_TableData(date_time,actualPower,wind_speed): tableData = []",
"# This Function formating the data to plot in Line Chart ... def",
"Chart ... def get_LineChartData(date_time,actualPower): lineChartData = [] for i,j in zip(date_time,actualPower): lineChartData.append(list((i,j))) return",
"Speed (m/s)', 'Wind Direction (°)', 'Humidity (%)']] for a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return",
"barChartData = [['Date-Time ', 'Wind Speed (m/s)', 'Wind Direction (°)', 'Humidity (%)']] for",
"'Wind Speed (m/s)', 'Wind Direction (°)', 'Humidity (%)']] for a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d)))",
"get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData = [['Date-Time ', 'Wind Speed (m/s)', 'Wind Direction (°)', 'Humidity (%)']]",
"formating the data to plot in Bar Chart ... def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData =",
"Function formating the data to plot in Line Chart ... def get_LineChartData(date_time,actualPower): lineChartData",
"formating the data to plot in Line Chart ... def get_LineChartData(date_time,actualPower): lineChartData =",
"for i,j in zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData # This Function formating the data",
"Direction (°)', 'Humidity (%)']] for a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return barChartData def get_TableData(date_time,actualPower,wind_speed):",
"'Humidity (%)']] for a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return barChartData def get_TableData(date_time,actualPower,wind_speed): tableData =",
"data to plot in Line Chart ... def get_LineChartData(date_time,actualPower): lineChartData = [] for",
"This Function formating the data to plot in Line Chart ... def get_LineChartData(date_time,actualPower):",
"data to plot in Bar Chart ... def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData = [['Date-Time ',",
"i,j in zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData # This Function formating the data to",
"Chart ... def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData = [['Date-Time ', 'Wind Speed (m/s)', 'Wind Direction",
"return lineChartData # This Function formating the data to plot in Bar Chart",
"def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData = [['Date-Time ', 'Wind Speed (m/s)', 'Wind Direction (°)', 'Humidity",
"', 'Wind Speed (m/s)', 'Wind Direction (°)', 'Humidity (%)']] for a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity):",
"(°)', 'Humidity (%)']] for a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return barChartData def get_TableData(date_time,actualPower,wind_speed): tableData",
"... def get_LineChartData(date_time,actualPower): lineChartData = [] for i,j in zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData",
"Line Chart ... def get_LineChartData(date_time,actualPower): lineChartData = [] for i,j in zip(date_time,actualPower): lineChartData.append(list((i,j)))",
"zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return barChartData def get_TableData(date_time,actualPower,wind_speed): tableData = [] for p,q,r in zip(date_time,actualPower,wind_speed):",
"the data to plot in Bar Chart ... def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData = [['Date-Time",
"return barChartData def get_TableData(date_time,actualPower,wind_speed): tableData = [] for p,q,r in zip(date_time,actualPower,wind_speed): tableData.append(list((p,q,r))) return",
"barChartData def get_TableData(date_time,actualPower,wind_speed): tableData = [] for p,q,r in zip(date_time,actualPower,wind_speed): tableData.append(list((p,q,r))) return tableData",
"'Wind Direction (°)', 'Humidity (%)']] for a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return barChartData def",
"[] for i,j in zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData # This Function formating the",
"the data to plot in Line Chart ... def get_LineChartData(date_time,actualPower): lineChartData = []",
"for a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return barChartData def get_TableData(date_time,actualPower,wind_speed): tableData = [] for",
"in Bar Chart ... def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData = [['Date-Time ', 'Wind Speed (m/s)',",
"zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData # This Function formating the data to plot in",
"plot in Line Chart ... def get_LineChartData(date_time,actualPower): lineChartData = [] for i,j in",
"in Line Chart ... def get_LineChartData(date_time,actualPower): lineChartData = [] for i,j in zip(date_time,actualPower):",
"Function formating the data to plot in Bar Chart ... def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData",
"plot in Bar Chart ... def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData = [['Date-Time ', 'Wind Speed",
"Bar Chart ... def get_BarChartData(date_time,wind_speed,wind_deg,humidity): barChartData = [['Date-Time ', 'Wind Speed (m/s)', 'Wind",
"to plot in Line Chart ... def get_LineChartData(date_time,actualPower): lineChartData = [] for i,j",
"= [] for i,j in zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData # This Function formating",
"This Function formating the data to plot in Bar Chart ... def get_BarChartData(date_time,wind_speed,wind_deg,humidity):",
"in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return barChartData def get_TableData(date_time,actualPower,wind_speed): tableData = [] for p,q,r in",
"def get_LineChartData(date_time,actualPower): lineChartData = [] for i,j in zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData #",
"a,b,c,d in zip(date_time,wind_speed,wind_deg,humidity): barChartData.append(list((a,b,c,d))) return barChartData def get_TableData(date_time,actualPower,wind_speed): tableData = [] for p,q,r",
"# This Function formating the data to plot in Bar Chart ... def",
"[['Date-Time ', 'Wind Speed (m/s)', 'Wind Direction (°)', 'Humidity (%)']] for a,b,c,d in",
"lineChartData = [] for i,j in zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData # This Function",
"<reponame>sujoy-coder/CFC-2020 # This Function formating the data to plot in Line Chart ..."
] |
[
"self._setting_url = value def parse_response_content(self, response_content): response = super(AlipayEcoDoctemplateSettingurlQueryResponse, self).parse_response_content(response_content) if 'setting_url' in",
"= value def parse_response_content(self, response_content): response = super(AlipayEcoDoctemplateSettingurlQueryResponse, self).parse_response_content(response_content) if 'setting_url' in response:",
"def parse_response_content(self, response_content): response = super(AlipayEcoDoctemplateSettingurlQueryResponse, self).parse_response_content(response_content) if 'setting_url' in response: self.setting_url =",
"value def parse_response_content(self, response_content): response = super(AlipayEcoDoctemplateSettingurlQueryResponse, self).parse_response_content(response_content) if 'setting_url' in response: self.setting_url",
"# -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse):",
"utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse,",
"return self._setting_url @setting_url.setter def setting_url(self, value): self._setting_url = value def parse_response_content(self, response_content): response",
"@property def setting_url(self): return self._setting_url @setting_url.setter def setting_url(self, value): self._setting_url = value def",
"import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url",
"class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url = None @property def setting_url(self): return",
"import AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url = None @property def",
"setting_url(self, value): self._setting_url = value def parse_response_content(self, response_content): response = super(AlipayEcoDoctemplateSettingurlQueryResponse, self).parse_response_content(response_content) if",
"coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self):",
"json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url =",
"value): self._setting_url = value def parse_response_content(self, response_content): response = super(AlipayEcoDoctemplateSettingurlQueryResponse, self).parse_response_content(response_content) if 'setting_url'",
"__init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url = None @property def setting_url(self): return self._setting_url @setting_url.setter def",
"alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url = None @property",
"None @property def setting_url(self): return self._setting_url @setting_url.setter def setting_url(self, value): self._setting_url = value",
"<filename>alipay/aop/api/response/AlipayEcoDoctemplateSettingurlQueryResponse.py #!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import",
"parse_response_content(self, response_content): response = super(AlipayEcoDoctemplateSettingurlQueryResponse, self).parse_response_content(response_content) if 'setting_url' in response: self.setting_url = response['setting_url']",
"AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url = None @property def setting_url(self): return self._setting_url",
"def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url = None @property def setting_url(self): return self._setting_url @setting_url.setter",
"super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url = None @property def setting_url(self): return self._setting_url @setting_url.setter def setting_url(self,",
"self).__init__() self._setting_url = None @property def setting_url(self): return self._setting_url @setting_url.setter def setting_url(self, value):",
"self._setting_url = None @property def setting_url(self): return self._setting_url @setting_url.setter def setting_url(self, value): self._setting_url",
"from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url = None",
"def setting_url(self): return self._setting_url @setting_url.setter def setting_url(self, value): self._setting_url = value def parse_response_content(self,",
"def setting_url(self, value): self._setting_url = value def parse_response_content(self, response_content): response = super(AlipayEcoDoctemplateSettingurlQueryResponse, self).parse_response_content(response_content)",
"@setting_url.setter def setting_url(self, value): self._setting_url = value def parse_response_content(self, response_content): response = super(AlipayEcoDoctemplateSettingurlQueryResponse,",
"-*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def",
"-*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__()",
"self._setting_url @setting_url.setter def setting_url(self, value): self._setting_url = value def parse_response_content(self, response_content): response =",
"python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class",
"AlipayResponse class AlipayEcoDoctemplateSettingurlQueryResponse(AlipayResponse): def __init__(self): super(AlipayEcoDoctemplateSettingurlQueryResponse, self).__init__() self._setting_url = None @property def setting_url(self):",
"setting_url(self): return self._setting_url @setting_url.setter def setting_url(self, value): self._setting_url = value def parse_response_content(self, response_content):",
"#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse",
"= None @property def setting_url(self): return self._setting_url @setting_url.setter def setting_url(self, value): self._setting_url ="
] |
[
"if value == args: return 'active' else: split_vals = value.split('/') if split_vals[1] ==",
"@register.filter(name='get_class') def get_class(value, args): if value == args: return 'active' else: split_vals =",
"def get_class(value, args): if value == args: return 'active' else: split_vals = value.split('/')",
"== args: return 'active' else: split_vals = value.split('/') if split_vals[1] == args: return",
"get_class(value, args): if value == args: return 'active' else: split_vals = value.split('/') if",
"template register = template.Library() @register.filter(name='get_class') def get_class(value, args): if value == args: return",
"register = template.Library() @register.filter(name='get_class') def get_class(value, args): if value == args: return 'active'",
"value == args: return 'active' else: split_vals = value.split('/') if split_vals[1] == args:",
"import template register = template.Library() @register.filter(name='get_class') def get_class(value, args): if value == args:",
"return 'active' else: split_vals = value.split('/') if split_vals[1] == args: return 'active' else:",
"'active' else: split_vals = value.split('/') if split_vals[1] == args: return 'active' else: return",
"from django import template register = template.Library() @register.filter(name='get_class') def get_class(value, args): if value",
"<reponame>Rebeccacheptoek/cpims-ovc-3.0<gh_stars>1-10 from django import template register = template.Library() @register.filter(name='get_class') def get_class(value, args): if",
"= template.Library() @register.filter(name='get_class') def get_class(value, args): if value == args: return 'active' else:",
"args): if value == args: return 'active' else: split_vals = value.split('/') if split_vals[1]",
"template.Library() @register.filter(name='get_class') def get_class(value, args): if value == args: return 'active' else: split_vals",
"args: return 'active' else: split_vals = value.split('/') if split_vals[1] == args: return 'active'",
"else: split_vals = value.split('/') if split_vals[1] == args: return 'active' else: return ''",
"django import template register = template.Library() @register.filter(name='get_class') def get_class(value, args): if value =="
] |
[
"answer = input(\"\"\"You are about to squash all users email. This action is",
"about to squash all users email. This action is IRREVERSIBLE! Are you sure",
"to squash all users email. This action is IRREVERSIBLE! Are you sure you",
"action is IRREVERSIBLE! Are you sure you want to do this? Type 'yes'",
"continue, or 'no' to cancel: \"\"\") self.stdout.write('\\n') if answer != \"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.'))",
"*args, **options): answer = input(\"\"\"You are about to squash all users email. This",
"handle(self, *args, **options): answer = input(\"\"\"You are about to squash all users email.",
"squash all users email. This action is IRREVERSIBLE! Are you sure you want",
"Command(BaseCommand): help = 'Squash all users email' def handle(self, *args, **options): answer =",
"is IRREVERSIBLE! Are you sure you want to do this? Type 'yes' to",
"IRREVERSIBLE! Are you sure you want to do this? Type 'yes' to continue,",
"all users email. This action is IRREVERSIBLE! Are you sure you want to",
"from django.core.management.base import BaseCommand from accounts.models import User class Command(BaseCommand): help = 'Squash",
"django.core.management.base import BaseCommand from accounts.models import User class Command(BaseCommand): help = 'Squash all",
"to continue, or 'no' to cancel: \"\"\") self.stdout.write('\\n') if answer != \"yes\": self.stdout.write(self.style.NOTICE('Action",
"Type 'yes' to continue, or 'no' to cancel: \"\"\") self.stdout.write('\\n') if answer !=",
"answer != \"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.')) return for user in User.objects.all(): user.email = ''",
"self.stdout.write(self.style.NOTICE('Action cancelled.')) return for user in User.objects.all(): user.email = '' user.save() self.stdout.write(self.style.SUCCESS('All emails",
"import BaseCommand from accounts.models import User class Command(BaseCommand): help = 'Squash all users",
"all users email' def handle(self, *args, **options): answer = input(\"\"\"You are about to",
"\"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.')) return for user in User.objects.all(): user.email = '' user.save() self.stdout.write(self.style.SUCCESS('All",
"'yes' to continue, or 'no' to cancel: \"\"\") self.stdout.write('\\n') if answer != \"yes\":",
"you want to do this? Type 'yes' to continue, or 'no' to cancel:",
"or 'no' to cancel: \"\"\") self.stdout.write('\\n') if answer != \"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.')) return",
"class Command(BaseCommand): help = 'Squash all users email' def handle(self, *args, **options): answer",
"if answer != \"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.')) return for user in User.objects.all(): user.email =",
"accounts.models import User class Command(BaseCommand): help = 'Squash all users email' def handle(self,",
"do this? Type 'yes' to continue, or 'no' to cancel: \"\"\") self.stdout.write('\\n') if",
"help = 'Squash all users email' def handle(self, *args, **options): answer = input(\"\"\"You",
"from accounts.models import User class Command(BaseCommand): help = 'Squash all users email' def",
"!= \"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.')) return for user in User.objects.all(): user.email = '' user.save()",
"BaseCommand from accounts.models import User class Command(BaseCommand): help = 'Squash all users email'",
"cancelled.')) return for user in User.objects.all(): user.email = '' user.save() self.stdout.write(self.style.SUCCESS('All emails squashed.'))",
"email' def handle(self, *args, **options): answer = input(\"\"\"You are about to squash all",
"email. This action is IRREVERSIBLE! Are you sure you want to do this?",
"import User class Command(BaseCommand): help = 'Squash all users email' def handle(self, *args,",
"**options): answer = input(\"\"\"You are about to squash all users email. This action",
"users email. This action is IRREVERSIBLE! Are you sure you want to do",
"'no' to cancel: \"\"\") self.stdout.write('\\n') if answer != \"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.')) return for",
"User class Command(BaseCommand): help = 'Squash all users email' def handle(self, *args, **options):",
"want to do this? Type 'yes' to continue, or 'no' to cancel: \"\"\")",
"'Squash all users email' def handle(self, *args, **options): answer = input(\"\"\"You are about",
"= input(\"\"\"You are about to squash all users email. This action is IRREVERSIBLE!",
"input(\"\"\"You are about to squash all users email. This action is IRREVERSIBLE! Are",
"to cancel: \"\"\") self.stdout.write('\\n') if answer != \"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.')) return for user",
"= 'Squash all users email' def handle(self, *args, **options): answer = input(\"\"\"You are",
"sure you want to do this? Type 'yes' to continue, or 'no' to",
"users email' def handle(self, *args, **options): answer = input(\"\"\"You are about to squash",
"to do this? Type 'yes' to continue, or 'no' to cancel: \"\"\") self.stdout.write('\\n')",
"\"\"\") self.stdout.write('\\n') if answer != \"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.')) return for user in User.objects.all():",
"are about to squash all users email. This action is IRREVERSIBLE! Are you",
"cancel: \"\"\") self.stdout.write('\\n') if answer != \"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.')) return for user in",
"you sure you want to do this? Type 'yes' to continue, or 'no'",
"self.stdout.write('\\n') if answer != \"yes\": self.stdout.write(self.style.NOTICE('Action cancelled.')) return for user in User.objects.all(): user.email",
"Are you sure you want to do this? Type 'yes' to continue, or",
"This action is IRREVERSIBLE! Are you sure you want to do this? Type",
"<reponame>JulienPalard/PonyConf<gh_stars>10-100 from django.core.management.base import BaseCommand from accounts.models import User class Command(BaseCommand): help =",
"this? Type 'yes' to continue, or 'no' to cancel: \"\"\") self.stdout.write('\\n') if answer",
"def handle(self, *args, **options): answer = input(\"\"\"You are about to squash all users"
] |
[
"\"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"),",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--nuclei\", lambda tempdir, *args, **kwargs: os.path.join(",
"], [ \"starfish\", \"decode\", \"-i\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"),",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--nuclei\", lambda tempdir, *args, **kwargs:",
"tempdir, \"results\", \"spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join(",
"[ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\") ],",
"*args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda tempdir, *args, **kwargs:",
"\"filtered\", \"nuclei.json\"), \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"Watershed\", \"--nuclei-threshold\",",
"\"-i\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda",
"This test and docs/source/usage/iss/iss_cli.sh test the same code paths and should be updated",
"[ \"starfish\", \"validate\", \"experiment\", EXPERIMENT_JSON_URL, ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda",
"\"\"\" import os import unittest import numpy as np import pandas as pd",
"\"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ],",
"tempdir, \"filtered\", \"dots.json\"), \"--blobs-axis\", \"r\", \"--blobs-axis\", \"c\", \"BlobDetector\", \"--min-sigma\", \"4\", \"--max-sigma\", \"6\", \"--num-sigma\",",
"\"filtered\", \"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda",
"\"dots.json\"), \"--blobs-axis\", \"r\", \"--blobs-axis\", \"c\", \"BlobDetector\", \"--min-sigma\", \"4\", \"--max-sigma\", \"6\", \"--num-sigma\", \"20\", \"--threshold\",",
"np.unique( intensities.coords[Features.TARGET], return_counts=True) gene_counts = pd.Series(counts, genes) # TODO THERE\"S NO HUMAN/MOUSE KEYS?",
"\"spots.nc\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"Label\", ], [",
"the same code paths and should be updated together \"\"\" import os import",
"\"targeted-spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\",",
"[ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\",",
"], # Validate results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join(",
"together \"\"\" import os import unittest import numpy as np import pandas as",
"os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"),",
"\"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\",",
"tempdir, \"registered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"WhiteTophat\",",
"os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"),",
"[ \"starfish\", \"learn_transform\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"--output\",",
"\"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"MaxProj\", \"--dims\", \"c\", \"--dims\",",
"\"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\") ], ) def verify_results(self,",
"\"transforms\", \"transforms.json\"), \"Warp\", ], [ \"starfish\", \"filter\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join(",
"**kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\",",
"\"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\") ], [ \"starfish\",",
") @property def stages(self): return ( [ \"starfish\", \"validate\", \"experiment\", EXPERIMENT_JSON_URL, ], [",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda tempdir, *args,",
"\"primary_images.json\"), \"MaxProj\", \"--dims\", \"c\", \"--dims\", \"z\" ], [ \"starfish\", \"learn_transform\", \"--input\", lambda tempdir,",
"same code paths and should be updated together \"\"\" import os import unittest",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"--intensities\", lambda tempdir, *args, **kwargs: os.path.join(",
"\"starfish\", \"detect_spots\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--output\", lambda",
"[ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\",",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"Label\", ], [ \"starfish\", \"decode\",",
"\"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\") ], [ \"starfish\",",
"*args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"np import pandas as pd import pytest from starfish.test.full_pipelines.cli._base_cli_test import CLITest from starfish.types",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join(",
"\"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\",",
"@property def stages(self): return ( [ \"starfish\", \"validate\", \"experiment\", EXPERIMENT_JSON_URL, ], [ \"starfish\",",
"\"--upsampling\", \"1000\", \"--axes\", \"r\" ], [ \"starfish\", \"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir,",
"**kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--transformation-list\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\",",
"os.path.join( tempdir, \"results\", \"spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs:",
"docs/source/usage/iss/iss_cli.sh test the same code paths and should be updated together \"\"\" import",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\") ], ) def verify_results(self, intensities): #",
"\"transforms\", \"transforms.json\"), \"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\", \"--axes\", \"r\" ], [ \"starfish\", \"apply_transform\",",
"os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Warp\", ], [ \"starfish\", \"filter\", \"--input\", lambda tempdir, *args,",
"return ( \"max_projected\", \"transforms\", \"registered\", \"filtered\", \"results\", ) @property def stages(self): return (",
"*args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"Label\", ], [ \"starfish\", \"decode\", \"-i\", lambda",
"import unittest import numpy as np import pandas as pd import pytest from",
"\"filtered\", \"dots.json\"), \"--blobs-axis\", \"r\", \"--blobs-axis\", \"c\", \"BlobDetector\", \"--min-sigma\", \"4\", \"--max-sigma\", \"6\", \"--num-sigma\", \"20\",",
"**kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\", \"--axes\", \"r\" ],",
"], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"\"results\", \"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\"),",
"**kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"--blobs-axis\", \"r\", \"--blobs-axis\", \"c\", \"BlobDetector\", \"--min-sigma\", \"4\", \"--max-sigma\",",
"\".22\", \"--min-distance\", \"57\", ], [ \"starfish\", \"target_assignment\", \"--label-image\", lambda tempdir, *args, **kwargs: os.path.join(",
"\"filtered\", \"results\", ) @property def stages(self): return ( [ \"starfish\", \"validate\", \"experiment\", EXPERIMENT_JSON_URL,",
"[ \"starfish\", \"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\",",
"\"primary_images.json\"), \"--nuclei\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"-o\", lambda tempdir,",
"**kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\") ], ) def verify_results(self, intensities): # TODO make",
"\"57\", ], [ \"starfish\", \"target_assignment\", \"--label-image\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\",",
"tempdir, \"results\", \"label_image.png\"), \"Watershed\", \"--nuclei-threshold\", \".16\", \"--input-threshold\", \".22\", \"--min-distance\", \"57\", ], [ \"starfish\",",
"----- This test and docs/source/usage/iss/iss_cli.sh test the same code paths and should be",
"return \"decoded-spots.nc\" @property def subdirs(self): return ( \"max_projected\", \"transforms\", \"registered\", \"filtered\", \"results\", )",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\",",
"\"results\", \"label_image.png\"), \"--intensities\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--output\", lambda",
"( \"max_projected\", \"transforms\", \"registered\", \"filtered\", \"results\", ) @property def stages(self): return ( [",
"EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class TestWithIssData(CLITest, unittest.TestCase): @property def spots_file(self): return \"decoded-spots.nc\" @property",
"[ \"starfish\", \"target_assignment\", \"--label-image\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"--intensities\",",
"], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"CLITest from starfish.types import Features EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class TestWithIssData(CLITest, unittest.TestCase): @property",
"*args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir,",
"pd import pytest from starfish.test.full_pipelines.cli._base_cli_test import CLITest from starfish.types import Features EXPERIMENT_JSON_URL =",
"\"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--transformation-list\",",
"\"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"WhiteTophat\", \"--masking-radius\",",
"\"--masking-radius\", \"15\", ], [ \"starfish\", \"detect_spots\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"def verify_results(self, intensities): # TODO make this test stronger genes, counts = np.unique(",
"*args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\", \"--axes\", \"r\"",
"\"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"WhiteTophat\",",
"tempdir, \"filtered\", \"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\",",
"\".16\", \"--input-threshold\", \".22\", \"--min-distance\", \"57\", ], [ \"starfish\", \"target_assignment\", \"--label-image\", lambda tempdir, *args,",
"**kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--blobs-stack\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\",",
"tempdir, \"max_projected\", \"primary_images.json\"), \"MaxProj\", \"--dims\", \"c\", \"--dims\", \"z\" ], [ \"starfish\", \"learn_transform\", \"--input\",",
"\"z\" ], [ \"starfish\", \"learn_transform\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\",",
"\"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class TestWithIssData(CLITest, unittest.TestCase): @property def spots_file(self): return \"decoded-spots.nc\" @property def subdirs(self):",
"tempdir, \"max_projected\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Translation\",",
"\"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\") ], ) def",
"\"transforms\", \"registered\", \"filtered\", \"results\", ) @property def stages(self): return ( [ \"starfish\", \"validate\",",
"tempdir, \"registered\", \"primary_images.json\"), \"--transformation-list\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Warp\",",
"tempdir, \"filtered\", \"primary_images.json\"), \"--nuclei\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"-o\",",
"\"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join(",
"], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"**kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"Watershed\", \"--nuclei-threshold\", \".16\", \"--input-threshold\", \".22\", \"--min-distance\", \"57\", ],",
"tempdir, \"filtered\", \"dots.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"detect_spots\", \"--input\", lambda tempdir,",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [",
"os.path.join( tempdir, \"filtered\", \"dots.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"detect_spots\", \"--input\", lambda",
"**kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"MaxProj\", \"--dims\", \"c\", \"--dims\", \"z\" ], [ \"starfish\",",
"= np.unique( intensities.coords[Features.TARGET], return_counts=True) gene_counts = pd.Series(counts, genes) # TODO THERE\"S NO HUMAN/MOUSE",
"\"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ],",
"\"registered\", \"filtered\", \"results\", ) @property def stages(self): return ( [ \"starfish\", \"validate\", \"experiment\",",
"*args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Warp\", ], [ \"starfish\", \"filter\", \"--input\", lambda",
"\"filtered\", \"dots.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"detect_spots\", \"--input\", lambda tempdir, *args,",
"\"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ], # Validate",
"[ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\") ],",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"MaxProj\", \"--dims\", \"c\", \"--dims\", \"z\"",
"import numpy as np import pandas as pd import pytest from starfish.test.full_pipelines.cli._base_cli_test import",
"\"max_projected\", \"transforms\", \"registered\", \"filtered\", \"results\", ) @property def stages(self): return ( [ \"starfish\",",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--transformation-list\", lambda tempdir, *args, **kwargs:",
"**kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\",",
"\"nuclei.json\"), \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"Watershed\", \"--nuclei-threshold\", \".16\",",
"\"transforms.json\"), \"Warp\", ], [ \"starfish\", \"filter\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"stronger genes, counts = np.unique( intensities.coords[Features.TARGET], return_counts=True) gene_counts = pd.Series(counts, genes) # TODO",
"], ) def verify_results(self, intensities): # TODO make this test stronger genes, counts",
"this test stronger genes, counts = np.unique( intensities.coords[Features.TARGET], return_counts=True) gene_counts = pd.Series(counts, genes)",
"and should be updated together \"\"\" import os import unittest import numpy as",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\", \"--axes\",",
"os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--nuclei\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"),",
"*args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ], # Validate results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\",",
"os.path.join( tempdir, \"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ], # Validate results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\", \"validate\", \"xarray\",",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\",",
"\"--nuclei-threshold\", \".16\", \"--input-threshold\", \".22\", \"--min-distance\", \"57\", ], [ \"starfish\", \"target_assignment\", \"--label-image\", lambda tempdir,",
"os.path.join( tempdir, \"results\", \"targeted-spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs:",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Warp\", ], [ \"starfish\", \"filter\", \"--input\",",
"*args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\",",
"\"detect_spots\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--output\", lambda tempdir,",
"\"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--blobs-stack\", lambda tempdir,",
"os.path.join( tempdir, \"results\", \"label_image.png\"), \"--intensities\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"),",
"\"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"Watershed\", \"--nuclei-threshold\", \".16\", \"--input-threshold\",",
"*args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--nuclei\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"\"\"\" Notes ----- This test and docs/source/usage/iss/iss_cli.sh test the same code paths and",
"\"registered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\",",
"tempdir, \"results\", \"label_image.png\"), \"--intensities\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--output\",",
"\"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda tempdir,",
"tempdir, \"results\", \"decoded-spots.nc\") ], ) def verify_results(self, intensities): # TODO make this test",
"], [ \"starfish\", \"detect_spots\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"),",
"**kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--nuclei\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\",",
"*args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--transformation-list\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"--intensities\", lambda tempdir, *args, **kwargs:",
"tempdir, \"results\", \"spots.nc\"), \"--blobs-stack\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"--blobs-axis\",",
"\"label_image.png\"), \"--intensities\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--output\", lambda tempdir,",
"*args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--blobs-stack\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"Watershed\", \"--nuclei-threshold\", \".16\", \"--input-threshold\", \".22\",",
"\"starfish\", \"validate\", \"experiment\", EXPERIMENT_JSON_URL, ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir,",
"**kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\",",
"**kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\",",
"], [ \"starfish\", \"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"and docs/source/usage/iss/iss_cli.sh test the same code paths and should be updated together \"\"\"",
"**kwargs: os.path.join( tempdir, \"results\", \"spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args,",
"\"MaxProj\", \"--dims\", \"c\", \"--dims\", \"z\" ], [ \"starfish\", \"learn_transform\", \"--input\", lambda tempdir, *args,",
"\"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\") ], [",
"from starfish.test.full_pipelines.cli._base_cli_test import CLITest from starfish.types import Features EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class",
"# Validate results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"\"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--blobs-stack\", lambda tempdir, *args,",
"intensities): # TODO make this test stronger genes, counts = np.unique( intensities.coords[Features.TARGET], return_counts=True)",
"\"dots.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"detect_spots\", \"--input\", lambda tempdir, *args, **kwargs:",
"], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\")",
"\"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda tempdir, *args,",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--blobs-stack\", lambda tempdir, *args, **kwargs: os.path.join(",
"\"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args,",
"\"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"detect_spots\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join(",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs:",
"import os import unittest import numpy as np import pandas as pd import",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [",
"\"filtered\", \"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda",
"\"targeted-spots.nc\"), \"Label\", ], [ \"starfish\", \"decode\", \"-i\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"\"--label-image\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"--intensities\", lambda tempdir, *args,",
"\"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"WhiteTophat\",",
"*args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\") ], ) def verify_results(self, intensities): # TODO",
"test the same code paths and should be updated together \"\"\" import os",
"updated together \"\"\" import os import unittest import numpy as np import pandas",
"make this test stronger genes, counts = np.unique( intensities.coords[Features.TARGET], return_counts=True) gene_counts = pd.Series(counts,",
"\"--blobs-axis\", \"r\", \"--blobs-axis\", \"c\", \"BlobDetector\", \"--min-sigma\", \"4\", \"--max-sigma\", \"6\", \"--num-sigma\", \"20\", \"--threshold\", \"0.01\",",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs:",
"\"4\", \"--max-sigma\", \"6\", \"--num-sigma\", \"20\", \"--threshold\", \"0.01\", ], [ \"starfish\", \"segment\", \"--primary-images\", lambda",
"\"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"),",
"\"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ], # Validate results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args,",
"\"--primary-images\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--nuclei\", lambda tempdir, *args,",
"\"decoded-spots.nc\") ], ) def verify_results(self, intensities): # TODO make this test stronger genes,",
"f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\",",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join(",
"starfish.types import Features EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class TestWithIssData(CLITest, unittest.TestCase): @property def spots_file(self):",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"Watershed\", \"--nuclei-threshold\", \".16\", \"--input-threshold\", \".22\", \"--min-distance\",",
"\"results\", \"spots.nc\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"Label\", ],",
"[ \"starfish\", \"segment\", \"--primary-images\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--nuclei\",",
"os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\",",
"tempdir, \"filtered\", \"nuclei.json\"), \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"Watershed\",",
"**kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ], # Validate results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\", \"validate\",",
"*args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"\"filtered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--blobs-stack\", lambda",
"os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"MaxProj\", \"--dims\", \"c\", \"--dims\", \"z\" ], [ \"starfish\", \"learn_transform\",",
"f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"MaxProj\", \"--dims\", \"c\",",
"unittest.TestCase): @property def spots_file(self): return \"decoded-spots.nc\" @property def subdirs(self): return ( \"max_projected\", \"transforms\",",
"os.path.join( tempdir, \"results\", \"spots.nc\"), \"--blobs-stack\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"),",
"os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\") ], ) def verify_results(self, intensities):",
"*args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"\"0.01\", ], [ \"starfish\", \"segment\", \"--primary-images\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\",",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\",",
"\"validate\", \"experiment\", EXPERIMENT_JSON_URL, ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args,",
"**kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\",",
"genes, counts = np.unique( intensities.coords[Features.TARGET], return_counts=True) gene_counts = pd.Series(counts, genes) # TODO THERE\"S",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--transformation-list\", lambda tempdir, *args, **kwargs: os.path.join(",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [",
"def stages(self): return ( [ \"starfish\", \"validate\", \"experiment\", EXPERIMENT_JSON_URL, ], [ \"starfish\", \"filter\",",
"\"starfish\", \"segment\", \"--primary-images\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--nuclei\", lambda",
"tempdir, \"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ], # Validate results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\", \"validate\", \"xarray\", lambda",
"return_counts=True) gene_counts = pd.Series(counts, genes) # TODO THERE\"S NO HUMAN/MOUSE KEYS? assert gene_counts['ACTB']",
"\"--blobs-axis\", \"c\", \"BlobDetector\", \"--min-sigma\", \"4\", \"--max-sigma\", \"6\", \"--num-sigma\", \"20\", \"--threshold\", \"0.01\", ], [",
"\"filter\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--output\", lambda tempdir,",
"\"results\", \"targeted-spots.nc\"), \"Label\", ], [ \"starfish\", \"decode\", \"-i\", lambda tempdir, *args, **kwargs: os.path.join(",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ], # Validate results/{spots,targeted-spots,decoded-spots}.nc [",
"[ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\",",
"\"experiment\", EXPERIMENT_JSON_URL, ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs:",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs:",
"os.path.join( tempdir, \"results\", \"spots.nc\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"),",
"Features EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class TestWithIssData(CLITest, unittest.TestCase): @property def spots_file(self): return \"decoded-spots.nc\"",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda",
"**kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"Label\", ], [ \"starfish\", \"decode\", \"-i\", lambda tempdir,",
"\"Label\", ], [ \"starfish\", \"decode\", \"-i\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\",",
"Validate results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\",",
"], [ \"starfish\", \"segment\", \"--primary-images\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"),",
"subdirs(self): return ( \"max_projected\", \"transforms\", \"registered\", \"filtered\", \"results\", ) @property def stages(self): return",
"\"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"),",
"Notes ----- This test and docs/source/usage/iss/iss_cli.sh test the same code paths and should",
"os.path.join( tempdir, \"results\", \"label_image.png\"), \"Watershed\", \"--nuclei-threshold\", \".16\", \"--input-threshold\", \".22\", \"--min-distance\", \"57\", ], [",
"], [ \"starfish\", \"learn_transform\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"),",
"os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\",",
"\"spots.nc\"), \"--blobs-stack\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"--blobs-axis\", \"r\", \"--blobs-axis\",",
"tempdir, \"filtered\", \"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\",",
"results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\")",
"\"results\", \"spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"\"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\") ], [ \"starfish\", \"validate\",",
"\"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\") ], )",
"tempdir, \"transforms\", \"transforms.json\"), \"Warp\", ], [ \"starfish\", \"filter\", \"--input\", lambda tempdir, *args, **kwargs:",
"f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--transformation-list\", lambda tempdir,",
"\"--min-sigma\", \"4\", \"--max-sigma\", \"6\", \"--num-sigma\", \"20\", \"--threshold\", \"0.01\", ], [ \"starfish\", \"segment\", \"--primary-images\",",
"f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\",",
"\"15\", ], [ \"starfish\", \"detect_spots\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\",",
"\"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\") ], [ \"starfish\", \"validate\",",
"tempdir, \"transforms\", \"transforms.json\"), \"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\", \"--axes\", \"r\" ], [ \"starfish\",",
"be updated together \"\"\" import os import unittest import numpy as np import",
"\"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ],",
"*args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"Watershed\", \"--nuclei-threshold\", \".16\", \"--input-threshold\", \".22\", \"--min-distance\", \"57\",",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda",
"os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"Label\", ], [ \"starfish\", \"decode\", \"-i\", lambda tempdir, *args,",
"should be updated together \"\"\" import os import unittest import numpy as np",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Warp\", ], [ \"starfish\", \"filter\",",
"os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"),",
"\"20\", \"--threshold\", \"0.01\", ], [ \"starfish\", \"segment\", \"--primary-images\", lambda tempdir, *args, **kwargs: os.path.join(",
"stages(self): return ( [ \"starfish\", \"validate\", \"experiment\", EXPERIMENT_JSON_URL, ], [ \"starfish\", \"filter\", \"--input\",",
"\"--dims\", \"z\" ], [ \"starfish\", \"learn_transform\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"Label\", ], [ \"starfish\", \"decode\", \"-i\",",
"\"decode\", \"-i\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\",",
"\"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda tempdir,",
"\"filtered\", \"primary_images.json\"), \"--nuclei\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"-o\", lambda",
"test stronger genes, counts = np.unique( intensities.coords[Features.TARGET], return_counts=True) gene_counts = pd.Series(counts, genes) #",
"pytest from starfish.test.full_pipelines.cli._base_cli_test import CLITest from starfish.types import Features EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow",
"\"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"Label\", ], [ \"starfish\",",
"\"decoded-spots.nc\" @property def subdirs(self): return ( \"max_projected\", \"transforms\", \"registered\", \"filtered\", \"results\", ) @property",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"MaxProj\", \"--dims\", \"c\", \"--dims\", \"z\" ],",
"\"results\", ) @property def stages(self): return ( [ \"starfish\", \"validate\", \"experiment\", EXPERIMENT_JSON_URL, ],",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"--blobs-axis\", \"r\", \"--blobs-axis\", \"c\", \"BlobDetector\",",
"*args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"--intensities\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"\"max_projected\", \"primary_images.json\"), \"MaxProj\", \"--dims\", \"c\", \"--dims\", \"z\" ], [ \"starfish\", \"learn_transform\", \"--input\", lambda",
"**kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\",",
"\"registered\", \"primary_images.json\"), \"--transformation-list\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Warp\", ],",
"as np import pandas as pd import pytest from starfish.test.full_pipelines.cli._base_cli_test import CLITest from",
"\"--threshold\", \"0.01\", ], [ \"starfish\", \"segment\", \"--primary-images\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"], [ \"starfish\", \"target_assignment\", \"--label-image\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"),",
"@property def spots_file(self): return \"decoded-spots.nc\" @property def subdirs(self): return ( \"max_projected\", \"transforms\", \"registered\",",
"EXPERIMENT_JSON_URL, ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join(",
"**kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Warp\", ], [ \"starfish\", \"filter\", \"--input\", lambda tempdir,",
"\"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--transformation-list\", lambda tempdir, *args,",
"os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--transformation-list\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"),",
"tempdir, \"filtered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--blobs-stack\",",
"def subdirs(self): return ( \"max_projected\", \"transforms\", \"registered\", \"filtered\", \"results\", ) @property def stages(self):",
"*args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir,",
"\"starfish\", \"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"),",
"], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\")",
"**kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"--intensities\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\",",
"*args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"--blobs-axis\", \"r\", \"--blobs-axis\", \"c\", \"BlobDetector\", \"--min-sigma\", \"4\",",
"\"--num-sigma\", \"20\", \"--threshold\", \"0.01\", ], [ \"starfish\", \"segment\", \"--primary-images\", lambda tempdir, *args, **kwargs:",
"\"--max-sigma\", \"6\", \"--num-sigma\", \"20\", \"--threshold\", \"0.01\", ], [ \"starfish\", \"segment\", \"--primary-images\", lambda tempdir,",
"\"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ],",
"\"target_assignment\", \"--label-image\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"--intensities\", lambda tempdir,",
"test and docs/source/usage/iss/iss_cli.sh test the same code paths and should be updated together",
"\"--dims\", \"c\", \"--dims\", \"z\" ], [ \"starfish\", \"learn_transform\", \"--input\", lambda tempdir, *args, **kwargs:",
"[ \"starfish\", \"detect_spots\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--output\",",
"\"label_image.png\"), \"Watershed\", \"--nuclei-threshold\", \".16\", \"--input-threshold\", \".22\", \"--min-distance\", \"57\", ], [ \"starfish\", \"target_assignment\", \"--label-image\",",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ], # Validate results/{spots,targeted-spots,decoded-spots}.nc",
"\"starfish\", \"filter\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--output\", lambda",
"\"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda tempdir, *args,",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda tempdir,",
"# TODO make this test stronger genes, counts = np.unique( intensities.coords[Features.TARGET], return_counts=True) gene_counts",
"\"results\", \"targeted-spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"\"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"--output\", lambda tempdir, *args,",
"intensities.coords[Features.TARGET], return_counts=True) gene_counts = pd.Series(counts, genes) # TODO THERE\"S NO HUMAN/MOUSE KEYS? assert",
"\"transforms.json\"), \"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\", \"--axes\", \"r\" ], [ \"starfish\", \"apply_transform\", \"--input\",",
"*args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"\"--blobs-stack\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"--blobs-axis\", \"r\", \"--blobs-axis\", \"c\",",
"*args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"MaxProj\", \"--dims\", \"c\", \"--dims\", \"z\" ], [",
"\"--input-threshold\", \".22\", \"--min-distance\", \"57\", ], [ \"starfish\", \"target_assignment\", \"--label-image\", lambda tempdir, *args, **kwargs:",
") def verify_results(self, intensities): # TODO make this test stronger genes, counts =",
"tempdir, \"results\", \"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\",",
"\"starfish\", \"decode\", \"-i\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\",",
"\"c\", \"--dims\", \"z\" ], [ \"starfish\", \"learn_transform\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join(",
"\"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\", \"--axes\", \"r\" ], [ \"starfish\", \"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\",",
"\"r\", \"--blobs-axis\", \"c\", \"BlobDetector\", \"--min-sigma\", \"4\", \"--max-sigma\", \"6\", \"--num-sigma\", \"20\", \"--threshold\", \"0.01\", ],",
"f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\", \"--axes\", \"r\" ], [ \"starfish\", \"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda",
"\"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--output\", lambda tempdir, *args, **kwargs:",
"numpy as np import pandas as pd import pytest from starfish.test.full_pipelines.cli._base_cli_test import CLITest",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join(",
"\"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"MaxProj\", \"--dims\",",
"import Features EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class TestWithIssData(CLITest, unittest.TestCase): @property def spots_file(self): return",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"-o\", lambda tempdir, *args, **kwargs: os.path.join(",
"\"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args,",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join(",
"starfish.test.full_pipelines.cli._base_cli_test import CLITest from starfish.types import Features EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class TestWithIssData(CLITest,",
"\"6\", \"--num-sigma\", \"20\", \"--threshold\", \"0.01\", ], [ \"starfish\", \"segment\", \"--primary-images\", lambda tempdir, *args,",
"**kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda tempdir, *args, **kwargs: os.path.join(",
"\"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\",",
"\"learn_transform\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"--output\", lambda tempdir,",
"[ \"starfish\", \"filter\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--output\",",
"\"c\", \"BlobDetector\", \"--min-sigma\", \"4\", \"--max-sigma\", \"6\", \"--num-sigma\", \"20\", \"--threshold\", \"0.01\", ], [ \"starfish\",",
"\"segment\", \"--primary-images\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--nuclei\", lambda tempdir,",
"\"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\") ], [",
"os.path.join( tempdir, \"filtered\", \"dots.json\"), \"--blobs-axis\", \"r\", \"--blobs-axis\", \"c\", \"BlobDetector\", \"--min-sigma\", \"4\", \"--max-sigma\", \"6\",",
"as pd import pytest from starfish.test.full_pipelines.cli._base_cli_test import CLITest from starfish.types import Features EXPERIMENT_JSON_URL",
"( [ \"starfish\", \"validate\", \"experiment\", EXPERIMENT_JSON_URL, ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\",",
"\"--axes\", \"r\" ], [ \"starfish\", \"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs:",
"return ( [ \"starfish\", \"validate\", \"experiment\", EXPERIMENT_JSON_URL, ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\",",
"**kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\",",
"tempdir, \"results\", \"spots.nc\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"Label\",",
"from starfish.types import Features EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class TestWithIssData(CLITest, unittest.TestCase): @property def",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--blobs-stack\", lambda tempdir, *args, **kwargs:",
"\"Warp\", ], [ \"starfish\", \"filter\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\",",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\",",
"verify_results(self, intensities): # TODO make this test stronger genes, counts = np.unique( intensities.coords[Features.TARGET],",
"\"--transformation-list\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Warp\", ], [ \"starfish\",",
"@property def subdirs(self): return ( \"max_projected\", \"transforms\", \"registered\", \"filtered\", \"results\", ) @property def",
"os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"),",
"\"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda tempdir, *args, **kwargs:",
"counts = np.unique( intensities.coords[Features.TARGET], return_counts=True) gene_counts = pd.Series(counts, genes) # TODO THERE\"S NO",
"class TestWithIssData(CLITest, unittest.TestCase): @property def spots_file(self): return \"decoded-spots.nc\" @property def subdirs(self): return (",
"import CLITest from starfish.types import Features EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class TestWithIssData(CLITest, unittest.TestCase):",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\",",
"\"15\", ], [ \"starfish\", \"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][nuclei]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join(",
"\"primary_images.json\"), \"--transformation-list\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Warp\", ], [",
"\"Watershed\", \"--nuclei-threshold\", \".16\", \"--input-threshold\", \".22\", \"--min-distance\", \"57\", ], [ \"starfish\", \"target_assignment\", \"--label-image\", lambda",
"\"--min-distance\", \"57\", ], [ \"starfish\", \"target_assignment\", \"--label-image\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"tempdir, \"results\", \"targeted-spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join(",
"os import unittest import numpy as np import pandas as pd import pytest",
"import pandas as pd import pytest from starfish.test.full_pipelines.cli._base_cli_test import CLITest from starfish.types import",
"\"starfish\", \"learn_transform\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"--output\", lambda",
"= \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\" @pytest.mark.slow class TestWithIssData(CLITest, unittest.TestCase): @property def spots_file(self): return \"decoded-spots.nc\" @property def",
"**kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"detect_spots\", \"--input\",",
"], [ \"starfish\", \"filter\", \"--input\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"),",
"TODO make this test stronger genes, counts = np.unique( intensities.coords[Features.TARGET], return_counts=True) gene_counts =",
"\"spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\",",
"\"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\", \"--axes\", \"r\" ], [ \"starfish\", \"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\",",
"\"results\", \"decoded-spots.nc\") ], ) def verify_results(self, intensities): # TODO make this test stronger",
"\"--intensities\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--output\", lambda tempdir, *args,",
"[ \"starfish\", \"decode\", \"-i\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\"), \"--codebook\",",
"f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ], #",
"\"BlobDetector\", \"--min-sigma\", \"4\", \"--max-sigma\", \"6\", \"--num-sigma\", \"20\", \"--threshold\", \"0.01\", ], [ \"starfish\", \"segment\",",
"TestWithIssData(CLITest, unittest.TestCase): @property def spots_file(self): return \"decoded-spots.nc\" @property def subdirs(self): return ( \"max_projected\",",
"os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\", \"1000\", \"--axes\", \"r\" ], [",
"\"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Translation\", \"--reference-stack\", f\"@{EXPERIMENT_JSON_URL}[fov_001][dots]\", \"--upsampling\",",
"\"PerRoundMaxChannelDecoder\", ], # Validate results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs:",
"**kwargs: os.path.join( tempdir, \"results\", \"targeted-spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args,",
"*args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir,",
"*args, **kwargs: os.path.join( tempdir, \"filtered\", \"primary_images.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"filter\",",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\"), \"--output\", lambda tempdir, *args, **kwargs:",
"*args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"WhiteTophat\", \"--masking-radius\", \"15\", ], [ \"starfish\", \"detect_spots\",",
"\"--nuclei\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"-o\", lambda tempdir, *args,",
"\"results\", \"label_image.png\"), \"Watershed\", \"--nuclei-threshold\", \".16\", \"--input-threshold\", \".22\", \"--min-distance\", \"57\", ], [ \"starfish\", \"target_assignment\",",
"spots_file(self): return \"decoded-spots.nc\" @property def subdirs(self): return ( \"max_projected\", \"transforms\", \"registered\", \"filtered\", \"results\",",
"@pytest.mark.slow class TestWithIssData(CLITest, unittest.TestCase): @property def spots_file(self): return \"decoded-spots.nc\" @property def subdirs(self): return",
"def spots_file(self): return \"decoded-spots.nc\" @property def subdirs(self): return ( \"max_projected\", \"transforms\", \"registered\", \"filtered\",",
"\"filter\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"max_projected\", \"primary_images.json\"), \"MaxProj\",",
"\"targeted-spots.nc\"), \"--codebook\", f\"@{EXPERIMENT_JSON_URL}\", \"-o\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\",",
"import pytest from starfish.test.full_pipelines.cli._base_cli_test import CLITest from starfish.types import Features EXPERIMENT_JSON_URL = \"https://d2nhj9g34unfro.cloudfront.net/20181005/ISS-TEST/experiment.json\"",
"code paths and should be updated together \"\"\" import os import unittest import",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"nuclei.json\"), \"-o\", lambda tempdir, *args, **kwargs:",
"\"starfish\", \"target_assignment\", \"--label-image\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"label_image.png\"), \"--intensities\", lambda",
"os.path.join( tempdir, \"results\", \"decoded-spots.nc\") ], ) def verify_results(self, intensities): # TODO make this",
"[ \"starfish\", \"validate\", \"xarray\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\") ],",
"tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"--blobs-axis\", \"r\", \"--blobs-axis\", \"c\", \"BlobDetector\", \"--min-sigma\",",
"\"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"registered\", \"primary_images.json\"), \"--transformation-list\", lambda",
"\"max_projected\", \"primary_images.json\"), \"--output\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"transforms\", \"transforms.json\"), \"Translation\", \"--reference-stack\",",
"pandas as pd import pytest from starfish.test.full_pipelines.cli._base_cli_test import CLITest from starfish.types import Features",
"paths and should be updated together \"\"\" import os import unittest import numpy",
"\"r\" ], [ \"starfish\", \"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args, **kwargs: os.path.join(",
"\"results\", \"spots.nc\"), \"--blobs-stack\", lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"filtered\", \"dots.json\"), \"--blobs-axis\", \"r\",",
"lambda tempdir, *args, **kwargs: os.path.join( tempdir, \"results\", \"spots.nc\") ], [ \"starfish\", \"validate\", \"xarray\",",
"unittest import numpy as np import pandas as pd import pytest from starfish.test.full_pipelines.cli._base_cli_test",
"\"results\", \"decoded-spots.nc\"), \"PerRoundMaxChannelDecoder\", ], # Validate results/{spots,targeted-spots,decoded-spots}.nc [ \"starfish\", \"validate\", \"xarray\", lambda tempdir,",
"\"1000\", \"--axes\", \"r\" ], [ \"starfish\", \"apply_transform\", \"--input\", f\"@{EXPERIMENT_JSON_URL}[fov_001][primary]\", \"--output\", lambda tempdir, *args,",
"tempdir, \"results\", \"targeted-spots.nc\"), \"Label\", ], [ \"starfish\", \"decode\", \"-i\", lambda tempdir, *args, **kwargs:"
] |
[
"the Q-network for s # and then we only update the Q-values for",
"originally Neural-fitted Q-iteration but with the addition of a separate target network) \"\"\"",
"avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0, 0.0, 0.0)) # Eval obs = self.env.reset(update_stats=False)",
"= [] episode_avg_defender_loss = [] # Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0,",
"for idx, row in enumerate(temp): t = row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx]) if not self.env.idsgame_config.game_config.reconnaissance_actions:",
"torch.tensor(r_defender_batch).float() s_1 = torch.tensor(s_defender_batch).float() s_2 = torch.tensor(s2_defender_batch).float() # Move to GPU if using",
"Move to the next state obs = obs_prime attacker_obs = obs_prime_attacker defender_obs =",
"self.config.attacker: path = self.config.save_dir + \"/\" + time_str + \"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network to:",
"row.tolist() t.append(a_pos[idx]) if self.env.fully_observed(): t.append(det_values[idx]) features.append(t) else: node_ids = attacker_obs[:, -1] if not",
"self.env.idsgame_config.game_config.reconnaissance_actions: det_values = defender_obs[:, -1] temp = defender_obs[:, 0:-1] - attacker_obs[:, 0:-1] else:",
"set to True but no video_dir is provided, please specify \" \"the video_dir",
"= self.defender_q_network(s_1) loss = self.loss_fn(prediction, target) # Zero gradients, perform a backward pass,",
"self.config.defender: episode_avg_defender_loss.append(episode_defender_loss / episode_step) else: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) #",
"zero_mean_defender_features.append(t) attacker_obs = np.array(zero_mean_attacker_features) defender_obs = np.array(zero_mean_defender_features) # Normalize if self.config.dqn_config.normalize_features: if not",
"self.env.render(mode=\"human\") # Decay LR after every episode lr = self.config.alpha if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step()",
"obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[])",
"bool = False, attacker : bool = True) -> int: \"\"\" Samples an",
"Render final frame when game completed if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode: {},",
"d_bool_features[i]) else: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1])) for i in range(f.shape[0]): f[i]",
"= attacker_obs[:, 0:-1] else: attacker_obs_1 = attacker_obs[:, 0:-2] zero_mean_attacker_features = [] for idx,",
"self.config.attacker and not self.config.defender: raise AssertionError(\"Must specify whether training an attacker agent or",
"= self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[]) obs_state_d_prime",
"the discounted estimated future # reward when following Q* estimated by the target",
"Update target network every <self.config.dqn_config.target_network_update_freq> episodes if episode % self.config.dqn_config.target_network_update_freq == 0: self.update_target_network()",
"# Reset for new eval episode done = False obs = self.env.reset(update_stats=False) attacker_obs,",
"if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device)",
"Perform a gradient descent step of the Q-network using targets produced by target",
"for the attacker (otherwise defender) :return: loss \"\"\" # Unpack batch of transitions",
"replay memory s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch =",
"self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] else: attacker_obs_1 = attacker_obs[:, 0:-2]",
"tag, value in self.attacker_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag +",
"if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features = attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs = attacker_obs[:, 0:a_obs_len] # else: #",
"-= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks += 1 self.num_eval_hacks_total +=1 # Log average metrics every <self.config.eval_log_frequency>",
"= ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories = False self.env.idsgame_config.save_attack_stats = False def warmup(self)",
"= attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs = attacker_obs[:, 0:a_obs_len] # else: # a_obs_len = self.env.idsgame_config.game_config.num_attack_types",
"train episode to keep track of logging :param log: whether to log the",
"if attacker: target_next = self.attacker_target_network(s_2).detach() else: target_next = self.defender_target_network(s_2).detach() for i in range(self.config.dqn_config.batch_size):",
"defender_obs_prime, attacker=True, state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime)",
"steps and fill the replay memory for i in range(self.config.dqn_config.replay_start_size): if i %",
"self.env.local_view_features(): a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 defender_obs = attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features",
"mini_batch of transitions from replay memory minibatch = self.buffer.sample(self.config.dqn_config.batch_size) # Perform a gradient",
"/ self.num_train_games_total else: self.train_hack_probability = 0.0 self.train_cumulative_hack_probability = 0.0 self.log_metrics(episode, self.train_result, episode_attacker_rewards, episode_defender_rewards,",
"a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types] # if self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features = attacker_obs[:, # a_obs_len +",
"range(f.shape[0]): f[i] = np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i]) else: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1]))",
"prediction = self.defender_q_network(s_1) loss = self.loss_fn(prediction, target) # Zero gradients, perform a backward",
"= self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self) -> ExperimentResult: \"\"\" Runs the DQN algorithm",
"if self.config.dqn_config.loss_fn == \"MSE\": self.loss_fn = torch.nn.MSELoss() elif self.config.dqn_config.loss_fn == \"Huber\": self.loss_fn =",
"obs_prime attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render final frame if self.config.render:",
"range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i]) > 0: temp[i] = neighbor_defense_attributes[i] - attacker_obs[i, 0:-1] features =",
"[] episode_avg_attacker_loss = [] episode_avg_defender_loss = [] # Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\",
"attacker and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 = defender_obs[:, 0:-1] / np.linalg.norm(defender_obs[:, 0:-1]) else: defender_obs_1 =",
"Take a step in the environment obs_prime, reward, done, _ = self.env.step(action) attacker_obs_prime,",
"for the next episode and update game stats done = False obs =",
"and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except: self.config.logger.warning(\"Error when",
"defender_obs[:, 0:] - attacker_obs[:, 0:-1] features = [] for idx, row in enumerate(temp):",
"np.ndarray, np.ndarray, np.ndarray, np.ndarray], attacker: bool = True) -> torch.Tensor: \"\"\" Performs a",
"# Record episode metrics self.num_train_games += 1 self.num_train_games_total += 1 if self.env.state.hacked: self.num_train_hacks",
"epsilon linearly self.anneal_epsilon() self.config.logger.info(\"Training Complete\") # Final evaluation (for saving Gifs etc) self.eval(self.config.num_episodes-1,",
"algorithm :return: Experiment result \"\"\" self.config.logger.info(\"Starting Warmup\") self.warmup() self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps)",
"0.0, 0.0, 0.0)) # Eval obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a",
"other game data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if self.config.save_dir is not None: time_str = str(time.time())",
"from the paper 'Human-level control through deep reinforcement learning' by Mnih et. al.",
"Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] episode_avg_attacker_loss =",
"# Initialize models self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim,",
"= 0 episode_step = 0 while not done: if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) #",
"state to sample an action for :param eval: boolean flag whether running in",
"attacker: target = self.attacker_q_network(s_1) else: target = self.defender_q_network(s_1) # Use the target network",
"self.train_cumulative_hack_probability = self.num_train_hacks_total / self.num_train_games_total else: self.train_hack_probability = 0.0 self.train_cumulative_hack_probability = 0.0 self.log_metrics(episode,",
"# temp = np.append(attacker_obs, neighbor_defense_attributes) state = np.append(state[1:], np.array([f]), axis=0) return state else:",
"(obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_eval.update(1) # Log average eval statistics if",
"LR decay if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def",
"= np.array(zero_mean_defender_features) # Normalize if self.config.dqn_config.normalize_features: if not self.env.local_view_features() or not attacker: attacker_obs_1",
"obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs # Tracking metrics episode_attacker_rewards =",
"eval stats self.num_eval_games +=1 self.num_eval_games_total += 1 if self.env.state.detected: self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward",
"in the optimizer constructor will contain the learnable # parameters of the layers",
"Saves the PyTorch Model Weights :return: None \"\"\" time_str = str(time.time()) if self.config.save_dir",
"gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent class DQNAgent(QAgent): \"\"\" An implementation of the DQN algorithm from",
"np.isnan(attacker_obs_1).any(): t = attacker_obs[idx] else: t = row.tolist() if not self.env.local_view_features() or not",
"class DQNAgent(QAgent): \"\"\" An implementation of the DQN algorithm from the paper 'Human-level",
"r_1 = torch.tensor(r_attacker_batch).float() s_1 = torch.tensor(s_attacker_batch).float() s_2 = torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train() self.defender_q_network.eval() r_1",
"s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch if",
"<self.config.dqn_config.replay_start_size> steps and fill the replay memory for i in range(self.config.dqn_config.replay_start_size): if i",
"np.linalg.norm(defender_obs[:, 0:-1]) else: defender_obs_1 = defender_obs / np.linalg.norm(defender_obs) normalized_defender_features = [] for idx,",
"log_str = \"[Warmup] step:{}, buffer_size: {}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) # Select random attacker",
"GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1)",
"state: np.ndarray = None, attacker: bool = True) -> np.ndarray: \"\"\" Update approximative",
"contain the learnable # parameters of the layers in the model if self.config.dqn_config.optimizer",
"0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval=True,",
"al. (DQN is originally Neural-fitted Q-iteration but with the addition of a separate",
"pass, and update the weights. if attacker: self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad() loss.backward()",
"done: if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) # Default initialization attacker_action = 0 defender_action =",
"self.config.dqn_config.loss_fn == \"MSE\": self.loss_fn = torch.nn.MSELoss() elif self.config.dqn_config.loss_fn == \"Huber\": self.loss_fn = torch.nn.SmoothL1Loss()",
"self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if self.config.save_dir is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\"",
"position=0) outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size: {}\".format(0, 0)) # Reset env obs = self.env.reset(update_stats=False) attacker_obs,",
"frame, global_step=train_episode, dataformats = \"HWC\") # Reset for new eval episode done =",
"None self.defender_target_network = None self.loss_fn = None self.attacker_optimizer = None self.defender_optimizer = None",
"row in enumerate(temp): t = row.tolist() t.append(a_pos[idx]) if self.env.fully_observed(): t.append(det_values[idx]) features.append(t) else: node_ids",
"= (obs_state_a_prime, obs_state_d_prime) # Add transition to replay memory self.buffer.add_tuple(obs, action, reward, done,",
"only want the loss to be computed for the Q-values of the actions",
"self.env.state.hacked: self.num_train_hacks += 1 self.num_train_hacks_total += 1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if episode_step > 0:",
"\\ \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0, 0.0, 0.0)) # Eval obs = self.env.reset(update_stats=False) attacker_obs,",
"{} steps\".format(episode, episode_step)) # Record episode metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) # Update eval",
"np.append(attacker_obs[i], neighbor_defense_attributes[i]) if self.config.dqn_config.state_length == 1: return f if len(state) == 0: s",
"done, obs_prime) # Sample random mini_batch of transitions from replay memory minibatch =",
"1 # Move to the next state obs = obs_prime attacker_obs = obs_prime_attacker",
"target network is not trainable it is only used for predictions, therefore we",
"eval=True, update_stats=True) self.env.close() self.config.logger.info(\"Evaluation Complete\") return self.eval_result def save_model(self) -> None: \"\"\" Saves",
"self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval=True, update_stats=True)",
"we initialize the target to the Q-values of the Q-network for s #",
"= torch.nn.MSELoss() elif self.config.dqn_config.loss_fn == \"Huber\": self.loss_fn = torch.nn.SmoothL1Loss() else: raise ValueError(\"Loss function",
"self.num_eval_hacks += 1 self.num_eval_hacks_total +=1 # Log average metrics every <self.config.eval_log_frequency> episodes if",
"a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch # Convert batch into",
"update game stats done = False obs = self.env.reset(update_stats=True) attacker_obs, defender_obs = obs",
"mean else: t = row if np.isnan(t).any(): t = defender_obs[idx] else: t =",
"ValueError(\"Optimizer not recognized\") # LR decay if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay",
"= obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False,",
"frame if self.config.render: self.env.render(mode=\"human\") # Decay LR after every episode lr = self.config.alpha",
"in range(self.config.dqn_config.replay_start_size): if i % self.config.train_log_frequency == 0: log_str = \"[Warmup] step:{}, buffer_size:",
"self.env.generate_gif(self.config.gif_dir + \"/episode_\" + str(train_episode) + \"_\" + time_str + \".gif\", self.config.video_fps) #",
"attacker_obs, defender_obs = obs for episode in range(self.config.eval_episodes): episode_attacker_reward = 0 episode_defender_reward =",
"combined_features.shape[1] + d_bool_features.shape[1])) for i in range(combined_features.shape[0]): f[i] = np.append(combined_features[i], d_bool_features[i]) combined_features =",
"new state obs = obs_prime outer_warmup.update(1) if done: obs = self.env.reset(update_stats=False) attacker_obs, defender_obs",
"parameters (histogram summary) to tensorboard if self.config.attacker: for tag, value in self.attacker_q_network.named_parameters(): tag",
"+ \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") return self.train_result def update_target_network(self)",
"if self.config.render: self.env.render(mode=\"human\") if not self.config.attacker and not self.config.defender: raise AssertionError(\"Must specify whether",
"networks. Delayed targets are used to stabilize training and partially remedy the problem",
"episode_step += 1 attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render final frame",
"self.config.eval_frequency == 0: self.eval(episode) # Save models every <self.config.checkpoint_frequency> episodes if episode %",
"None: if self.config.attacker: path = self.config.save_dir + \"/\" + time_str + \"_attacker_q_network.pt\" self.config.logger.info(\"Saving",
"= attacker_obs[:, # a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types] # if self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features = attacker_obs[:,",
"if np.isnan(t).any(): t = defender_obs[idx] else: t = t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs =",
"configuration \"\"\" super(DQNAgent, self).__init__(env, config) self.attacker_q_network = None self.attacker_target_network = None self.defender_q_network =",
"f[i] = np.append(combined_features[i], d_bool_features[i]) combined_features = f return np.array(combined_features) return np.append(attacker_obs, defender_obs) else:",
"value.grad.data.cpu().numpy(), episode) episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] self.num_train_games =",
"in self.attacker_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_attacker/grad', value.grad.data.cpu().numpy(),",
"-> None: \"\"\" A warmup without any learning just to populate the replay",
"defender_obs = obs # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps",
"\"\"\" Initialize models :return: None \"\"\" # Initialize models self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim,",
"self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 = defender_obs[:, 0:-1] / np.linalg.norm(defender_obs[:, 0:-1]) else: defender_obs_1 = defender_obs /",
"loss.item() # Update metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward",
"if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1 =",
"attacker_obs[:, 0:-1] else: temp = defender_obs[:, 0:] - attacker_obs[:, 0:-1] features = []",
"\"\"\" self.config.logger.info(\"Starting Evaluation\") time_str = str(time.time()) self.num_eval_games = 0 self.num_eval_hacks = 0 if",
"obs_prime) # Sample random mini_batch of transitions from replay memory minibatch = self.buffer.sample(self.config.dqn_config.batch_size)",
"not the entire # vector of all Q-values. Therefore we initialize the target",
"= None self.attacker_target_network = None self.defender_q_network = None self.defender_target_network = None self.loss_fn =",
"eval) \\ or (eval and np.random.random() < self.config.eval_epsilon): return np.random.choice(legal_actions) with torch.no_grad(): if",
"or not attacker: a_pos = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = defender_obs[:,",
"step of the Deep-Q-learning algorithm (implemented in PyTorch) :param mini_batch: a minibatch to",
"self.config.logger.warning(\"starting training with non-empty result object\") done = False obs = self.env.reset(update_stats=False) attacker_obs,",
"[] episode_steps = [] self.num_train_games = 0 self.num_train_hacks = 0 # Update target",
"for idx, row in enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any(): t = attacker_obs[idx] else: t =",
"for tag, value in self.defender_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag",
"\"_eval_results_checkpoint.csv\") # Reset environment for the next episode and update game stats done",
"self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") self.config.logger.info(\"Running on the GPU\") else: device = torch.device(\"cpu\") self.config.logger.info(\"Running",
"self.outer_eval.update(1) # Log average eval statistics if log: if self.num_eval_hacks > 0: self.eval_hack_probability",
"metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward += attacker_reward episode_defender_reward",
"self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" + str(idx), frame, global_step=train_episode, dataformats = \"HWC\") # Reset for",
"defender_obs / np.linalg.norm(defender_obs) normalized_defender_features = [] for idx, row in enumerate(defender_obs_1): if np.isnan(defender_obs_1).any():",
"gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def training_step(self, mini_batch: Union[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,",
"f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1] + d_bool_features.shape[1])) for i in range(f.shape[0]): f[i]",
"typing import Union import numpy as np import time import tqdm import torch",
"if self.config.render: self.env.render(mode=\"human\") # Decay LR after every episode lr = self.config.alpha if",
"\"\"\" Updates the target networks. Delayed targets are used to stabilize training and",
"obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[])",
"s_1 = torch.tensor(s_attacker_batch).float() s_2 = torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train() self.defender_q_network.eval() r_1 = torch.tensor(r_defender_batch).float() s_1",
"target[i][a_defender_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) # Compute loss if attacker: prediction",
"frames to tensorboard for idx, frame in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" + str(idx),",
"state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Add transition to replay memory self.buffer.add_tuple(obs, action,",
"device = torch.device(\"cpu\") self.config.logger.info(\"Running on the CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device) # Set",
"= torch.device(\"cpu\") self.config.logger.info(\"Running on the CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device) # Set the",
"self.defender_q_network(s_1) # Use the target network to compute the Q-values of s' with",
"row.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if",
"Add transition to replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Move to",
"str(time.time()) if self.config.save_dir is not None: if self.config.attacker: path = self.config.save_dir + \"/\"",
"initialize_models(self) -> None: \"\"\" Initialize models :return: None \"\"\" # Initialize models self.attacker_q_network",
"Normalize if self.config.dqn_config.normalize_features: if not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1]",
"\"Adam\": self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif self.config.dqn_config.optimizer == \"SGD\":",
"GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") r_1 = r_1.to(device) s_1 =",
"episode_defender_rewards = [] episode_steps = [] self.num_train_games = 0 self.num_train_hacks = 0 #",
"not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir",
"'/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_defender/grad', value.grad.data.cpu().numpy(), episode) episode_attacker_rewards = [] episode_defender_rewards",
"torch.device(\"cpu\") self.config.logger.info(\"Running on the CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device) # Set the target",
"target network if self.config.attacker: loss = self.training_step(minibatch, attacker=True) episode_attacker_loss += loss.item() if self.config.defender:",
"== \"Adam\": self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif self.config.dqn_config.optimizer ==",
"return s # if not self.env.local_view_features() or not attacker: # temp = np.append(attacker_obs,",
"import FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent class DQNAgent(QAgent): \"\"\"",
"if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss / episode_step) else: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step)",
"t.append(det_values[idx]) features.append(t) else: node_ids = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = neighbor_defense_attributes[:,",
"Log average metrics every <self.config.eval_log_frequency> episodes if episode % self.config.eval_log_frequency == 0 and",
"t = row.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1])",
"torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def training_step(self, mini_batch: Union[np.ndarray, np.ndarray, np.ndarray, np.ndarray,",
"= self.get_action(defender_obs, eval=True, attacker=False) action = (attacker_action, defender_action) # Take a step in",
"obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs",
"from gym_idsgame.agents.dao.experiment_result import ExperimentResult from gym_idsgame.envs.constants import constants from gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear from",
"import tqdm import torch from torch.utils.tensorboard import SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor from",
"if not self.env.local_view_features() or not attacker: # temp = np.append(attacker_obs, defender_obs) # else:",
"future # reward when following Q* estimated by the target network. else: a",
"defined by Mnih et. al. : For terminal states the Q-target should be",
"if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") r_1 = r_1.to(device) s_1 = s_1.to(device)",
"s2_attacker_batch, s2_defender_batch = mini_batch if self.config.attacker: s_1 = torch.tensor(s_attacker_batch).float() # Move to GPU",
"\"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") # Reset environment for the",
":param attacker: whether doing a training step for the attacker (otherwise defender) :return:",
"self.update_target_network() # Run evaluation every <self.config.eval_frequency> episodes if episode % self.config.eval_frequency == 0:",
"== \"MSE\": self.loss_fn = torch.nn.MSELoss() elif self.config.dqn_config.loss_fn == \"Huber\": self.loss_fn = torch.nn.SmoothL1Loss() else:",
"FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) #",
"= list(filter(lambda action: self.env.is_attack_legal(action), actions)) else: actions = list(range(self.env.num_defense_actions)) legal_actions = list(filter(lambda action:",
"done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs,",
"self.env.idsgame_config.game_config.reconnaissance_actions and attacker: combined_features = [] for idx, row in enumerate(attacker_obs): combined_row =",
"= neighbor_defense_attributes[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: temp = neighbor_defense_attributes[:, 0:-1] - attacker_obs[:, 0:-1]",
"{}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path) if self.config.defender: path = self.config.save_dir + \"/\" + time_str +",
"Log average metrics every <self.config.train_log_frequency> episodes if episode % self.config.train_log_frequency == 0: if",
"= self.loss_fn(prediction, target) # Zero gradients, perform a backward pass, and update the",
"video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = []",
"if self.env.state.hacked: self.num_train_hacks += 1 self.num_train_hacks_total += 1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if episode_step >",
"defender_obs_1 = defender_obs / np.linalg.norm(defender_obs) normalized_defender_features = [] for idx, row in enumerate(defender_obs_1):",
"+= defender_reward episode_step += 1 attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render",
"t = row normalized_defender_features.append(t) attacker_obs = np.array(normalized_attacker_features) defender_obs = np.array(normalized_defender_features) if self.env.local_view_features() and",
"after {} steps\".format(episode, episode_step)) # Record episode metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) # Update",
"= tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_defender/grad', value.grad.data.cpu().numpy(), episode) episode_attacker_rewards =",
"from gym_idsgame.envs.idsgame_env import IdsGameEnv from gym_idsgame.agents.dao.experiment_result import ExperimentResult from gym_idsgame.envs.constants import constants from",
"== 0: self.eval(episode) # Save models every <self.config.checkpoint_frequency> episodes if episode % self.config.checkpoint_freq",
"if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) # Log average metrics every <self.config.train_log_frequency>",
"defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs,",
"a minibatch to use for the training step :param attacker: whether doing a",
"attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime,",
"actions taken, not the entire # vector of all Q-values. Therefore we initialize",
"elif self.config.dqn_config.loss_fn == \"Huber\": self.loss_fn = torch.nn.SmoothL1Loss() else: raise ValueError(\"Loss function not recognized\")",
"range(features.shape[0]): f[i] = np.append(features[i], d_bool_features[i]) features = f if self.config.dqn_config.state_length == 1: return",
"< self.config.eval_epsilon): return np.random.choice(legal_actions) with torch.no_grad(): if attacker: act_values = self.attacker_q_network(state) else: act_values",
"FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent class DQNAgent(QAgent): \"\"\" An",
"GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1)",
"if attacker: return np.array([attacker_obs] * self.config.dqn_config.state_length) else: return np.array([defender_obs] * self.config.dqn_config.state_length) if attacker:",
"self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if self.config.defender: s_1 = torch.tensor(s_defender_batch).float() # Move to GPU if using",
"time.sleep(self.config.eval_sleep) # Default initialization attacker_action = 0 defender_action = 0 # Get attacker",
"for predictions, therefore we set it to eval mode # to turn of",
"self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval = True, update_stats=False) # Save gifs if",
"np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray], attacker: bool = True) ->",
"- attacker_obs[i, 0:-1] features = [] for idx, row in enumerate(temp): t =",
"# vector of all Q-values. Therefore we initialize the target to the Q-values",
"tqdm import torch from torch.utils.tensorboard import SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config",
"constants from gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent",
"graph to tensorboard with a sample batch as input mini_batch = self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch,",
"if self.config.attacker: attacker_action = self.get_action(attacker_obs, eval=True, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, eval=True,",
"path not defined, not saving Q-networks to disk\") def update_state(self, attacker_obs: np.ndarray =",
"0.0)) # Eval obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs,",
"attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features = attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs = attacker_obs[:, 0:a_obs_len] #",
"outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size: {}\".format(0, 0)) # Reset env",
"temp[i] = neighbor_defense_attributes[i] - attacker_obs[i, 0:-1] features = [] for idx, row in",
"outer_warmup.update(1) if done: obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs,",
"np.array(combined_features) f = np.zeros( (combined_features.shape[0], combined_features.shape[1] + d_bool_features.shape[1])) for i in range(combined_features.shape[0]): f[i]",
"self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked: self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -=",
"obs_state_d) attacker_obs, defender_obs = obs # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards =",
"self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Move to new state obs = obs_prime",
"not done: if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) # Default initialization attacker_action = 0 defender_action",
"FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) # Specify device if torch.cuda.is_available() and self.config.dqn_config.gpu: device",
"self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr) # Log values and gradients of",
"target network to compute the Q-values of s' with torch.no_grad(): if attacker: target_next",
"= None self.loss_fn = None self.attacker_optimizer = None self.defender_optimizer = None self.attacker_lr_decay =",
"0:-2] zero_mean_attacker_features = [] for idx, row in enumerate(attacker_obs_1): mean = np.mean(row) if",
"Therefore we initialize the target to the Q-values of the Q-network for s",
"episode_attacker_rewards, episode_defender_rewards, episode_steps, eval=True, update_stats=True) self.env.close() self.config.logger.info(\"Evaluation Complete\") return self.eval_result def save_model(self) ->",
"t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 = defender_obs[:, 0:-1] / np.linalg.norm(defender_obs[:, 0:-1])",
"= torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def training_step(self, mini_batch: Union[np.ndarray, np.ndarray, np.ndarray,",
"if episode % self.config.train_log_frequency == 0: if self.num_train_games > 0 and self.num_train_games_total >",
"descent step of the Q-network using targets produced by target network if self.config.attacker:",
"network every <self.config.dqn_config.target_network_update_freq> episodes if episode % self.config.dqn_config.target_network_update_freq == 0: self.update_target_network() # Run",
"self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a,",
"# a_obs_len + self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs = attacker_obs[:, 0:a_obs_len] if not attacker and",
"self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else: raise ValueError(\"Optimizer not recognized\") # LR decay if",
"= 0.0 episode_defender_loss = 0.0 while not done: if self.config.render: self.env.render(mode=\"human\") if not",
"config) self.attacker_q_network = None self.attacker_target_network = None self.defender_q_network = None self.defender_target_network = None",
"False self.env.idsgame_config.save_attack_stats = False def warmup(self) -> None: \"\"\" A warmup without any",
"network if self.config.attacker: loss = self.training_step(minibatch, attacker=True) episode_attacker_loss += loss.item() if self.config.defender: loss",
"= [] # Logging self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1) self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\"",
"= r_1.to(device) s_1 = s_1.to(device) s_2 = s_2.to(device) # Set target baseline. We",
"self.train_hack_probability = 0.0 self.train_cumulative_hack_probability = 0.0 self.log_metrics(episode, self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss,",
"and self.env.idsgame_config.game_config.reconnaissance_actions: t = row.tolist() t.append(defender_obs[idx][-1]) else: t = row normalized_defender_features.append(t) attacker_obs =",
"constructor will contain the learnable # parameters of the layers in the model",
"whether to log the result :return: None \"\"\" self.config.logger.info(\"Starting Evaluation\") time_str = str(time.time())",
"the DQN algorithm :return: Experiment result \"\"\" self.config.logger.info(\"Starting Warmup\") self.warmup() self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str())",
"# Record episode metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) # Update eval stats self.num_eval_games +=1",
"new state \"\"\" if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: #if not self.env.local_view_features(): a_obs_len = self.env.idsgame_config.game_config.num_attack_types",
"+ str(idx), frame, global_step=train_episode, dataformats = \"HWC\") # Reset for new eval episode",
"if np.isnan(t).any(): t = attacker_obs[idx] else: t = t.tolist() if not self.env.local_view_features() or",
"the parameters (histogram summary) to tensorboard if self.config.attacker: for tag, value in self.attacker_q_network.named_parameters():",
"self.num_train_games > 0 and self.num_train_games_total > 0: self.train_hack_probability = self.num_train_hacks / self.num_train_games self.train_cumulative_hack_probability",
"<filename>gym_idsgame/agents/training_agents/q_learning/dqn/dqn.py \"\"\" An agent for the IDSGameEnv that implements the DQN algorithm. \"\"\"",
"PyTorch) :param mini_batch: a minibatch to use for the training step :param attacker:",
"Q-values for the affected actions with the real targets if attacker: target =",
"weights. if attacker: self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step() return loss def",
"replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Sample random mini_batch of transitions",
":param log: whether to log the result :return: None \"\"\" self.config.logger.info(\"Starting Evaluation\") time_str",
"the Q-values of s' with torch.no_grad(): if attacker: target_next = self.attacker_target_network(s_2).detach() else: target_next",
"> 0 and self.num_train_games_total > 0: self.train_hack_probability = self.num_train_hacks / self.num_train_games self.train_cumulative_hack_probability =",
"loss = self.training_step(minibatch, attacker=False) episode_defender_loss += loss.item() # Update metrics attacker_reward, defender_reward =",
"action: self.env.is_defense_legal(action), defender_actions)) attacker_action = np.random.choice(legal_attack_actions) defender_action = np.random.choice(legal_defense_actions) action = (attacker_action, defender_action)",
"> 0: self.config.logger.warning(\"starting training with non-empty result object\") done = False obs =",
"Samples an action according to a epsilon-greedy strategy using the Q-network :param state:",
"training_step(self, mini_batch: Union[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray], attacker: bool",
"next state obs = obs_prime attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render",
"= obs_prime_defender # Render final frame if self.config.render: self.env.render(mode=\"human\") # Decay LR after",
"an action for :param eval: boolean flag whether running in evaluation mode :param",
"self.config.attacker: loss = self.training_step(minibatch, attacker=True) episode_attacker_loss += loss.item() if self.config.defender: loss = self.training_step(minibatch,",
"episodes if episode % self.config.checkpoint_freq == 0: self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if self.config.save_dir is",
"s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except: self.config.logger.warning(\"Error when trying to add network graph to tensorboard\")",
"1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if episode_step > 0: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss",
"loss.item() if self.config.defender: loss = self.training_step(minibatch, attacker=False) episode_defender_loss += loss.item() # Update metrics",
"path) if self.config.defender: path = self.config.save_dir + \"/\" + time_str + \"_defender_q_network.pt\" self.config.logger.info(\"Saving",
"= neighbor_defense_attributes[:, 0:-1] - attacker_obs[:, 0:-1] else: temp = np.full(neighbor_defense_attributes.shape, -1) for i",
"if self.env.idsgame_config.game_config.reconnaissance_actions and attacker: combined_features = [] for idx, row in enumerate(attacker_obs): combined_row",
"if self.env.idsgame_config.reconnaissance_bool_features: combined_features = np.array(combined_features) f = np.zeros( (combined_features.shape[0], combined_features.shape[1] + d_bool_features.shape[1])) for",
"row in enumerate(temp): t = row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx]) if not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t)",
"= None self.attacker_lr_decay = None self.defender_lr_decay = None self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer =",
"agent\") # Default initialization attacker_action = 0 defender_action = 0 # Get attacker",
"recognized\") # LR decay if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer,",
"terminal states the Q-target should be the immediate reward plus the discounted estimated",
"obs_prime episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step += 1 attacker_obs = obs_prime_attacker",
"An implementation of the DQN algorithm from the paper 'Human-level control through deep",
"the Q-values of the Q-network for s # and then we only update",
"tensorboard for idx, frame in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" + str(idx), frame, global_step=train_episode,",
"Q-networks to disk\") def update_state(self, attacker_obs: np.ndarray = None, defender_obs: np.ndarray = None,",
"{}\".format(path)) torch.save(self.defender_q_network.state_dict(), path) else: self.config.logger.warning(\"Save path not defined, not saving Q-networks to disk\")",
"device = torch.device(\"cuda:0\") self.config.logger.info(\"Running on the GPU\") else: device = torch.device(\"cpu\") self.config.logger.info(\"Running on",
"defender_action = np.random.choice(legal_defense_actions) action = (attacker_action, defender_action) # Take action in the environment",
"self.num_train_hacks / self.num_train_games self.train_cumulative_hack_probability = self.num_train_hacks_total / self.num_train_games_total else: self.train_hack_probability = 0.0 self.train_cumulative_hack_probability",
"log: whether to log the result :return: None \"\"\" self.config.logger.info(\"Starting Evaluation\") time_str =",
"reward when following Q* estimated by the target network. else: a = torch.argmax(target_next[i]).detach()",
"update the Q-values for the affected actions with the real targets if attacker:",
"mini_batch: a minibatch to use for the training step :param attacker: whether doing",
"network graph to tensorboard with a sample batch as input mini_batch = self.buffer.sample(self.config.dqn_config.batch_size)",
"Q-iteration but with the addition of a separate target network) \"\"\" def __init__(self,",
"0: s = np.array([f] * self.config.dqn_config.state_length) return s # if not self.env.local_view_features() or",
"target baseline. We only want the loss to be computed for the Q-values",
"t = row - mean else: t = row if np.isnan(t).any(): t =",
"to fill replay buffer\") # Perform <self.config.dqn_config.replay_start_size> steps and fill the replay memory",
"The sampled action id \"\"\" state = torch.from_numpy(state.flatten()).float() # Move to GPU if",
"id = int(attacker_obs[node][-1]) neighbor_defense_attributes[node] = defender_obs[id] else: neighbor_defense_attributes = defender_obs if self.env.fully_observed() or",
"gifs if self.config.gifs and self.config.video: self.env.generate_gif(self.config.gif_dir + \"/episode_\" + str(train_episode) + \"_\" +",
"# a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 # defender_obs = attacker_obs[:, # a_obs_len:a_obs_len +",
"dropouts, batch norms, gradient computations etc. self.attacker_target_network.eval() self.defender_target_network.eval() # Construct loss function if",
"import time import tqdm import torch from torch.utils.tensorboard import SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor import",
"using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network,",
"episode_defender_rewards = [] episode_steps = [] episode_avg_attacker_loss = [] episode_avg_defender_loss = [] #",
"Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] # Logging",
"defender_obs = np.array(zero_mean_defender_features) # Normalize if self.config.dqn_config.normalize_features: if not self.env.local_view_features() or not attacker:",
"temp = defender_obs[:, 0:] - attacker_obs[:, 0:-1] features = [] for idx, row",
"time import tqdm import torch from torch.utils.tensorboard import SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor",
"Update eval stats self.num_eval_games +=1 self.num_eval_games_total += 1 if self.env.state.detected: self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD",
"update_stats=False) # Save gifs if self.config.gifs and self.config.video: self.env.generate_gif(self.config.gif_dir + \"/episode_\" + str(train_episode)",
"self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories = False self.env.idsgame_config.save_attack_stats = False def",
"d_batch[i]: if attacker: target[i][a_attacker_batch[i]] = r_1[i] else: target[i][a_defender_batch[i]] = r_1[i] # For non",
"defender actions attacker_actions = list(range(self.env.num_attack_actions)) defender_actions = list(range(self.env.num_defense_actions)) legal_attack_actions = list(filter(lambda action: self.env.is_attack_legal(action),",
"state information and metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward",
"action, reward, done, obs_prime) # Move to new state obs = obs_prime outer_warmup.update(1)",
"0: if self.num_train_games > 0 and self.num_train_games_total > 0: self.train_hack_probability = self.num_train_hacks /",
"torch tensors and set Q-network in train mode and target network in eval",
"attacker: act_values = self.attacker_q_network(state) else: act_values = self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self) ->",
"= tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1) self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0,",
"-1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = neighbor_defense_attributes[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: temp =",
"to be computed for the Q-values of the actions taken, not the entire",
"= self.attacker_lr_decay.get_lr()[0] # Record episode metrics self.num_train_games += 1 self.num_train_games_total += 1 if",
"True) -> int: \"\"\" Samples an action according to a epsilon-greedy strategy using",
"if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if attacker",
"self.config.eval_log_frequency == 0 and log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) /",
"every <self.config.checkpoint_frequency> episodes if episode % self.config.checkpoint_freq == 0: self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if",
"self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards,",
"defender_obs = obs for episode in range(self.config.eval_episodes): episode_attacker_reward = 0 episode_defender_reward = 0",
"i in range(features.shape[0]): f[i] = np.append(features[i], d_bool_features[i]) features = f if self.config.dqn_config.state_length ==",
"np.array(normalized_defender_features) if self.env.local_view_features() and attacker: if not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes = np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for",
"torch.tensor(s_defender_batch).float() s_2 = torch.tensor(s2_defender_batch).float() # Move to GPU if using GPU if torch.cuda.is_available()",
"policy with respect to the learned Q-values :param train_episode: the train episode to",
"defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, eval=True, attacker=True) if self.config.defender: defender_action =",
"Eval obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True,",
"episode_avg_attacker_loss = [] episode_avg_defender_loss = [] # Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon,",
"1 self.num_eval_hacks_total +=1 # Log average metrics every <self.config.eval_log_frequency> episodes if episode %",
"target[i][a_attacker_batch[i]] = r_1[i] else: target[i][a_defender_batch[i]] = r_1[i] # For non terminal states the",
"game stats done = False obs = self.env.reset(update_stats=True) attacker_obs, defender_obs = obs obs_state_a",
"else: t = t.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2])",
"= \"HWC\") # Reset for new eval episode done = False obs =",
"path) else: self.config.logger.warning(\"Save path not defined, not saving Q-networks to disk\") def update_state(self,",
"% self.config.train_log_frequency == 0: if self.num_train_games > 0 and self.num_train_games_total > 0: self.train_hack_probability",
"if log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games) if self.num_eval_games_total",
"minibatch = self.buffer.sample(self.config.dqn_config.batch_size) # Perform a gradient descent step of the Q-network using",
"s_1) except: self.config.logger.warning(\"Error when trying to add network graph to tensorboard\") def initialize_models(self)",
"please specify \" \"the video_dir argument\") self.env = IdsGameMonitor(self.env, self.config.video_dir + \"/\" +",
"np.random.choice(legal_defense_actions) action = (attacker_action, defender_action) # Take action in the environment obs_prime, reward,",
"if not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] else: attacker_obs_1 =",
"self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif self.config.dqn_config.optimizer == \"SGD\": self.attacker_optimizer",
"= torch.tensor(r_attacker_batch).float() s_1 = torch.tensor(s_attacker_batch).float() s_2 = torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train() self.defender_q_network.eval() r_1 =",
"\"_eval_results_checkpoint.csv\") return self.train_result def update_target_network(self) -> None: \"\"\" Updates the target networks. Delayed",
"initialization attacker_action = 0 defender_action = 0 # Get attacker and defender actions",
"target network) \"\"\" def __init__(self, env:IdsGameEnv, config: QAgentConfig): \"\"\" Initialize environment and hyperparameters",
"in range(self.config.dqn_config.batch_size): # As defined by Mnih et. al. : For terminal states",
"episode_defender_rewards, episode_steps, eval = True, update_stats=False) # Save gifs if self.config.gifs and self.config.video:",
"Reset for new eval episode done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs",
"stabilize training and partially remedy the problem with non-stationary targets in RL with",
"float(self.num_eval_hacks) / float(self.num_eval_games) if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total)",
"not self.env.local_view_features() or not attacker: if self.env.idsgame_config.game_config.reconnaissance_actions and attacker: combined_features = [] for",
"from gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent class DQNAgent(QAgent): \"\"\" An implementation of the DQN algorithm",
"0:-1] else: temp = np.full(neighbor_defense_attributes.shape, -1) for i in range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i]) >",
"training an attacker agent or defender agent\") # Default initialization attacker_action = 0",
"agent or defender agent\") # Default initialization attacker_action = 0 defender_action = 0",
"for i in range(combined_features.shape[0]): f[i] = np.append(combined_features[i], d_bool_features[i]) combined_features = f return np.array(combined_features)",
"Experiment result \"\"\" self.config.logger.info(\"Starting Warmup\") self.warmup() self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps) > 0:",
"= obs_prime episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step += 1 # Move",
"episodes if episode % self.config.eval_frequency == 0: self.eval(episode) # Save models every <self.config.checkpoint_frequency>",
"IdsGameEnv from gym_idsgame.agents.dao.experiment_result import ExperimentResult from gym_idsgame.envs.constants import constants from gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear",
"import constants from gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent import",
"Q-networks self.save_model() # Save other game data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if self.config.save_dir is not",
"self.config.logger.warning(\"starting eval with non-empty result object\") if self.config.eval_episodes < 1: return done =",
"and update game stats done = False obs = self.env.reset(update_stats=True) attacker_obs, defender_obs =",
"d_bool_features.shape[1])) for i in range(f.shape[0]): f[i] = np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i]) else: f =",
"import torch from torch.utils.tensorboard import SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config import",
"affected actions with the real targets if attacker: target = self.attacker_q_network(s_1) else: target",
"final frame if self.config.render: self.env.render(mode=\"human\") # Decay LR after every episode lr =",
"s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except: self.config.logger.warning(\"Error when trying to add network graph",
"combined_features = f return np.array(combined_features) return np.append(attacker_obs, defender_obs) else: if self.env.idsgame_config.reconnaissance_bool_features: f =",
"attacker_obs[:, # a_obs_len + self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs = attacker_obs[:, 0:a_obs_len] if not attacker",
"self.config.dqn_config.state_length) return s state = np.append(state[1:], np.array([features]), axis=0) return state else: if not",
"1: if attacker: return np.array(attacker_obs) else: return np.array(defender_obs) if len(state) == 0: if",
"al. : For terminal states the Q-target should be equal to the immediate",
"observation :param state: current state :param attacker: boolean flag whether it is attacker",
"values and gradients of the parameters (histogram summary) to tensorboard if self.config.attacker: for",
"import QAgentConfig from gym_idsgame.envs.idsgame_env import IdsGameEnv from gym_idsgame.agents.dao.experiment_result import ExperimentResult from gym_idsgame.envs.constants import",
"+ \"_eval_results_checkpoint.csv\") return self.train_result def update_target_network(self) -> None: \"\"\" Updates the target networks.",
"= state.to(device) if attacker: actions = list(range(self.env.num_attack_actions)) legal_actions = list(filter(lambda action: self.env.is_attack_legal(action), actions))",
"if np.sum(neighbor_defense_attributes[i]) > 0: temp[i] = neighbor_defense_attributes[i] - attacker_obs[i, 0:-1] features = []",
"Define Optimizer. The call to model.parameters() in the optimizer constructor will contain the",
"def train(self) -> ExperimentResult: \"\"\" Runs the DQN algorithm :return: Experiment result \"\"\"",
"self.config.defender: raise AssertionError(\"Must specify whether training an attacker agent or defender agent\") #",
"= \"[Warmup] step:{}, buffer_size: {}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) # Select random attacker and",
"loss = self.training_step(minibatch, attacker=True) episode_attacker_loss += loss.item() if self.config.defender: loss = self.training_step(minibatch, attacker=False)",
"obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime",
"self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers,",
"= self.attacker_target_network(s_2).detach() else: target_next = self.defender_target_network(s_2).detach() for i in range(self.config.dqn_config.batch_size): # As defined",
"self.defender_q_network = None self.defender_target_network = None self.loss_fn = None self.attacker_optimizer = None self.defender_optimizer",
"Initialize models :return: None \"\"\" # Initialize models self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim,",
"self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def training_step(self, mini_batch: Union[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,",
"not self.env.local_view_features(): a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 defender_obs = attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features:",
"= defender_obs[:, 0:-1] / np.linalg.norm(defender_obs[:, 0:-1]) else: defender_obs_1 = defender_obs / np.linalg.norm(defender_obs) normalized_defender_features",
"[] for idx, row in enumerate(attacker_obs): combined_row = np.append(row, defender_obs[idx]) combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features:",
"attacker_obs = np.array(zero_mean_attacker_features) defender_obs = np.array(zero_mean_defender_features) # Normalize if self.config.dqn_config.normalize_features: if not self.env.local_view_features()",
"episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step += 1 attacker_obs = obs_prime_attacker defender_obs",
"of transitions from the replay memory s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\",
"state obs = obs_prime outer_warmup.update(1) if done: obs = self.env.reset(update_stats=False) attacker_obs, defender_obs =",
"torch.save(self.attacker_q_network.state_dict(), path) if self.config.defender: path = self.config.save_dir + \"/\" + time_str + \"_defender_q_network.pt\"",
"self.env.fully_observed(): t.append(det_values[idx]) features.append(t) else: node_ids = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values =",
"in enumerate(defender_obs_1): if np.isnan(defender_obs_1).any(): t = defender_obs[idx] else: if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: t",
"0,0, 0.0, 0.0, 0.0, 0.0)) # Eval obs = self.env.reset(update_stats=False) attacker_obs, defender_obs =",
": bool = True) -> int: \"\"\" Samples an action according to a",
"and fill the replay memory for i in range(self.config.dqn_config.replay_start_size): if i % self.config.train_log_frequency",
"episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] episode_avg_attacker_loss = [] episode_avg_defender_loss",
"= True) -> np.ndarray: \"\"\" Update approximative Markov state :param attacker_obs: attacker obs",
"(target_next[i][a]) else: target[i][a_defender_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) # Compute loss if",
": bool = False, attacker : bool = True) -> int: \"\"\" Samples",
"self.config.video_dir + \"/\" + time_str, force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps # Tracking metrics",
":return: new state \"\"\" if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: #if not self.env.local_view_features(): a_obs_len =",
"+ \"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path) if self.config.defender: path = self.config.save_dir",
"np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray], attacker: bool = True) -> torch.Tensor: \"\"\"",
"\"\"\" An implementation of the DQN algorithm from the paper 'Human-level control through",
"return np.random.choice(legal_actions) with torch.no_grad(): if attacker: act_values = self.attacker_q_network(state) else: act_values = self.defender_q_network(state)",
"float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval=True, update_stats=True) self.env.close() self.config.logger.info(\"Evaluation",
"Final evaluation (for saving Gifs etc) self.eval(self.config.num_episodes-1, log=False) # Save Q-networks self.save_model() #",
"if attacker: state = np.append(state[1:], np.array([attacker_obs]), axis=0) else: state = np.append(state[1:], np.array([defender_obs]), axis=0)",
"for i in range(self.config.dqn_config.replay_start_size): if i % self.config.train_log_frequency == 0: log_str = \"[Warmup]",
"\"\"\" time_str = str(time.time()) if self.config.save_dir is not None: if self.config.attacker: path =",
"defender_action) # Take a step in the environment obs_prime, reward, done, _ =",
"d_bool_features = attacker_obs[:, # a_obs_len + self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs = attacker_obs[:, 0:a_obs_len] if",
"time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") # Reset environment",
"the layers in the model if self.config.dqn_config.optimizer == \"Adam\": self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha)",
"r_1[i] else: target[i][a_defender_batch[i]] = r_1[i] # For non terminal states the Q-target should",
"s_1.to(device) s_2 = s_2.to(device) # Set target baseline. We only want the loss",
"assume defender) :return: The sampled action id \"\"\" state = torch.from_numpy(state.flatten()).float() # Move",
"t.append(det_values[idx]) features.append(t) features = np.array(features) if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((features.shape[0], features.shape[1] + d_bool_features.shape[1]))",
"-> ExperimentResult: \"\"\" Runs the DQN algorithm :return: Experiment result \"\"\" self.config.logger.info(\"Starting Warmup\")",
"loss function if self.config.dqn_config.loss_fn == \"MSE\": self.loss_fn = torch.nn.MSELoss() elif self.config.dqn_config.loss_fn == \"Huber\":",
"Deep-Q-learning algorithm (implemented in PyTorch) :param mini_batch: a minibatch to use for the",
"self.warmup() self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting training with non-empty result",
"if self.config.dqn_config.merged_ad_features: if not self.env.local_view_features() or not attacker: a_pos = attacker_obs[:, -1] if",
"== \"Huber\": self.loss_fn = torch.nn.SmoothL1Loss() else: raise ValueError(\"Loss function not recognized\") # Define",
"update_target_network(self) -> None: \"\"\" Updates the target networks. Delayed targets are used to",
"-> None: \"\"\" Updates the target networks. Delayed targets are used to stabilize",
"self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs for",
"paper 'Human-level control through deep reinforcement learning' by Mnih et. al. (DQN is",
"def __init__(self, env:IdsGameEnv, config: QAgentConfig): \"\"\" Initialize environment and hyperparameters :param config: the",
"the paper 'Human-level control through deep reinforcement learning' by Mnih et. al. (DQN",
"path = self.config.save_dir + \"/\" + time_str + \"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path))",
"to the learned Q-values :param train_episode: the train episode to keep track of",
"0 episode_step = 0 while not done: if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) # Default",
"else: if self.config.dqn_config.state_length == 1: if attacker: return np.array(attacker_obs) else: return np.array(defender_obs) if",
"control through deep reinforcement learning' by Mnih et. al. (DQN is originally Neural-fitted",
"[] episode_avg_defender_loss = [] # Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0,",
"desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size: {}\".format(0, 0)) # Reset env obs = self.env.reset(update_stats=False)",
"idx, row in enumerate(defender_obs_1): if np.isnan(defender_obs_1).any(): t = defender_obs[idx] else: if attacker and",
"# Select random attacker and defender actions attacker_actions = list(range(self.env.num_attack_actions)) defender_actions = list(range(self.env.num_defense_actions))",
"= np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for node in range(attacker_obs.shape[0]): id = int(attacker_obs[node][-1]) neighbor_defense_attributes[node] = defender_obs[id]",
"if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode: {}, Game ended after {} steps\".format(episode, episode_step))",
"attacker_obs_1 = attacker_obs[:, 0:-2] zero_mean_attacker_features = [] for idx, row in enumerate(attacker_obs_1): mean",
"with non-empty result object\") done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs =",
"episode: {}, Game ended after {} steps\".format(episode, episode_step)) # Record episode metrics episode_attacker_rewards.append(episode_attacker_reward)",
"= False self.env.idsgame_config.save_attack_stats = False def warmup(self) -> None: \"\"\" A warmup without",
"= 0 episode_attacker_loss = 0.0 episode_defender_loss = 0.0 while not done: if self.config.render:",
"== 1: return f if len(state) == 0: s = np.array([f] * self.config.dqn_config.state_length)",
"used to stabilize training and partially remedy the problem with non-stationary targets in",
"time_str + \"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path) if self.config.defender: path =",
"attacker_obs = np.array(normalized_attacker_features) defender_obs = np.array(normalized_defender_features) if self.env.local_view_features() and attacker: if not self.env.idsgame_config.game_config.reconnaissance_actions:",
"if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1] + d_bool_features.shape[1])) for i in",
"self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories = False self.env.idsgame_config.save_attack_stats",
"not attacker: a_pos = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = defender_obs[:, -1]",
"and self.env.local_view_features(): attacker_obs = self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero mean if self.config.dqn_config.zero_mean_features:",
"in the model if self.config.dqn_config.optimizer == \"Adam\": self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer =",
"mode and target network in eval mode if attacker: self.attacker_q_network.train() self.attacker_target_network.eval() r_1 =",
"self.attacker_q_network.train() self.attacker_target_network.eval() r_1 = torch.tensor(r_attacker_batch).float() s_1 = torch.tensor(s_attacker_batch).float() s_2 = torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train()",
"return done = False # Video config if self.config.video: if self.config.video_dir is None:",
"self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if self.config.defender: s_1 =",
"self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except: self.config.logger.warning(\"Error when trying to add network graph to tensorboard\") def",
"to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path) if self.config.defender: path = self.config.save_dir + \"/\" + time_str",
"to model.parameters() in the optimizer constructor will contain the learnable # parameters of",
"defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime,",
"average metrics every <self.config.eval_log_frequency> episodes if episode % self.config.eval_log_frequency == 0 and log:",
"else: defender_obs_1 = defender_obs / np.linalg.norm(defender_obs) normalized_defender_features = [] for idx, row in",
"> 0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games) if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability =",
"np import time import tqdm import torch from torch.utils.tensorboard import SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor",
"to a epsilon-greedy strategy using the Q-network :param state: the state to sample",
"defender_obs[idx]) combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features: combined_features = np.array(combined_features) f = np.zeros( (combined_features.shape[0], combined_features.shape[1] +",
"environment for the next episode and update game stats done = False obs",
"num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim,",
"self.num_train_games self.train_cumulative_hack_probability = self.num_train_hacks_total / self.num_train_games_total else: self.train_hack_probability = 0.0 self.train_cumulative_hack_probability = 0.0",
"and gradients of the parameters (histogram summary) to tensorboard if self.config.attacker: for tag,",
"of dropouts, batch norms, gradient computations etc. self.attacker_target_network.eval() self.defender_target_network.eval() # Construct loss function",
"= self.attacker_q_network(s_1) else: target = self.defender_q_network(s_1) # Use the target network to compute",
"result object\") if self.config.eval_episodes < 1: return done = False # Video config",
"if self.config.eval_episodes < 1: return done = False # Video config if self.config.video:",
"return np.append(attacker_obs, defender_obs) else: if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1] +",
"action, reward, done, obs_prime) # Sample random mini_batch of transitions from replay memory",
"if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss / episode_step) else: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if",
"!= 0: t = row - mean else: t = row if np.isnan(t).any():",
"with torch.no_grad(): if attacker: target_next = self.attacker_target_network(s_2).detach() else: target_next = self.defender_target_network(s_2).detach() for i",
"Specify device if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") self.config.logger.info(\"Running on the GPU\")",
"+ \"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(), path) else: self.config.logger.warning(\"Save path not defined,",
"attacker obs :param defender_obs: defender observation :param state: current state :param attacker: boolean",
"state else: if not self.env.local_view_features() or not attacker: if self.env.idsgame_config.game_config.reconnaissance_actions and attacker: combined_features",
"self.anneal_epsilon() self.config.logger.info(\"Training Complete\") # Final evaluation (for saving Gifs etc) self.eval(self.config.num_episodes-1, log=False) #",
"(eval and np.random.random() < self.config.eval_epsilon): return np.random.choice(legal_actions) with torch.no_grad(): if attacker: act_values =",
"# Log average metrics every <self.config.train_log_frequency> episodes if episode % self.config.train_log_frequency == 0:",
"row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx]) if not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t) features = np.array(features) if self.env.idsgame_config.reconnaissance_bool_features:",
"= np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1] + d_bool_features.shape[1])) for i in range(f.shape[0]): f[i] =",
"self.config.gamma * (target_next[i][a]) # Compute loss if attacker: prediction = self.attacker_q_network(s_1) else: prediction",
"populate the replay buffer following a random strategy :return: None \"\"\" # Setup",
"False, attacker : bool = True) -> int: \"\"\" Samples an action according",
"self.num_eval_hacks = 0 if len(self.eval_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting eval with non-empty result object\")",
"if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 = defender_obs[:, 0:-1] / np.linalg.norm(defender_obs[:, 0:-1]) else: defender_obs_1",
"self.buffer.size())) self.env.close() try: # Add network graph to tensorboard with a sample batch",
"= self.defender_q_network(s_1) # Use the target network to compute the Q-values of s'",
"self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes = np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for node in range(attacker_obs.shape[0]): id = int(attacker_obs[node][-1]) neighbor_defense_attributes[node]",
"defender_action) # Take action in the environment obs_prime, reward, done, info = self.env.step(action)",
"np.random.choice(legal_attack_actions) defender_action = np.random.choice(legal_defense_actions) action = (attacker_action, defender_action) # Take action in the",
"buffer following a random strategy :return: None \"\"\" # Setup logging outer_warmup =",
"not self.env.idsgame_config.game_config.reconnaissance_actions: temp = neighbor_defense_attributes[:, 0:-1] - attacker_obs[:, 0:-1] else: temp = np.full(neighbor_defense_attributes.shape,",
"= 0 self.num_train_hacks = 0 # Update target network every <self.config.dqn_config.target_network_update_freq> episodes if",
"with the real targets if attacker: target = self.attacker_q_network(s_1) else: target = self.defender_q_network(s_1)",
"# Update target network every <self.config.dqn_config.target_network_update_freq> episodes if episode % self.config.dqn_config.target_network_update_freq == 0:",
"= torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if self.config.defender: s_1 = torch.tensor(s_defender_batch).float() #",
"through deep reinforcement learning' by Mnih et. al. (DQN is originally Neural-fitted Q-iteration",
"num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim,",
"attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs # Tracking metrics",
"= reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step",
"neighbor_defense_attributes[:, 0:-1] - attacker_obs[:, 0:-1] else: temp = np.full(neighbor_defense_attributes.shape, -1) for i in",
"the replay memory for i in range(self.config.dqn_config.replay_start_size): if i % self.config.train_log_frequency == 0:",
"\"_\" + time_str + \".gif\", self.config.video_fps) # Add frames to tensorboard for idx,",
"self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1] + d_bool_features.shape[1])) for i in range(f.shape[0]):",
"episode_defender_rewards.append(episode_defender_reward) if episode_step > 0: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss / episode_step)",
"in range(f.shape[0]): f[i] = np.append(attacker_obs[i], neighbor_defense_attributes[i]) if self.config.dqn_config.state_length == 1: return f if",
"# Move to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device =",
"\"\"\" self.config.logger.info(\"Updating target network\") if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def",
"attacker_obs[:, 0:-2] / np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features = [] for idx, row in enumerate(attacker_obs_1):",
"obs_prime outer_warmup.update(1) if done: obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a =",
"= defender_obs[:, 0:-1] - attacker_obs[:, 0:-1] else: temp = defender_obs[:, 0:] - attacker_obs[:,",
"defender_obs = attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features = attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs = attacker_obs[:,",
"1 self.num_train_hacks_total += 1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if episode_step > 0: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step)",
"attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 = defender_obs[:,",
"argument\") self.env = IdsGameMonitor(self.env, self.config.video_dir + \"/\" + time_str, force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] =",
"= [] for idx, row in enumerate(defender_obs_1): mean = np.mean(row) if mean !=",
"f = np.zeros((features.shape[0], features.shape[1] + d_bool_features.shape[1])) for i in range(features.shape[0]): f[i] = np.append(features[i],",
"= np.array(combined_features) f = np.zeros( (combined_features.shape[0], combined_features.shape[1] + d_bool_features.shape[1])) for i in range(combined_features.shape[0]):",
"reward, done, obs_prime) # Sample random mini_batch of transitions from replay memory minibatch",
"self.env.state.detected: self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked: self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward",
"= attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = defender_obs[:, -1] temp = defender_obs[:,",
"self.config.dqn_config.state_length) else: return np.array([defender_obs] * self.config.dqn_config.state_length) if attacker: state = np.append(state[1:], np.array([attacker_obs]), axis=0)",
"else: if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1] + d_bool_features.shape[1])) for i",
"respect to the learned Q-values :param train_episode: the train episode to keep track",
"# and then we only update the Q-values for the affected actions with",
"self.train_hack_probability = self.num_train_hacks / self.num_train_games self.train_cumulative_hack_probability = self.num_train_hacks_total / self.num_train_games_total else: self.train_hack_probability =",
"0 and self.num_train_games_total > 0: self.train_hack_probability = self.num_train_hacks / self.num_train_games self.train_cumulative_hack_probability = self.num_train_hacks_total",
"self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) # Specify device if torch.cuda.is_available() and",
"= f return np.array(combined_features) return np.append(attacker_obs, defender_obs) else: if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((attacker_obs.shape[0],",
"with a sample batch as input mini_batch = self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch,",
"learning just to populate the replay buffer following a random strategy :return: None",
"= True) -> int: \"\"\" Samples an action according to a epsilon-greedy strategy",
"LR after every episode lr = self.config.alpha if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr = self.attacker_lr_decay.get_lr()[0]",
"features = [] for idx, row in enumerate(temp): t = row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx])",
"features.shape[1] + d_bool_features.shape[1])) for i in range(features.shape[0]): f[i] = np.append(features[i], d_bool_features[i]) features =",
"+ \"/\" + time_str + \"_eval_results_checkpoint.csv\") return self.train_result def update_target_network(self) -> None: \"\"\"",
"self.num_train_hacks_total += 1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if episode_step > 0: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if",
"0.0, 0.0, 0.0, 0.0)) # Training for episode in range(self.config.num_episodes): episode_attacker_reward = 0",
"= torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif self.config.dqn_config.optimizer == \"SGD\": self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer =",
"if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) # Default initialization attacker_action = 0 defender_action = 0",
"from gym_idsgame.envs.constants import constants from gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer from",
"the immediate reward if d_batch[i]: if attacker: target[i][a_attacker_batch[i]] = r_1[i] else: target[i][a_defender_batch[i]] =",
"episode and update game stats done = False obs = self.env.reset(update_stats=True) attacker_obs, defender_obs",
"t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1 = defender_obs[:, 0:-1] zero_mean_defender_features = [] for idx, row",
"sampled action id \"\"\" state = torch.from_numpy(state.flatten()).float() # Move to GPU if using",
"episode_defender_reward += defender_reward episode_step += 1 attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender #",
"self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games) if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability",
"= np.append(attacker_obs, defender_obs) # else: # temp = np.append(attacker_obs, neighbor_defense_attributes) state = np.append(state[1:],",
"self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) # Select random attacker and defender actions attacker_actions = list(range(self.env.num_attack_actions))",
"{}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) # Select random attacker and defender actions attacker_actions =",
"= self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs",
"= self.attacker_q_network(state) else: act_values = self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self) -> ExperimentResult: \"\"\"",
"predictions, therefore we set it to eval mode # to turn of dropouts,",
"1 if self.env.state.hacked: self.num_train_hacks += 1 self.num_train_hacks_total += 1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if episode_step",
"self.num_train_games += 1 self.num_train_games_total += 1 if self.env.state.hacked: self.num_train_hacks += 1 self.num_train_hacks_total +=",
"random mini_batch of transitions from replay memory minibatch = self.buffer.sample(self.config.dqn_config.batch_size) # Perform a",
"estimated future # reward when following Q* estimated by the target network. else:",
"The call to model.parameters() in the optimizer constructor will contain the learnable #",
"* self.config.dqn_config.state_length) return s # if not self.env.local_view_features() or not attacker: # temp",
"defender_obs[idx] else: t = t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs = np.array(zero_mean_attacker_features) defender_obs = np.array(zero_mean_defender_features)",
"and not eval) \\ or (eval and np.random.random() < self.config.eval_epsilon): return np.random.choice(legal_actions) with",
"t = row if np.isnan(t).any(): t = attacker_obs[idx] else: t = t.tolist() if",
"attacker: bool = True) -> torch.Tensor: \"\"\" Performs a training step of the",
"if mean != 0: t = row - mean else: t = row",
"self.config.logger.info(\"Running on the CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device) # Set the target network",
"== 0: s = np.array([f] * self.config.dqn_config.state_length) return s # if not self.env.local_view_features()",
"not self.config.attacker and not self.config.defender: raise AssertionError(\"Must specify whether training an attacker agent",
"s_2 = torch.tensor(s2_defender_batch).float() # Move to GPU if using GPU if torch.cuda.is_available() and",
"\"\"\" Update approximative Markov state :param attacker_obs: attacker obs :param defender_obs: defender observation",
"None: \"\"\" Saves the PyTorch Model Weights :return: None \"\"\" time_str = str(time.time())",
"obs_prime_defender = obs_prime episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step += 1 attacker_obs",
"__init__(self, env:IdsGameEnv, config: QAgentConfig): \"\"\" Initialize environment and hyperparameters :param config: the configuration",
"0:-1] else: attacker_obs_1 = attacker_obs[:, 0:-2] zero_mean_attacker_features = [] for idx, row in",
"np.linalg.norm(attacker_obs[:, 0:-1]) else: attacker_obs_1 = attacker_obs[:, 0:-2] / np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features = []",
"# Move to new state obs = obs_prime outer_warmup.update(1) if done: obs =",
"episode_defender_loss += loss.item() # Update metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender =",
"'/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_attacker/grad', value.grad.data.cpu().numpy(), episode) if self.config.defender: for tag,",
"= str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" +",
"= None self.defender_target_network = None self.loss_fn = None self.attacker_optimizer = None self.defender_optimizer =",
"= obs_prime outer_warmup.update(1) if done: obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a",
"is not trainable it is only used for predictions, therefore we set it",
"set Q-network in train mode and target network in eval mode if attacker:",
"a training step for the attacker (otherwise defender) :return: loss \"\"\" # Unpack",
"attacker : bool = True) -> int: \"\"\" Samples an action according to",
"Anneal epsilon linearly self.anneal_epsilon() self.config.logger.info(\"Training Complete\") # Final evaluation (for saving Gifs etc)",
"return self.train_result def update_target_network(self) -> None: \"\"\" Updates the target networks. Delayed targets",
"\"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0, 0.0, 0.0)) # Eval obs = self.env.reset(update_stats=False) attacker_obs, defender_obs",
"= np.append(combined_features[i], d_bool_features[i]) combined_features = f return np.array(combined_features) return np.append(attacker_obs, defender_obs) else: if",
"t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1 = defender_obs[:, 0:-1] zero_mean_defender_features = [] for",
"\"SGD\": self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else: raise ValueError(\"Optimizer not",
"# Convert batch into torch tensors and set Q-network in train mode and",
"self.env.is_defense_legal(action), defender_actions)) attacker_action = np.random.choice(legal_attack_actions) defender_action = np.random.choice(legal_defense_actions) action = (attacker_action, defender_action) #",
"self.config.attacker: s_1 = torch.tensor(s_attacker_batch).float() # Move to GPU if using GPU if torch.cuda.is_available()",
"with non-empty result object\") if self.config.eval_episodes < 1: return done = False #",
"environment obs_prime, reward, done, info = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime =",
"eval = True, update_stats=False) # Save gifs if self.config.gifs and self.config.video: self.env.generate_gif(self.config.gif_dir +",
"r_1[i] + self.config.gamma * (target_next[i][a]) else: target[i][a_defender_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a])",
"defender_obs if self.env.fully_observed() or \\ (self.env.idsgame_config.game_config.reconnaissance_actions and attacker): if self.config.dqn_config.merged_ad_features: if not self.env.local_view_features()",
"try: # Add network graph to tensorboard with a sample batch as input",
"np.ndarray, np.ndarray, np.ndarray], attacker: bool = True) -> torch.Tensor: \"\"\" Performs a training",
"1 self.num_train_games_total += 1 if self.env.state.hacked: self.num_train_hacks += 1 self.num_train_hacks_total += 1 episode_attacker_rewards.append(episode_attacker_reward)",
"= list(range(self.env.num_defense_actions)) legal_actions = list(filter(lambda action: self.env.is_defense_legal(action), actions)) if (np.random.rand() < self.config.epsilon and",
"numpy as np import time import tqdm import torch from torch.utils.tensorboard import SummaryWriter",
"the weights. if attacker: self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step() return loss",
"self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval=True, update_stats=True) self.env.close() self.config.logger.info(\"Evaluation Complete\") return self.eval_result",
"r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch if self.config.attacker: s_1 = torch.tensor(s_attacker_batch).float() #",
"+ neighbor_defense_attributes.shape[1] + d_bool_features.shape[1])) for i in range(f.shape[0]): f[i] = np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i])",
"as np import time import tqdm import torch from torch.utils.tensorboard import SummaryWriter from",
"+ \"_eval_results_checkpoint.csv\") # Reset environment for the next episode and update game stats",
"state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Update",
"= np.array(normalized_defender_features) if self.env.local_view_features() and attacker: if not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes = np.zeros((attacker_obs.shape[0], defender_obs.shape[1]))",
"= torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def training_step(self, mini_batch: Union[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,",
"self).__init__(env, config) self.attacker_q_network = None self.attacker_target_network = None self.defender_q_network = None self.defender_target_network =",
"/ np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features = [] for idx, row in enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any():",
"self.config.video_dir is None: raise AssertionError(\"Video is set to True but no video_dir is",
"is provided, please specify \" \"the video_dir argument\") self.env = IdsGameMonitor(self.env, self.config.video_dir +",
"None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir +",
"[] for idx, row in enumerate(defender_obs_1): if np.isnan(defender_obs_1).any(): t = defender_obs[idx] else: if",
"t = attacker_obs[idx] else: t = row.tolist() if not self.env.local_view_features() or not attacker:",
"approximation. :return: None \"\"\" self.config.logger.info(\"Updating target network\") if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if self.config.defender:",
"t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs = np.array(zero_mean_attacker_features) defender_obs = np.array(zero_mean_defender_features) # Normalize if self.config.dqn_config.normalize_features: if",
"Union[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray], attacker: bool = True)",
"Complete\") return self.eval_result def save_model(self) -> None: \"\"\" Saves the PyTorch Model Weights",
"a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch if self.config.attacker: s_1",
"= [] for idx, row in enumerate(attacker_obs): combined_row = np.append(row, defender_obs[idx]) combined_features.append(combined_row) if",
"[] episode_defender_rewards = [] episode_steps = [] # Logging self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval",
"else: t = row if np.isnan(t).any(): t = defender_obs[idx] else: t = t.tolist()",
"env:IdsGameEnv, config: QAgentConfig): \"\"\" Initialize environment and hyperparameters :param config: the configuration \"\"\"",
"self.defender_q_network(s_1) loss = self.loss_fn(prediction, target) # Zero gradients, perform a backward pass, and",
"buffer_size: {}\".format(0, 0)) # Reset env obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs",
"> 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps,",
"Model Weights :return: None \"\"\" time_str = str(time.time()) if self.config.save_dir is not None:",
"Setup logging outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size: {}\".format(0, 0)) #",
"+ \"_\" + time_str + \".gif\", self.config.video_fps) # Add frames to tensorboard for",
"or not :return: new state \"\"\" if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: #if not self.env.local_view_features():",
"reward if d_batch[i]: if attacker: target[i][a_attacker_batch[i]] = r_1[i] else: target[i][a_defender_batch[i]] = r_1[i] #",
"def eval(self, train_episode, log=True) -> ExperimentResult: \"\"\" Performs evaluation with the greedy policy",
"+ d_bool_features.shape[1])) for i in range(features.shape[0]): f[i] = np.append(features[i], d_bool_features[i]) features = f",
"log=False) # Save Q-networks self.save_model() # Save other game data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if",
"for episode in range(self.config.num_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step = 0",
"f if len(state) == 0: s = np.array([f] * self.config.dqn_config.state_length) return s #",
"replay buffer size: {}\".format( self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close() try: # Add network graph to",
"= False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs,",
"and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, eval=True, attacker=True) if self.config.defender: defender_action",
"float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval = True, update_stats=False)",
"attacker_obs[idx] else: t = row.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else:",
"local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero mean if self.config.dqn_config.zero_mean_features: if not self.env.local_view_features() or not attacker:",
"# Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] episode_avg_attacker_loss",
"episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr) # Log values and gradients of the parameters (histogram",
"= torch.nn.SmoothL1Loss() else: raise ValueError(\"Loss function not recognized\") # Define Optimizer. The call",
"actions = list(range(self.env.num_defense_actions)) legal_actions = list(filter(lambda action: self.env.is_defense_legal(action), actions)) if (np.random.rand() < self.config.epsilon",
"attacker: if self.env.idsgame_config.game_config.reconnaissance_actions and attacker: combined_features = [] for idx, row in enumerate(attacker_obs):",
"be equal to the immediate reward if d_batch[i]: if attacker: target[i][a_attacker_batch[i]] = r_1[i]",
"= np.array([features] * self.config.dqn_config.state_length) return s state = np.append(state[1:], np.array([features]), axis=0) return state",
"attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = neighbor_defense_attributes[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: temp",
"= torch.argmax(target_next[i]).detach() if attacker: target[i][a_attacker_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) else: target[i][a_defender_batch[i]]",
"= 0 # Get attacker and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs,",
"Markov state :param attacker_obs: attacker obs :param defender_obs: defender observation :param state: current",
"# Decay LR after every episode lr = self.config.alpha if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr",
"return state else: if not self.env.local_view_features() or not attacker: if self.env.idsgame_config.game_config.reconnaissance_actions and attacker:",
"defender_obs) else: if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1] + d_bool_features.shape[1])) for",
"Q-target should be equal to the immediate reward if d_batch[i]: if attacker: target[i][a_attacker_batch[i]]",
"metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] # Logging self.outer_eval",
"defender_reward episode_step += 1 # Move to the next state obs = obs_prime",
": For terminal states the Q-target should be equal to the immediate reward",
"self.attacker_q_network(s_1) else: prediction = self.defender_q_network(s_1) loss = self.loss_fn(prediction, target) # Zero gradients, perform",
"norms, gradient computations etc. self.attacker_target_network.eval() self.defender_target_network.eval() # Construct loss function if self.config.dqn_config.loss_fn ==",
"np.array([f]), axis=0) return state else: if self.config.dqn_config.state_length == 1: if attacker: return np.array(attacker_obs)",
"torch.nn.SmoothL1Loss() else: raise ValueError(\"Loss function not recognized\") # Define Optimizer. The call to",
"1 if self.env.state.detected: self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked: self.eval_attacker_cumulative_reward +=",
"if self.config.save_dir is not None: if self.config.attacker: path = self.config.save_dir + \"/\" +",
"attacker_obs = attacker_obs[:, 0:a_obs_len] # else: # a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 #",
"self.config.save_dir is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\" + time_str +",
"whether doing a training step for the attacker (otherwise defender) :return: loss \"\"\"",
"while not done: if self.config.render: self.env.render(mode=\"human\") if not self.config.attacker and not self.config.defender: raise",
"torch.tensor(s_attacker_batch).float() # Move to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device",
"combined_features = np.array(combined_features) f = np.zeros( (combined_features.shape[0], combined_features.shape[1] + d_bool_features.shape[1])) for i in",
"= self.buffer.sample(self.config.dqn_config.batch_size) # Perform a gradient descent step of the Q-network using targets",
"torch from torch.utils.tensorboard import SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig",
"= None self.attacker_optimizer = None self.defender_optimizer = None self.attacker_lr_decay = None self.defender_lr_decay =",
"episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step += 1 # Move to the",
"= 0.0 self.train_cumulative_hack_probability = 0.0 self.log_metrics(episode, self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr)",
"defender_obs = attacker_obs[:, # a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types] # if self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features =",
"neighbor_defense_attributes[node] = defender_obs[id] else: neighbor_defense_attributes = defender_obs if self.env.fully_observed() or \\ (self.env.idsgame_config.game_config.reconnaissance_actions and",
"Initialize models self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim,",
"s_1 = torch.tensor(s_defender_batch).float() s_2 = torch.tensor(s2_defender_batch).float() # Move to GPU if using GPU",
"'Human-level control through deep reinforcement learning' by Mnih et. al. (DQN is originally",
"det_values = defender_obs[:, -1] temp = defender_obs[:, 0:-1] - attacker_obs[:, 0:-1] else: temp",
"# LR decay if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate)",
"# Run evaluation every <self.config.eval_frequency> episodes if episode % self.config.eval_frequency == 0: self.eval(episode)",
"approximative Markov state :param attacker_obs: attacker obs :param defender_obs: defender observation :param state:",
"= row.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t)",
"if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = defender_obs[:, -1] temp = defender_obs[:, 0:-1] - attacker_obs[:,",
"0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval",
"np.append(combined_features[i], d_bool_features[i]) combined_features = f return np.array(combined_features) return np.append(attacker_obs, defender_obs) else: if self.env.idsgame_config.reconnaissance_bool_features:",
"episode_attacker_reward = 0 episode_defender_reward = 0 episode_step = 0 while not done: if",
"enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" + str(idx), frame, global_step=train_episode, dataformats = \"HWC\") # Reset",
"for idx, row in enumerate(temp): t = row.tolist() t.append(a_pos[idx]) if self.env.fully_observed(): t.append(det_values[idx]) features.append(t)",
"a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features = attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs = attacker_obs[:, 0:a_obs_len] # else:",
"attacker: combined_features = [] for idx, row in enumerate(attacker_obs): combined_row = np.append(row, defender_obs[idx])",
"attacker_actions = list(range(self.env.num_attack_actions)) defender_actions = list(range(self.env.num_defense_actions)) legal_attack_actions = list(filter(lambda action: self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions",
"defender_obs = obs_prime_defender # Render final frame when game completed if self.config.eval_render: self.env.render()",
"= [] for idx, row in enumerate(temp): t = row.tolist() t.append(a_pos[idx]) if self.env.fully_observed():",
"self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif self.config.dqn_config.optimizer == \"SGD\": self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer",
"estimated by the target network. else: a = torch.argmax(target_next[i]).detach() if attacker: target[i][a_attacker_batch[i]] =",
"act_values = self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self) -> ExperimentResult: \"\"\" Runs the DQN",
"in train mode and target network in eval mode if attacker: self.attacker_q_network.train() self.attacker_target_network.eval()",
"obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_train.update(1) # Anneal epsilon linearly",
"not recognized\") # Define Optimizer. The call to model.parameters() in the optimizer constructor",
"\\ (self.env.idsgame_config.game_config.reconnaissance_actions and attacker): if self.config.dqn_config.merged_ad_features: if not self.env.local_view_features() or not attacker: a_pos",
"features.append(t) features = np.array(features) if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((features.shape[0], features.shape[1] + d_bool_features.shape[1])) for",
"perform a backward pass, and update the weights. if attacker: self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step()",
"= [] episode_defender_rewards = [] episode_steps = [] # Logging self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes,",
"self.config.dqn_config.loss_fn == \"Huber\": self.loss_fn = torch.nn.SmoothL1Loss() else: raise ValueError(\"Loss function not recognized\") #",
"train_episode: the train episode to keep track of logging :param log: whether to",
"torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif self.config.dqn_config.optimizer == \"SGD\": self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(),",
"- attacker_obs[:, 0:-1] else: temp = defender_obs[:, 0:] - attacker_obs[:, 0:-1] features =",
"eval=True, attacker=False) action = (attacker_action, defender_action) # Take a step in the environment",
"loss to be computed for the Q-values of the actions taken, not the",
"return self.eval_result def save_model(self) -> None: \"\"\" Saves the PyTorch Model Weights :return:",
"self.loss_fn = None self.attacker_optimizer = None self.defender_optimizer = None self.attacker_lr_decay = None self.defender_lr_decay",
"a_obs_len + self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs = attacker_obs[:, 0:a_obs_len] if not attacker and self.env.local_view_features():",
"in enumerate(attacker_obs_1): mean = np.mean(row) if mean != 0: t = row -",
"self.attacker_q_network = None self.attacker_target_network = None self.defender_q_network = None self.defender_target_network = None self.loss_fn",
"eval mode # to turn of dropouts, batch norms, gradient computations etc. self.attacker_target_network.eval()",
"= defender_obs / np.linalg.norm(defender_obs) normalized_defender_features = [] for idx, row in enumerate(defender_obs_1): if",
"states the Q-target should be equal to the immediate reward if d_batch[i]: if",
"torch.tensor(r_attacker_batch).float() s_1 = torch.tensor(s_attacker_batch).float() s_2 = torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train() self.defender_q_network.eval() r_1 = torch.tensor(r_defender_batch).float()",
"\"\"\" Runs the DQN algorithm :return: Experiment result \"\"\" self.config.logger.info(\"Starting Warmup\") self.warmup() self.config.logger.info(\"Starting",
"episode) if self.config.defender: for tag, value in self.defender_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag,",
"replay buffer following a random strategy :return: None \"\"\" # Setup logging outer_warmup",
"= [] episode_steps = [] # Logging self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1)",
"enumerate(attacker_obs_1): mean = np.mean(row) if mean != 0: t = row - mean",
"self.defender_target_network.eval() # Construct loss function if self.config.dqn_config.loss_fn == \"MSE\": self.loss_fn = torch.nn.MSELoss() elif",
"neighbor_defense_attributes.shape[1])) for i in range(f.shape[0]): f[i] = np.append(attacker_obs[i], neighbor_defense_attributes[i]) if self.config.dqn_config.state_length == 1:",
"batch as input mini_batch = self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\",
"= r_1[i] else: target[i][a_defender_batch[i]] = r_1[i] # For non terminal states the Q-target",
"= r_1[i] + self.config.gamma * (target_next[i][a]) # Compute loss if attacker: prediction =",
"else: target = self.defender_q_network(s_1) # Use the target network to compute the Q-values",
"self.train_cumulative_hack_probability = 0.0 self.log_metrics(episode, self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr) # Log",
"episode_steps = [] # Logging self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1) self.outer_eval.set_description_str( \"[Eval]",
"# Log average eval statistics if log: if self.num_eval_hacks > 0: self.eval_hack_probability =",
"t = t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs = np.array(zero_mean_attacker_features) defender_obs = np.array(zero_mean_defender_features) # Normalize",
"attacker_obs.shape[1] + neighbor_defense_attributes.shape[1] + d_bool_features.shape[1])) for i in range(f.shape[0]): f[i] = np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]),",
"is None: raise AssertionError(\"Video is set to True but no video_dir is provided,",
"obs_state_d) self.config.logger.info(\"{} Warmup steps completed, replay buffer size: {}\".format( self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close() try:",
"state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_eval.update(1) # Log average",
"QAgentConfig): \"\"\" Initialize environment and hyperparameters :param config: the configuration \"\"\" super(DQNAgent, self).__init__(env,",
"= torch.device(\"cuda:0\") r_1 = r_1.to(device) s_1 = s_1.to(device) s_2 = s_2.to(device) # Set",
"[] self.num_train_games = 0 self.num_train_hacks = 0 # Update target network every <self.config.dqn_config.target_network_update_freq>",
"episode % self.config.eval_frequency == 0: self.eval(episode) # Save models every <self.config.checkpoint_frequency> episodes if",
"if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") state = state.to(device) if attacker: actions",
"0: self.train_hack_probability = self.num_train_hacks / self.num_train_games self.train_cumulative_hack_probability = self.num_train_hacks_total / self.num_train_games_total else: self.train_hack_probability",
"initialize the target to the Q-values of the Q-network for s # and",
"self.config.defender: s_1 = torch.tensor(s_defender_batch).float() # Move to GPU if using GPU if torch.cuda.is_available()",
"algorithm (implemented in PyTorch) :param mini_batch: a minibatch to use for the training",
"attacker: bool = True) -> np.ndarray: \"\"\" Update approximative Markov state :param attacker_obs:",
"according to a epsilon-greedy strategy using the Q-network :param state: the state to",
"hyperparameters :param config: the configuration \"\"\" super(DQNAgent, self).__init__(env, config) self.attacker_q_network = None self.attacker_target_network",
"# Add network graph to tensorboard with a sample batch as input mini_batch",
"+= loss.item() # Update metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime",
"config if self.config.video: if self.config.video_dir is None: raise AssertionError(\"Video is set to True",
"else: target[i][a_defender_batch[i]] = r_1[i] # For non terminal states the Q-target should be",
"of the Deep-Q-learning algorithm (implemented in PyTorch) :param mini_batch: a minibatch to use",
"a = torch.argmax(target_next[i]).detach() if attacker: target[i][a_attacker_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) else:",
"= list(range(self.env.num_attack_actions)) defender_actions = list(range(self.env.num_defense_actions)) legal_attack_actions = list(filter(lambda action: self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions =",
"obs_prime = (obs_state_a_prime, obs_state_d_prime) # Add transition to replay memory self.buffer.add_tuple(obs, action, reward,",
"mode :param attacker: boolean flag whether running in attacker mode (if false assume",
"= self.training_step(minibatch, attacker=False) episode_defender_loss += loss.item() # Update metrics attacker_reward, defender_reward = reward",
"# Training for episode in range(self.config.num_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step",
"[] for idx, row in enumerate(temp): t = row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx]) if not",
"Set target baseline. We only want the loss to be computed for the",
"not eval) \\ or (eval and np.random.random() < self.config.eval_epsilon): return np.random.choice(legal_actions) with torch.no_grad():",
"any learning just to populate the replay buffer following a random strategy :return:",
"self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_defender/grad', value.grad.data.cpu().numpy(), episode) episode_attacker_rewards = [] episode_defender_rewards =",
"ExperimentResult from gym_idsgame.envs.constants import constants from gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer",
"for idx, row in enumerate(attacker_obs): combined_row = np.append(row, defender_obs[idx]) combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features: combined_features",
"attacker_action = 0 defender_action = 0 # Get attacker and defender actions if",
"0: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss / episode_step) else: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss)",
"whether running in evaluation mode :param attacker: boolean flag whether running in attacker",
"time_str + \"_eval_results_checkpoint.csv\") # Reset environment for the next episode and update game",
"self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] / np.linalg.norm(attacker_obs[:, 0:-1]) else: attacker_obs_1",
"Move to new state obs = obs_prime outer_warmup.update(1) if done: obs = self.env.reset(update_stats=False)",
"np.append(row, defender_obs[idx]) combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features: combined_features = np.array(combined_features) f = np.zeros( (combined_features.shape[0], combined_features.shape[1]",
"np.array([features]), axis=0) return state else: if not self.env.local_view_features() or not attacker: if self.env.idsgame_config.game_config.reconnaissance_actions",
"want the loss to be computed for the Q-values of the actions taken,",
"doing a training step for the attacker (otherwise defender) :return: loss \"\"\" #",
"{}\".format(0, 0)) # Reset env obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a",
"obs_prime_attacker defender_obs = obs_prime_defender # Render final frame when game completed if self.config.eval_render:",
"s2_defender_batch = mini_batch # Convert batch into torch tensors and set Q-network in",
"if not self.env.idsgame_config.game_config.reconnaissance_actions: temp = neighbor_defense_attributes[:, 0:-1] - attacker_obs[:, 0:-1] else: temp =",
"learned Q-values :param train_episode: the train episode to keep track of logging :param",
"actions with the real targets if attacker: target = self.attacker_q_network(s_1) else: target =",
"= obs_prime episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step += 1 attacker_obs =",
"non-empty result object\") done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs",
"+ 1 # defender_obs = attacker_obs[:, # a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types] # if self.env.idsgame_config.reconnaissance_bool_features:",
"0 # Get attacker and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, attacker=True)",
"with respect to the learned Q-values :param train_episode: the train episode to keep",
"= defender_obs if self.env.fully_observed() or \\ (self.env.idsgame_config.game_config.reconnaissance_actions and attacker): if self.config.dqn_config.merged_ad_features: if not",
"a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 defender_obs = attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features =",
"obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"Starting warmup phase",
"if self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features = attacker_obs[:, # a_obs_len + self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs =",
"attacker_obs_1 = attacker_obs[:, 0:-1] else: attacker_obs_1 = attacker_obs[:, 0:-2] zero_mean_attacker_features = [] for",
"learning' by Mnih et. al. (DQN is originally Neural-fitted Q-iteration but with the",
"if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def eval(self, train_episode, log=True) -> ExperimentResult: \"\"\" Performs evaluation",
"eval(self, train_episode, log=True) -> ExperimentResult: \"\"\" Performs evaluation with the greedy policy with",
"# Define Optimizer. The call to model.parameters() in the optimizer constructor will contain",
"train(self) -> ExperimentResult: \"\"\" Runs the DQN algorithm :return: Experiment result \"\"\" self.config.logger.info(\"Starting",
"t = row.tolist() t.append(a_pos[idx]) if self.env.fully_observed(): t.append(det_values[idx]) features.append(t) else: node_ids = attacker_obs[:, -1]",
"the target networks. Delayed targets are used to stabilize training and partially remedy",
"for idx, row in enumerate(defender_obs_1): mean = np.mean(row) if mean != 0: t",
"et. al. (DQN is originally Neural-fitted Q-iteration but with the addition of a",
"following a random strategy :return: None \"\"\" # Setup logging outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size,",
"self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_train.update(1)",
"self.defender_target_network.to(device) # Set the target network to use the same weights initialization as",
"= torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else: raise ValueError(\"Optimizer not recognized\") #",
"\"\"\" Performs evaluation with the greedy policy with respect to the learned Q-values",
"self.config.defender: for tag, value in self.defender_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode)",
"if len(self.train_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting training with non-empty result object\") done = False",
"information and metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward +=",
"self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"{} Warmup steps completed, replay",
"from torch.utils.tensorboard import SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig from",
"\"\"\" self.config.logger.info(\"Starting Warmup\") self.warmup() self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting training",
"tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1) self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0, 0.0,",
"= self.get_action(defender_obs, attacker=False) action = (attacker_action, defender_action) # Take a step in the",
":param config: the configuration \"\"\" super(DQNAgent, self).__init__(env, config) self.attacker_q_network = None self.attacker_target_network =",
"but with the addition of a separate target network) \"\"\" def __init__(self, env:IdsGameEnv,",
"be computed for the Q-values of the actions taken, not the entire #",
"attacker: target[i][a_attacker_batch[i]] = r_1[i] else: target[i][a_defender_batch[i]] = r_1[i] # For non terminal states",
"device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except: self.config.logger.warning(\"Error when trying to",
"self.config.logger.info(\"Eval episode: {}, Game ended after {} steps\".format(episode, episode_step)) # Record episode metrics",
"0:-1] - attacker_obs[:, 0:-1] else: temp = np.full(neighbor_defense_attributes.shape, -1) for i in range(len(neighbor_defense_attributes)):",
"self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim,",
"attacker_actions)) legal_defense_actions = list(filter(lambda action: self.env.is_defense_legal(action), defender_actions)) attacker_action = np.random.choice(legal_attack_actions) defender_action = np.random.choice(legal_defense_actions)",
"by Mnih et. al. (DQN is originally Neural-fitted Q-iteration but with the addition",
"\"\"\" # Initialize models self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network =",
"np.ndarray, eval : bool = False, attacker : bool = True) -> int:",
"torch.no_grad(): if attacker: act_values = self.attacker_q_network(state) else: act_values = self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()] def",
"\"\"\" Saves the PyTorch Model Weights :return: None \"\"\" time_str = str(time.time()) if",
"else: raise ValueError(\"Optimizer not recognized\") # LR decay if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer,",
"= obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False,",
"> 0: self.train_hack_probability = self.num_train_hacks / self.num_train_games self.train_cumulative_hack_probability = self.num_train_hacks_total / self.num_train_games_total else:",
"None, defender_obs: np.ndarray = None, state: np.ndarray = None, attacker: bool = True)",
"= self.config.save_dir + \"/\" + time_str + \"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(),",
"A warmup without any learning just to populate the replay buffer following a",
"training and partially remedy the problem with non-stationary targets in RL with function",
"episode_step)) # Record episode metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) # Update eval stats self.num_eval_games",
"(otherwise defender) :return: loss \"\"\" # Unpack batch of transitions from the replay",
"self.env.close() self.config.logger.info(\"Evaluation Complete\") return self.eval_result def save_model(self) -> None: \"\"\" Saves the PyTorch",
"self.get_action(attacker_obs, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, attacker=False) action = (attacker_action, defender_action) #",
"s_2.to(device) # Set target baseline. We only want the loss to be computed",
"obs_prime) # Move to new state obs = obs_prime outer_warmup.update(1) if done: obs",
"next episode and update game stats done = False obs = self.env.reset(update_stats=True) attacker_obs,",
"and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, attacker=True) if self.config.defender: defender_action =",
"None: \"\"\" A warmup without any learning just to populate the replay buffer",
"state: the state to sample an action for :param eval: boolean flag whether",
"= torch.tensor(s_defender_batch).float() s_2 = torch.tensor(s2_defender_batch).float() # Move to GPU if using GPU if",
"summary) to tensorboard if self.config.attacker: for tag, value in self.attacker_q_network.named_parameters(): tag = tag.replace('.',",
"\"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0, 0.0, 0.0)) # Eval obs =",
"a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 # defender_obs = attacker_obs[:, # a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types]",
"Optimizer. The call to model.parameters() in the optimizer constructor will contain the learnable",
"defender_obs[idx] else: if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: t = row.tolist() t.append(defender_obs[idx][-1]) else: t =",
"else: return np.array(defender_obs) if len(state) == 0: if attacker: return np.array([attacker_obs] * self.config.dqn_config.state_length)",
"episode done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a =",
"else: return np.array([defender_obs] * self.config.dqn_config.state_length) if attacker: state = np.append(state[1:], np.array([attacker_obs]), axis=0) else:",
"in range(f.shape[0]): f[i] = np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i]) else: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] +",
"optimizer constructor will contain the learnable # parameters of the layers in the",
"if len(self.eval_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting eval with non-empty result object\") if self.config.eval_episodes <",
"str(idx), frame, global_step=train_episode, dataformats = \"HWC\") # Reset for new eval episode done",
"import ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent class DQNAgent(QAgent): \"\"\" An implementation of the",
"self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The target network is not trainable it is only used",
"defender_obs[id] else: neighbor_defense_attributes = defender_obs if self.env.fully_observed() or \\ (self.env.idsgame_config.game_config.reconnaissance_actions and attacker): if",
"the affected actions with the real targets if attacker: target = self.attacker_q_network(s_1) else:",
"when following Q* estimated by the target network. else: a = torch.argmax(target_next[i]).detach() if",
"metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) # Update eval stats self.num_eval_games +=1 self.num_eval_games_total += 1",
"True but no video_dir is provided, please specify \" \"the video_dir argument\") self.env",
"str(train_episode) + \"_\" + time_str + \".gif\", self.config.video_fps) # Add frames to tensorboard",
"np.zeros( (combined_features.shape[0], combined_features.shape[1] + d_bool_features.shape[1])) for i in range(combined_features.shape[0]): f[i] = np.append(combined_features[i], d_bool_features[i])",
"self.training_step(minibatch, attacker=True) episode_attacker_loss += loss.item() if self.config.defender: loss = self.training_step(minibatch, attacker=False) episode_defender_loss +=",
"saving Q-networks to disk\") def update_state(self, attacker_obs: np.ndarray = None, defender_obs: np.ndarray =",
"and defender actions attacker_actions = list(range(self.env.num_attack_actions)) defender_actions = list(range(self.env.num_defense_actions)) legal_attack_actions = list(filter(lambda action:",
"attacker mode (if false assume defender) :return: The sampled action id \"\"\" state",
"state :param attacker: boolean flag whether it is attacker or not :return: new",
"attacker: whether doing a training step for the attacker (otherwise defender) :return: loss",
"# parameters of the layers in the model if self.config.dqn_config.optimizer == \"Adam\": self.attacker_optimizer",
"float( self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval=True, update_stats=True) self.env.close() self.config.logger.info(\"Evaluation Complete\") return",
"hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim,",
"defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_train.update(1) #",
"self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval =",
"d_batch, s2_attacker_batch, s2_defender_batch = mini_batch # Convert batch into torch tensors and set",
"\"HWC\") # Reset for new eval episode done = False obs = self.env.reset(update_stats=False)",
"phase to fill replay buffer\") # Perform <self.config.dqn_config.replay_start_size> steps and fill the replay",
"torch.save(self.defender_q_network.state_dict(), path) else: self.config.logger.warning(\"Save path not defined, not saving Q-networks to disk\") def",
"self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks += 1 self.num_eval_hacks_total +=1 # Log average metrics every",
"self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim,",
"np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray], attacker: bool = True) -> torch.Tensor: \"\"\" Performs",
"defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs for episode",
"in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" + str(idx), frame, global_step=train_episode, dataformats = \"HWC\") #",
"[] # Logging self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1) self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\",
"np.array(normalized_attacker_features) defender_obs = np.array(normalized_defender_features) if self.env.local_view_features() and attacker: if not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes =",
"warmup without any learning just to populate the replay buffer following a random",
"= mini_batch # Convert batch into torch tensors and set Q-network in train",
"= torch.tensor(s_attacker_batch).float() s_2 = torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train() self.defender_q_network.eval() r_1 = torch.tensor(r_defender_batch).float() s_1 =",
"= attacker_obs[idx] else: t = t.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1])",
"= self.attacker_q_network(s_1) else: prediction = self.defender_q_network(s_1) loss = self.loss_fn(prediction, target) # Zero gradients,",
"obs_state_d_prime) # Add transition to replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) #",
"self.config.gamma * (target_next[i][a]) else: target[i][a_defender_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) # Compute",
"'_attacker/grad', value.grad.data.cpu().numpy(), episode) if self.config.defender: for tag, value in self.defender_q_network.named_parameters(): tag = tag.replace('.',",
"defender_obs = obs self.outer_train.update(1) # Anneal epsilon linearly self.anneal_epsilon() self.config.logger.info(\"Training Complete\") # Final",
"to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") r_1",
"self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"Starting warmup phase to fill",
"eval with non-empty result object\") if self.config.eval_episodes < 1: return done = False",
"in RL with function approximation. :return: None \"\"\" self.config.logger.info(\"Updating target network\") if self.config.attacker:",
"for idx, frame in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" + str(idx), frame, global_step=train_episode, dataformats",
"to add network graph to tensorboard\") def initialize_models(self) -> None: \"\"\" Initialize models",
"= str(time.time()) self.num_eval_games = 0 self.num_eval_hacks = 0 if len(self.eval_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting",
"\\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch if self.config.attacker: s_1 = torch.tensor(s_attacker_batch).float() # Move",
"fill the replay memory for i in range(self.config.dqn_config.replay_start_size): if i % self.config.train_log_frequency ==",
"self.env.save_attack_data(checkpoint=False) if self.config.save_dir is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\" +",
"self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) # Specify device if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\")",
"if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games) if self.num_eval_games_total > 0:",
"(if false assume defender) :return: The sampled action id \"\"\" state = torch.from_numpy(state.flatten()).float()",
"episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] self.num_train_games = 0 self.num_train_hacks",
"self.env.reset(update_stats=True) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d =",
"reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero mean if self.config.dqn_config.zero_mean_features: if not self.env.local_view_features() or not attacker: attacker_obs_1",
"defender) :return: The sampled action id \"\"\" state = torch.from_numpy(state.flatten()).float() # Move to",
"obs = (obs_state_a, obs_state_d) self.config.logger.info(\"Starting warmup phase to fill replay buffer\") # Perform",
"self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval=True, update_stats=True) self.env.close() self.config.logger.info(\"Evaluation Complete\") return self.eval_result def",
"target = self.attacker_q_network(s_1) else: target = self.defender_q_network(s_1) # Use the target network to",
"i in range(combined_features.shape[0]): f[i] = np.append(combined_features[i], d_bool_features[i]) combined_features = f return np.array(combined_features) return",
"self.attacker_optimizer = None self.defender_optimizer = None self.attacker_lr_decay = None self.defender_lr_decay = None self.tensorboard_writer",
"Run evaluation every <self.config.eval_frequency> episodes if episode % self.config.eval_frequency == 0: self.eval(episode) #",
"or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1 = defender_obs[:, 0:-1] zero_mean_defender_features",
"gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig from gym_idsgame.envs.idsgame_env import IdsGameEnv from gym_idsgame.agents.dao.experiment_result import ExperimentResult from gym_idsgame.envs.constants",
"boolean flag whether running in attacker mode (if false assume defender) :return: The",
"id \"\"\" state = torch.from_numpy(state.flatten()).float() # Move to GPU if using GPU if",
"attacker=True) episode_attacker_loss += loss.item() if self.config.defender: loss = self.training_step(minibatch, attacker=False) episode_defender_loss += loss.item()",
"self.eval_result def save_model(self) -> None: \"\"\" Saves the PyTorch Model Weights :return: None",
"in the environment obs_prime, reward, done, _ = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime",
"if self.num_train_games > 0 and self.num_train_games_total > 0: self.train_hack_probability = self.num_train_hacks / self.num_train_games",
"self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs = attacker_obs[:, 0:a_obs_len] if not attacker and self.env.local_view_features(): attacker_obs =",
"+ \"_eval_frames/\" + str(idx), frame, global_step=train_episode, dataformats = \"HWC\") # Reset for new",
"self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def training_step(self, mini_batch: Union[np.ndarray, np.ndarray,",
"and then we only update the Q-values for the affected actions with the",
"the environment obs_prime, reward, done, info = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime",
"Save models every <self.config.checkpoint_frequency> episodes if episode % self.config.checkpoint_freq == 0: self.save_model() self.env.save_trajectories(checkpoint=True)",
"self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((features.shape[0], features.shape[1] + d_bool_features.shape[1])) for i in range(features.shape[0]): f[i] =",
"to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") state",
"neighbor_defense_attributes.shape[1] + d_bool_features.shape[1])) for i in range(f.shape[0]): f[i] = np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i]) else:",
"[] for idx, row in enumerate(temp): t = row.tolist() t.append(a_pos[idx]) if self.env.fully_observed(): t.append(det_values[idx])",
"(combined_features.shape[0], combined_features.shape[1] + d_bool_features.shape[1])) for i in range(combined_features.shape[0]): f[i] = np.append(combined_features[i], d_bool_features[i]) combined_features",
"to disk\") def update_state(self, attacker_obs: np.ndarray = None, defender_obs: np.ndarray = None, state:",
"ExperimentResult: \"\"\" Runs the DQN algorithm :return: Experiment result \"\"\" self.config.logger.info(\"Starting Warmup\") self.warmup()",
"to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1",
"self.env.local_view_features() and attacker: if not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes = np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for node in",
"attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward += attacker_reward episode_defender_reward +=",
"= (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs # Tracking metrics episode_attacker_rewards = []",
"= defender_obs[:, -1] temp = defender_obs[:, 0:-1] - attacker_obs[:, 0:-1] else: temp =",
"f[i] = np.append(features[i], d_bool_features[i]) features = f if self.config.dqn_config.state_length == 1: return features",
"\"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(), path) else: self.config.logger.warning(\"Save path not defined, not",
"self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if attacker and self.env.idsgame_config.game_config.reconnaissance_actions:",
"+= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks += 1 self.num_eval_hacks_total +=1 # Log average",
"list(range(self.env.num_defense_actions)) legal_actions = list(filter(lambda action: self.env.is_defense_legal(action), actions)) if (np.random.rand() < self.config.epsilon and not",
"-> np.ndarray: \"\"\" Update approximative Markov state :param attacker_obs: attacker obs :param defender_obs:",
"attacker=False) episode_defender_loss += loss.item() # Update metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender",
"to True but no video_dir is provided, please specify \" \"the video_dir argument\")",
"not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] else: attacker_obs_1 = attacker_obs[:,",
"idx, row in enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any(): t = attacker_obs[idx] else: t = row.tolist()",
"game completed if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode: {}, Game ended after {}",
"obs_state_d) attacker_obs, defender_obs = obs self.outer_train.update(1) # Anneal epsilon linearly self.anneal_epsilon() self.config.logger.info(\"Training Complete\")",
"of the layers in the model if self.config.dqn_config.optimizer == \"Adam\": self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(),",
"state = state.to(device) if attacker: actions = list(range(self.env.num_attack_actions)) legal_actions = list(filter(lambda action: self.env.is_attack_legal(action),",
"i in range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i]) > 0: temp[i] = neighbor_defense_attributes[i] - attacker_obs[i, 0:-1]",
"0:a_obs_len] # else: # a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 # defender_obs = attacker_obs[:,",
"= f if self.config.dqn_config.state_length == 1: return features if len(state) == 0: s",
"self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def eval(self, train_episode, log=True) -> ExperimentResult: \"\"\" Performs evaluation with",
":param mini_batch: a minibatch to use for the training step :param attacker: whether",
"the replay buffer following a random strategy :return: None \"\"\" # Setup logging",
"np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for node in range(attacker_obs.shape[0]): id = int(attacker_obs[node][-1]) neighbor_defense_attributes[node] = defender_obs[id] else:",
"attacker (otherwise defender) :return: loss \"\"\" # Unpack batch of transitions from the",
"Q* estimated by the target network. else: a = torch.argmax(target_next[i]).detach() if attacker: target[i][a_attacker_batch[i]]",
"< self.config.epsilon and not eval) \\ or (eval and np.random.random() < self.config.eval_epsilon): return",
"gamma=self.config.dqn_config.lr_decay_rate) def training_step(self, mini_batch: Union[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray],",
"+= attacker_reward episode_defender_reward += defender_reward episode_step += 1 # Move to the next",
"Game ended after {} steps\".format(episode, episode_step)) # Record episode metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step)",
"self.config.video: if self.config.video_dir is None: raise AssertionError(\"Video is set to True but no",
"self.config.gifs and self.config.video: self.env.generate_gif(self.config.gif_dir + \"/episode_\" + str(train_episode) + \"_\" + time_str +",
"= FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation)",
"device if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") self.config.logger.info(\"Running on the GPU\") else:",
"baseline. We only want the loss to be computed for the Q-values of",
"attacker: self.attacker_q_network.train() self.attacker_target_network.eval() r_1 = torch.tensor(r_attacker_batch).float() s_1 = torch.tensor(s_attacker_batch).float() s_2 = torch.tensor(s2_attacker_batch).float() else:",
"Episode', position=1) self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0, 0.0, 0.0)) #",
"np.array([attacker_obs] * self.config.dqn_config.state_length) else: return np.array([defender_obs] * self.config.dqn_config.state_length) if attacker: state = np.append(state[1:],",
"attacker_obs = self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero mean if self.config.dqn_config.zero_mean_features: if not",
"prediction = self.attacker_q_network(s_1) else: prediction = self.defender_q_network(s_1) loss = self.loss_fn(prediction, target) # Zero",
"enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any(): t = attacker_obs[idx] else: t = row.tolist() if not self.env.local_view_features()",
"self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards,",
"== 0: log_str = \"[Warmup] step:{}, buffer_size: {}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) # Select",
"row if np.isnan(t).any(): t = attacker_obs[idx] else: t = t.tolist() if not self.env.local_view_features()",
"attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs,",
"defender_obs: np.ndarray = None, state: np.ndarray = None, attacker: bool = True) ->",
"reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step +=",
"Mnih et. al. : For terminal states the Q-target should be equal to",
"obs :param defender_obs: defender observation :param state: current state :param attacker: boolean flag",
"in range(self.config.eval_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step = 0 while not",
"it to eval mode # to turn of dropouts, batch norms, gradient computations",
"tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_attacker/grad', value.grad.data.cpu().numpy(), episode) if",
"if not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] / np.linalg.norm(attacker_obs[:, 0:-1])",
"for i in range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i]) > 0: temp[i] = neighbor_defense_attributes[i] - attacker_obs[i,",
"= np.array([f] * self.config.dqn_config.state_length) return s # if not self.env.local_view_features() or not attacker:",
"to turn of dropouts, batch norms, gradient computations etc. self.attacker_target_network.eval() self.defender_target_network.eval() # Construct",
"-1] if not self.env.idsgame_config.game_config.reconnaissance_actions: temp = neighbor_defense_attributes[:, 0:-1] - attacker_obs[:, 0:-1] else: temp",
"tensorboard\") def initialize_models(self) -> None: \"\"\" Initialize models :return: None \"\"\" # Initialize",
"Construct loss function if self.config.dqn_config.loss_fn == \"MSE\": self.loss_fn = torch.nn.MSELoss() elif self.config.dqn_config.loss_fn ==",
"the Q-values for the affected actions with the real targets if attacker: target",
"Q-values. Therefore we initialize the target to the Q-values of the Q-network for",
"episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr) # Log values and gradients of the parameters (histogram summary)",
"ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories = False self.env.idsgame_config.save_attack_stats = False def warmup(self) ->",
"if attacker: self.attacker_q_network.train() self.attacker_target_network.eval() r_1 = torch.tensor(r_attacker_batch).float() s_1 = torch.tensor(s_attacker_batch).float() s_2 = torch.tensor(s2_attacker_batch).float()",
"obs_prime_defender # Render final frame when game completed if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval",
"zero_mean_defender_features = [] for idx, row in enumerate(defender_obs_1): mean = np.mean(row) if mean",
"when trying to add network graph to tensorboard\") def initialize_models(self) -> None: \"\"\"",
"np.append(state[1:], np.array([f]), axis=0) return state else: if self.config.dqn_config.state_length == 1: if attacker: return",
"0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) # Training for episode in range(self.config.num_episodes): episode_attacker_reward",
"str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str",
"0 defender_action = 0 # Get attacker and defender actions if self.config.attacker: attacker_action",
"(obs_state_a, obs_state_d) attacker_obs, defender_obs = obs for episode in range(self.config.eval_episodes): episode_attacker_reward = 0",
"attacker: return np.array([attacker_obs] * self.config.dqn_config.state_length) else: return np.array([defender_obs] * self.config.dqn_config.state_length) if attacker: state",
"log=True) -> ExperimentResult: \"\"\" Performs evaluation with the greedy policy with respect to",
"attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Add transition to replay memory self.buffer.add_tuple(obs,",
"\"\"\" Performs a training step of the Deep-Q-learning algorithm (implemented in PyTorch) :param",
"+ neighbor_defense_attributes.shape[1])) for i in range(f.shape[0]): f[i] = np.append(attacker_obs[i], neighbor_defense_attributes[i]) if self.config.dqn_config.state_length ==",
"= None self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories =",
"frame when game completed if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode: {}, Game ended",
"self.loss_fn = torch.nn.MSELoss() elif self.config.dqn_config.loss_fn == \"Huber\": self.loss_fn = torch.nn.SmoothL1Loss() else: raise ValueError(\"Loss",
"f[i] = np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i]) else: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1])) for",
"1 defender_obs = attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features = attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs =",
"defender_action = self.get_action(defender_obs, attacker=False) action = (attacker_action, defender_action) # Take a step in",
"value in self.defender_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_defender/grad',",
"defender_obs[:, 0:-1] zero_mean_defender_features = [] for idx, row in enumerate(defender_obs_1): mean = np.mean(row)",
"loss \"\"\" # Unpack batch of transitions from the replay memory s_attacker_batch, s_defender_batch,",
"the DQN algorithm. \"\"\" from typing import Union import numpy as np import",
"> 0: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss / episode_step) else: if self.config.attacker:",
"= True) -> torch.Tensor: \"\"\" Performs a training step of the Deep-Q-learning algorithm",
"episode_attacker_rewards, episode_defender_rewards, episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr) # Log values and gradients of the",
"= self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch =",
"vector of all Q-values. Therefore we initialize the target to the Q-values of",
"def update_state(self, attacker_obs: np.ndarray = None, defender_obs: np.ndarray = None, state: np.ndarray =",
"not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if attacker and",
"= attacker_obs[:, # a_obs_len + self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs = attacker_obs[:, 0:a_obs_len] if not",
"ended after {} steps\".format(episode, episode_step)) # Record episode metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) #",
"i in range(f.shape[0]): f[i] = np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i]) else: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1]",
"the actions taken, not the entire # vector of all Q-values. Therefore we",
"or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] else: attacker_obs_1 = attacker_obs[:, 0:-2] zero_mean_attacker_features",
"[] episode_defender_rewards = [] episode_steps = [] self.num_train_games = 0 self.num_train_hacks = 0",
"% self.config.eval_frequency == 0: self.eval(episode) # Save models every <self.config.checkpoint_frequency> episodes if episode",
"if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: t = row.tolist() t.append(defender_obs[idx][-1]) else: t = row normalized_defender_features.append(t)",
"= self.env.idsgame_config.game_config.num_attack_types + 1 defender_obs = attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features = attacker_obs[:,",
"equal to the immediate reward if d_batch[i]: if attacker: target[i][a_attacker_batch[i]] = r_1[i] else:",
"eval mode if attacker: self.attacker_q_network.train() self.attacker_target_network.eval() r_1 = torch.tensor(r_attacker_batch).float() s_1 = torch.tensor(s_attacker_batch).float() s_2",
"a training step of the Deep-Q-learning algorithm (implemented in PyTorch) :param mini_batch: a",
"attacker_obs, defender_obs = obs self.outer_train.update(1) # Anneal epsilon linearly self.anneal_epsilon() self.config.logger.info(\"Training Complete\") #",
"== 1: return features if len(state) == 0: s = np.array([features] * self.config.dqn_config.state_length)",
"< 1: return done = False # Video config if self.config.video: if self.config.video_dir",
"in enumerate(attacker_obs): combined_row = np.append(row, defender_obs[idx]) combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features: combined_features = np.array(combined_features) f",
"len(state) == 0: s = np.array([f] * self.config.dqn_config.state_length) return s # if not",
"not self.config.defender: raise AssertionError(\"Must specify whether training an attacker agent or defender agent\")",
"\"MSE\": self.loss_fn = torch.nn.MSELoss() elif self.config.dqn_config.loss_fn == \"Huber\": self.loss_fn = torch.nn.SmoothL1Loss() else: raise",
"obs_prime, reward, done, _ = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime,",
"= self.training_step(minibatch, attacker=True) episode_attacker_loss += loss.item() if self.config.defender: loss = self.training_step(minibatch, attacker=False) episode_defender_loss",
"num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) # Specify device if",
"False def warmup(self) -> None: \"\"\" A warmup without any learning just to",
"self.loss_fn(prediction, target) # Zero gradients, perform a backward pass, and update the weights.",
"QAgent class DQNAgent(QAgent): \"\"\" An implementation of the DQN algorithm from the paper",
"of the Q-network for s # and then we only update the Q-values",
"Runs the DQN algorithm :return: Experiment result \"\"\" self.config.logger.info(\"Starting Warmup\") self.warmup() self.config.logger.info(\"Starting Training\")",
"to replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Sample random mini_batch of",
"target[i][a_defender_batch[i]] = r_1[i] # For non terminal states the Q-target should be the",
"else: self.defender_q_network.train() self.defender_q_network.eval() r_1 = torch.tensor(r_defender_batch).float() s_1 = torch.tensor(s_defender_batch).float() s_2 = torch.tensor(s2_defender_batch).float() #",
"models :return: None \"\"\" # Initialize models self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers,",
"= np.array(normalized_attacker_features) defender_obs = np.array(normalized_defender_features) if self.env.local_view_features() and attacker: if not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes",
"episode_step = 0 while not done: if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) # Default initialization",
"= row - mean else: t = row if np.isnan(t).any(): t = attacker_obs[idx]",
"in eval mode if attacker: self.attacker_q_network.train() self.attacker_target_network.eval() r_1 = torch.tensor(r_attacker_batch).float() s_1 = torch.tensor(s_attacker_batch).float()",
"if attacker: actions = list(range(self.env.num_attack_actions)) legal_actions = list(filter(lambda action: self.env.is_attack_legal(action), actions)) else: actions",
"\\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch # Convert batch into torch tensors and",
"we only update the Q-values for the affected actions with the real targets",
"DQN algorithm :return: Experiment result \"\"\" self.config.logger.info(\"Starting Warmup\") self.warmup() self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str()) if",
"time_str + \".gif\", self.config.video_fps) # Add frames to tensorboard for idx, frame in",
"-1] temp = defender_obs[:, 0:-1] - attacker_obs[:, 0:-1] else: temp = defender_obs[:, 0:]",
"(obs_state_a_prime, obs_state_d_prime) # Update state information and metrics attacker_reward, defender_reward = reward obs_prime_attacker,",
"SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories = False self.env.idsgame_config.save_attack_stats = False",
"self.attacker_q_network(s_1) else: target = self.defender_q_network(s_1) # Use the target network to compute the",
"else: attacker_obs_1 = attacker_obs[:, 0:-2] zero_mean_attacker_features = [] for idx, row in enumerate(attacker_obs_1):",
"self.env.local_view_features() or not attacker: if self.env.idsgame_config.game_config.reconnaissance_actions and attacker: combined_features = [] for idx,",
"taken, not the entire # vector of all Q-values. Therefore we initialize the",
"Set the target network to use the same weights initialization as the q-network",
"# else: # temp = np.append(attacker_obs, neighbor_defense_attributes) state = np.append(state[1:], np.array([f]), axis=0) return",
"self.env.is_defense_legal(action), actions)) if (np.random.rand() < self.config.epsilon and not eval) \\ or (eval and",
"mean else: t = row if np.isnan(t).any(): t = attacker_obs[idx] else: t =",
"episode_steps, eval=True, update_stats=True) self.env.close() self.config.logger.info(\"Evaluation Complete\") return self.eval_result def save_model(self) -> None: \"\"\"",
"= mini_batch if self.config.attacker: s_1 = torch.tensor(s_attacker_batch).float() # Move to GPU if using",
"the next episode and update game stats done = False obs = self.env.reset(update_stats=True)",
"use the same weights initialization as the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The target",
":param attacker_obs: attacker obs :param defender_obs: defender observation :param state: current state :param",
"state else: if self.config.dqn_config.state_length == 1: if attacker: return np.array(attacker_obs) else: return np.array(defender_obs)",
"= (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_train.update(1) # Anneal epsilon linearly self.anneal_epsilon()",
"self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Update state information and",
"self.config.logger.info(log_str) # Select random attacker and defender actions attacker_actions = list(range(self.env.num_attack_actions)) defender_actions =",
"0.0, 0.0, 0.0)) # Training for episode in range(self.config.num_episodes): episode_attacker_reward = 0 episode_defender_reward",
"/ self.num_train_games self.train_cumulative_hack_probability = self.num_train_hacks_total / self.num_train_games_total else: self.train_hack_probability = 0.0 self.train_cumulative_hack_probability =",
"= self.env.reset(update_stats=True) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d",
"to new state obs = obs_prime outer_warmup.update(1) if done: obs = self.env.reset(update_stats=False) attacker_obs,",
"with torch.no_grad(): if attacker: act_values = self.attacker_q_network(state) else: act_values = self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()]",
"None self.defender_q_network = None self.defender_target_network = None self.loss_fn = None self.attacker_optimizer = None",
"defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"{} Warmup steps completed, replay buffer",
"f return np.array(combined_features) return np.append(attacker_obs, defender_obs) else: if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1]",
"value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_defender/grad', value.grad.data.cpu().numpy(), episode) episode_attacker_rewards = [] episode_defender_rewards = []",
"list(range(self.env.num_attack_actions)) defender_actions = list(range(self.env.num_defense_actions)) legal_attack_actions = list(filter(lambda action: self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions = list(filter(lambda",
"gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent class DQNAgent(QAgent):",
"= row.tolist() t.append(defender_obs[idx][-1]) else: t = row normalized_defender_features.append(t) attacker_obs = np.array(normalized_attacker_features) defender_obs =",
"= self.config.alpha if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr = self.attacker_lr_decay.get_lr()[0] # Record episode metrics self.num_train_games",
"if self.env.local_view_features() and attacker: if not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes = np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for node",
"axis=0) return state else: if self.config.dqn_config.state_length == 1: if attacker: return np.array(attacker_obs) else:",
"AssertionError(\"Must specify whether training an attacker agent or defender agent\") # Default initialization",
"time_str = str(time.time()) self.num_eval_games = 0 self.num_eval_hacks = 0 if len(self.eval_result.avg_episode_steps) > 0:",
"= [] episode_avg_attacker_loss = [] episode_avg_defender_loss = [] # Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\"",
"return np.array([attacker_obs] * self.config.dqn_config.state_length) else: return np.array([defender_obs] * self.config.dqn_config.state_length) if attacker: state =",
"stats done = False obs = self.env.reset(update_stats=True) attacker_obs, defender_obs = obs obs_state_a =",
"= self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Update state information",
"= s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if self.config.defender: s_1 = torch.tensor(s_defender_batch).float() # Move to GPU",
"immediate reward plus the discounted estimated future # reward when following Q* estimated",
"episode_attacker_rewards, episode_defender_rewards, episode_steps, eval = True, update_stats=False) # Save gifs if self.config.gifs and",
"obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step += 1",
"the IDSGameEnv that implements the DQN algorithm. \"\"\" from typing import Union import",
"# Compute loss if attacker: prediction = self.attacker_q_network(s_1) else: prediction = self.defender_q_network(s_1) loss",
"episode_step > 0: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss / episode_step) else: if",
"of the actions taken, not the entire # vector of all Q-values. Therefore",
"attacker: # temp = np.append(attacker_obs, defender_obs) # else: # temp = np.append(attacker_obs, neighbor_defense_attributes)",
"-1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = defender_obs[:, -1] temp = defender_obs[:, 0:-1] -",
"lr=self.config.alpha) else: raise ValueError(\"Optimizer not recognized\") # LR decay if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay =",
"obs_state_d) attacker_obs, defender_obs = obs for episode in range(self.config.eval_episodes): episode_attacker_reward = 0 episode_defender_reward",
"frame in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" + str(idx), frame, global_step=train_episode, dataformats = \"HWC\")",
"data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if self.config.save_dir is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir +",
"mini_batch: Union[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray], attacker: bool =",
"transitions from replay memory minibatch = self.buffer.sample(self.config.dqn_config.batch_size) # Perform a gradient descent step",
"if self.config.defender: defender_action = self.get_action(defender_obs, eval=True, attacker=False) action = (attacker_action, defender_action) # Take",
"range(self.config.eval_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step = 0 while not done:",
"attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"Starting warmup phase to fill replay buffer\")",
"0: s = np.array([features] * self.config.dqn_config.state_length) return s state = np.append(state[1:], np.array([features]), axis=0)",
"0.0, 0.0)) # Eval obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a =",
"+ time_str + \"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path) if self.config.defender: path",
"attacker_obs: attacker obs :param defender_obs: defender observation :param state: current state :param attacker:",
"= [] for idx, row in enumerate(attacker_obs_1): mean = np.mean(row) if mean !=",
"np.ndarray = None, state: np.ndarray = None, attacker: bool = True) -> np.ndarray:",
"= (obs_state_a, obs_state_d) self.config.logger.info(\"{} Warmup steps completed, replay buffer size: {}\".format( self.config.dqn_config.replay_start_size, self.buffer.size()))",
"attacker: boolean flag whether running in attacker mode (if false assume defender) :return:",
"episode_steps = [] self.num_train_games = 0 self.num_train_hacks = 0 # Update target network",
"with the greedy policy with respect to the learned Q-values :param train_episode: the",
"self.env.state.hacked: self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks += 1 self.num_eval_hacks_total +=1 #",
"= SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories = False self.env.idsgame_config.save_attack_stats =",
"None self.attacker_target_network = None self.defender_q_network = None self.defender_target_network = None self.loss_fn = None",
"gradient descent step of the Q-network using targets produced by target network if",
"Default initialization attacker_action = 0 defender_action = 0 # Get attacker and defender",
"value in self.attacker_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_attacker/grad',",
"attacker_reward episode_defender_reward += defender_reward episode_step += 1 attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender",
"# else: # a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 # defender_obs = attacker_obs[:, #",
"time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") return self.train_result def",
"episode_steps.append(episode_step) # Update eval stats self.num_eval_games +=1 self.num_eval_games_total += 1 if self.env.state.detected: self.eval_attacker_cumulative_reward",
"attacker_obs[:, 0:a_obs_len] # else: # a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 # defender_obs =",
"= self.env.idsgame_config.game_config.num_attack_types + 1 # defender_obs = attacker_obs[:, # a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types] #",
"the real targets if attacker: target = self.attacker_q_network(s_1) else: target = self.defender_q_network(s_1) #",
"episode lr = self.config.alpha if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr = self.attacker_lr_decay.get_lr()[0] # Record episode",
"RL with function approximation. :return: None \"\"\" self.config.logger.info(\"Updating target network\") if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict())",
"= torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train() self.defender_q_network.eval() r_1 = torch.tensor(r_defender_batch).float() s_1 = torch.tensor(s_defender_batch).float() s_2 =",
"and log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games) if self.num_eval_games_total",
"by target network if self.config.attacker: loss = self.training_step(minibatch, attacker=True) episode_attacker_loss += loss.item() if",
"= t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs = np.array(zero_mean_attacker_features) defender_obs = np.array(zero_mean_defender_features) # Normalize if",
"self.get_action(attacker_obs, eval=True, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, eval=True, attacker=False) action = (attacker_action,",
"metrics every <self.config.train_log_frequency> episodes if episode % self.config.train_log_frequency == 0: if self.num_train_games >",
"constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks += 1 self.num_eval_hacks_total +=1 # Log average metrics",
"0: if attacker: return np.array([attacker_obs] * self.config.dqn_config.state_length) else: return np.array([defender_obs] * self.config.dqn_config.state_length) if",
"idx, row in enumerate(temp): t = row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx]) if not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx])",
"if attacker: act_values = self.attacker_q_network(state) else: act_values = self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self)",
"plus the discounted estimated future # reward when following Q* estimated by the",
"self.config.logger.info(\"Starting warmup phase to fill replay buffer\") # Perform <self.config.dqn_config.replay_start_size> steps and fill",
"attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"{}",
"self.eval(episode) # Save models every <self.config.checkpoint_frequency> episodes if episode % self.config.checkpoint_freq == 0:",
"if self.config.video: if self.config.video_dir is None: raise AssertionError(\"Video is set to True but",
"obs_prime_defender # Render final frame if self.config.render: self.env.render(mode=\"human\") # Decay LR after every",
"(histogram summary) to tensorboard if self.config.attacker: for tag, value in self.attacker_q_network.named_parameters(): tag =",
"eval episode done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a",
"[] for idx, row in enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any(): t = attacker_obs[idx] else: t",
"= obs_prime_attacker defender_obs = obs_prime_defender # Render final frame if self.config.render: self.env.render(mode=\"human\") #",
"else: # a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 # defender_obs = attacker_obs[:, # a_obs_len:a_obs_len",
"= None self.defender_optimizer = None self.attacker_lr_decay = None self.defender_lr_decay = None self.tensorboard_writer =",
"mode # to turn of dropouts, batch norms, gradient computations etc. self.attacker_target_network.eval() self.defender_target_network.eval()",
"= torch.tensor(r_defender_batch).float() s_1 = torch.tensor(s_defender_batch).float() s_2 = torch.tensor(s2_defender_batch).float() # Move to GPU if",
"done, obs_prime) # Move to new state obs = obs_prime outer_warmup.update(1) if done:",
"False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True,",
"function approximation. :return: None \"\"\" self.config.logger.info(\"Updating target network\") if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if",
"= torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except: self.config.logger.warning(\"Error when trying to add",
"= np.zeros( (combined_features.shape[0], combined_features.shape[1] + d_bool_features.shape[1])) for i in range(combined_features.shape[0]): f[i] = np.append(combined_features[i],",
"learnable # parameters of the layers in the model if self.config.dqn_config.optimizer == \"Adam\":",
"network in eval mode if attacker: self.attacker_q_network.train() self.attacker_target_network.eval() r_1 = torch.tensor(r_attacker_batch).float() s_1 =",
"temp = np.full(neighbor_defense_attributes.shape, -1) for i in range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i]) > 0: temp[i]",
"strategy using the Q-network :param state: the state to sample an action for",
"to tensorboard for idx, frame in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" + str(idx), frame,",
"by the target network. else: a = torch.argmax(target_next[i]).detach() if attacker: target[i][a_attacker_batch[i]] = r_1[i]",
"defender_obs = obs_prime_defender # Render final frame if self.config.render: self.env.render(mode=\"human\") # Decay LR",
"0: self.config.logger.warning(\"starting training with non-empty result object\") done = False obs = self.env.reset(update_stats=False)",
"graph to tensorboard\") def initialize_models(self) -> None: \"\"\" Initialize models :return: None \"\"\"",
"episode_defender_loss = 0.0 while not done: if self.config.render: self.env.render(mode=\"human\") if not self.config.attacker and",
"following Q* estimated by the target network. else: a = torch.argmax(target_next[i]).detach() if attacker:",
"attacker_obs[:, # a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types] # if self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features = attacker_obs[:, #",
"not defined, not saving Q-networks to disk\") def update_state(self, attacker_obs: np.ndarray = None,",
"enumerate(defender_obs_1): mean = np.mean(row) if mean != 0: t = row - mean",
"self.config.defender: path = self.config.save_dir + \"/\" + time_str + \"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network to:",
"import numpy as np import time import tqdm import torch from torch.utils.tensorboard import",
"if self.config.defender: loss = self.training_step(minibatch, attacker=False) episode_defender_loss += loss.item() # Update metrics attacker_reward,",
"from typing import Union import numpy as np import time import tqdm import",
"batch into torch tensors and set Q-network in train mode and target network",
"else: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) # Log average metrics every",
"s' with torch.no_grad(): if attacker: target_next = self.attacker_target_network(s_2).detach() else: target_next = self.defender_target_network(s_2).detach() for",
"(attacker_action, defender_action) # Take a step in the environment obs_prime, reward, done, _",
"set it to eval mode # to turn of dropouts, batch norms, gradient",
"hidden_activation=self.config.dqn_config.hidden_activation) # Specify device if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") self.config.logger.info(\"Running on",
"0:-1] else: temp = defender_obs[:, 0:] - attacker_obs[:, 0:-1] features = [] for",
"= FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation)",
"etc. self.attacker_target_network.eval() self.defender_target_network.eval() # Construct loss function if self.config.dqn_config.loss_fn == \"MSE\": self.loss_fn =",
"np.mean(row) if mean != 0: t = row - mean else: t =",
"if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards,",
"Warmup\") self.warmup() self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting training with non-empty",
"remedy the problem with non-stationary targets in RL with function approximation. :return: None",
"obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_eval.update(1) # Log average eval",
"str(time.time()) self.num_eval_games = 0 self.num_eval_hacks = 0 if len(self.eval_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting eval",
"completed, replay buffer size: {}\".format( self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close() try: # Add network graph",
"\"\"\" def __init__(self, env:IdsGameEnv, config: QAgentConfig): \"\"\" Initialize environment and hyperparameters :param config:",
"ValueError(\"Loss function not recognized\") # Define Optimizer. The call to model.parameters() in the",
"state = torch.from_numpy(state.flatten()).float() # Move to GPU if using GPU if torch.cuda.is_available() and",
"Get attacker and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, attacker=True) if self.config.defender:",
"loss def get_action(self, state: np.ndarray, eval : bool = False, attacker : bool",
"self.train_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str +",
"+ time_str + \"_eval_results_checkpoint.csv\") # Reset environment for the next episode and update",
"training step for the attacker (otherwise defender) :return: loss \"\"\" # Unpack batch",
"* self.config.dqn_config.state_length) else: return np.array([defender_obs] * self.config.dqn_config.state_length) if attacker: state = np.append(state[1:], np.array([attacker_obs]),",
"For non terminal states the Q-target should be the immediate reward plus the",
"and self.config.video: self.env.generate_gif(self.config.gif_dir + \"/episode_\" + str(train_episode) + \"_\" + time_str + \".gif\",",
"tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_defender/grad', value.grad.data.cpu().numpy(), episode) episode_attacker_rewards",
"if np.isnan(attacker_obs_1).any(): t = attacker_obs[idx] else: t = row.tolist() if not self.env.local_view_features() or",
"an action according to a epsilon-greedy strategy using the Q-network :param state: the",
"else: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1])) for i in range(f.shape[0]): f[i] =",
"episode metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) # Update eval stats self.num_eval_games +=1 self.num_eval_games_total +=",
"# Setup logging outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size: {}\".format(0, 0))",
"for i in range(f.shape[0]): f[i] = np.append(attacker_obs[i], neighbor_defense_attributes[i]) if self.config.dqn_config.state_length == 1: return",
"should be equal to the immediate reward if d_batch[i]: if attacker: target[i][a_attacker_batch[i]] =",
"use for the training step :param attacker: whether doing a training step for",
"= None, state: np.ndarray = None, attacker: bool = True) -> np.ndarray: \"\"\"",
"Video config if self.config.video: if self.config.video_dir is None: raise AssertionError(\"Video is set to",
"\"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path) if self.config.defender: path = self.config.save_dir +",
"or \\ (self.env.idsgame_config.game_config.reconnaissance_actions and attacker): if self.config.dqn_config.merged_ad_features: if not self.env.local_view_features() or not attacker:",
"torch.from_numpy(state.flatten()).float() # Move to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device",
"env obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True,",
"row.tolist() t.append(defender_obs[idx][-1]) else: t = row normalized_defender_features.append(t) attacker_obs = np.array(normalized_attacker_features) defender_obs = np.array(normalized_defender_features)",
"r_1[i] # For non terminal states the Q-target should be the immediate reward",
"except: self.config.logger.warning(\"Error when trying to add network graph to tensorboard\") def initialize_models(self) ->",
"non terminal states the Q-target should be the immediate reward plus the discounted",
"only update the Q-values for the affected actions with the real targets if",
"if self.config.save_dir is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\" + time_str",
"transition to replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Move to new",
"torch.utils.tensorboard import SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig from gym_idsgame.envs.idsgame_env",
"= self.get_action(attacker_obs, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, attacker=False) action = (attacker_action, defender_action)",
"batch of transitions from the replay memory s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch,",
"# Render final frame if self.config.render: self.env.render(mode=\"human\") # Decay LR after every episode",
"self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked: self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks +=",
"int: \"\"\" Samples an action according to a epsilon-greedy strategy using the Q-network",
"reinforcement learning' by Mnih et. al. (DQN is originally Neural-fitted Q-iteration but with",
"same weights initialization as the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The target network is",
"<self.config.dqn_config.target_network_update_freq> episodes if episode % self.config.dqn_config.target_network_update_freq == 0: self.update_target_network() # Run evaluation every",
"+= constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked: self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks += 1",
"self.config.defender: defender_action = self.get_action(defender_obs, eval=True, attacker=False) action = (attacker_action, defender_action) # Take a",
"time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode: {}, Game ended after {} steps\".format(episode, episode_step)) # Record episode",
"self.env.idsgame_config.game_config.num_attack_types] # if self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features = attacker_obs[:, # a_obs_len + self.env.idsgame_config.game_config.num_attack_types:] #",
"= (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_eval.update(1) # Log average eval statistics",
"the replay memory s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch",
"self.num_eval_hacks_total +=1 # Log average metrics every <self.config.eval_log_frequency> episodes if episode % self.config.eval_log_frequency",
"action id \"\"\" state = torch.from_numpy(state.flatten()).float() # Move to GPU if using GPU",
"actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, eval=True, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs,",
"self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[]) obs_state_d_prime =",
"linearly self.anneal_epsilon() self.config.logger.info(\"Training Complete\") # Final evaluation (for saving Gifs etc) self.eval(self.config.num_episodes-1, log=False)",
"warmup phase to fill replay buffer\") # Perform <self.config.dqn_config.replay_start_size> steps and fill the",
"r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch # Convert batch into torch tensors",
"DQNAgent(QAgent): \"\"\" An implementation of the DQN algorithm from the paper 'Human-level control",
"self.config.save_dir is not None: if self.config.attacker: path = self.config.save_dir + \"/\" + time_str",
"episode_defender_reward += defender_reward episode_step += 1 # Move to the next state obs",
"neighbor_defense_attributes[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: temp = neighbor_defense_attributes[:, 0:-1] - attacker_obs[:, 0:-1] else:",
"= np.array(features) if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((features.shape[0], features.shape[1] + d_bool_features.shape[1])) for i in",
"d_bool_features = attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs = attacker_obs[:, 0:a_obs_len] # else: # a_obs_len =",
"for the training step :param attacker: whether doing a training step for the",
"= FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) # Specify device if torch.cuda.is_available() and self.config.dqn_config.gpu:",
"and target network in eval mode if attacker: self.attacker_q_network.train() self.attacker_target_network.eval() r_1 = torch.tensor(r_attacker_batch).float()",
"return features if len(state) == 0: s = np.array([features] * self.config.dqn_config.state_length) return s",
"# Set target baseline. We only want the loss to be computed for",
"neighbor_defense_attributes[i] - attacker_obs[i, 0:-1] features = [] for idx, row in enumerate(temp): t",
"(attacker_action, defender_action) # Take action in the environment obs_prime, reward, done, info =",
"self.config.eval_epsilon): return np.random.choice(legal_actions) with torch.no_grad(): if attacker: act_values = self.attacker_q_network(state) else: act_values =",
"episode_defender_reward = 0 episode_step = 0 while not done: if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep)",
"the result :return: None \"\"\" self.config.logger.info(\"Starting Evaluation\") time_str = str(time.time()) self.num_eval_games = 0",
"+ time_str + \"_eval_results_checkpoint.csv\") return self.train_result def update_target_network(self) -> None: \"\"\" Updates the",
"not None: if self.config.attacker: path = self.config.save_dir + \"/\" + time_str + \"_attacker_q_network.pt\"",
"attacker_obs, defender_obs = obs # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = []",
"s state = np.append(state[1:], np.array([features]), axis=0) return state else: if not self.env.local_view_features() or",
"torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except: self.config.logger.warning(\"Error",
"torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else: raise ValueError(\"Optimizer not recognized\") # LR",
"s_2 = torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train() self.defender_q_network.eval() r_1 = torch.tensor(r_defender_batch).float() s_1 = torch.tensor(s_defender_batch).float() s_2",
"self.attacker_target_network.eval() if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def eval(self, train_episode, log=True) -> ExperimentResult: \"\"\" Performs",
"object\") if self.config.eval_episodes < 1: return done = False # Video config if",
"= np.append(state[1:], np.array([features]), axis=0) return state else: if not self.env.local_view_features() or not attacker:",
"state: np.ndarray, eval : bool = False, attacker : bool = True) ->",
"for idx, row in enumerate(defender_obs_1): if np.isnan(defender_obs_1).any(): t = defender_obs[idx] else: if attacker",
"attacker and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, attacker=True) if self.config.defender: defender_action",
"memory s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch",
"np.array(zero_mean_attacker_features) defender_obs = np.array(zero_mean_defender_features) # Normalize if self.config.dqn_config.normalize_features: if not self.env.local_view_features() or not",
"targets are used to stabilize training and partially remedy the problem with non-stationary",
"parameters of the layers in the model if self.config.dqn_config.optimizer == \"Adam\": self.attacker_optimizer =",
"replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Move to new state obs",
"else: actions = list(range(self.env.num_defense_actions)) legal_actions = list(filter(lambda action: self.env.is_defense_legal(action), actions)) if (np.random.rand() <",
"= obs self.outer_train.update(1) # Anneal epsilon linearly self.anneal_epsilon() self.config.logger.info(\"Training Complete\") # Final evaluation",
"idx, row in enumerate(attacker_obs_1): mean = np.mean(row) if mean != 0: t =",
"# Perform <self.config.dqn_config.replay_start_size> steps and fill the replay memory for i in range(self.config.dqn_config.replay_start_size):",
"\"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) # Training for episode",
"Logging self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1) self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0, 0,0,",
"state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"{} Warmup steps completed, replay buffer size: {}\".format(",
"(DQN is originally Neural-fitted Q-iteration but with the addition of a separate target",
"features = [] for idx, row in enumerate(temp): t = row.tolist() t.append(a_pos[idx]) if",
":return: None \"\"\" time_str = str(time.time()) if self.config.save_dir is not None: if self.config.attacker:",
"entire # vector of all Q-values. Therefore we initialize the target to the",
"episode in range(self.config.eval_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step = 0 while",
"if episode % self.config.eval_log_frequency == 0 and log: if self.num_eval_hacks > 0: self.eval_hack_probability",
"\"/episode_\" + str(train_episode) + \"_\" + time_str + \".gif\", self.config.video_fps) # Add frames",
"0: log_str = \"[Warmup] step:{}, buffer_size: {}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) # Select random",
"training step :param attacker: whether doing a training step for the attacker (otherwise",
"if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def eval(self, train_episode, log=True) ->",
"self.num_train_games_total += 1 if self.env.state.hacked: self.num_train_hacks += 1 self.num_train_hacks_total += 1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward)",
"== 0 and log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games)",
"turn of dropouts, batch norms, gradient computations etc. self.attacker_target_network.eval() self.defender_target_network.eval() # Construct loss",
"from gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent class",
"game data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if self.config.save_dir is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir",
"# Specify device if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") self.config.logger.info(\"Running on the",
"else: if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: t = row.tolist() t.append(defender_obs[idx][-1]) else: t = row",
"lr=self.config.alpha) self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else: raise ValueError(\"Optimizer not recognized\") # LR decay",
"t = defender_obs[idx] else: t = t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs = np.array(zero_mean_attacker_features) defender_obs",
"else: target_next = self.defender_target_network(s_2).detach() for i in range(self.config.dqn_config.batch_size): # As defined by Mnih",
"False # Video config if self.config.video: if self.config.video_dir is None: raise AssertionError(\"Video is",
"attacker_action = self.get_action(attacker_obs, eval=True, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, eval=True, attacker=False) action",
"defender_actions = list(range(self.env.num_defense_actions)) legal_attack_actions = list(filter(lambda action: self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions = list(filter(lambda action:",
"constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked: self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks += 1 self.num_eval_hacks_total",
"self.num_train_hacks = 0 # Update target network every <self.config.dqn_config.target_network_update_freq> episodes if episode %",
"torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif self.config.dqn_config.optimizer == \"SGD\": self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(),",
"float(self.num_eval_games) if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(episode, self.eval_result,",
"models every <self.config.checkpoint_frequency> episodes if episode % self.config.checkpoint_freq == 0: self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True)",
"in range(attacker_obs.shape[0]): id = int(attacker_obs[node][-1]) neighbor_defense_attributes[node] = defender_obs[id] else: neighbor_defense_attributes = defender_obs if",
"if self.config.dqn_config.state_length == 1: return f if len(state) == 0: s = np.array([f]",
"separate target network) \"\"\" def __init__(self, env:IdsGameEnv, config: QAgentConfig): \"\"\" Initialize environment and",
"for the IDSGameEnv that implements the DQN algorithm. \"\"\" from typing import Union",
"self.defender_optimizer.step() return loss def get_action(self, state: np.ndarray, eval : bool = False, attacker",
"if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr = self.attacker_lr_decay.get_lr()[0] # Record episode metrics self.num_train_games += 1",
"self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) # Log average metrics every <self.config.train_log_frequency> episodes",
"self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def eval(self, train_episode, log=True) -> ExperimentResult:",
"and np.random.random() < self.config.eval_epsilon): return np.random.choice(legal_actions) with torch.no_grad(): if attacker: act_values = self.attacker_q_network(state)",
"\"/\" + time_str, force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps # Tracking metrics episode_attacker_rewards =",
"flag whether running in attacker mode (if false assume defender) :return: The sampled",
"attacker and defender actions attacker_actions = list(range(self.env.num_attack_actions)) defender_actions = list(range(self.env.num_defense_actions)) legal_attack_actions = list(filter(lambda",
"decay if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def training_step(self,",
"defined, not saving Q-networks to disk\") def update_state(self, attacker_obs: np.ndarray = None, defender_obs:",
"attacker and self.env.idsgame_config.game_config.reconnaissance_actions: t = row.tolist() t.append(defender_obs[idx][-1]) else: t = row normalized_defender_features.append(t) attacker_obs",
"= attacker_obs[:, 0:a_obs_len] if not attacker and self.env.local_view_features(): attacker_obs = self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False,",
"# As defined by Mnih et. al. : For terminal states the Q-target",
"we set it to eval mode # to turn of dropouts, batch norms,",
"node in range(attacker_obs.shape[0]): id = int(attacker_obs[node][-1]) neighbor_defense_attributes[node] = defender_obs[id] else: neighbor_defense_attributes = defender_obs",
"s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if self.config.defender: s_1 = torch.tensor(s_defender_batch).float() # Move to GPU if",
"attacker and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, eval=True, attacker=True) if self.config.defender:",
"else: self.train_hack_probability = 0.0 self.train_cumulative_hack_probability = 0.0 self.log_metrics(episode, self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, episode_avg_attacker_loss,",
"state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Add",
"# reward when following Q* estimated by the target network. else: a =",
"to the next state obs = obs_prime attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender",
"state \"\"\" if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: #if not self.env.local_view_features(): a_obs_len = self.env.idsgame_config.game_config.num_attack_types +",
"memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Sample random mini_batch of transitions from",
"result object\") done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a",
"disk\") def update_state(self, attacker_obs: np.ndarray = None, defender_obs: np.ndarray = None, state: np.ndarray",
"# Construct loss function if self.config.dqn_config.loss_fn == \"MSE\": self.loss_fn = torch.nn.MSELoss() elif self.config.dqn_config.loss_fn",
"if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except:",
"\"the video_dir argument\") self.env = IdsGameMonitor(self.env, self.config.video_dir + \"/\" + time_str, force=True, video_frequency=self.config.video_frequency)",
"be the immediate reward plus the discounted estimated future # reward when following",
":param state: current state :param attacker: boolean flag whether it is attacker or",
"but no video_dir is provided, please specify \" \"the video_dir argument\") self.env =",
"idx, row in enumerate(defender_obs_1): mean = np.mean(row) if mean != 0: t =",
"else: temp = defender_obs[:, 0:] - attacker_obs[:, 0:-1] features = [] for idx,",
"-> None: \"\"\" Saves the PyTorch Model Weights :return: None \"\"\" time_str =",
"to log the result :return: None \"\"\" self.config.logger.info(\"Starting Evaluation\") time_str = str(time.time()) self.num_eval_games",
"DQN algorithm from the paper 'Human-level control through deep reinforcement learning' by Mnih",
"while not done: if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) # Default initialization attacker_action = 0",
"defender_obs, attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d)",
"the Deep-Q-learning algorithm (implemented in PyTorch) :param mini_batch: a minibatch to use for",
"to sample an action for :param eval: boolean flag whether running in evaluation",
"\".gif\", self.config.video_fps) # Add frames to tensorboard for idx, frame in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode)",
"else: t = t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs = np.array(zero_mean_attacker_features) defender_obs = np.array(zero_mean_defender_features) #",
"Q-network :param state: the state to sample an action for :param eval: boolean",
"s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch if self.config.attacker:",
"self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") return self.train_result def update_target_network(self) -> None:",
"self.env.idsgame_config.game_config.reconnaissance_actions: t = row.tolist() t.append(defender_obs[idx][-1]) else: t = row normalized_defender_features.append(t) attacker_obs = np.array(normalized_attacker_features)",
"# if not self.env.local_view_features() or not attacker: # temp = np.append(attacker_obs, defender_obs) #",
"import QAgent class DQNAgent(QAgent): \"\"\" An implementation of the DQN algorithm from the",
":return: Experiment result \"\"\" self.config.logger.info(\"Starting Warmup\") self.warmup() self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps) >",
"\"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) # Training for episode in range(self.config.num_episodes):",
"object\") done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a =",
"produced by target network if self.config.attacker: loss = self.training_step(minibatch, attacker=True) episode_attacker_loss += loss.item()",
"of logging :param log: whether to log the result :return: None \"\"\" self.config.logger.info(\"Starting",
"# Render final frame when game completed if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode:",
"obs_state_d) attacker_obs, defender_obs = obs self.outer_eval.update(1) # Log average eval statistics if log:",
"else: t = row.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2])",
"hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) # Specify device if torch.cuda.is_available()",
"the entire # vector of all Q-values. Therefore we initialize the target to",
"# Take a step in the environment obs_prime, reward, done, _ = self.env.step(action)",
"attacker_action = np.random.choice(legal_attack_actions) defender_action = np.random.choice(legal_defense_actions) action = (attacker_action, defender_action) # Take action",
"+ '_attacker/grad', value.grad.data.cpu().numpy(), episode) if self.config.defender: for tag, value in self.defender_q_network.named_parameters(): tag =",
"time_str + \"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(), path) else: self.config.logger.warning(\"Save path not",
"[] episode_steps = [] episode_avg_attacker_loss = [] episode_avg_defender_loss = [] # Logging self.outer_train.set_description_str(\"[Train]",
"0:-1]) else: defender_obs_1 = defender_obs / np.linalg.norm(defender_obs) normalized_defender_features = [] for idx, row",
"attacker_obs[:, 0:-1] features = [] for idx, row in enumerate(temp): t = row.tolist()",
"0:-1] features = [] for idx, row in enumerate(temp): t = row.tolist() t.append(node_ids[idx])",
"size: {}\".format( self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close() try: # Add network graph to tensorboard with",
"return np.array([defender_obs] * self.config.dqn_config.state_length) if attacker: state = np.append(state[1:], np.array([attacker_obs]), axis=0) else: state",
"an attacker agent or defender agent\") # Default initialization attacker_action = 0 defender_action",
"algorithm from the paper 'Human-level control through deep reinforcement learning' by Mnih et.",
"whether training an attacker agent or defender agent\") # Default initialization attacker_action =",
"+ \"/\" + time_str, force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps # Tracking metrics episode_attacker_rewards",
"t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 = defender_obs[:, 0:-1]",
"obs_state_d) self.config.logger.info(\"Starting warmup phase to fill replay buffer\") # Perform <self.config.dqn_config.replay_start_size> steps and",
"len(state) == 0: s = np.array([features] * self.config.dqn_config.state_length) return s state = np.append(state[1:],",
"targets in RL with function approximation. :return: None \"\"\" self.config.logger.info(\"Updating target network\") if",
"row - mean else: t = row if np.isnan(t).any(): t = defender_obs[idx] else:",
"0:-1] zero_mean_defender_features = [] for idx, row in enumerate(defender_obs_1): mean = np.mean(row) if",
"call to model.parameters() in the optimizer constructor will contain the learnable # parameters",
"after every episode lr = self.config.alpha if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr = self.attacker_lr_decay.get_lr()[0] #",
"attacker): if self.config.dqn_config.merged_ad_features: if not self.env.local_view_features() or not attacker: a_pos = attacker_obs[:, -1]",
"to keep track of logging :param log: whether to log the result :return:",
"actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, attacker=False)",
"just to populate the replay buffer following a random strategy :return: None \"\"\"",
"s2_attacker_batch, s2_defender_batch = mini_batch # Convert batch into torch tensors and set Q-network",
"saving Gifs etc) self.eval(self.config.num_episodes-1, log=False) # Save Q-networks self.save_model() # Save other game",
"= float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval=True, update_stats=True) self.env.close()",
"episode_avg_defender_loss = [] # Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0,",
"# Logging self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1) self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0,",
"episode_attacker_loss += loss.item() if self.config.defender: loss = self.training_step(minibatch, attacker=False) episode_defender_loss += loss.item() #",
"torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except: self.config.logger.warning(\"Error when trying to add network",
"attacker_obs[:, 0:-1] else: temp = np.full(neighbor_defense_attributes.shape, -1) for i in range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i])",
"attacker and self.env.idsgame_config.game_config.reconnaissance_actions: #if not self.env.local_view_features(): a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 defender_obs =",
"defender_obs[:, -1] temp = defender_obs[:, 0:-1] - attacker_obs[:, 0:-1] else: temp = defender_obs[:,",
"s_1) if self.config.defender: s_1 = torch.tensor(s_defender_batch).float() # Move to GPU if using GPU",
"the target network. else: a = torch.argmax(target_next[i]).detach() if attacker: target[i][a_attacker_batch[i]] = r_1[i] +",
"if i % self.config.train_log_frequency == 0: log_str = \"[Warmup] step:{}, buffer_size: {}\".format(i, self.buffer.size())",
"self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(), path) else: self.config.logger.warning(\"Save path not defined, not saving",
"= [] for idx, row in enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any(): t = attacker_obs[idx] else:",
"episode % self.config.checkpoint_freq == 0: self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if self.config.save_dir is not None:",
"Q-values of the actions taken, not the entire # vector of all Q-values.",
"> 0: self.config.logger.warning(\"starting eval with non-empty result object\") if self.config.eval_episodes < 1: return",
"self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr = self.attacker_lr_decay.get_lr()[0] # Record episode metrics self.num_train_games += 1 self.num_train_games_total",
"= [] episode_steps = [] episode_avg_attacker_loss = [] episode_avg_defender_loss = [] # Logging",
"value.grad.data.cpu().numpy(), episode) if self.config.defender: for tag, value in self.defender_q_network.named_parameters(): tag = tag.replace('.', '/')",
"= True, update_stats=False) # Save gifs if self.config.gifs and self.config.video: self.env.generate_gif(self.config.gif_dir + \"/episode_\"",
"Save Q-networks self.save_model() # Save other game data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if self.config.save_dir is",
"a step in the environment obs_prime, reward, done, _ = self.env.step(action) attacker_obs_prime, defender_obs_prime",
"None, state: np.ndarray = None, attacker: bool = True) -> np.ndarray: \"\"\" Update",
"else: raise ValueError(\"Loss function not recognized\") # Define Optimizer. The call to model.parameters()",
"state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs # Tracking metrics episode_attacker_rewards",
"trying to add network graph to tensorboard\") def initialize_models(self) -> None: \"\"\" Initialize",
"+= attacker_reward episode_defender_reward += defender_reward episode_step += 1 attacker_obs = obs_prime_attacker defender_obs =",
"\"\"\" # Unpack batch of transitions from the replay memory s_attacker_batch, s_defender_batch, a_attacker_batch,",
"legal_actions = list(filter(lambda action: self.env.is_attack_legal(action), actions)) else: actions = list(range(self.env.num_defense_actions)) legal_actions = list(filter(lambda",
"the Q-target should be equal to the immediate reward if d_batch[i]: if attacker:",
"eval : bool = False, attacker : bool = True) -> int: \"\"\"",
"if d_batch[i]: if attacker: target[i][a_attacker_batch[i]] = r_1[i] else: target[i][a_defender_batch[i]] = r_1[i] # For",
"it is only used for predictions, therefore we set it to eval mode",
"self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else: raise ValueError(\"Optimizer not recognized\")",
"in range(self.config.num_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step = 0 episode_attacker_loss =",
"loss = self.loss_fn(prediction, target) # Zero gradients, perform a backward pass, and update",
"episode) self.tensorboard_writer.add_histogram(tag + '_defender/grad', value.grad.data.cpu().numpy(), episode) episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps",
"if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(episode, self.eval_result, episode_attacker_rewards,",
"self.config.dqn_config.zero_mean_features: if not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] else: attacker_obs_1",
"self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device) # Set the target network to use the same weights",
"defender_actions)) attacker_action = np.random.choice(legal_attack_actions) defender_action = np.random.choice(legal_defense_actions) action = (attacker_action, defender_action) # Take",
"network\") if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def eval(self, train_episode, log=True)",
"and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") state = state.to(device) if attacker: actions = list(range(self.env.num_attack_actions))",
"for new eval episode done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs =",
"None: \"\"\" Initialize models :return: None \"\"\" # Initialize models self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim,",
"None self.attacker_lr_decay = None self.defender_lr_decay = None self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size)",
"neighbor_defense_attributes[i]) if self.config.dqn_config.state_length == 1: return f if len(state) == 0: s =",
"eval=True, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, eval=True, attacker=False) action = (attacker_action, defender_action)",
"None self.defender_optimizer = None self.attacker_lr_decay = None self.defender_lr_decay = None self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir)",
"for s # and then we only update the Q-values for the affected",
"\"\"\" A warmup without any learning just to populate the replay buffer following",
"0)) # Reset env obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a =",
"obs = obs_prime outer_warmup.update(1) if done: obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs",
"np.array([defender_obs] * self.config.dqn_config.state_length) if attacker: state = np.append(state[1:], np.array([attacker_obs]), axis=0) else: state =",
"self.env.is_attack_legal(action), actions)) else: actions = list(range(self.env.num_defense_actions)) legal_actions = list(filter(lambda action: self.env.is_defense_legal(action), actions)) if",
"% self.config.checkpoint_freq == 0: self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if self.config.save_dir is not None: time_str",
"enumerate(defender_obs_1): if np.isnan(defender_obs_1).any(): t = defender_obs[idx] else: if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: t =",
"desc='Eval Episode', position=1) self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0, 0.0, 0.0))",
"[] # Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0, 0.0, 0.0,",
"lr=lr) # Log values and gradients of the parameters (histogram summary) to tensorboard",
"self.config.train_log_frequency == 0: if self.num_train_games > 0 and self.num_train_games_total > 0: self.train_hack_probability =",
"self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) # Specify device",
"replay memory for i in range(self.config.dqn_config.replay_start_size): if i % self.config.train_log_frequency == 0: log_str",
"= self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d",
"None \"\"\" self.config.logger.info(\"Starting Evaluation\") time_str = str(time.time()) self.num_eval_games = 0 self.num_eval_hacks = 0",
"obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs for episode in range(self.config.eval_episodes): episode_attacker_reward",
"None \"\"\" # Initialize models self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network",
"attacker_obs_1 = attacker_obs[:, 0:-2] / np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features = [] for idx, row",
"self.config.epsilon and not eval) \\ or (eval and np.random.random() < self.config.eval_epsilon): return np.random.choice(legal_actions)",
"environment and hyperparameters :param config: the configuration \"\"\" super(DQNAgent, self).__init__(env, config) self.attacker_q_network =",
"Mnih et. al. (DQN is originally Neural-fitted Q-iteration but with the addition of",
"and set Q-network in train mode and target network in eval mode if",
"reward, done, obs_prime) # Move to new state obs = obs_prime outer_warmup.update(1) if",
"attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render final frame if self.config.render: self.env.render(mode=\"human\")",
"defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_eval.update(1) #",
"self.num_eval_games_total += 1 if self.env.state.detected: self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked:",
"def initialize_models(self) -> None: \"\"\" Initialize models :return: None \"\"\" # Initialize models",
"= tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_attacker/grad', value.grad.data.cpu().numpy(), episode) if self.config.defender:",
"self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Sample random mini_batch of transitions from replay",
"defender_obs: defender observation :param state: current state :param attacker: boolean flag whether it",
"row - mean else: t = row if np.isnan(t).any(): t = attacker_obs[idx] else:",
"buffer_size: {}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) # Select random attacker and defender actions attacker_actions",
"= np.full(neighbor_defense_attributes.shape, -1) for i in range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i]) > 0: temp[i] =",
"network is not trainable it is only used for predictions, therefore we set",
"Q-network using targets produced by target network if self.config.attacker: loss = self.training_step(minibatch, attacker=True)",
"to tensorboard\") def initialize_models(self) -> None: \"\"\" Initialize models :return: None \"\"\" #",
"metrics every <self.config.eval_log_frequency> episodes if episode % self.config.eval_log_frequency == 0 and log: if",
"torch.argmax(target_next[i]).detach() if attacker: target[i][a_attacker_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) else: target[i][a_defender_batch[i]] =",
"if self.config.defender: s_1 = torch.tensor(s_defender_batch).float() # Move to GPU if using GPU if",
"= self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"{} Warmup steps completed,",
"tensorboard with a sample batch as input mini_batch = self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch, a_attacker_batch,",
"\"\"\" Samples an action according to a epsilon-greedy strategy using the Q-network :param",
"self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions = list(filter(lambda action: self.env.is_defense_legal(action), defender_actions)) attacker_action = np.random.choice(legal_attack_actions) defender_action =",
"action: self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions = list(filter(lambda action: self.env.is_defense_legal(action), defender_actions)) attacker_action = np.random.choice(legal_attack_actions) defender_action",
"= row if np.isnan(t).any(): t = defender_obs[idx] else: t = t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t)",
"0 episode_attacker_loss = 0.0 episode_defender_loss = 0.0 while not done: if self.config.render: self.env.render(mode=\"human\")",
"self.config.defender: loss = self.training_step(minibatch, attacker=False) episode_defender_loss += loss.item() # Update metrics attacker_reward, defender_reward",
":param train_episode: the train episode to keep track of logging :param log: whether",
"obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Update state",
"= 0 episode_defender_reward = 0 episode_step = 0 while not done: if self.config.eval_render:",
"self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting training with non-empty result object\")",
"We only want the loss to be computed for the Q-values of the",
"if episode_step > 0: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss / episode_step) else:",
"self.env.idsgame_config.save_trajectories = False self.env.idsgame_config.save_attack_stats = False def warmup(self) -> None: \"\"\" A warmup",
"video_dir is provided, please specify \" \"the video_dir argument\") self.env = IdsGameMonitor(self.env, self.config.video_dir",
"features.append(t) else: node_ids = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = neighbor_defense_attributes[:, -1]",
"self.config.dqn_config.state_length == 1: if attacker: return np.array(attacker_obs) else: return np.array(defender_obs) if len(state) ==",
"episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) # Update eval stats self.num_eval_games +=1 self.num_eval_games_total += 1 if",
"% self.config.eval_log_frequency == 0 and log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks)",
"using the Q-network :param state: the state to sample an action for :param",
"self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime,",
"in the environment obs_prime, reward, done, info = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime",
"import ExperimentResult from gym_idsgame.envs.constants import constants from gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import",
"else: attacker_obs_1 = attacker_obs[:, 0:-2] / np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features = [] for idx,",
"device = torch.device(\"cuda:0\") r_1 = r_1.to(device) s_1 = s_1.to(device) s_2 = s_2.to(device) #",
"of s' with torch.no_grad(): if attacker: target_next = self.attacker_target_network(s_2).detach() else: target_next = self.defender_target_network(s_2).detach()",
"Zero mean if self.config.dqn_config.zero_mean_features: if not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:,",
"target network every <self.config.dqn_config.target_network_update_freq> episodes if episode % self.config.dqn_config.target_network_update_freq == 0: self.update_target_network() #",
"random attacker and defender actions attacker_actions = list(range(self.env.num_attack_actions)) defender_actions = list(range(self.env.num_defense_actions)) legal_attack_actions =",
"s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if self.config.defender: s_1 = torch.tensor(s_defender_batch).float() # Move to",
"s = np.array([features] * self.config.dqn_config.state_length) return s state = np.append(state[1:], np.array([features]), axis=0) return",
"Q-values of the Q-network for s # and then we only update the",
"a gradient descent step of the Q-network using targets produced by target network",
"Q-network for s # and then we only update the Q-values for the",
"float(self.num_eval_games) if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result,",
"self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t) features = np.array(features) if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((features.shape[0], features.shape[1] +",
"# Add frames to tensorboard for idx, frame in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\"",
"and hyperparameters :param config: the configuration \"\"\" super(DQNAgent, self).__init__(env, config) self.attacker_q_network = None",
"list(filter(lambda action: self.env.is_attack_legal(action), actions)) else: actions = list(range(self.env.num_defense_actions)) legal_actions = list(filter(lambda action: self.env.is_defense_legal(action),",
"torch.nn.MSELoss() elif self.config.dqn_config.loss_fn == \"Huber\": self.loss_fn = torch.nn.SmoothL1Loss() else: raise ValueError(\"Loss function not",
"= [] self.num_train_games = 0 self.num_train_hacks = 0 # Update target network every",
"training step of the Deep-Q-learning algorithm (implemented in PyTorch) :param mini_batch: a minibatch",
"# Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))",
"attacker: boolean flag whether it is attacker or not :return: new state \"\"\"",
"ExperimentResult: \"\"\" Performs evaluation with the greedy policy with respect to the learned",
"episode_attacker_loss = 0.0 episode_defender_loss = 0.0 while not done: if self.config.render: self.env.render(mode=\"human\") if",
"/ float(self.num_eval_games) if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(train_episode,",
"+=1 self.num_eval_games_total += 1 if self.env.state.detected: self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD if",
"# Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] #",
"None self.loss_fn = None self.attacker_optimizer = None self.defender_optimizer = None self.attacker_lr_decay = None",
"not trainable it is only used for predictions, therefore we set it to",
":param defender_obs: defender observation :param state: current state :param attacker: boolean flag whether",
"self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_eval.update(1)",
"or not attacker: # temp = np.append(attacker_obs, defender_obs) # else: # temp =",
"boolean flag whether it is attacker or not :return: new state \"\"\" if",
"torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") self.config.logger.info(\"Running on the GPU\") else: device =",
"\"\"\" super(DQNAgent, self).__init__(env, config) self.attacker_q_network = None self.attacker_target_network = None self.defender_q_network = None",
"actions)) if (np.random.rand() < self.config.epsilon and not eval) \\ or (eval and np.random.random()",
"attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, eval=True, attacker=False) action = (attacker_action, defender_action) #",
"= [] episode_defender_rewards = [] episode_steps = [] self.num_train_games = 0 self.num_train_hacks =",
"# Update eval stats self.num_eval_games +=1 self.num_eval_games_total += 1 if self.env.state.detected: self.eval_attacker_cumulative_reward -=",
"For terminal states the Q-target should be equal to the immediate reward if",
"self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") # Reset environment for the next",
"train mode and target network in eval mode if attacker: self.attacker_q_network.train() self.attacker_target_network.eval() r_1",
"legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self) -> ExperimentResult: \"\"\" Runs the DQN algorithm :return: Experiment result",
"An agent for the IDSGameEnv that implements the DQN algorithm. \"\"\" from typing",
"self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except: self.config.logger.warning(\"Error when trying",
"= row.tolist() t.append(a_pos[idx]) if self.env.fully_observed(): t.append(det_values[idx]) features.append(t) else: node_ids = attacker_obs[:, -1] if",
"episode_steps.append(episode_step) # Log average metrics every <self.config.train_log_frequency> episodes if episode % self.config.train_log_frequency ==",
"average metrics every <self.config.train_log_frequency> episodes if episode % self.config.train_log_frequency == 0: if self.num_train_games",
"self.config.train_log_frequency == 0: log_str = \"[Warmup] step:{}, buffer_size: {}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) #",
"sample batch as input mini_batch = self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch,",
"episode_step += 1 # Move to the next state obs = obs_prime attacker_obs",
"range(self.config.dqn_config.replay_start_size): if i % self.config.train_log_frequency == 0: log_str = \"[Warmup] step:{}, buffer_size: {}\".format(i,",
"target networks. Delayed targets are used to stabilize training and partially remedy the",
"self.env.idsgame_config.game_config.reconnaissance_actions: #if not self.env.local_view_features(): a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 defender_obs = attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types]",
"(implemented in PyTorch) :param mini_batch: a minibatch to use for the training step",
"# if self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features = attacker_obs[:, # a_obs_len + self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs",
"self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def training_step(self, mini_batch: Union[np.ndarray,",
"self.config.dqn_config.merged_ad_features: if not self.env.local_view_features() or not attacker: a_pos = attacker_obs[:, -1] if not",
"0: self.update_target_network() # Run evaluation every <self.config.eval_frequency> episodes if episode % self.config.eval_frequency ==",
"self.num_train_games_total > 0: self.train_hack_probability = self.num_train_hacks / self.num_train_games self.train_cumulative_hack_probability = self.num_train_hacks_total / self.num_train_games_total",
"/ np.linalg.norm(attacker_obs[:, 0:-1]) else: attacker_obs_1 = attacker_obs[:, 0:-2] / np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features =",
"self.defender_q_network.eval() r_1 = torch.tensor(r_defender_batch).float() s_1 = torch.tensor(s_defender_batch).float() s_2 = torch.tensor(s2_defender_batch).float() # Move to",
"t = t.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1])",
"d_bool_features[i]) combined_features = f return np.array(combined_features) return np.append(attacker_obs, defender_obs) else: if self.env.idsgame_config.reconnaissance_bool_features: f",
"gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent class DQNAgent(QAgent): \"\"\" An implementation of",
"target network to use the same weights initialization as the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict())",
"= self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime =",
"attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"Starting",
"if self.config.defender: defender_action = self.get_action(defender_obs, attacker=False) action = (attacker_action, defender_action) # Take a",
"self.env.idsgame_config.reconnaissance_bool_features: combined_features = np.array(combined_features) f = np.zeros( (combined_features.shape[0], combined_features.shape[1] + d_bool_features.shape[1])) for i",
"elif self.config.dqn_config.optimizer == \"SGD\": self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else:",
"memory for i in range(self.config.dqn_config.replay_start_size): if i % self.config.train_log_frequency == 0: log_str =",
"state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs for episode in range(self.config.eval_episodes):",
"+ self.config.gamma * (target_next[i][a]) else: target[i][a_defender_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) #",
"= [] for idx, row in enumerate(temp): t = row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx]) if",
"False obs = self.env.reset(update_stats=True) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True,",
"else: node_ids = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = neighbor_defense_attributes[:, -1] if",
"not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes = np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for node in range(attacker_obs.shape[0]): id = int(attacker_obs[node][-1])",
"row in enumerate(attacker_obs_1): mean = np.mean(row) if mean != 0: t = row",
"- attacker_obs[:, 0:-1] else: temp = np.full(neighbor_defense_attributes.shape, -1) for i in range(len(neighbor_defense_attributes)): if",
"self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") state = state.to(device) if attacker: actions = list(range(self.env.num_attack_actions)) legal_actions",
"self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval = True, update_stats=False) # Save gifs if self.config.gifs",
"computations etc. self.attacker_target_network.eval() self.defender_target_network.eval() # Construct loss function if self.config.dqn_config.loss_fn == \"MSE\": self.loss_fn",
"0:a_obs_len] if not attacker and self.env.local_view_features(): attacker_obs = self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) #",
"f[i] = np.append(attacker_obs[i], neighbor_defense_attributes[i]) if self.config.dqn_config.state_length == 1: return f if len(state) ==",
"range(self.config.num_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step = 0 episode_attacker_loss = 0.0",
"self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval=True, update_stats=True) self.env.close() self.config.logger.info(\"Evaluation Complete\") return self.eval_result def save_model(self)",
"= False # Video config if self.config.video: if self.config.video_dir is None: raise AssertionError(\"Video",
"return np.array(combined_features) return np.append(attacker_obs, defender_obs) else: if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] +",
"1: return done = False # Video config if self.config.video: if self.config.video_dir is",
"\\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) # Training for episode in",
"only used for predictions, therefore we set it to eval mode # to",
"final frame when game completed if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode: {}, Game",
"# Normalize if self.config.dqn_config.normalize_features: if not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:,",
"s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch #",
"step in the environment obs_prime, reward, done, _ = self.env.step(action) attacker_obs_prime, defender_obs_prime =",
"+ str(train_episode) + \"_\" + time_str + \".gif\", self.config.video_fps) # Add frames to",
"Sample random mini_batch of transitions from replay memory minibatch = self.buffer.sample(self.config.dqn_config.batch_size) # Perform",
"act_values = self.attacker_q_network(state) else: act_values = self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self) -> ExperimentResult:",
"or (eval and np.random.random() < self.config.eval_epsilon): return np.random.choice(legal_actions) with torch.no_grad(): if attacker: act_values",
"\"\"\" Initialize environment and hyperparameters :param config: the configuration \"\"\" super(DQNAgent, self).__init__(env, config)",
"attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render final frame when game completed",
"tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size: {}\".format(0, 0)) # Reset env obs =",
"normalized_attacker_features = [] for idx, row in enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any(): t = attacker_obs[idx]",
"= 0.0 self.log_metrics(episode, self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr) # Log values",
"# attacker_obs = attacker_obs[:, 0:a_obs_len] if not attacker and self.env.local_view_features(): attacker_obs = self.env.state.get_attacker_observation(",
"the loss to be computed for the Q-values of the actions taken, not",
"else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 = defender_obs[:, 0:-1] /",
"action according to a epsilon-greedy strategy using the Q-network :param state: the state",
"len(state) == 0: if attacker: return np.array([attacker_obs] * self.config.dqn_config.state_length) else: return np.array([defender_obs] *",
"implements the DQN algorithm. \"\"\" from typing import Union import numpy as np",
"episode_defender_rewards, episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr) # Log values and gradients of the parameters",
"return np.array(defender_obs) if len(state) == 0: if attacker: return np.array([attacker_obs] * self.config.dqn_config.state_length) else:",
"= torch.from_numpy(state.flatten()).float() # Move to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu:",
"r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch if self.config.attacker: s_1 = torch.tensor(s_attacker_batch).float()",
"memory minibatch = self.buffer.sample(self.config.dqn_config.batch_size) # Perform a gradient descent step of the Q-network",
"update the weights. if attacker: self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step() return",
"None: raise AssertionError(\"Video is set to True but no video_dir is provided, please",
"immediate reward if d_batch[i]: if attacker: target[i][a_attacker_batch[i]] = r_1[i] else: target[i][a_defender_batch[i]] = r_1[i]",
"legal_defense_actions = list(filter(lambda action: self.env.is_defense_legal(action), defender_actions)) attacker_action = np.random.choice(legal_attack_actions) defender_action = np.random.choice(legal_defense_actions) action",
"= obs_prime attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render final frame if",
"not attacker: if self.env.idsgame_config.game_config.reconnaissance_actions and attacker: combined_features = [] for idx, row in",
"deep reinforcement learning' by Mnih et. al. (DQN is originally Neural-fitted Q-iteration but",
"-> None: \"\"\" Initialize models :return: None \"\"\" # Initialize models self.attacker_q_network =",
"self.config.defender: defender_action = self.get_action(defender_obs, attacker=False) action = (attacker_action, defender_action) # Take a step",
"combined_row = np.append(row, defender_obs[idx]) combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features: combined_features = np.array(combined_features) f = np.zeros(",
"from replay memory minibatch = self.buffer.sample(self.config.dqn_config.batch_size) # Perform a gradient descent step of",
"# d_bool_features = attacker_obs[:, # a_obs_len + self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs = attacker_obs[:, 0:a_obs_len]",
"not done: if self.config.render: self.env.render(mode=\"human\") if not self.config.attacker and not self.config.defender: raise AssertionError(\"Must",
"evaluation (for saving Gifs etc) self.eval(self.config.num_episodes-1, log=False) # Save Q-networks self.save_model() # Save",
"minibatch to use for the training step :param attacker: whether doing a training",
"without any learning just to populate the replay buffer following a random strategy",
"the target to the Q-values of the Q-network for s # and then",
"t.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1",
"features if len(state) == 0: s = np.array([features] * self.config.dqn_config.state_length) return s state",
"# Use the target network to compute the Q-values of s' with torch.no_grad():",
"float( self.num_eval_games_total) self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval = True, update_stats=False) # Save",
"-1) for i in range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i]) > 0: temp[i] = neighbor_defense_attributes[i] -",
"self.tensorboard_writer.add_histogram(tag + '_defender/grad', value.grad.data.cpu().numpy(), episode) episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps =",
"neighbor_defense_attributes) state = np.append(state[1:], np.array([f]), axis=0) return state else: if self.config.dqn_config.state_length == 1:",
"by Mnih et. al. : For terminal states the Q-target should be equal",
"gradients of the parameters (histogram summary) to tensorboard if self.config.attacker: for tag, value",
"to populate the replay buffer following a random strategy :return: None \"\"\" #",
"= row - mean else: t = row if np.isnan(t).any(): t = defender_obs[idx]",
"attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs for episode in",
"targets produced by target network if self.config.attacker: loss = self.training_step(minibatch, attacker=True) episode_attacker_loss +=",
"a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch if self.config.attacker: s_1 =",
"of the parameters (histogram summary) to tensorboard if self.config.attacker: for tag, value in",
"+=1 # Log average metrics every <self.config.eval_log_frequency> episodes if episode % self.config.eval_log_frequency ==",
"attacker agent or defender agent\") # Default initialization attacker_action = 0 defender_action =",
"log the result :return: None \"\"\" self.config.logger.info(\"Starting Evaluation\") time_str = str(time.time()) self.num_eval_games =",
"Delayed targets are used to stabilize training and partially remedy the problem with",
"None \"\"\" # Setup logging outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size:",
"episode_defender_rewards, episode_steps, eval=True, update_stats=True) self.env.close() self.config.logger.info(\"Evaluation Complete\") return self.eval_result def save_model(self) -> None:",
"problem with non-stationary targets in RL with function approximation. :return: None \"\"\" self.config.logger.info(\"Updating",
"time_str = str(time.time()) if self.config.save_dir is not None: if self.config.attacker: path = self.config.save_dir",
"= tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size: {}\".format(0, 0)) # Reset env obs",
"network. else: a = torch.argmax(target_next[i]).detach() if attacker: target[i][a_attacker_batch[i]] = r_1[i] + self.config.gamma *",
"Add frames to tensorboard for idx, frame in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" +",
"not recognized\") # LR decay if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay =",
"Compute loss if attacker: prediction = self.attacker_q_network(s_1) else: prediction = self.defender_q_network(s_1) loss =",
"agent for the IDSGameEnv that implements the DQN algorithm. \"\"\" from typing import",
"== 1: if attacker: return np.array(attacker_obs) else: return np.array(defender_obs) if len(state) == 0:",
"def warmup(self) -> None: \"\"\" A warmup without any learning just to populate",
"self.num_eval_games = 0 self.num_eval_hacks = 0 if len(self.eval_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting eval with",
"f if self.config.dqn_config.state_length == 1: return features if len(state) == 0: s =",
"0:-1] features = [] for idx, row in enumerate(temp): t = row.tolist() t.append(a_pos[idx])",
"every <self.config.eval_frequency> episodes if episode % self.config.eval_frequency == 0: self.eval(episode) # Save models",
"and not self.config.defender: raise AssertionError(\"Must specify whether training an attacker agent or defender",
"episode % self.config.train_log_frequency == 0: if self.num_train_games > 0 and self.num_train_games_total > 0:",
"for idx, row in enumerate(attacker_obs_1): mean = np.mean(row) if mean != 0: t",
"self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero mean if self.config.dqn_config.zero_mean_features: if not self.env.local_view_features() or",
"Render final frame if self.config.render: self.env.render(mode=\"human\") # Decay LR after every episode lr",
"when game completed if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode: {}, Game ended after",
"the Q-network :param state: the state to sample an action for :param eval:",
"s # if not self.env.local_view_features() or not attacker: # temp = np.append(attacker_obs, defender_obs)",
"non-stationary targets in RL with function approximation. :return: None \"\"\" self.config.logger.info(\"Updating target network\")",
"0.0 self.train_cumulative_hack_probability = 0.0 self.log_metrics(episode, self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr) #",
"self.config.dqn_config.target_network_update_freq == 0: self.update_target_network() # Run evaluation every <self.config.eval_frequency> episodes if episode %",
"attacker: return np.array(attacker_obs) else: return np.array(defender_obs) if len(state) == 0: if attacker: return",
"Zero gradients, perform a backward pass, and update the weights. if attacker: self.attacker_optimizer.zero_grad()",
"state = np.append(state[1:], np.array([f]), axis=0) return state else: if self.config.dqn_config.state_length == 1: if",
"the DQN algorithm from the paper 'Human-level control through deep reinforcement learning' by",
"result \"\"\" self.config.logger.info(\"Starting Warmup\") self.warmup() self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting",
"self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1 = defender_obs[:, 0:-1]",
"\"/\" + time_str + \"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(), path) else: self.config.logger.warning(\"Save",
"obs = obs_prime attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render final frame",
"self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps",
"np.ndarray = None, attacker: bool = True) -> np.ndarray: \"\"\" Update approximative Markov",
"= None self.defender_q_network = None self.defender_target_network = None self.loss_fn = None self.attacker_optimizer =",
"* self.config.dqn_config.state_length) if attacker: state = np.append(state[1:], np.array([attacker_obs]), axis=0) else: state = np.append(state[1:],",
"if not self.env.local_view_features() or not attacker: if self.env.idsgame_config.game_config.reconnaissance_actions and attacker: combined_features = []",
"obs_prime_attacker defender_obs = obs_prime_defender # Render final frame if self.config.render: self.env.render(mode=\"human\") # Decay",
"the PyTorch Model Weights :return: None \"\"\" time_str = str(time.time()) if self.config.save_dir is",
"defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs # Tracking",
"attacker_obs[:, 0:-1] else: attacker_obs_1 = attacker_obs[:, 0:-2] zero_mean_attacker_features = [] for idx, row",
"<self.config.checkpoint_frequency> episodes if episode % self.config.checkpoint_freq == 0: self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if self.config.save_dir",
"obs_prime = (obs_state_a_prime, obs_state_d_prime) # Update state information and metrics attacker_reward, defender_reward =",
"recognized\") # Define Optimizer. The call to model.parameters() in the optimizer constructor will",
"position=1) self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0, 0.0, 0.0)) # Eval",
"states the Q-target should be the immediate reward plus the discounted estimated future",
"0 episode_defender_reward = 0 episode_step = 0 episode_attacker_loss = 0.0 episode_defender_loss = 0.0",
"+= 1 # Move to the next state obs = obs_prime attacker_obs =",
"not :return: new state \"\"\" if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: #if not self.env.local_view_features(): a_obs_len",
"np.zeros((features.shape[0], features.shape[1] + d_bool_features.shape[1])) for i in range(features.shape[0]): f[i] = np.append(features[i], d_bool_features[i]) features",
"t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs = np.array(zero_mean_attacker_features) defender_obs = np.array(zero_mean_defender_features) # Normalize if self.config.dqn_config.normalize_features:",
"logging :param log: whether to log the result :return: None \"\"\" self.config.logger.info(\"Starting Evaluation\")",
"on the GPU\") else: device = torch.device(\"cpu\") self.config.logger.info(\"Running on the CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device)",
"the Q-values of the actions taken, not the entire # vector of all",
"self.env.idsgame_config.game_config.reconnaissance_actions: temp = neighbor_defense_attributes[:, 0:-1] - attacker_obs[:, 0:-1] else: temp = np.full(neighbor_defense_attributes.shape, -1)",
"t.append(node_ids[idx]) #t.append(node_reachable[idx]) if not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t) features = np.array(features) if self.env.idsgame_config.reconnaissance_bool_features: f",
"1 attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render final frame when game",
":return: loss \"\"\" # Unpack batch of transitions from the replay memory s_attacker_batch,",
"= np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i]) else: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1])) for i",
"= (obs_state_a_prime, obs_state_d_prime) # Update state information and metrics attacker_reward, defender_reward = reward",
"epsilon-greedy strategy using the Q-network :param state: the state to sample an action",
"attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_train.update(1) # Anneal",
"self.train_result def update_target_network(self) -> None: \"\"\" Updates the target networks. Delayed targets are",
"neighbor_defense_attributes = np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for node in range(attacker_obs.shape[0]): id = int(attacker_obs[node][-1]) neighbor_defense_attributes[node] =",
"if self.env.fully_observed() or \\ (self.env.idsgame_config.game_config.reconnaissance_actions and attacker): if self.config.dqn_config.merged_ad_features: if not self.env.local_view_features() or",
"[] episode_defender_rewards = [] episode_steps = [] episode_avg_attacker_loss = [] episode_avg_defender_loss = []",
"\"/\" + time_str + \"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path) if self.config.defender:",
"legal_actions = list(filter(lambda action: self.env.is_defense_legal(action), actions)) if (np.random.rand() < self.config.epsilon and not eval)",
"np.append(features[i], d_bool_features[i]) features = f if self.config.dqn_config.state_length == 1: return features if len(state)",
"defender_obs = obs self.outer_eval.update(1) # Log average eval statistics if log: if self.num_eval_hacks",
"# defender_obs = attacker_obs[:, # a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types] # if self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features",
"self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) # Specify",
"zero_mean_attacker_features.append(t) defender_obs_1 = defender_obs[:, 0:-1] zero_mean_defender_features = [] for idx, row in enumerate(defender_obs_1):",
"# Log values and gradients of the parameters (histogram summary) to tensorboard if",
"not saving Q-networks to disk\") def update_state(self, attacker_obs: np.ndarray = None, defender_obs: np.ndarray",
"np.append(state[1:], np.array([features]), axis=0) return state else: if not self.env.local_view_features() or not attacker: if",
"\"Huber\": self.loss_fn = torch.nn.SmoothL1Loss() else: raise ValueError(\"Loss function not recognized\") # Define Optimizer.",
"= (attacker_action, defender_action) # Take a step in the environment obs_prime, reward, done,",
"features = np.array(features) if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((features.shape[0], features.shape[1] + d_bool_features.shape[1])) for i",
"transitions from the replay memory s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch,",
"the train episode to keep track of logging :param log: whether to log",
"and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if self.config.defender: s_1",
"= False def warmup(self) -> None: \"\"\" A warmup without any learning just",
"# Save models every <self.config.checkpoint_frequency> episodes if episode % self.config.checkpoint_freq == 0: self.save_model()",
"+ time_str + \".gif\", self.config.video_fps) # Add frames to tensorboard for idx, frame",
"<self.config.train_log_frequency> episodes if episode % self.config.train_log_frequency == 0: if self.num_train_games > 0 and",
"gym_idsgame.agents.dao.experiment_result import ExperimentResult from gym_idsgame.envs.constants import constants from gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer",
"episode_steps, eval = True, update_stats=False) # Save gifs if self.config.gifs and self.config.video: self.env.generate_gif(self.config.gif_dir",
"the CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device) # Set the target network to use",
"to tensorboard with a sample batch as input mini_batch = self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch,",
"= defender_obs[:, 0:-1] zero_mean_defender_features = [] for idx, row in enumerate(defender_obs_1): mean =",
"network to use the same weights initialization as the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) #",
"np.array(defender_obs) if len(state) == 0: if attacker: return np.array([attacker_obs] * self.config.dqn_config.state_length) else: return",
"if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = neighbor_defense_attributes[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: temp = neighbor_defense_attributes[:,",
"self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games) if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) /",
"episodes if episode % self.config.train_log_frequency == 0: if self.num_train_games > 0 and self.num_train_games_total",
"np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1])) for i in range(f.shape[0]): f[i] = np.append(attacker_obs[i], neighbor_defense_attributes[i]) if",
"= torch.tensor(s_defender_batch).float() # Move to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu:",
"to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(), path) else: self.config.logger.warning(\"Save path not defined, not saving Q-networks to",
"self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def eval(self, train_episode, log=True) -> ExperimentResult: \"\"\" Performs evaluation with the",
"every <self.config.train_log_frequency> episodes if episode % self.config.train_log_frequency == 0: if self.num_train_games > 0",
"with function approximation. :return: None \"\"\" self.config.logger.info(\"Updating target network\") if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval()",
"if len(state) == 0: s = np.array([f] * self.config.dqn_config.state_length) return s # if",
"it is attacker or not :return: new state \"\"\" if attacker and self.env.idsgame_config.game_config.reconnaissance_actions:",
"self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close() try: # Add network graph to tensorboard with a sample",
"gradient computations etc. self.attacker_target_network.eval() self.defender_target_network.eval() # Construct loss function if self.config.dqn_config.loss_fn == \"MSE\":",
"function not recognized\") # Define Optimizer. The call to model.parameters() in the optimizer",
"layers in the model if self.config.dqn_config.optimizer == \"Adam\": self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer",
"= [] # Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0, 0.0,",
"self.config.logger.info(\"Training Complete\") # Final evaluation (for saving Gifs etc) self.eval(self.config.num_episodes-1, log=False) # Save",
"+ self.config.gamma * (target_next[i][a]) # Compute loss if attacker: prediction = self.attacker_q_network(s_1) else:",
"self.env.local_view_features(): attacker_obs = self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero mean if self.config.dqn_config.zero_mean_features: if",
"from gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig from gym_idsgame.envs.idsgame_env import IdsGameEnv from gym_idsgame.agents.dao.experiment_result import ExperimentResult from",
"buffer size: {}\".format( self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close() try: # Add network graph to tensorboard",
"self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network =",
"and update the weights. if attacker: self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step()",
"not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 =",
"+ time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") # Reset",
"Save other game data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if self.config.save_dir is not None: time_str =",
"self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode: {}, Game ended after {} steps\".format(episode, episode_step)) # Record",
"every <self.config.eval_log_frequency> episodes if episode % self.config.eval_log_frequency == 0 and log: if self.num_eval_hacks",
"= self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Add transition to",
"self.defender_target_network(s_2).detach() for i in range(self.config.dqn_config.batch_size): # As defined by Mnih et. al. :",
"defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Add transition to replay memory",
"and attacker: combined_features = [] for idx, row in enumerate(attacker_obs): combined_row = np.append(row,",
"obs = (obs_state_a, obs_state_d) self.config.logger.info(\"{} Warmup steps completed, replay buffer size: {}\".format( self.config.dqn_config.replay_start_size,",
"obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[])",
"self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs #",
"{}, Game ended after {} steps\".format(episode, episode_step)) # Record episode metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward)",
"zero_mean_attacker_features = [] for idx, row in enumerate(attacker_obs_1): mean = np.mean(row) if mean",
"not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] / np.linalg.norm(attacker_obs[:, 0:-1]) else: attacker_obs_1 = attacker_obs[:,",
"from the replay memory s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch,",
"def save_model(self) -> None: \"\"\" Saves the PyTorch Model Weights :return: None \"\"\"",
"0 while not done: if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) # Default initialization attacker_action =",
"\"\"\" from typing import Union import numpy as np import time import tqdm",
"= torch.tensor(s2_defender_batch).float() # Move to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu:",
"GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") r_1 =",
"temp = neighbor_defense_attributes[:, 0:-1] - attacker_obs[:, 0:-1] else: temp = np.full(neighbor_defense_attributes.shape, -1) for",
"state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"{} Warmup",
"# Zero gradients, perform a backward pass, and update the weights. if attacker:",
"= float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval = True,",
"raise ValueError(\"Loss function not recognized\") # Define Optimizer. The call to model.parameters() in",
"Reset environment for the next episode and update game stats done = False",
"= self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"Starting warmup phase to",
"(obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_train.update(1) # Anneal epsilon linearly self.anneal_epsilon() self.config.logger.info(\"Training",
"As defined by Mnih et. al. : For terminal states the Q-target should",
"is only used for predictions, therefore we set it to eval mode #",
"== \"SGD\": self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else: raise ValueError(\"Optimizer",
"state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs",
"torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train() self.defender_q_network.eval() r_1 = torch.tensor(r_defender_batch).float() s_1 = torch.tensor(s_defender_batch).float() s_2 = torch.tensor(s2_defender_batch).float()",
"(for saving Gifs etc) self.eval(self.config.num_episodes-1, log=False) # Save Q-networks self.save_model() # Save other",
"= torch.device(\"cuda:0\") self.config.logger.info(\"Running on the GPU\") else: device = torch.device(\"cpu\") self.config.logger.info(\"Running on the",
"# Update state information and metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender =",
"attacker: target[i][a_attacker_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) else: target[i][a_defender_batch[i]] = r_1[i] +",
"0.0, 0.0, 0.0, 0.0, 0.0)) # Training for episode in range(self.config.num_episodes): episode_attacker_reward =",
"episode_defender_reward = 0 episode_step = 0 episode_attacker_loss = 0.0 episode_defender_loss = 0.0 while",
"the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The target network is not trainable it is",
"mini_batch # Convert batch into torch tensors and set Q-network in train mode",
"list(range(self.env.num_defense_actions)) legal_attack_actions = list(filter(lambda action: self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions = list(filter(lambda action: self.env.is_defense_legal(action), defender_actions))",
"raise ValueError(\"Optimizer not recognized\") # LR decay if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate)",
"target network in eval mode if attacker: self.attacker_q_network.train() self.attacker_target_network.eval() r_1 = torch.tensor(r_attacker_batch).float() s_1",
"self.attacker_lr_decay = None self.defender_lr_decay = None self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models()",
"self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self) -> ExperimentResult: \"\"\" Runs the DQN algorithm :return:",
"video_dir argument\") self.env = IdsGameMonitor(self.env, self.config.video_dir + \"/\" + time_str, force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"]",
"Evaluation\") time_str = str(time.time()) self.num_eval_games = 0 self.num_eval_hacks = 0 if len(self.eval_result.avg_episode_steps) >",
"features = f if self.config.dqn_config.state_length == 1: return features if len(state) == 0:",
"self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def eval(self, train_episode, log=True) -> ExperimentResult: \"\"\"",
"tensors and set Q-network in train mode and target network in eval mode",
"# Reset env obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs,",
"backward pass, and update the weights. if attacker: self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad()",
"raise AssertionError(\"Must specify whether training an attacker agent or defender agent\") # Default",
"self.num_eval_games_total) self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval = True, update_stats=False) # Save gifs",
"self.env.local_view_features() or not attacker: # temp = np.append(attacker_obs, defender_obs) # else: # temp",
"if not attacker and self.env.local_view_features(): attacker_obs = self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero",
"self.attacker_target_network.eval() self.defender_target_network.eval() # Construct loss function if self.config.dqn_config.loss_fn == \"MSE\": self.loss_fn = torch.nn.MSELoss()",
"# Perform a gradient descent step of the Q-network using targets produced by",
"1 # defender_obs = attacker_obs[:, # a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types] # if self.env.idsgame_config.reconnaissance_bool_features: #",
"row in enumerate(defender_obs_1): mean = np.mean(row) if mean != 0: t = row",
"list(filter(lambda action: self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions = list(filter(lambda action: self.env.is_defense_legal(action), defender_actions)) attacker_action = np.random.choice(legal_attack_actions)",
"range(self.config.dqn_config.batch_size): # As defined by Mnih et. al. : For terminal states the",
"t = row if np.isnan(t).any(): t = defender_obs[idx] else: t = t.tolist() t.append(defender_obs[idx][-1])",
"statistics if log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games) if",
"Union import numpy as np import time import tqdm import torch from torch.utils.tensorboard",
"not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = defender_obs[:, -1] temp = defender_obs[:, 0:-1] - attacker_obs[:, 0:-1]",
"self.config.save_dir + \"/\" + time_str + \"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(), path)",
"a sample batch as input mini_batch = self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch,",
"* (target_next[i][a]) else: target[i][a_defender_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) # Compute loss",
"the learned Q-values :param train_episode: the train episode to keep track of logging",
"(obs_state_a, obs_state_d) self.config.logger.info(\"Starting warmup phase to fill replay buffer\") # Perform <self.config.dqn_config.replay_start_size> steps",
"and partially remedy the problem with non-stationary targets in RL with function approximation.",
"# Eval obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs,",
"= obs self.outer_eval.update(1) # Log average eval statistics if log: if self.num_eval_hacks >",
"defender_obs[:, 0:-1] - attacker_obs[:, 0:-1] else: temp = defender_obs[:, 0:] - attacker_obs[:, 0:-1]",
"/ np.linalg.norm(defender_obs) normalized_defender_features = [] for idx, row in enumerate(defender_obs_1): if np.isnan(defender_obs_1).any(): t",
"Performs a training step of the Deep-Q-learning algorithm (implemented in PyTorch) :param mini_batch:",
"actions)) else: actions = list(range(self.env.num_defense_actions)) legal_actions = list(filter(lambda action: self.env.is_defense_legal(action), actions)) if (np.random.rand()",
"Q-values of s' with torch.no_grad(): if attacker: target_next = self.attacker_target_network(s_2).detach() else: target_next =",
"torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else: raise ValueError(\"Optimizer not recognized\") # LR decay if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay",
"warmup(self) -> None: \"\"\" A warmup without any learning just to populate the",
"1: return f if len(state) == 0: s = np.array([f] * self.config.dqn_config.state_length) return",
"then we only update the Q-values for the affected actions with the real",
"(obs_state_a, obs_state_d) attacker_obs, defender_obs = obs # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards",
"running in attacker mode (if false assume defender) :return: The sampled action id",
"\"\"\" An agent for the IDSGameEnv that implements the DQN algorithm. \"\"\" from",
"+ time_str, force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps # Tracking metrics episode_attacker_rewards = []",
"None self.attacker_optimizer = None self.defender_optimizer = None self.attacker_lr_decay = None self.defender_lr_decay = None",
"episode % self.config.dqn_config.target_network_update_freq == 0: self.update_target_network() # Run evaluation every <self.config.eval_frequency> episodes if",
"+= 1 if self.env.state.detected: self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked: self.eval_attacker_cumulative_reward",
"= 0 # Update target network every <self.config.dqn_config.target_network_update_freq> episodes if episode % self.config.dqn_config.target_network_update_freq",
"True) -> np.ndarray: \"\"\" Update approximative Markov state :param attacker_obs: attacker obs :param",
"not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] else: attacker_obs_1 = attacker_obs[:, 0:-2] zero_mean_attacker_features =",
"super(DQNAgent, self).__init__(env, config) self.attacker_q_network = None self.attacker_target_network = None self.defender_q_network = None self.defender_target_network",
"for the affected actions with the real targets if attacker: target = self.attacker_q_network(s_1)",
"the target network to compute the Q-values of s' with torch.no_grad(): if attacker:",
"and self.num_train_games_total > 0: self.train_hack_probability = self.num_train_hacks / self.num_train_games self.train_cumulative_hack_probability = self.num_train_hacks_total /",
"# For non terminal states the Q-target should be the immediate reward plus",
"= attacker_obs[:, 0:-2] zero_mean_attacker_features = [] for idx, row in enumerate(attacker_obs_1): mean =",
"attacker: target_next = self.attacker_target_network(s_2).detach() else: target_next = self.defender_target_network(s_2).detach() for i in range(self.config.dqn_config.batch_size): #",
"self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories = False self.env.idsgame_config.save_attack_stats = False def warmup(self) -> None: \"\"\"",
"if self.config.dqn_config.state_length == 1: if attacker: return np.array(attacker_obs) else: return np.array(defender_obs) if len(state)",
"row if np.isnan(t).any(): t = defender_obs[idx] else: t = t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs",
"should be the immediate reward plus the discounted estimated future # reward when",
"episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] # Logging self.outer_eval =",
"step:{}, buffer_size: {}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) # Select random attacker and defender actions",
"(obs_state_a, obs_state_d) self.config.logger.info(\"{} Warmup steps completed, replay buffer size: {}\".format( self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close()",
"i in range(self.config.dqn_config.replay_start_size): if i % self.config.train_log_frequency == 0: log_str = \"[Warmup] step:{},",
"that implements the DQN algorithm. \"\"\" from typing import Union import numpy as",
"/ episode_step) else: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) # Log average",
"s = np.array([f] * self.config.dqn_config.state_length) return s # if not self.env.local_view_features() or not",
"value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_attacker/grad', value.grad.data.cpu().numpy(), episode) if self.config.defender: for tag, value in",
"if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if",
"not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = neighbor_defense_attributes[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: temp = neighbor_defense_attributes[:, 0:-1]",
"if attacker: self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step() return loss def get_action(self,",
"every <self.config.dqn_config.target_network_update_freq> episodes if episode % self.config.dqn_config.target_network_update_freq == 0: self.update_target_network() # Run evaluation",
"-= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked: self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD",
"np.full(neighbor_defense_attributes.shape, -1) for i in range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i]) > 0: temp[i] = neighbor_defense_attributes[i]",
"attacker_obs.shape[1] + neighbor_defense_attributes.shape[1])) for i in range(f.shape[0]): f[i] = np.append(attacker_obs[i], neighbor_defense_attributes[i]) if self.config.dqn_config.state_length",
"+= 1 self.num_train_hacks_total += 1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if episode_step > 0: if self.config.attacker:",
"attacker: attacker_obs_1 = attacker_obs[:, 0:-1] else: attacker_obs_1 = attacker_obs[:, 0:-2] zero_mean_attacker_features = []",
"np.ndarray], attacker: bool = True) -> torch.Tensor: \"\"\" Performs a training step of",
"done: obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True,",
"self.config.logger.warning(\"Save path not defined, not saving Q-networks to disk\") def update_state(self, attacker_obs: np.ndarray",
"np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features = [] for idx, row in enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any(): t",
"etc) self.eval(self.config.num_episodes-1, log=False) # Save Q-networks self.save_model() # Save other game data self.env.save_trajectories(checkpoint=False)",
"np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i]) else: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1])) for i in",
"# Get attacker and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, eval=True, attacker=True)",
"0:-2]) normalized_attacker_features = [] for idx, row in enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any(): t =",
"= int(attacker_obs[node][-1]) neighbor_defense_attributes[node] = defender_obs[id] else: neighbor_defense_attributes = defender_obs if self.env.fully_observed() or \\",
"else: prediction = self.defender_q_network(s_1) loss = self.loss_fn(prediction, target) # Zero gradients, perform a",
"# Save gifs if self.config.gifs and self.config.video: self.env.generate_gif(self.config.gif_dir + \"/episode_\" + str(train_episode) +",
"= np.array(zero_mean_attacker_features) defender_obs = np.array(zero_mean_defender_features) # Normalize if self.config.dqn_config.normalize_features: if not self.env.local_view_features() or",
"network graph to tensorboard\") def initialize_models(self) -> None: \"\"\" Initialize models :return: None",
"obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs =",
"self.config.attacker: for tag, value in self.attacker_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode)",
"= (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs for episode in range(self.config.eval_episodes): episode_attacker_reward =",
"self.attacker_q_network(state) else: act_values = self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self) -> ExperimentResult: \"\"\" Runs",
"self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss / episode_step) else: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender:",
"mean != 0: t = row - mean else: t = row if",
"in enumerate(temp): t = row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx]) if not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t) features",
"global_step=train_episode, dataformats = \"HWC\") # Reset for new eval episode done = False",
"self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks += 1 self.num_eval_hacks_total +=1 # Log",
"Reset env obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs,",
"= obs_prime_defender # Render final frame when game completed if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep)",
"for tag, value in self.attacker_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag",
"self.config.dqn_config.state_length == 1: return features if len(state) == 0: s = np.array([features] *",
"= [] for idx, row in enumerate(defender_obs_1): if np.isnan(defender_obs_1).any(): t = defender_obs[idx] else:",
"specify \" \"the video_dir argument\") self.env = IdsGameMonitor(self.env, self.config.video_dir + \"/\" + time_str,",
"if attacker: target[i][a_attacker_batch[i]] = r_1[i] else: target[i][a_defender_batch[i]] = r_1[i] # For non terminal",
"= np.mean(row) if mean != 0: t = row - mean else: t",
"self.attacker_lr_decay.step() lr = self.attacker_lr_decay.get_lr()[0] # Record episode metrics self.num_train_games += 1 self.num_train_games_total +=",
"# Video config if self.config.video: if self.config.video_dir is None: raise AssertionError(\"Video is set",
"self.attacker_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_attacker/grad', value.grad.data.cpu().numpy(), episode)",
"d_bool_features[i]) features = f if self.config.dqn_config.state_length == 1: return features if len(state) ==",
"real targets if attacker: target = self.attacker_q_network(s_1) else: target = self.defender_q_network(s_1) # Use",
"bool = True) -> torch.Tensor: \"\"\" Performs a training step of the Deep-Q-learning",
"combined_features = [] for idx, row in enumerate(attacker_obs): combined_row = np.append(row, defender_obs[idx]) combined_features.append(combined_row)",
"eval statistics if log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games)",
"list(range(self.env.num_attack_actions)) legal_actions = list(filter(lambda action: self.env.is_attack_legal(action), actions)) else: actions = list(range(self.env.num_defense_actions)) legal_actions =",
"- mean else: t = row if np.isnan(t).any(): t = defender_obs[idx] else: t",
"self.config.attacker: attacker_action = self.get_action(attacker_obs, eval=True, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, eval=True, attacker=False)",
"with non-stationary targets in RL with function approximation. :return: None \"\"\" self.config.logger.info(\"Updating target",
"if self.env.state.hacked: self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks += 1 self.num_eval_hacks_total +=1",
"done = False obs = self.env.reset(update_stats=True) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs,",
"= torch.tensor(s_attacker_batch).float() # Move to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu:",
"target_next = self.defender_target_network(s_2).detach() for i in range(self.config.dqn_config.batch_size): # As defined by Mnih et.",
"the immediate reward plus the discounted estimated future # reward when following Q*",
"= defender_obs[id] else: neighbor_defense_attributes = defender_obs if self.env.fully_observed() or \\ (self.env.idsgame_config.game_config.reconnaissance_actions and attacker):",
"network) \"\"\" def __init__(self, env:IdsGameEnv, config: QAgentConfig): \"\"\" Initialize environment and hyperparameters :param",
"GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 =",
"target_next = self.attacker_target_network(s_2).detach() else: target_next = self.defender_target_network(s_2).detach() for i in range(self.config.dqn_config.batch_size): # As",
"list(filter(lambda action: self.env.is_defense_legal(action), actions)) if (np.random.rand() < self.config.epsilon and not eval) \\ or",
"[] for idx, row in enumerate(attacker_obs_1): mean = np.mean(row) if mean != 0:",
"target network. else: a = torch.argmax(target_next[i]).detach() if attacker: target[i][a_attacker_batch[i]] = r_1[i] + self.config.gamma",
"lr = self.attacker_lr_decay.get_lr()[0] # Record episode metrics self.num_train_games += 1 self.num_train_games_total += 1",
"self.env.fully_observed() or \\ (self.env.idsgame_config.game_config.reconnaissance_actions and attacker): if self.config.dqn_config.merged_ad_features: if not self.env.local_view_features() or not",
"True) -> torch.Tensor: \"\"\" Performs a training step of the Deep-Q-learning algorithm (implemented",
"= np.append(attacker_obs[i], neighbor_defense_attributes[i]) if self.config.dqn_config.state_length == 1: return f if len(state) == 0:",
"if len(state) == 0: s = np.array([features] * self.config.dqn_config.state_length) return s state =",
":return: None \"\"\" # Setup logging outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup] step:{},",
"self.attacker_target_network = None self.defender_q_network = None self.defender_target_network = None self.loss_fn = None self.attacker_optimizer",
"torch.device(\"cuda:0\") self.config.logger.info(\"Running on the GPU\") else: device = torch.device(\"cpu\") self.config.logger.info(\"Running on the CPU\")",
"terminal states the Q-target should be equal to the immediate reward if d_batch[i]:",
"self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers,",
"# Move to the next state obs = obs_prime attacker_obs = obs_prime_attacker defender_obs",
"self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if self.config.save_dir is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir +",
"and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") r_1 = r_1.to(device) s_1 = s_1.to(device) s_2 =",
"save_model(self) -> None: \"\"\" Saves the PyTorch Model Weights :return: None \"\"\" time_str",
"= attacker_obs[idx] else: t = row.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1])",
"np.isnan(t).any(): t = attacker_obs[idx] else: t = t.tolist() if not self.env.local_view_features() or not",
"i in range(f.shape[0]): f[i] = np.append(attacker_obs[i], neighbor_defense_attributes[i]) if self.config.dqn_config.state_length == 1: return f",
"np.ndarray: \"\"\" Update approximative Markov state :param attacker_obs: attacker obs :param defender_obs: defender",
"episode_steps = [] episode_avg_attacker_loss = [] episode_avg_defender_loss = [] # Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\"",
"replay memory minibatch = self.buffer.sample(self.config.dqn_config.batch_size) # Perform a gradient descent step of the",
"if episode % self.config.eval_frequency == 0: self.eval(episode) # Save models every <self.config.checkpoint_frequency> episodes",
"of all Q-values. Therefore we initialize the target to the Q-values of the",
"# Zero mean if self.config.dqn_config.zero_mean_features: if not self.env.local_view_features() or not attacker: attacker_obs_1 =",
"defender observation :param state: current state :param attacker: boolean flag whether it is",
"all Q-values. Therefore we initialize the target to the Q-values of the Q-network",
"self.training_step(minibatch, attacker=False) episode_defender_loss += loss.item() # Update metrics attacker_reward, defender_reward = reward obs_prime_attacker,",
":return: None \"\"\" # Initialize models self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation)",
"= False, attacker : bool = True) -> int: \"\"\" Samples an action",
"evaluation with the greedy policy with respect to the learned Q-values :param train_episode:",
"'_defender/grad', value.grad.data.cpu().numpy(), episode) episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] self.num_train_games",
"is originally Neural-fitted Q-iteration but with the addition of a separate target network)",
"replay buffer\") # Perform <self.config.dqn_config.replay_start_size> steps and fill the replay memory for i",
"else: if not self.env.local_view_features() or not attacker: if self.env.idsgame_config.game_config.reconnaissance_actions and attacker: combined_features =",
"= row if np.isnan(t).any(): t = attacker_obs[idx] else: t = t.tolist() if not",
"outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size: {}\".format(0, 0)) # Reset env obs = self.env.reset(update_stats=False) attacker_obs, defender_obs",
"# temp = np.append(attacker_obs, defender_obs) # else: # temp = np.append(attacker_obs, neighbor_defense_attributes) state",
"weights initialization as the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The target network is not",
"0 episode_step = 0 episode_attacker_loss = 0.0 episode_defender_loss = 0.0 while not done:",
"np.linalg.norm(defender_obs) normalized_defender_features = [] for idx, row in enumerate(defender_obs_1): if np.isnan(defender_obs_1).any(): t =",
"gym_idsgame.envs.constants import constants from gym_idsgame.agents.training_agents.models.fnn_w_linear import FNNwithLinear from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent",
"AssertionError(\"Video is set to True but no video_dir is provided, please specify \"",
"= obs for episode in range(self.config.eval_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step",
"self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) # Training",
"Log average eval statistics if log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks)",
"0 self.num_train_hacks = 0 # Update target network every <self.config.dqn_config.target_network_update_freq> episodes if episode",
"self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch",
"\"/\" + time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") return",
"buffer\") # Perform <self.config.dqn_config.replay_start_size> steps and fill the replay memory for i in",
"episode) episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] self.num_train_games = 0",
"algorithm. \"\"\" from typing import Union import numpy as np import time import",
"input mini_batch = self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch,",
"= FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation)",
"= defender_obs[idx] else: if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: t = row.tolist() t.append(defender_obs[idx][-1]) else: t",
"obs_prime episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step += 1 # Move to",
"attacker_obs, defender_obs = obs self.outer_eval.update(1) # Log average eval statistics if log: if",
"logging outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size: {}\".format(0, 0)) # Reset",
"average eval statistics if log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) /",
"enumerate(temp): t = row.tolist() t.append(a_pos[idx]) if self.env.fully_observed(): t.append(det_values[idx]) features.append(t) else: node_ids = attacker_obs[:,",
"GPU\") else: device = torch.device(\"cpu\") self.config.logger.info(\"Running on the CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device)",
"the configuration \"\"\" super(DQNAgent, self).__init__(env, config) self.attacker_q_network = None self.attacker_target_network = None self.defender_q_network",
"r_1 = torch.tensor(r_defender_batch).float() s_1 = torch.tensor(s_defender_batch).float() s_2 = torch.tensor(s2_defender_batch).float() # Move to GPU",
"target network\") if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def eval(self, train_episode,",
"action = (attacker_action, defender_action) # Take a step in the environment obs_prime, reward,",
"== 0: self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if self.config.save_dir is not None: time_str = str(time.time())",
"self.config.render: self.env.render(mode=\"human\") if not self.config.attacker and not self.config.defender: raise AssertionError(\"Must specify whether training",
"or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1",
"function if self.config.dqn_config.loss_fn == \"MSE\": self.loss_fn = torch.nn.MSELoss() elif self.config.dqn_config.loss_fn == \"Huber\": self.loss_fn",
"self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features = attacker_obs[:, # a_obs_len + self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs = attacker_obs[:,",
"GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") state = state.to(device) if attacker:",
"episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss / episode_step) else: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss)",
"defender_obs[:, 0:-1] / np.linalg.norm(defender_obs[:, 0:-1]) else: defender_obs_1 = defender_obs / np.linalg.norm(defender_obs) normalized_defender_features =",
"np.append(attacker_obs, defender_obs) else: if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1] + d_bool_features.shape[1]))",
"environment obs_prime, reward, done, _ = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime =",
"= torch.device(\"cuda:0\") state = state.to(device) if attacker: actions = list(range(self.env.num_attack_actions)) legal_actions = list(filter(lambda",
"\"\"\" state = torch.from_numpy(state.flatten()).float() # Move to GPU if using GPU if torch.cuda.is_available()",
"0:-1] / np.linalg.norm(attacker_obs[:, 0:-1]) else: attacker_obs_1 = attacker_obs[:, 0:-2] / np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features",
"if not self.env.local_view_features() or not attacker: a_pos = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions:",
"Use the target network to compute the Q-values of s' with torch.no_grad(): if",
"return f if len(state) == 0: s = np.array([f] * self.config.dqn_config.state_length) return s",
"computed for the Q-values of the actions taken, not the entire # vector",
"for the Q-values of the actions taken, not the entire # vector of",
"greedy policy with respect to the learned Q-values :param train_episode: the train episode",
"in evaluation mode :param attacker: boolean flag whether running in attacker mode (if",
"running in evaluation mode :param attacker: boolean flag whether running in attacker mode",
"d_bool_features.shape[1])) for i in range(combined_features.shape[0]): f[i] = np.append(combined_features[i], d_bool_features[i]) combined_features = f return",
"a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs = attacker_obs[:, 0:a_obs_len] # else: # a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1",
"self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting training with non-empty result object\") done =",
"if self.config.dqn_config.state_length == 1: return features if len(state) == 0: s = np.array([features]",
"in attacker mode (if false assume defender) :return: The sampled action id \"\"\"",
"+= 1 attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render final frame when",
"s # and then we only update the Q-values for the affected actions",
"in self.defender_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_defender/grad', value.grad.data.cpu().numpy(),",
"using targets produced by target network if self.config.attacker: loss = self.training_step(minibatch, attacker=True) episode_attacker_loss",
"= self.config.save_dir + \"/\" + time_str + \"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(),",
"of the DQN algorithm from the paper 'Human-level control through deep reinforcement learning'",
"= obs # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps =",
"self.config.dqn_config.normalize_features: if not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] / np.linalg.norm(attacker_obs[:,",
"self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step() return loss def get_action(self, state: np.ndarray, eval :",
"= list(filter(lambda action: self.env.is_defense_legal(action), defender_actions)) attacker_action = np.random.choice(legal_attack_actions) defender_action = np.random.choice(legal_defense_actions) action =",
"None self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories = False",
"force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards =",
"= np.random.choice(legal_defense_actions) action = (attacker_action, defender_action) # Take action in the environment obs_prime,",
"the greedy policy with respect to the learned Q-values :param train_episode: the train",
"attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs,",
"+ d_bool_features.shape[1])) for i in range(combined_features.shape[0]): f[i] = np.append(combined_features[i], d_bool_features[i]) combined_features = f",
"reward plus the discounted estimated future # reward when following Q* estimated by",
"obs_prime, reward, done, info = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime,",
"self.defender_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_defender/grad', value.grad.data.cpu().numpy(), episode)",
"/ float(self.num_eval_games) if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(episode,",
"= None self.defender_lr_decay = None self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(),",
"Weights :return: None \"\"\" time_str = str(time.time()) if self.config.save_dir is not None: if",
"to the Q-values of the Q-network for s # and then we only",
"a_pos = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = defender_obs[:, -1] temp =",
"if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: #if not self.env.local_view_features(): a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 defender_obs",
"in range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i]) > 0: temp[i] = neighbor_defense_attributes[i] - attacker_obs[i, 0:-1] features",
"None \"\"\" time_str = str(time.time()) if self.config.save_dir is not None: if self.config.attacker: path",
"current state :param attacker: boolean flag whether it is attacker or not :return:",
"constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked: self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks",
"import Union import numpy as np import time import tqdm import torch from",
"if self.config.dqn_config.zero_mean_features: if not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] else:",
"def update_target_network(self) -> None: \"\"\" Updates the target networks. Delayed targets are used",
"= row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx]) if not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t) features = np.array(features) if",
"target[i][a_attacker_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) else: target[i][a_defender_batch[i]] = r_1[i] + self.config.gamma",
"attacker: self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step() return loss def get_action(self, state:",
"flag whether running in evaluation mode :param attacker: boolean flag whether running in",
"ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent class DQNAgent(QAgent): \"\"\" An implementation of the DQN",
"done = False # Video config if self.config.video: if self.config.video_dir is None: raise",
"and self.env.idsgame_config.game_config.reconnaissance_actions: #if not self.env.local_view_features(): a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 defender_obs = attacker_obs[:,",
"torch.device(\"cuda:0\") state = state.to(device) if attacker: actions = list(range(self.env.num_attack_actions)) legal_actions = list(filter(lambda action:",
"if self.config.attacker: path = self.config.save_dir + \"/\" + time_str + \"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network",
"= self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs =",
"s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch # Convert",
"else: t = row if np.isnan(t).any(): t = attacker_obs[idx] else: t = t.tolist()",
"episodes if episode % self.config.eval_log_frequency == 0 and log: if self.num_eval_hacks > 0:",
"episode) self.tensorboard_writer.add_histogram(tag + '_attacker/grad', value.grad.data.cpu().numpy(), episode) if self.config.defender: for tag, value in self.defender_q_network.named_parameters():",
"state = np.append(state[1:], np.array([attacker_obs]), axis=0) else: state = np.append(state[1:], np.array([defender_obs]), axis=0) return state",
"torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if self.config.defender:",
"self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d =",
"+ \"/\" + time_str + \"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(), path) else:",
"neighbor_defense_attributes = defender_obs if self.env.fully_observed() or \\ (self.env.idsgame_config.game_config.reconnaissance_actions and attacker): if self.config.dqn_config.merged_ad_features: if",
"as input mini_batch = self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch,",
"0: t = row - mean else: t = row if np.isnan(t).any(): t",
"lr = self.config.alpha if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr = self.attacker_lr_decay.get_lr()[0] # Record episode metrics",
"attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"{} Warmup steps completed, replay buffer size:",
"True, update_stats=False) # Save gifs if self.config.gifs and self.config.video: self.env.generate_gif(self.config.gif_dir + \"/episode_\" +",
"self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers,",
"self.config.save_dir + \"/\" + time_str + \"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path)",
"flag whether it is attacker or not :return: new state \"\"\" if attacker",
"not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1 = defender_obs[:, 0:-1] zero_mean_defender_features =",
"= s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network, s_1) except: self.config.logger.warning(\"Error when trying to add network graph to",
"0.0 self.log_metrics(episode, self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr) # Log values and",
"== 0: if attacker: return np.array([attacker_obs] * self.config.dqn_config.state_length) else: return np.array([defender_obs] * self.config.dqn_config.state_length)",
"self.buffer.sample(self.config.dqn_config.batch_size) # Perform a gradient descent step of the Q-network using targets produced",
"episode_defender_rewards = [] episode_steps = [] # Logging self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode',",
"= (attacker_action, defender_action) # Take action in the environment obs_prime, reward, done, info",
"self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) # Log average metrics every <self.config.train_log_frequency> episodes if episode %",
"the learnable # parameters of the layers in the model if self.config.dqn_config.optimizer ==",
"\"/\" + time_str + \"_eval_results_checkpoint.csv\") return self.train_result def update_target_network(self) -> None: \"\"\" Updates",
"or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] / np.linalg.norm(attacker_obs[:, 0:-1]) else: attacker_obs_1 =",
"idx, row in enumerate(temp): t = row.tolist() t.append(a_pos[idx]) if self.env.fully_observed(): t.append(det_values[idx]) features.append(t) else:",
"self.config.checkpoint_freq == 0: self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if self.config.save_dir is not None: time_str =",
"if not self.config.attacker and not self.config.defender: raise AssertionError(\"Must specify whether training an attacker",
"using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") r_1 = r_1.to(device) s_1",
"episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) # Log average metrics every <self.config.train_log_frequency> episodes if episode % self.config.train_log_frequency",
"None: \"\"\" Updates the target networks. Delayed targets are used to stabilize training",
"else: self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step() return loss def get_action(self, state: np.ndarray, eval : bool",
"target to the Q-values of the Q-network for s # and then we",
"len(self.eval_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting eval with non-empty result object\") if self.config.eval_episodes < 1:",
"= t.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t)",
"and attacker): if self.config.dqn_config.merged_ad_features: if not self.env.local_view_features() or not attacker: a_pos = attacker_obs[:,",
"constants.GAME_CONFIG.POSITIVE_REWARD self.num_eval_hacks += 1 self.num_eval_hacks_total +=1 # Log average metrics every <self.config.eval_log_frequency> episodes",
"obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Add transition",
"r_1[i] + self.config.gamma * (target_next[i][a]) # Compute loss if attacker: prediction = self.attacker_q_network(s_1)",
"if self.config.defender: path = self.config.save_dir + \"/\" + time_str + \"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network",
"0: self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if self.config.save_dir is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir",
"+ d_bool_features.shape[1])) for i in range(f.shape[0]): f[i] = np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i]) else: f",
"step for the attacker (otherwise defender) :return: loss \"\"\" # Unpack batch of",
"Logging self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) #",
"a backward pass, and update the weights. if attacker: self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step() else:",
"if episode % self.config.checkpoint_freq == 0: self.save_model() self.env.save_trajectories(checkpoint=True) self.env.save_attack_data(checkpoint=True) if self.config.save_dir is not",
"the GPU\") else: device = torch.device(\"cpu\") self.config.logger.info(\"Running on the CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device)",
"non-empty result object\") if self.config.eval_episodes < 1: return done = False # Video",
"0:-2] / np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features = [] for idx, row in enumerate(attacker_obs_1): if",
"if self.config.attacker: attacker_action = self.get_action(attacker_obs, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, attacker=False) action",
"FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network",
"self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode: {}, Game ended after {} steps\".format(episode, episode_step)) #",
"# Reset environment for the next episode and update game stats done =",
"Log values and gradients of the parameters (histogram summary) to tensorboard if self.config.attacker:",
"+ 1 defender_obs = attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features = attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs",
"normalized_attacker_features.append(t) if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 = defender_obs[:, 0:-1] / np.linalg.norm(defender_obs[:, 0:-1]) else:",
"if self.config.attacker: s_1 = torch.tensor(s_attacker_batch).float() # Move to GPU if using GPU if",
"# Save other game data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if self.config.save_dir is not None: time_str",
"not attacker: # temp = np.append(attacker_obs, defender_obs) # else: # temp = np.append(attacker_obs,",
"for i in range(features.shape[0]): f[i] = np.append(features[i], d_bool_features[i]) features = f if self.config.dqn_config.state_length",
"implementation of the DQN algorithm from the paper 'Human-level control through deep reinforcement",
"config: QAgentConfig): \"\"\" Initialize environment and hyperparameters :param config: the configuration \"\"\" super(DQNAgent,",
"time_str, force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards",
"self.config.video_fps # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = []",
"self.config.render: self.env.render(mode=\"human\") # Decay LR after every episode lr = self.config.alpha if self.config.dqn_config.lr_exp_decay:",
"attacker: a_pos = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = defender_obs[:, -1] temp",
"et. al. : For terminal states the Q-target should be equal to the",
"0.0)) # Training for episode in range(self.config.num_episodes): episode_attacker_reward = 0 episode_defender_reward = 0",
"= list(range(self.env.num_attack_actions)) legal_actions = list(filter(lambda action: self.env.is_attack_legal(action), actions)) else: actions = list(range(self.env.num_defense_actions)) legal_actions",
"np.array([features] * self.config.dqn_config.state_length) return s state = np.append(state[1:], np.array([features]), axis=0) return state else:",
"attacker: state = np.append(state[1:], np.array([attacker_obs]), axis=0) else: state = np.append(state[1:], np.array([defender_obs]), axis=0) return",
"initialization as the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The target network is not trainable",
"IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig from gym_idsgame.envs.idsgame_env import IdsGameEnv from gym_idsgame.agents.dao.experiment_result import ExperimentResult",
"Update metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward += attacker_reward",
"self.tensorboard_writer.add_histogram(tag + '_attacker/grad', value.grad.data.cpu().numpy(), episode) if self.config.defender: for tag, value in self.defender_q_network.named_parameters(): tag",
"if attacker: return np.array(attacker_obs) else: return np.array(defender_obs) if len(state) == 0: if attacker:",
"self.num_train_games_total else: self.train_hack_probability = 0.0 self.train_cumulative_hack_probability = 0.0 self.log_metrics(episode, self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps,",
"and metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward += attacker_reward",
"else: device = torch.device(\"cpu\") self.config.logger.info(\"Running on the CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device) #",
"# The target network is not trainable it is only used for predictions,",
"q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The target network is not trainable it is only",
"self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path) if self.config.defender: path = self.config.save_dir + \"/\"",
"# Get attacker and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, attacker=True) if",
"action: self.env.is_defense_legal(action), actions)) if (np.random.rand() < self.config.epsilon and not eval) \\ or (eval",
"episode_avg_defender_loss.append(episode_defender_loss / episode_step) else: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) # Log",
"if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) # Log average metrics every <self.config.train_log_frequency> episodes if episode",
"IDSGameEnv that implements the DQN algorithm. \"\"\" from typing import Union import numpy",
"self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network =",
"s_1 = s_1.to(device) s_2 = s_2.to(device) # Set target baseline. We only want",
"t.append(defender_obs[idx][-1]) else: t = row normalized_defender_features.append(t) attacker_obs = np.array(normalized_attacker_features) defender_obs = np.array(normalized_defender_features) if",
"if self.config.attacker: for tag, value in self.attacker_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(),",
"completed if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) self.config.logger.info(\"Eval episode: {}, Game ended after {} steps\".format(episode,",
"is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_train_results_checkpoint.csv\")",
"compute the Q-values of s' with torch.no_grad(): if attacker: target_next = self.attacker_target_network(s_2).detach() else:",
"step of the Q-network using targets produced by target network if self.config.attacker: loss",
"attacker_reward episode_defender_reward += defender_reward episode_step += 1 # Move to the next state",
"in range(features.shape[0]): f[i] = np.append(features[i], d_bool_features[i]) features = f if self.config.dqn_config.state_length == 1:",
"attacker: prediction = self.attacker_q_network(s_1) else: prediction = self.defender_q_network(s_1) loss = self.loss_fn(prediction, target) #",
"epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\" \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) # Training for",
"if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") self.config.logger.info(\"Running on the GPU\") else: device",
"+ time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") return self.train_result",
"return legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self) -> ExperimentResult: \"\"\" Runs the DQN algorithm :return: Experiment",
"row normalized_defender_features.append(t) attacker_obs = np.array(normalized_attacker_features) defender_obs = np.array(normalized_defender_features) if self.env.local_view_features() and attacker: if",
"the environment obs_prime, reward, done, _ = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime",
"torch.tensor(s2_defender_batch).float() # Move to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device",
"targets if attacker: target = self.attacker_q_network(s_1) else: target = self.defender_q_network(s_1) # Use the",
"0:-1] / np.linalg.norm(defender_obs[:, 0:-1]) else: defender_obs_1 = defender_obs / np.linalg.norm(defender_obs) normalized_defender_features = []",
"num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) # Specify device if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") self.config.logger.info(\"Running",
"= attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features = attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs = attacker_obs[:, 0:a_obs_len]",
"add network graph to tensorboard\") def initialize_models(self) -> None: \"\"\" Initialize models :return:",
"self.env.render(mode=\"human\") if not self.config.attacker and not self.config.defender: raise AssertionError(\"Must specify whether training an",
"transition to replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Sample random mini_batch",
"tag, value in self.defender_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag +",
"self.env = IdsGameMonitor(self.env, self.config.video_dir + \"/\" + time_str, force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps",
"not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] / np.linalg.norm(attacker_obs[:, 0:-1]) else:",
"attacker=True, state=[]) obs_state_d_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) #",
"np.ndarray, np.ndarray], attacker: bool = True) -> torch.Tensor: \"\"\" Performs a training step",
"i in range(self.config.dqn_config.batch_size): # As defined by Mnih et. al. : For terminal",
"+ \"/\" + time_str + \"_attacker_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path) if",
"self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero mean if self.config.dqn_config.zero_mean_features: if not self.env.local_view_features() or not",
"for node in range(attacker_obs.shape[0]): id = int(attacker_obs[node][-1]) neighbor_defense_attributes[node] = defender_obs[id] else: neighbor_defense_attributes =",
"+ \"/\" + time_str + \"_eval_results_checkpoint.csv\") # Reset environment for the next episode",
"DQN algorithm. \"\"\" from typing import Union import numpy as np import time",
"if self.config.dqn_config.normalize_features: if not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1] /",
"if not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t) features = np.array(features) if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((features.shape[0],",
"+ time_str + \"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(), path) else: self.config.logger.warning(\"Save path",
"else: self.config.logger.warning(\"Save path not defined, not saving Q-networks to disk\") def update_state(self, attacker_obs:",
"boolean flag whether running in evaluation mode :param attacker: boolean flag whether running",
"= defender_obs[:, 0:] - attacker_obs[:, 0:-1] features = [] for idx, row in",
"torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") r_1 = r_1.to(device) s_1 = s_1.to(device) s_2",
"random strategy :return: None \"\"\" # Setup logging outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0)",
"action in the environment obs_prime, reward, done, info = self.env.step(action) attacker_obs_prime, defender_obs_prime =",
"GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") state =",
"tensorboard if self.config.attacker: for tag, value in self.attacker_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag,",
"if self.config.video_dir is None: raise AssertionError(\"Video is set to True but no video_dir",
"a epsilon-greedy strategy using the Q-network :param state: the state to sample an",
"self.log_metrics(episode, self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, episode_avg_attacker_loss, episode_avg_defender_loss, lr=lr) # Log values and gradients",
"for i in range(f.shape[0]): f[i] = np.append(np.append(attacker_obs[i], neighbor_defense_attributes[i]), d_bool_features[i]) else: f = np.zeros((attacker_obs.shape[0],",
"self.defender_q_network.to(device) self.defender_target_network.to(device) # Set the target network to use the same weights initialization",
":param attacker: boolean flag whether it is attacker or not :return: new state",
"np.ndarray = None, defender_obs: np.ndarray = None, state: np.ndarray = None, attacker: bool",
"update_state(self, attacker_obs: np.ndarray = None, defender_obs: np.ndarray = None, state: np.ndarray = None,",
"using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") state = state.to(device) if",
"every episode lr = self.config.alpha if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr = self.attacker_lr_decay.get_lr()[0] # Record",
"# Log average metrics every <self.config.eval_log_frequency> episodes if episode % self.config.eval_log_frequency == 0",
"# Update metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward +=",
"self.defender_lr_decay = None self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories",
"track of logging :param log: whether to log the result :return: None \"\"\"",
"Q-network to: {}\".format(path)) torch.save(self.attacker_q_network.state_dict(), path) if self.config.defender: path = self.config.save_dir + \"/\" +",
"np.array([f] * self.config.dqn_config.state_length) return s # if not self.env.local_view_features() or not attacker: #",
"for i in range(self.config.dqn_config.batch_size): # As defined by Mnih et. al. : For",
"\"/\" + time_str + \"_eval_results_checkpoint.csv\") # Reset environment for the next episode and",
"attacker: if not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes = np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for node in range(attacker_obs.shape[0]): id",
"train_episode, log=True) -> ExperimentResult: \"\"\" Performs evaluation with the greedy policy with respect",
"torch.device(\"cuda:0\") r_1 = r_1.to(device) s_1 = s_1.to(device) s_2 = s_2.to(device) # Set target",
"= row normalized_defender_features.append(t) attacker_obs = np.array(normalized_attacker_features) defender_obs = np.array(normalized_defender_features) if self.env.local_view_features() and attacker:",
"if not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes = np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for node in range(attacker_obs.shape[0]): id =",
"defender_action = 0 # Get attacker and defender actions if self.config.attacker: attacker_action =",
"range(f.shape[0]): f[i] = np.append(attacker_obs[i], neighbor_defense_attributes[i]) if self.config.dqn_config.state_length == 1: return f if len(state)",
"else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1 = defender_obs[:, 0:-1] zero_mean_defender_features = [] for idx,",
"torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if self.config.defender: s_1 = torch.tensor(s_defender_batch).float() # Move",
"if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") r_1 = r_1.to(device)",
"to compute the Q-values of s' with torch.no_grad(): if attacker: target_next = self.attacker_target_network(s_2).detach()",
"if (np.random.rand() < self.config.epsilon and not eval) \\ or (eval and np.random.random() <",
"self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_attacker/grad', value.grad.data.cpu().numpy(), episode) if self.config.defender: for tag, value",
"self.config.logger.info(\"Starting Evaluation\") time_str = str(time.time()) self.num_eval_games = 0 self.num_eval_hacks = 0 if len(self.eval_result.avg_episode_steps)",
"self.num_train_hacks += 1 self.num_train_hacks_total += 1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if episode_step > 0: if",
"attacker_obs_1 = attacker_obs[:, 0:-1] / np.linalg.norm(attacker_obs[:, 0:-1]) else: attacker_obs_1 = attacker_obs[:, 0:-2] /",
"Update state information and metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime",
"= 0 if len(self.eval_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting eval with non-empty result object\") if",
"normalized_defender_features.append(t) attacker_obs = np.array(normalized_attacker_features) defender_obs = np.array(normalized_defender_features) if self.env.local_view_features() and attacker: if not",
"steps completed, replay buffer size: {}\".format( self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close() try: # Add network",
"self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) # Specify device if torch.cuda.is_available() and self.config.dqn_config.gpu: device =",
"the state to sample an action for :param eval: boolean flag whether running",
"= None, defender_obs: np.ndarray = None, state: np.ndarray = None, attacker: bool =",
":param state: the state to sample an action for :param eval: boolean flag",
"Complete\") # Final evaluation (for saving Gifs etc) self.eval(self.config.num_episodes-1, log=False) # Save Q-networks",
"range(attacker_obs.shape[0]): id = int(attacker_obs[node][-1]) neighbor_defense_attributes[node] = defender_obs[id] else: neighbor_defense_attributes = defender_obs if self.env.fully_observed()",
"+= 1 if self.env.state.hacked: self.num_train_hacks += 1 self.num_train_hacks_total += 1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if",
"false assume defender) :return: The sampled action id \"\"\" state = torch.from_numpy(state.flatten()).float() #",
"Record episode metrics self.num_train_games += 1 self.num_train_games_total += 1 if self.env.state.hacked: self.num_train_hacks +=",
"to eval mode # to turn of dropouts, batch norms, gradient computations etc.",
"no video_dir is provided, please specify \" \"the video_dir argument\") self.env = IdsGameMonitor(self.env,",
":param eval: boolean flag whether running in evaluation mode :param attacker: boolean flag",
"The target network is not trainable it is only used for predictions, therefore",
"t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1 = defender_obs[:, 0:-1] zero_mean_defender_features = [] for idx, row in",
"obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"{} Warmup steps",
"def get_action(self, state: np.ndarray, eval : bool = False, attacker : bool =",
"+ '_defender/grad', value.grad.data.cpu().numpy(), episode) episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = []",
"attacker_obs[:, 0:a_obs_len] if not attacker and self.env.local_view_features(): attacker_obs = self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions)",
"if self.config.gifs and self.config.video: self.env.generate_gif(self.config.gif_dir + \"/episode_\" + str(train_episode) + \"_\" + time_str",
"tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_attacker/grad', value.grad.data.cpu().numpy(), episode) if self.config.defender: for",
"self.env.save_attack_data(checkpoint=True) if self.config.save_dir is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\" +",
"in enumerate(defender_obs_1): mean = np.mean(row) if mean != 0: t = row -",
"t = attacker_obs[idx] else: t = t.tolist() if not self.env.local_view_features() or not attacker:",
"temp = np.append(attacker_obs, defender_obs) # else: # temp = np.append(attacker_obs, neighbor_defense_attributes) state =",
"state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_train.update(1) # Anneal epsilon",
"self.config.dqn_config.state_length) return s # if not self.env.local_view_features() or not attacker: # temp =",
"_ = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[])",
"self.num_train_hacks_total / self.num_train_games_total else: self.train_hack_probability = 0.0 self.train_cumulative_hack_probability = 0.0 self.log_metrics(episode, self.train_result, episode_attacker_rewards,",
"np.array(combined_features) return np.append(attacker_obs, defender_obs) else: if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1]",
"if self.env.fully_observed(): t.append(det_values[idx]) features.append(t) else: node_ids = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values",
"Neural-fitted Q-iteration but with the addition of a separate target network) \"\"\" def",
"defender_obs_1 = defender_obs[:, 0:-1] / np.linalg.norm(defender_obs[:, 0:-1]) else: defender_obs_1 = defender_obs / np.linalg.norm(defender_obs)",
"i % self.config.train_log_frequency == 0: log_str = \"[Warmup] step:{}, buffer_size: {}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str)",
"= r_1[i] + self.config.gamma * (target_next[i][a]) else: target[i][a_defender_batch[i]] = r_1[i] + self.config.gamma *",
"Record episode metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) # Update eval stats self.num_eval_games +=1 self.num_eval_games_total",
"Warmup steps completed, replay buffer size: {}\".format( self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close() try: # Add",
"else: act_values = self.defender_q_network(state) return legal_actions[torch.argmax(act_values[legal_actions]).item()] def train(self) -> ExperimentResult: \"\"\" Runs the",
"if self.config.attacker: loss = self.training_step(minibatch, attacker=True) episode_attacker_loss += loss.item() if self.config.defender: loss =",
"= list(filter(lambda action: self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions = list(filter(lambda action: self.env.is_defense_legal(action), defender_actions)) attacker_action =",
"mini_batch = self.buffer.sample(self.config.dqn_config.batch_size) s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch",
"self.update_state(attacker_obs_prime, defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Add transition to replay",
"loss.backward() self.defender_optimizer.step() return loss def get_action(self, state: np.ndarray, eval : bool = False,",
"-> int: \"\"\" Samples an action according to a epsilon-greedy strategy using the",
"attacker_action = self.get_action(attacker_obs, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, attacker=False) action = (attacker_action,",
"obs = self.env.reset(update_stats=True) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[])",
"if self.env.state.detected: self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD if self.env.state.hacked: self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD",
"trainable it is only used for predictions, therefore we set it to eval",
"self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1) self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0,",
"= attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = neighbor_defense_attributes[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions:",
"= np.append(row, defender_obs[idx]) combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features: combined_features = np.array(combined_features) f = np.zeros( (combined_features.shape[0],",
"if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def training_step(self, mini_batch:",
"np.isnan(t).any(): t = defender_obs[idx] else: t = t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs = np.array(zero_mean_attacker_features)",
"IdsGameMonitor(self.env, self.config.video_dir + \"/\" + time_str, force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps # Tracking",
"Training\") self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting training with non-empty result object\") done",
"attacker_obs[:, 0:-2] zero_mean_attacker_features = [] for idx, row in enumerate(attacker_obs_1): mean = np.mean(row)",
"= torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif self.config.dqn_config.optimizer == \"SGD\": self.attacker_optimizer =",
"f = np.zeros( (combined_features.shape[0], combined_features.shape[1] + d_bool_features.shape[1])) for i in range(combined_features.shape[0]): f[i] =",
"a random strategy :return: None \"\"\" # Setup logging outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup',",
"sample an action for :param eval: boolean flag whether running in evaluation mode",
"action: self.env.is_attack_legal(action), actions)) else: actions = list(range(self.env.num_defense_actions)) legal_actions = list(filter(lambda action: self.env.is_defense_legal(action), actions))",
"as the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The target network is not trainable it",
"else: t = row normalized_defender_features.append(t) attacker_obs = np.array(normalized_attacker_features) defender_obs = np.array(normalized_defender_features) if self.env.local_view_features()",
"return state else: if self.config.dqn_config.state_length == 1: if attacker: return np.array(attacker_obs) else: return",
"node_ids = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = neighbor_defense_attributes[:, -1] if not",
"QAgentConfig from gym_idsgame.envs.idsgame_env import IdsGameEnv from gym_idsgame.agents.dao.experiment_result import ExperimentResult from gym_idsgame.envs.constants import constants",
"self.config.logger.warning(\"Error when trying to add network graph to tensorboard\") def initialize_models(self) -> None:",
"import IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig from gym_idsgame.envs.idsgame_env import IdsGameEnv from gym_idsgame.agents.dao.experiment_result import",
"= defender_obs[idx] else: t = t.tolist() t.append(defender_obs[idx][-1]) zero_mean_defender_features.append(t) attacker_obs = np.array(zero_mean_attacker_features) defender_obs =",
"if len(state) == 0: if attacker: return np.array([attacker_obs] * self.config.dqn_config.state_length) else: return np.array([defender_obs]",
"into torch tensors and set Q-network in train mode and target network in",
"self.save_model() # Save other game data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if self.config.save_dir is not None:",
"self.defender_q_network.train() self.defender_q_network.eval() r_1 = torch.tensor(r_defender_batch).float() s_1 = torch.tensor(s_defender_batch).float() s_2 = torch.tensor(s2_defender_batch).float() # Move",
"the model if self.config.dqn_config.optimizer == \"Adam\": self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(),",
"Perform <self.config.dqn_config.replay_start_size> steps and fill the replay memory for i in range(self.config.dqn_config.replay_start_size): if",
"== 0: if self.num_train_games > 0 and self.num_train_games_total > 0: self.train_hack_probability = self.num_train_hacks",
"whether it is attacker or not :return: new state \"\"\" if attacker and",
"return s state = np.append(state[1:], np.array([features]), axis=0) return state else: if not self.env.local_view_features()",
"= [] episode_defender_rewards = [] episode_steps = [] episode_avg_attacker_loss = [] episode_avg_defender_loss =",
"self.config.dqn_config.state_length) if attacker: state = np.append(state[1:], np.array([attacker_obs]), axis=0) else: state = np.append(state[1:], np.array([defender_obs]),",
"to tensorboard if self.config.attacker: for tag, value in self.attacker_q_network.named_parameters(): tag = tag.replace('.', '/')",
"self.config.alpha if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr = self.attacker_lr_decay.get_lr()[0] # Record episode metrics self.num_train_games +=",
"episode_step) else: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) # Log average metrics",
"0 episode_defender_reward = 0 episode_step = 0 while not done: if self.config.eval_render: self.env.render()",
"r_1.to(device) s_1 = s_1.to(device) s_2 = s_2.to(device) # Set target baseline. We only",
"Convert batch into torch tensors and set Q-network in train mode and target",
"Training for episode in range(self.config.num_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step =",
"[] episode_steps = [] # Logging self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1) self.outer_eval.set_description_str(",
"> 0: temp[i] = neighbor_defense_attributes[i] - attacker_obs[i, 0:-1] features = [] for idx,",
"evaluation mode :param attacker: boolean flag whether running in attacker mode (if false",
"stats self.num_eval_games +=1 self.num_eval_games_total += 1 if self.env.state.detected: self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward +=",
"Select random attacker and defender actions attacker_actions = list(range(self.env.num_attack_actions)) defender_actions = list(range(self.env.num_defense_actions)) legal_attack_actions",
"len(self.train_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting training with non-empty result object\") done = False obs",
"Decay LR after every episode lr = self.config.alpha if self.config.dqn_config.lr_exp_decay: self.attacker_lr_decay.step() lr =",
"self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The target network is not trainable it is only used for",
"outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) # Select random attacker and defender actions attacker_actions = list(range(self.env.num_attack_actions)) defender_actions",
"def training_step(self, mini_batch: Union[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray], attacker:",
"action for :param eval: boolean flag whether running in evaluation mode :param attacker:",
"obs_prime_defender = obs_prime episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward episode_step += 1 #",
"t = row.tolist() t.append(defender_obs[idx][-1]) else: t = row normalized_defender_features.append(t) attacker_obs = np.array(normalized_attacker_features) defender_obs",
"if self.config.defender: for tag, value in self.defender_q_network.named_parameters(): tag = tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(),",
"eval: boolean flag whether running in evaluation mode :param attacker: boolean flag whether",
"= [] episode_steps = [] self.num_train_games = 0 self.num_train_hacks = 0 # Update",
"mean = np.mean(row) if mean != 0: t = row - mean else:",
"defender_obs = np.array(normalized_defender_features) if self.env.local_view_features() and attacker: if not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes = np.zeros((attacker_obs.shape[0],",
"None, attacker: bool = True) -> np.ndarray: \"\"\" Update approximative Markov state :param",
"config: the configuration \"\"\" super(DQNAgent, self).__init__(env, config) self.attacker_q_network = None self.attacker_target_network = None",
"the Q-network using targets produced by target network if self.config.attacker: loss = self.training_step(minibatch,",
"to stabilize training and partially remedy the problem with non-stationary targets in RL",
"= np.append(features[i], d_bool_features[i]) features = f if self.config.dqn_config.state_length == 1: return features if",
"import SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig from gym_idsgame.envs.idsgame_env import",
"(self.env.idsgame_config.game_config.reconnaissance_actions and attacker): if self.config.dqn_config.merged_ad_features: if not self.env.local_view_features() or not attacker: a_pos =",
"action = (attacker_action, defender_action) # Take action in the environment obs_prime, reward, done,",
"state obs = obs_prime attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render final",
"torch.tensor(s_attacker_batch).float() s_2 = torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train() self.defender_q_network.eval() r_1 = torch.tensor(r_defender_batch).float() s_1 = torch.tensor(s_defender_batch).float()",
"list(filter(lambda action: self.env.is_defense_legal(action), defender_actions)) attacker_action = np.random.choice(legal_attack_actions) defender_action = np.random.choice(legal_defense_actions) action = (attacker_action,",
"0 # Get attacker and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, eval=True,",
"attacker_obs[:, 0:-1] / np.linalg.norm(attacker_obs[:, 0:-1]) else: attacker_obs_1 = attacker_obs[:, 0:-2] / np.linalg.norm(attacker_obs[:, 0:-2])",
"{}) self.env.idsgame_config.save_trajectories = False self.env.idsgame_config.save_attack_stats = False def warmup(self) -> None: \"\"\" A",
"step:{}, buffer_size: {}\".format(0, 0)) # Reset env obs = self.env.reset(update_stats=False) attacker_obs, defender_obs =",
"is attacker or not :return: new state \"\"\" if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: #if",
"self.config.attacker: attacker_action = self.get_action(attacker_obs, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, attacker=False) action =",
"attacker_obs[idx] else: t = t.tolist() if not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else:",
"np.array(attacker_obs) else: return np.array(defender_obs) if len(state) == 0: if attacker: return np.array([attacker_obs] *",
"0.0 while not done: if self.config.render: self.env.render(mode=\"human\") if not self.config.attacker and not self.config.defender:",
"0: self.eval(episode) # Save models every <self.config.checkpoint_frequency> episodes if episode % self.config.checkpoint_freq ==",
"torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer, gamma=self.config.dqn_config.lr_decay_rate) def training_step(self, mini_batch: Union[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,",
"Add transition to replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Sample random",
"state = np.append(state[1:], np.array([features]), axis=0) return state else: if not self.env.local_view_features() or not",
"else: a = torch.argmax(target_next[i]).detach() if attacker: target[i][a_attacker_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a])",
"device = torch.device(\"cuda:0\") state = state.to(device) if attacker: actions = list(range(self.env.num_attack_actions)) legal_actions =",
"done: if self.config.render: self.env.render(mode=\"human\") if not self.config.attacker and not self.config.defender: raise AssertionError(\"Must specify",
"episode_avg_attacker_loss.append(episode_attacker_loss) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss) episode_steps.append(episode_step) # Log average metrics every <self.config.train_log_frequency> episodes if",
"self.config.dqn_config.optimizer == \"SGD\": self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else: raise",
"whether running in attacker mode (if false assume defender) :return: The sampled action",
"self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {}) self.env.idsgame_config.save_trajectories = False self.env.idsgame_config.save_attack_stats = False def warmup(self) -> None:",
"defender_action = self.get_action(defender_obs, eval=True, attacker=False) action = (attacker_action, defender_action) # Take a step",
"legal_attack_actions = list(filter(lambda action: self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions = list(filter(lambda action: self.env.is_defense_legal(action), defender_actions)) attacker_action",
"if attacker: target[i][a_attacker_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) else: target[i][a_defender_batch[i]] = r_1[i]",
"row in enumerate(attacker_obs): combined_row = np.append(row, defender_obs[idx]) combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features: combined_features = np.array(combined_features)",
":return: None \"\"\" self.config.logger.info(\"Updating target network\") if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict())",
"of transitions from replay memory minibatch = self.buffer.sample(self.config.dqn_config.batch_size) # Perform a gradient descent",
"# Sample random mini_batch of transitions from replay memory minibatch = self.buffer.sample(self.config.dqn_config.batch_size) #",
"- attacker_obs[:, 0:-1] features = [] for idx, row in enumerate(temp): t =",
"self.env.local_view_features() or not attacker: a_pos = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values =",
"result :return: None \"\"\" self.config.logger.info(\"Starting Evaluation\") time_str = str(time.time()) self.num_eval_games = 0 self.num_eval_hacks",
"self.outer_eval.set_description_str( \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\ \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0, 0.0, 0.0)) # Eval obs",
"Get attacker and defender actions if self.config.attacker: attacker_action = self.get_action(attacker_obs, eval=True, attacker=True) if",
"dataformats = \"HWC\") # Reset for new eval episode done = False obs",
"self.outer_train.update(1) # Anneal epsilon linearly self.anneal_epsilon() self.config.logger.info(\"Training Complete\") # Final evaluation (for saving",
"np.array(zero_mean_defender_features) # Normalize if self.config.dqn_config.normalize_features: if not self.env.local_view_features() or not attacker: attacker_obs_1 =",
"s_1 = torch.tensor(s_attacker_batch).float() # Move to GPU if using GPU if torch.cuda.is_available() and",
"of a separate target network) \"\"\" def __init__(self, env:IdsGameEnv, config: QAgentConfig): \"\"\" Initialize",
"memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Move to new state obs =",
"# Take action in the environment obs_prime, reward, done, info = self.env.step(action) attacker_obs_prime,",
"self.config.video_fps) # Add frames to tensorboard for idx, frame in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) +",
"target) # Zero gradients, perform a backward pass, and update the weights. if",
"defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs, attacker=True, state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs,",
"episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) # Update eval stats self.num_eval_games +=1 self.num_eval_games_total += 1 if self.env.state.detected:",
"bool = True) -> np.ndarray: \"\"\" Update approximative Markov state :param attacker_obs: attacker",
"= attacker_obs[:, 0:-2] / np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features = [] for idx, row in",
"to use for the training step :param attacker: whether doing a training step",
"reward, done, info = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime,",
"self.attacker_optimizer.zero_grad() loss.backward() self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step() return loss def get_action(self, state: np.ndarray,",
"using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.defender_q_network,",
"row in enumerate(defender_obs_1): if np.isnan(defender_obs_1).any(): t = defender_obs[idx] else: if attacker and self.env.idsgame_config.game_config.reconnaissance_actions:",
"# Anneal epsilon linearly self.anneal_epsilon() self.config.logger.info(\"Training Complete\") # Final evaluation (for saving Gifs",
"and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") self.config.logger.info(\"Running on the GPU\") else: device = torch.device(\"cpu\")",
"np.sum(neighbor_defense_attributes[i]) > 0: temp[i] = neighbor_defense_attributes[i] - attacker_obs[i, 0:-1] features = [] for",
"#if not self.env.local_view_features(): a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 defender_obs = attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if",
"self.defender_optimizer = None self.attacker_lr_decay = None self.defender_lr_decay = None self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer",
"self.get_action(defender_obs, attacker=False) action = (attacker_action, defender_action) # Take a step in the environment",
"in enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any(): t = attacker_obs[idx] else: t = row.tolist() if not",
"episode_attacker_reward = 0 episode_defender_reward = 0 episode_step = 0 episode_attacker_loss = 0.0 episode_defender_loss",
"+ \"/\" + time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\")",
"self.config.dqn_config.optimizer == \"Adam\": self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif self.config.dqn_config.optimizer",
"to replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Move to new state",
"+= 1 self.num_eval_hacks_total +=1 # Log average metrics every <self.config.eval_log_frequency> episodes if episode",
"attacker_obs[i, 0:-1] features = [] for idx, row in enumerate(temp): t = row.tolist()",
"not self.env.local_view_features() or not attacker: a_pos = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values",
"strategy :return: None \"\"\" # Setup logging outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup]",
"in PyTorch) :param mini_batch: a minibatch to use for the training step :param",
"self.defender_target_network = None self.loss_fn = None self.attacker_optimizer = None self.defender_optimizer = None self.attacker_lr_decay",
"# Add transition to replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Move",
"keep track of logging :param log: whether to log the result :return: None",
"mode if attacker: self.attacker_q_network.train() self.attacker_target_network.eval() r_1 = torch.tensor(r_attacker_batch).float() s_1 = torch.tensor(s_attacker_batch).float() s_2 =",
"self.attacker_target_network(s_2).detach() else: target_next = self.defender_target_network(s_2).detach() for i in range(self.config.dqn_config.batch_size): # As defined by",
"episodes if episode % self.config.dqn_config.target_network_update_freq == 0: self.update_target_network() # Run evaluation every <self.config.eval_frequency>",
"if self.config.dqn_config.optimizer == \"Adam\": self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif",
"range(combined_features.shape[0]): f[i] = np.append(combined_features[i], d_bool_features[i]) combined_features = f return np.array(combined_features) return np.append(attacker_obs, defender_obs)",
"if np.isnan(defender_obs_1).any(): t = defender_obs[idx] else: if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: t = row.tolist()",
"* (target_next[i][a]) # Compute loss if attacker: prediction = self.attacker_q_network(s_1) else: prediction =",
"\"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") return self.train_result def update_target_network(self) ->",
"attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1 = defender_obs[:, 0:-1] zero_mean_defender_features = []",
"Add network graph to tensorboard with a sample batch as input mini_batch =",
"and attacker: if not self.env.idsgame_config.game_config.reconnaissance_actions: neighbor_defense_attributes = np.zeros((attacker_obs.shape[0], defender_obs.shape[1])) for node in range(attacker_obs.shape[0]):",
"self.config.dqn_config.state_length == 1: return f if len(state) == 0: s = np.array([f] *",
"obs self.outer_eval.update(1) # Log average eval statistics if log: if self.num_eval_hacks > 0:",
"Q-network to: {}\".format(path)) torch.save(self.defender_q_network.state_dict(), path) else: self.config.logger.warning(\"Save path not defined, not saving Q-networks",
"loss if attacker: prediction = self.attacker_q_network(s_1) else: prediction = self.defender_q_network(s_1) loss = self.loss_fn(prediction,",
"= np.random.choice(legal_attack_actions) defender_action = np.random.choice(legal_defense_actions) action = (attacker_action, defender_action) # Take action in",
"episode metrics self.num_train_games += 1 self.num_train_games_total += 1 if self.env.state.hacked: self.num_train_hacks += 1",
"attacker=False, state=[]) obs = (obs_state_a, obs_state_d) attacker_obs, defender_obs = obs self.outer_eval.update(1) # Log",
"(target_next[i][a]) # Compute loss if attacker: prediction = self.attacker_q_network(s_1) else: prediction = self.defender_q_network(s_1)",
"np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1] + d_bool_features.shape[1])) for i in range(f.shape[0]): f[i] = np.append(np.append(attacker_obs[i],",
"= False obs = self.env.reset(update_stats=True) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs,",
"self.env.idsgame_config.reconnaissance_bool_features: d_bool_features = attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs = attacker_obs[:, 0:a_obs_len] # else: # a_obs_len",
"int(attacker_obs[node][-1]) neighbor_defense_attributes[node] = defender_obs[id] else: neighbor_defense_attributes = defender_obs if self.env.fully_observed() or \\ (self.env.idsgame_config.game_config.reconnaissance_actions",
"axis=0) return state else: if not self.env.local_view_features() or not attacker: if self.env.idsgame_config.game_config.reconnaissance_actions and",
"Q-target should be the immediate reward plus the discounted estimated future # reward",
"raise AssertionError(\"Video is set to True but no video_dir is provided, please specify",
"= 0 defender_action = 0 # Get attacker and defender actions if self.config.attacker:",
"the training step :param attacker: whether doing a training step for the attacker",
"self.num_train_games = 0 self.num_train_hacks = 0 # Update target network every <self.config.dqn_config.target_network_update_freq> episodes",
"0:] - attacker_obs[:, 0:-1] features = [] for idx, row in enumerate(temp): t",
"/ float( self.num_eval_games_total) self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval = True, update_stats=False) #",
"combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features: combined_features = np.array(combined_features) f = np.zeros( (combined_features.shape[0], combined_features.shape[1] + d_bool_features.shape[1]))",
"0.0, 0.0)) # Training for episode in range(self.config.num_episodes): episode_attacker_reward = 0 episode_defender_reward =",
"self.config.logger.info(\"Running on the GPU\") else: device = torch.device(\"cpu\") self.config.logger.info(\"Running on the CPU\") self.attacker_q_network.to(device)",
"+ \"/episode_\" + str(train_episode) + \"_\" + time_str + \".gif\", self.config.video_fps) # Add",
"- mean else: t = row if np.isnan(t).any(): t = attacker_obs[idx] else: t",
"attacker=False) action = (attacker_action, defender_action) # Take a step in the environment obs_prime,",
"to the immediate reward if d_batch[i]: if attacker: target[i][a_attacker_batch[i]] = r_1[i] else: target[i][a_defender_batch[i]]",
"# Default initialization attacker_action = 0 defender_action = 0 # Get attacker and",
"s_2 = s_2.to(device) # Set target baseline. We only want the loss to",
"self.eval(self.config.num_episodes-1, log=False) # Save Q-networks self.save_model() # Save other game data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False)",
"target = self.defender_q_network(s_1) # Use the target network to compute the Q-values of",
"= list(filter(lambda action: self.env.is_defense_legal(action), actions)) if (np.random.rand() < self.config.epsilon and not eval) \\",
"s_1 = torch.tensor(s_defender_batch).float() # Move to GPU if using GPU if torch.cuda.is_available() and",
"attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, attacker=False) action = (attacker_action, defender_action) # Take",
"PyTorch Model Weights :return: None \"\"\" time_str = str(time.time()) if self.config.save_dir is not",
"model.parameters() in the optimizer constructor will contain the learnable # parameters of the",
"self.attacker_lr_decay.get_lr()[0] # Record episode metrics self.num_train_games += 1 self.num_train_games_total += 1 if self.env.state.hacked:",
"else: neighbor_defense_attributes = defender_obs if self.env.fully_observed() or \\ (self.env.idsgame_config.game_config.reconnaissance_actions and attacker): if self.config.dqn_config.merged_ad_features:",
"mean if self.config.dqn_config.zero_mean_features: if not self.env.local_view_features() or not attacker: attacker_obs_1 = attacker_obs[:, 0:-1]",
"the attacker (otherwise defender) :return: loss \"\"\" # Unpack batch of transitions from",
"np.append(attacker_obs, neighbor_defense_attributes) state = np.append(state[1:], np.array([f]), axis=0) return state else: if self.config.dqn_config.state_length ==",
"== 0: self.update_target_network() # Run evaluation every <self.config.eval_frequency> episodes if episode % self.config.eval_frequency",
"= 0 self.num_eval_hacks = 0 if len(self.eval_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting eval with non-empty",
"0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games) if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total)",
"discounted estimated future # reward when following Q* estimated by the target network.",
"therefore we set it to eval mode # to turn of dropouts, batch",
"hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim,",
"CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device) # Set the target network to use the",
"obs_state_d_prime) # Update state information and metrics attacker_reward, defender_reward = reward obs_prime_attacker, obs_prime_defender",
"time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\"",
"in enumerate(temp): t = row.tolist() t.append(a_pos[idx]) if self.env.fully_observed(): t.append(det_values[idx]) features.append(t) else: node_ids =",
"else: temp = np.full(neighbor_defense_attributes.shape, -1) for i in range(len(neighbor_defense_attributes)): if np.sum(neighbor_defense_attributes[i]) > 0:",
"= s_1.to(device) s_2 = s_2.to(device) # Set target baseline. We only want the",
"get_action(self, state: np.ndarray, eval : bool = False, attacker : bool = True)",
"gradients, perform a backward pass, and update the weights. if attacker: self.attacker_optimizer.zero_grad() loss.backward()",
"\"/\" + time_str + \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") #",
"reward, done, _ = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime,",
"r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch # Convert batch into torch",
"network to compute the Q-values of s' with torch.no_grad(): if attacker: target_next =",
"= (obs_state_a, obs_state_d) self.config.logger.info(\"Starting warmup phase to fill replay buffer\") # Perform <self.config.dqn_config.replay_start_size>",
"tag.replace('.', '/') self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), episode) self.tensorboard_writer.add_histogram(tag + '_defender/grad', value.grad.data.cpu().numpy(), episode) episode_attacker_rewards = []",
"= None, attacker: bool = True) -> np.ndarray: \"\"\" Update approximative Markov state",
"Update approximative Markov state :param attacker_obs: attacker obs :param defender_obs: defender observation :param",
"of the Q-network using targets produced by target network if self.config.attacker: loss =",
"= obs_prime_attacker defender_obs = obs_prime_defender # Render final frame when game completed if",
"to use the same weights initialization as the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The",
"state=[]) obs_state_d = self.update_state(attacker_obs, defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"Starting warmup",
"attacker: actions = list(range(self.env.num_attack_actions)) legal_actions = list(filter(lambda action: self.env.is_attack_legal(action), actions)) else: actions =",
"Performs evaluation with the greedy policy with respect to the learned Q-values :param",
"\\ or (eval and np.random.random() < self.config.eval_epsilon): return np.random.choice(legal_actions) with torch.no_grad(): if attacker:",
"self.env.render() time.sleep(self.config.eval_sleep) # Default initialization attacker_action = 0 defender_action = 0 # Get",
"np.random.random() < self.config.eval_epsilon): return np.random.choice(legal_actions) with torch.no_grad(): if attacker: act_values = self.attacker_q_network(state) else:",
"the problem with non-stationary targets in RL with function approximation. :return: None \"\"\"",
"== 0: s = np.array([features] * self.config.dqn_config.state_length) return s state = np.append(state[1:], np.array([features]),",
"evaluation every <self.config.eval_frequency> episodes if episode % self.config.eval_frequency == 0: self.eval(episode) # Save",
"0 # Update target network every <self.config.dqn_config.target_network_update_freq> episodes if episode % self.config.dqn_config.target_network_update_freq ==",
"torch.tensor(s_defender_batch).float() # Move to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device",
"if attacker: prediction = self.attacker_q_network(s_1) else: prediction = self.defender_q_network(s_1) loss = self.loss_fn(prediction, target)",
":return: None \"\"\" self.config.logger.info(\"Starting Evaluation\") time_str = str(time.time()) self.num_eval_games = 0 self.num_eval_hacks =",
"= torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha) else: raise ValueError(\"Optimizer not recognized\") # LR decay if self.config.dqn_config.lr_exp_decay:",
"0:-1]) else: attacker_obs_1 = attacker_obs[:, 0:-2] / np.linalg.norm(attacker_obs[:, 0:-2]) normalized_attacker_features = [] for",
"+= defender_reward episode_step += 1 # Move to the next state obs =",
"+= 1 self.num_train_games_total += 1 if self.env.state.hacked: self.num_train_hacks += 1 self.num_train_hacks_total += 1",
"new eval episode done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs",
"np.isnan(defender_obs_1).any(): t = defender_obs[idx] else: if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: t = row.tolist() t.append(defender_obs[idx][-1])",
"t = row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx]) if not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t) features = np.array(features)",
"+ \"_train_results_checkpoint.csv\") self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\") # Reset environment for",
"= r_1[i] # For non terminal states the Q-target should be the immediate",
"attacker and self.env.local_view_features(): attacker_obs = self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero mean if",
"1: return features if len(state) == 0: s = np.array([features] * self.config.dqn_config.state_length) return",
"episode to keep track of logging :param log: whether to log the result",
"defender agent\") # Default initialization attacker_action = 0 defender_action = 0 # Get",
"self.env.idsgame_config.game_config.reconnaissance_actions: det_values = neighbor_defense_attributes[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: temp = neighbor_defense_attributes[:, 0:-1] -",
"provided, please specify \" \"the video_dir argument\") self.env = IdsGameMonitor(self.env, self.config.video_dir + \"/\"",
"Updates the target networks. Delayed targets are used to stabilize training and partially",
"+ self.env.idsgame_config.game_config.num_attack_types:] # attacker_obs = attacker_obs[:, 0:a_obs_len] if not attacker and self.env.local_view_features(): attacker_obs",
"row in enumerate(attacker_obs_1): if np.isnan(attacker_obs_1).any(): t = attacker_obs[idx] else: t = row.tolist() if",
"= 0 episode_defender_reward = 0 episode_step = 0 episode_attacker_loss = 0.0 episode_defender_loss =",
"None \"\"\" self.config.logger.info(\"Updating target network\") if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval()",
"= np.append(state[1:], np.array([f]), axis=0) return state else: if self.config.dqn_config.state_length == 1: if attacker:",
"info = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True, state=[])",
"self.config.logger.info(\"Updating target network\") if self.config.attacker: self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.attacker_target_network.eval() if self.config.defender: self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) self.defender_target_network.eval() def eval(self,",
"the next state obs = obs_prime attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender #",
"from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig from gym_idsgame.envs.idsgame_env import IdsGameEnv from",
"= self.get_action(attacker_obs, eval=True, attacker=True) if self.config.defender: defender_action = self.get_action(defender_obs, eval=True, attacker=False) action =",
"0: self.config.logger.warning(\"starting eval with non-empty result object\") if self.config.eval_episodes < 1: return done",
"-> torch.Tensor: \"\"\" Performs a training step of the Deep-Q-learning algorithm (implemented in",
"0: temp[i] = neighbor_defense_attributes[i] - attacker_obs[i, 0:-1] features = [] for idx, row",
"defender) :return: loss \"\"\" # Unpack batch of transitions from the replay memory",
"\" \"the video_dir argument\") self.env = IdsGameMonitor(self.env, self.config.video_dir + \"/\" + time_str, force=True,",
"0 and log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games) if",
"t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) normalized_attacker_features.append(t) if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 = defender_obs[:, 0:-1] / np.linalg.norm(defender_obs[:,",
"Move to GPU if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\")",
"the same weights initialization as the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict()) self.defender_target_network.load_state_dict(self.defender_q_network.state_dict()) # The target network",
"/ float( self.num_eval_games_total) self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps, eval=True, update_stats=True) self.env.close() self.config.logger.info(\"Evaluation Complete\")",
"= 0.0 while not done: if self.config.render: self.env.render(mode=\"human\") if not self.config.attacker and not",
"return loss def get_action(self, state: np.ndarray, eval : bool = False, attacker :",
"s2_defender_batch = mini_batch if self.config.attacker: s_1 = torch.tensor(s_attacker_batch).float() # Move to GPU if",
"det_values = neighbor_defense_attributes[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: temp = neighbor_defense_attributes[:, 0:-1] - attacker_obs[:,",
"on the CPU\") self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device) # Set the target network to",
"% self.config.dqn_config.target_network_update_freq == 0: self.update_target_network() # Run evaluation every <self.config.eval_frequency> episodes if episode",
"state: current state :param attacker: boolean flag whether it is attacker or not",
"% self.config.train_log_frequency == 0: log_str = \"[Warmup] step:{}, buffer_size: {}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str)",
"+= loss.item() if self.config.defender: loss = self.training_step(minibatch, attacker=False) episode_defender_loss += loss.item() # Update",
":return: The sampled action id \"\"\" state = torch.from_numpy(state.flatten()).float() # Move to GPU",
"episode_step = 0 episode_attacker_loss = 0.0 episode_defender_loss = 0.0 while not done: if",
"= IdsGameMonitor(self.env, self.config.video_dir + \"/\" + time_str, force=True, video_frequency=self.config.video_frequency) self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps #",
"enumerate(temp): t = row.tolist() t.append(node_ids[idx]) #t.append(node_reachable[idx]) if not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t) features =",
"for episode in range(self.config.eval_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step = 0",
"Q-network in train mode and target network in eval mode if attacker: self.attacker_q_network.train()",
"0 if len(self.eval_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting eval with non-empty result object\") if self.config.eval_episodes",
"if done: obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs obs_state_a = self.update_state(attacker_obs, defender_obs,",
"state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Update state information and metrics attacker_reward, defender_reward",
"path = self.config.save_dir + \"/\" + time_str + \"_defender_q_network.pt\" self.config.logger.info(\"Saving Q-network to: {}\".format(path))",
"= self.config.video_fps # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps =",
"[] for idx, row in enumerate(defender_obs_1): mean = np.mean(row) if mean != 0:",
"torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") state = state.to(device) if attacker: actions =",
"= np.zeros((features.shape[0], features.shape[1] + d_bool_features.shape[1])) for i in range(features.shape[0]): f[i] = np.append(features[i], d_bool_features[i])",
"-> ExperimentResult: \"\"\" Performs evaluation with the greedy policy with respect to the",
"attacker_obs = attacker_obs[:, 0:a_obs_len] if not attacker and self.env.local_view_features(): attacker_obs = self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config,",
"{}\".format( self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close() try: # Add network graph to tensorboard with a",
"obs for episode in range(self.config.eval_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step =",
"if attacker: target = self.attacker_q_network(s_1) else: target = self.defender_q_network(s_1) # Use the target",
"the addition of a separate target network) \"\"\" def __init__(self, env:IdsGameEnv, config: QAgentConfig):",
"attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions: det_values = defender_obs[:, -1] temp = defender_obs[:, 0:-1]",
"fill replay buffer\") # Perform <self.config.dqn_config.replay_start_size> steps and fill the replay memory for",
"self.env.idsgame_config.game_config.num_attack_types + 1 defender_obs = attacker_obs[:, a_obs_len:a_obs_len+self.env.idsgame_config.game_config.num_attack_types] if self.env.idsgame_config.reconnaissance_bool_features: d_bool_features = attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:]",
"torch.Tensor: \"\"\" Performs a training step of the Deep-Q-learning algorithm (implemented in PyTorch)",
"else: # temp = np.append(attacker_obs, neighbor_defense_attributes) state = np.append(state[1:], np.array([f]), axis=0) return state",
"actions = list(range(self.env.num_attack_actions)) legal_actions = list(filter(lambda action: self.env.is_attack_legal(action), actions)) else: actions = list(range(self.env.num_defense_actions))",
"\"\"\" if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: #if not self.env.local_view_features(): a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1",
"update_stats=True) self.env.close() self.config.logger.info(\"Evaluation Complete\") return self.eval_result def save_model(self) -> None: \"\"\" Saves the",
"<self.config.eval_frequency> episodes if episode % self.config.eval_frequency == 0: self.eval(episode) # Save models every",
"None self.defender_lr_decay = None self.tensorboard_writer = SummaryWriter(self.config.dqn_config.tensorboard_dir) self.buffer = ReplayBuffer(config.dqn_config.replay_memory_size) self.initialize_models() self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {})",
"with the addition of a separate target network) \"\"\" def __init__(self, env:IdsGameEnv, config:",
"import IdsGameEnv from gym_idsgame.agents.dao.experiment_result import ExperimentResult from gym_idsgame.envs.constants import constants from gym_idsgame.agents.training_agents.models.fnn_w_linear import",
"in range(combined_features.shape[0]): f[i] = np.append(combined_features[i], d_bool_features[i]) combined_features = f return np.array(combined_features) return np.append(attacker_obs,",
"state :param attacker_obs: attacker obs :param defender_obs: defender observation :param state: current state",
"self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) # Default initialization attacker_action = 0 defender_action = 0 #",
"attacker or not :return: new state \"\"\" if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: #if not",
"if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((features.shape[0], features.shape[1] + d_bool_features.shape[1])) for i in range(features.shape[0]): f[i]",
"lr=self.config.alpha) elif self.config.dqn_config.optimizer == \"SGD\": self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.SGD(self.defender_q_network.parameters(), lr=self.config.alpha)",
"self.attacker_q_network.to(device) self.attacker_target_network.to(device) self.defender_q_network.to(device) self.defender_target_network.to(device) # Set the target network to use the same",
"self.attacker_target_network.eval() r_1 = torch.tensor(r_attacker_batch).float() s_1 = torch.tensor(s_attacker_batch).float() s_2 = torch.tensor(s2_attacker_batch).float() else: self.defender_q_network.train() self.defender_q_network.eval()",
"is set to True but no video_dir is provided, please specify \" \"the",
"model if self.config.dqn_config.optimizer == \"Adam\": self.attacker_optimizer = torch.optim.Adam(self.attacker_q_network.parameters(), lr=self.config.alpha) self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha)",
"self.config.logger.info(\"Starting Warmup\") self.warmup() self.config.logger.info(\"Starting Training\") self.config.logger.info(self.config.to_str()) if len(self.train_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting training with",
"mini_batch if self.config.attacker: s_1 = torch.tensor(s_attacker_batch).float() # Move to GPU if using GPU",
"mode (if false assume defender) :return: The sampled action id \"\"\" state =",
"= self.num_train_hacks_total / self.num_train_games_total else: self.train_hack_probability = 0.0 self.train_cumulative_hack_probability = 0.0 self.log_metrics(episode, self.train_result,",
"used for predictions, therefore we set it to eval mode # to turn",
"actions attacker_actions = list(range(self.env.num_attack_actions)) defender_actions = list(range(self.env.num_defense_actions)) legal_attack_actions = list(filter(lambda action: self.env.is_attack_legal(action), attacker_actions))",
"state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"Starting warmup phase to fill replay buffer\") #",
"or defender agent\") # Default initialization attacker_action = 0 defender_action = 0 #",
"SummaryWriter from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig from gym_idsgame.envs.idsgame_env import IdsGameEnv",
"episode % self.config.eval_log_frequency == 0 and log: if self.num_eval_hacks > 0: self.eval_hack_probability =",
"attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Update state information and metrics attacker_reward,",
"a_attacker_batch, a_defender_batch, r_attacker_batch, r_defender_batch, \\ d_batch, s2_attacker_batch, s2_defender_batch = mini_batch # Convert batch",
"done, info = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True,",
"Q-values :param train_episode: the train episode to keep track of logging :param log:",
"self.env.close() try: # Add network graph to tensorboard with a sample batch as",
"0.0 episode_defender_loss = 0.0 while not done: if self.config.render: self.env.render(mode=\"human\") if not self.config.attacker",
"self.env.idsgame_config.save_attack_stats = False def warmup(self) -> None: \"\"\" A warmup without any learning",
"is not None: if self.config.attacker: path = self.config.save_dir + \"/\" + time_str +",
"obs self.outer_train.update(1) # Anneal epsilon linearly self.anneal_epsilon() self.config.logger.info(\"Training Complete\") # Final evaluation (for",
"+= 1 episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if episode_step > 0: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender:",
"the optimizer constructor will contain the learnable # parameters of the layers in",
"\"\"\" # Setup logging outer_warmup = tqdm.tqdm(total=self.config.dqn_config.replay_start_size, desc='Warmup', position=0) outer_warmup.set_description_str(\"[Warmup] step:{}, buffer_size: {}\".format(0,",
"self.config.logger.info(\"{} Warmup steps completed, replay buffer size: {}\".format( self.config.dqn_config.replay_start_size, self.buffer.size())) self.env.close() try: #",
"self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step() return loss def get_action(self, state: np.ndarray, eval : bool =",
"0 self.num_eval_hacks = 0 if len(self.eval_result.avg_episode_steps) > 0: self.config.logger.warning(\"starting eval with non-empty result",
"idx, frame in enumerate(self.env.episode_frames): self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" + str(idx), frame, global_step=train_episode, dataformats =",
"attacker_obs[:, a_obs_len+self.env.idsgame_config.game_config.num_attack_types:] attacker_obs = attacker_obs[:, 0:a_obs_len] # else: # a_obs_len = self.env.idsgame_config.game_config.num_attack_types +",
"temp = defender_obs[:, 0:-1] - attacker_obs[:, 0:-1] else: temp = defender_obs[:, 0:] -",
"normalized_defender_features = [] for idx, row in enumerate(defender_obs_1): if np.isnan(defender_obs_1).any(): t = defender_obs[idx]",
"self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") r_1 = r_1.to(device) s_1 = s_1.to(device) s_2 = s_2.to(device)",
"r_1 = r_1.to(device) s_1 = s_1.to(device) s_2 = s_2.to(device) # Set target baseline.",
"batch norms, gradient computations etc. self.attacker_target_network.eval() self.defender_target_network.eval() # Construct loss function if self.config.dqn_config.loss_fn",
"time_str + \"_eval_results_checkpoint.csv\") return self.train_result def update_target_network(self) -> None: \"\"\" Updates the target",
"if episode % self.config.dqn_config.target_network_update_freq == 0: self.update_target_network() # Run evaluation every <self.config.eval_frequency> episodes",
"device = torch.device(\"cuda:0\") s_1 = s_1.to(device) self.tensorboard_writer.add_graph(self.attacker_q_network, s_1) if self.config.defender: s_1 = torch.tensor(s_defender_batch).float()",
"# to turn of dropouts, batch norms, gradient computations etc. self.attacker_target_network.eval() self.defender_target_network.eval() #",
"t.append(a_pos[idx]) if self.env.fully_observed(): t.append(det_values[idx]) features.append(t) else: node_ids = attacker_obs[:, -1] if not self.env.idsgame_config.game_config.reconnaissance_actions:",
"= float(self.num_eval_hacks) / float(self.num_eval_games) if self.num_eval_games_total > 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float(",
"# Set the target network to use the same weights initialization as the",
"self.config.logger.info(\"Evaluation Complete\") return self.eval_result def save_model(self) -> None: \"\"\" Saves the PyTorch Model",
"state.to(device) if attacker: actions = list(range(self.env.num_attack_actions)) legal_actions = list(filter(lambda action: self.env.is_attack_legal(action), actions)) else:",
"done, _ = self.env.step(action) attacker_obs_prime, defender_obs_prime = obs_prime obs_state_a_prime = self.update_state(attacker_obs_prime, defender_obs_prime, attacker=True,",
"metrics self.num_train_games += 1 self.num_train_games_total += 1 if self.env.state.hacked: self.num_train_hacks += 1 self.num_train_hacks_total",
"= s_2.to(device) # Set target baseline. We only want the loss to be",
"addition of a separate target network) \"\"\" def __init__(self, env:IdsGameEnv, config: QAgentConfig): \"\"\"",
"= self.defender_target_network(s_2).detach() for i in range(self.config.dqn_config.batch_size): # As defined by Mnih et. al.",
"Initialize environment and hyperparameters :param config: the configuration \"\"\" super(DQNAgent, self).__init__(env, config) self.attacker_q_network",
"specify whether training an attacker agent or defender agent\") # Default initialization attacker_action",
"= attacker_obs[:, 0:-1] / np.linalg.norm(attacker_obs[:, 0:-1]) else: attacker_obs_1 = attacker_obs[:, 0:-2] / np.linalg.norm(attacker_obs[:,",
"#t.append(node_reachable[idx]) if not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t) features = np.array(features) if self.env.idsgame_config.reconnaissance_bool_features: f =",
"self.config.video: self.env.generate_gif(self.config.gif_dir + \"/episode_\" + str(train_episode) + \"_\" + time_str + \".gif\", self.config.video_fps)",
"= self.num_train_hacks / self.num_train_games self.train_cumulative_hack_probability = self.num_train_hacks_total / self.num_train_games_total else: self.train_hack_probability = 0.0",
"0:-1] - attacker_obs[:, 0:-1] else: temp = defender_obs[:, 0:] - attacker_obs[:, 0:-1] features",
"metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = [] episode_avg_attacker_loss = []",
"not attacker and self.env.local_view_features(): attacker_obs = self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero mean",
"temp = np.append(attacker_obs, neighbor_defense_attributes) state = np.append(state[1:], np.array([f]), axis=0) return state else: if",
"step :param attacker: whether doing a training step for the attacker (otherwise defender)",
"= attacker_obs[:, 0:a_obs_len] # else: # a_obs_len = self.env.idsgame_config.game_config.num_attack_types + 1 # defender_obs",
"self.defender_target_network.eval() def eval(self, train_episode, log=True) -> ExperimentResult: \"\"\" Performs evaluation with the greedy",
"(obs_state_a_prime, obs_state_d_prime) # Add transition to replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime)",
"self.num_eval_games +=1 self.num_eval_games_total += 1 if self.env.state.detected: self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD",
"d_batch, s2_attacker_batch, s2_defender_batch = mini_batch if self.config.attacker: s_1 = torch.tensor(s_attacker_batch).float() # Move to",
"loss.backward() self.attacker_optimizer.step() else: self.defender_optimizer.zero_grad() loss.backward() self.defender_optimizer.step() return loss def get_action(self, state: np.ndarray, eval",
"not self.env.idsgame_config.game_config.reconnaissance_actions: t.append(det_values[idx]) features.append(t) features = np.array(features) if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((features.shape[0], features.shape[1]",
"f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1])) for i in range(f.shape[0]): f[i] = np.append(attacker_obs[i],",
"defender_reward = reward obs_prime_attacker, obs_prime_defender = obs_prime episode_attacker_reward += attacker_reward episode_defender_reward += defender_reward",
"self.env.idsgame_config.game_config.num_attack_types + 1 # defender_obs = attacker_obs[:, # a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types] # if",
"lr=self.config.alpha) self.defender_optimizer = torch.optim.Adam(self.defender_q_network.parameters(), lr=self.config.alpha) elif self.config.dqn_config.optimizer == \"SGD\": self.attacker_optimizer = torch.optim.SGD(self.attacker_q_network.parameters(), lr=self.config.alpha)",
"= self.env.state.get_attacker_observation( self.env.idsgame_config.game_config.network_config, local_view=False, reconnaissance=self.env.idsgame_config.reconnaissance_actions) # Zero mean if self.config.dqn_config.zero_mean_features: if not self.env.local_view_features()",
"t = defender_obs[idx] else: if attacker and self.env.idsgame_config.game_config.reconnaissance_actions: t = row.tolist() t.append(defender_obs[idx][-1]) else:",
"= str(time.time()) if self.config.save_dir is not None: if self.config.attacker: path = self.config.save_dir +",
"= np.append(attacker_obs, neighbor_defense_attributes) state = np.append(state[1:], np.array([f]), axis=0) return state else: if self.config.dqn_config.state_length",
"# a_obs_len:a_obs_len + self.env.idsgame_config.game_config.num_attack_types] # if self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features = attacker_obs[:, # a_obs_len",
"will contain the learnable # parameters of the layers in the model if",
"bool = True) -> int: \"\"\" Samples an action according to a epsilon-greedy",
"Save gifs if self.config.gifs and self.config.video: self.env.generate_gif(self.config.gif_dir + \"/episode_\" + str(train_episode) + \"_\"",
"Gifs etc) self.eval(self.config.num_episodes-1, log=False) # Save Q-networks self.save_model() # Save other game data",
"attacker: attacker_obs_1 = attacker_obs[:, 0:-1] / np.linalg.norm(attacker_obs[:, 0:-1]) else: attacker_obs_1 = attacker_obs[:, 0:-2]",
"* self.config.dqn_config.state_length) return s state = np.append(state[1:], np.array([features]), axis=0) return state else: if",
"# Final evaluation (for saving Gifs etc) self.eval(self.config.num_episodes-1, log=False) # Save Q-networks self.save_model()",
"defender_obs, attacker=False, state=[]) obs = (obs_state_a, obs_state_d) self.config.logger.info(\"Starting warmup phase to fill replay",
"gym_idsgame.envs.idsgame_env import IdsGameEnv from gym_idsgame.agents.dao.experiment_result import ExperimentResult from gym_idsgame.envs.constants import constants from gym_idsgame.agents.training_agents.models.fnn_w_linear",
"np.random.choice(legal_actions) with torch.no_grad(): if attacker: act_values = self.attacker_q_network(state) else: act_values = self.defender_q_network(state) return",
"= 0 while not done: if self.config.eval_render: self.env.render() time.sleep(self.config.eval_sleep) # Default initialization attacker_action",
"self.get_action(defender_obs, eval=True, attacker=False) action = (attacker_action, defender_action) # Take a step in the",
"are used to stabilize training and partially remedy the problem with non-stationary targets",
"episode_avg_defender_loss, lr=lr) # Log values and gradients of the parameters (histogram summary) to",
"> 0: self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float( self.num_eval_games_total) self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps,",
"else: target[i][a_defender_batch[i]] = r_1[i] + self.config.gamma * (target_next[i][a]) # Compute loss if attacker:",
"= 0 episode_step = 0 episode_attacker_loss = 0.0 episode_defender_loss = 0.0 while not",
"attacker_obs: np.ndarray = None, defender_obs: np.ndarray = None, state: np.ndarray = None, attacker:",
"torch.no_grad(): if attacker: target_next = self.attacker_target_network(s_2).detach() else: target_next = self.defender_target_network(s_2).detach() for i in",
"obs # Tracking metrics episode_attacker_rewards = [] episode_defender_rewards = [] episode_steps = []",
"or not attacker: if self.env.idsgame_config.game_config.reconnaissance_actions and attacker: combined_features = [] for idx, row",
"if using GPU if torch.cuda.is_available() and self.config.dqn_config.gpu: device = torch.device(\"cuda:0\") state = state.to(device)",
"defender_obs.shape[1])) for node in range(attacker_obs.shape[0]): id = int(attacker_obs[node][-1]) neighbor_defense_attributes[node] = defender_obs[id] else: neighbor_defense_attributes",
"= neighbor_defense_attributes[i] - attacker_obs[i, 0:-1] features = [] for idx, row in enumerate(temp):",
"self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if self.config.save_dir is not None: time_str = str(time.time()) self.train_result.to_csv(self.config.save_dir + \"/\"",
"defender_obs_prime, attacker=False, state=[]) obs_prime = (obs_state_a_prime, obs_state_d_prime) # Update state information and metrics",
"gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor from gym_idsgame.agents.training_agents.q_learning.q_agent_config import QAgentConfig from gym_idsgame.envs.idsgame_env import IdsGameEnv from gym_idsgame.agents.dao.experiment_result",
"np.append(attacker_obs, defender_obs) # else: # temp = np.append(attacker_obs, neighbor_defense_attributes) state = np.append(state[1:], np.array([f]),",
"= list(range(self.env.num_defense_actions)) legal_attack_actions = list(filter(lambda action: self.env.is_attack_legal(action), attacker_actions)) legal_defense_actions = list(filter(lambda action: self.env.is_defense_legal(action),",
"episode in range(self.config.num_episodes): episode_attacker_reward = 0 episode_defender_reward = 0 episode_step = 0 episode_attacker_loss",
"/ np.linalg.norm(defender_obs[:, 0:-1]) else: defender_obs_1 = defender_obs / np.linalg.norm(defender_obs) normalized_defender_features = [] for",
"steps\".format(episode, episode_step)) # Record episode metrics episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) episode_steps.append(episode_step) # Update eval stats",
"d_bool_features.shape[1])) for i in range(features.shape[0]): f[i] = np.append(features[i], d_bool_features[i]) features = f if",
"a separate target network) \"\"\" def __init__(self, env:IdsGameEnv, config: QAgentConfig): \"\"\" Initialize environment",
"# Unpack batch of transitions from the replay memory s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch,",
"for :param eval: boolean flag whether running in evaluation mode :param attacker: boolean",
"partially remedy the problem with non-stationary targets in RL with function approximation. :return:",
"np.array(features) if self.env.idsgame_config.reconnaissance_bool_features: f = np.zeros((features.shape[0], features.shape[1] + d_bool_features.shape[1])) for i in range(features.shape[0]):",
"return np.array(attacker_obs) else: return np.array(defender_obs) if len(state) == 0: if attacker: return np.array([attacker_obs]",
"self.loss_fn = torch.nn.SmoothL1Loss() else: raise ValueError(\"Loss function not recognized\") # Define Optimizer. The",
"0.0, 0.0, 0.0, 0.0)) # Eval obs = self.env.reset(update_stats=False) attacker_obs, defender_obs = obs",
"log: if self.num_eval_hacks > 0: self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games) if self.num_eval_games_total >",
":param attacker: boolean flag whether running in attacker mode (if false assume defender)",
"neighbor_defense_attributes[i]), d_bool_features[i]) else: f = np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1])) for i in range(f.shape[0]):",
"<self.config.eval_log_frequency> episodes if episode % self.config.eval_log_frequency == 0 and log: if self.num_eval_hacks >",
"\"_eval_frames/\" + str(idx), frame, global_step=train_episode, dataformats = \"HWC\") # Reset for new eval",
"defender_obs) # else: # temp = np.append(attacker_obs, neighbor_defense_attributes) state = np.append(state[1:], np.array([f]), axis=0)",
"Take action in the environment obs_prime, reward, done, info = self.env.step(action) attacker_obs_prime, defender_obs_prime",
"idx, row in enumerate(attacker_obs): combined_row = np.append(row, defender_obs[idx]) combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features: combined_features =",
"models self.attacker_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.attacker_target_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim,",
"FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.attacker_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_q_network = FNNwithLinear(self.config.dqn_config.input_dim, self.config.dqn_config.defender_output_dim, self.config.dqn_config.hidden_dim, num_hidden_layers=self.config.dqn_config.num_hidden_layers, hidden_activation=self.config.dqn_config.hidden_activation) self.defender_target_network",
"+ self.env.idsgame_config.game_config.num_attack_types] # if self.env.idsgame_config.reconnaissance_bool_features: # d_bool_features = attacker_obs[:, # a_obs_len + self.env.idsgame_config.game_config.num_attack_types:]",
"episode_attacker_rewards.append(episode_attacker_reward) episode_defender_rewards.append(episode_defender_reward) if episode_step > 0: if self.config.attacker: episode_avg_attacker_loss.append(episode_attacker_loss/episode_step) if self.config.defender: episode_avg_defender_loss.append(episode_defender_loss /",
"from gym_idsgame.agents.training_agents.q_learning.experience_replay.replay_buffer import ReplayBuffer from gym_idsgame.agents.training_agents.q_learning.q_agent import QAgent class DQNAgent(QAgent): \"\"\" An implementation",
"the Q-target should be the immediate reward plus the discounted estimated future #",
"the target network to use the same weights initialization as the q-network self.attacker_target_network.load_state_dict(self.attacker_q_network.state_dict())",
"# Save Q-networks self.save_model() # Save other game data self.env.save_trajectories(checkpoint=False) self.env.save_attack_data(checkpoint=False) if self.config.save_dir",
"np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray], attacker: bool = True) -> torch.Tensor:",
"Unpack batch of transitions from the replay memory s_attacker_batch, s_defender_batch, a_attacker_batch, a_defender_batch, r_attacker_batch,",
"training with non-empty result object\") done = False obs = self.env.reset(update_stats=False) attacker_obs, defender_obs",
"self.config.eval_episodes < 1: return done = False # Video config if self.config.video: if",
"\"[Warmup] step:{}, buffer_size: {}\".format(i, self.buffer.size()) outer_warmup.set_description_str(log_str) self.config.logger.info(log_str) # Select random attacker and defender",
"+ \".gif\", self.config.video_fps) # Add frames to tensorboard for idx, frame in enumerate(self.env.episode_frames):",
"not self.env.local_view_features() or not attacker: t.append(attacker_obs[idx][-1]) else: t.append(attacker_obs[idx][-2]) t.append(attacker_obs[idx][-1]) zero_mean_attacker_features.append(t) defender_obs_1 = defender_obs[:,",
"enumerate(attacker_obs): combined_row = np.append(row, defender_obs[idx]) combined_features.append(combined_row) if self.env.idsgame_config.reconnaissance_bool_features: combined_features = np.array(combined_features) f =",
"# Add transition to replay memory self.buffer.add_tuple(obs, action, reward, done, obs_prime) # Sample",
"defender_obs_1 = defender_obs[:, 0:-1] zero_mean_defender_features = [] for idx, row in enumerate(defender_obs_1): mean",
"defender_reward episode_step += 1 attacker_obs = obs_prime_attacker defender_obs = obs_prime_defender # Render final",
"and self.env.idsgame_config.game_config.reconnaissance_actions: defender_obs_1 = defender_obs[:, 0:-1] / np.linalg.norm(defender_obs[:, 0:-1]) else: defender_obs_1 = defender_obs",
"= np.zeros((attacker_obs.shape[0], attacker_obs.shape[1] + neighbor_defense_attributes.shape[1])) for i in range(f.shape[0]): f[i] = np.append(attacker_obs[i], neighbor_defense_attributes[i])",
"(np.random.rand() < self.config.epsilon and not eval) \\ or (eval and np.random.random() < self.config.eval_epsilon):",
"not self.env.local_view_features() or not attacker: # temp = np.append(attacker_obs, defender_obs) # else: #"
] |
[
"setup( name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(), description=\"A web framework that is silly\",",
"find_packages import SillyServer setup( name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(), description=\"A web framework",
"url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(), description=\"A web framework that is silly\", keywords=\"silly server\", test_suite=\"nose.collector\" )",
"# coding=utf-8 from setuptools import setup, find_packages import SillyServer setup( name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__,",
"python # coding=utf-8 from setuptools import setup, find_packages import SillyServer setup( name=\"SillyServer\", version=SillyServer.__VERSION__,",
"name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(), description=\"A web framework that is silly\", keywords=\"silly",
"SillyServer setup( name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(), description=\"A web framework that is",
"!/usr/bin/env python # coding=utf-8 from setuptools import setup, find_packages import SillyServer setup( name=\"SillyServer\",",
"author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(), description=\"A web framework that is silly\", keywords=\"silly server\", test_suite=\"nose.collector\"",
"# !/usr/bin/env python # coding=utf-8 from setuptools import setup, find_packages import SillyServer setup(",
"coding=utf-8 from setuptools import setup, find_packages import SillyServer setup( name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__,",
"setup, find_packages import SillyServer setup( name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(), description=\"A web",
"setuptools import setup, find_packages import SillyServer setup( name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(),",
"version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(), description=\"A web framework that is silly\", keywords=\"silly server\",",
"import setup, find_packages import SillyServer setup( name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(), description=\"A",
"from setuptools import setup, find_packages import SillyServer setup( name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__,",
"import SillyServer setup( name=\"SillyServer\", version=SillyServer.__VERSION__, author=SillyServer.__AUTHOR__, url=SillyServer.__URL__, license=SillyServer.__LICENSE__, packages=find_packages(), description=\"A web framework that"
] |
[
"session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items) == 2 assert page.count == 2 assert page.items[0].text == 'annotation",
"1) annotation2 = file.add_sticky_note(\"annotation 2\", 100, 200, 1) annotation3 = file.add_sticky_note(\"annotation 3\", 100,",
"doc.attach_file('fixtures/resources/files/basket.txt') annotation = file.add_sticky_note(\"annotation 1\", 100, 200, 1) sleep(2) file.add_sticky_note(\"annotation 2\", 100, 200,",
"1\", 100, 200, 1) sleep(2) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100,",
"= doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\", 100, 200, 1) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation",
"1) first_page = session.annotations.list(page_size=2) assert len(first_page.items) == 2 assert first_page.count == 3 assert",
"assert page.count == 1 annotation = page.items[0] assert annotation.text == \"A nice annotation\"",
"with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc = create_document(session) file = doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\", 100, 200, 1)",
"sleep(2) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) page =",
"<reponame>membranepotential/mendeley-python-sdk<filename>test/manual/annotations/test_list_annotations.py from test import get_user_session, cassette, sleep from test.resources.documents import create_document, delete_all_documents def",
"first_page.items[1].text == 'annotation 1' second_page = first_page.next_page assert len(second_page.items) == 1 assert second_page.count",
"3 assert second_page.items[0].text == 'annotation 3' def test_should_list_annotations_modified_since(): session = get_user_session() delete_all_documents() with",
"== 3 assert first_page.items[0].text == 'annotation 2' assert first_page.items[1].text == 'annotation 1' second_page",
"= get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt')",
"100, 200, 1) page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items) == 2 assert page.count ==",
"cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc = create_document(session) file = doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\", 100, 200, 1) file.add_sticky_note(\"annotation",
"== 2 assert page.items[0].text == 'annotation 2' assert page.items[1].text == 'annotation 3' def",
"first_page.items[0].text == 'annotation 2' assert first_page.items[1].text == 'annotation 1' second_page = first_page.next_page assert",
"create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation1 = file.add_sticky_note(\"annotation 1\", 100, 200, 1)",
"1) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) first_page =",
"annotation.type == 'note' assert annotation.last_modified assert annotation.profile.id assert annotation.profile.display_name assert annotation.document().id == doc.id",
"assert first_page.count == 3 assert first_page.items[0].text == 'annotation 2' assert first_page.items[1].text == 'annotation",
"= file.add_sticky_note(\"annotation 2\", 100, 200, 1) annotation3 = file.add_sticky_note(\"annotation 3\", 100, 200, 1)",
"= session.annotations.list() assert len(page.items) == 1 assert page.count == 1 annotation = page.items[0]",
"1 assert second_page.count == 3 assert second_page.items[0].text == 'annotation 3' def test_should_list_annotations_modified_since(): session",
"annotation.document().id == doc.id assert annotation.document().title == doc.title def test_should_page_through_annotations(): session = get_user_session() delete_all_documents()",
"== doc.id assert annotation.document().title == doc.title def test_should_page_through_annotations(): session = get_user_session() delete_all_documents() with",
"doc = create_document(session) file = doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\", 100, 200, 1) file.add_sticky_note(\"annotation 2\",",
"second_page.items[0].text == 'annotation 3' def test_should_list_annotations_modified_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc",
"page.count == 1 annotation = page.items[0] assert annotation.text == \"A nice annotation\" assert",
"100, 200, 1) annotation2 = file.add_sticky_note(\"annotation 2\", 100, 200, 1) annotation3 = file.add_sticky_note(\"annotation",
"assert annotation.profile.id assert annotation.profile.display_name assert annotation.document().id == doc.id assert annotation.document().title == doc.title def",
"= get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc = create_document(session) file = doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\",",
"1) page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items) == 2 assert page.count == 2 assert",
"annotation.document().title == doc.title def test_should_page_through_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc =",
"3\", 100, 200, 1) page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items) == 2 assert page.count",
"doc.add_note(\"A nice annotation\") page = session.annotations.list() assert len(page.items) == 1 assert page.count ==",
"file = doc.attach_file('fixtures/resources/files/basket.txt') annotation = file.add_sticky_note(\"annotation 1\", 100, 200, 1) sleep(2) file.add_sticky_note(\"annotation 2\",",
"assert len(page.items) == 2 assert page.count == 2 assert page.items[0].text == 'annotation 2'",
"200, 1) annotation1.delete() sleep(2) annotation2.delete() annotation3.delete() page = session.annotations.list(deleted_since=annotation3.created.replace(seconds=+1)) assert len(page.items) == 2",
"cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc = create_document(session) doc.add_note(\"A nice annotation\") page = session.annotations.list() assert len(page.items) ==",
"'annotation 3' def test_should_list_annotations_modified_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc = create_document(session,",
"annotation.last_modified assert annotation.profile.id assert annotation.profile.display_name assert annotation.document().id == doc.id assert annotation.document().title == doc.title",
"import get_user_session, cassette, sleep from test.resources.documents import create_document, delete_all_documents def test_should_list_annotations(): session =",
"test_should_list_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc = create_document(session) doc.add_note(\"A nice annotation\")",
"import create_document, delete_all_documents def test_should_list_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc =",
"'annotation 1' second_page = first_page.next_page assert len(second_page.items) == 1 assert second_page.count == 3",
"'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation1 = file.add_sticky_note(\"annotation 1\", 100, 200, 1) annotation2",
"2\", 100, 200, 1) annotation3 = file.add_sticky_note(\"annotation 3\", 100, 200, 1) annotation1.delete() sleep(2)",
"assert annotation.document().title == doc.title def test_should_page_through_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc",
"3' def test_should_list_annotations_modified_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc = create_document(session, 'title",
"def test_should_list_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc = create_document(session) doc.add_note(\"A nice",
"cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation1 = file.add_sticky_note(\"annotation 1\",",
"page.items[0] assert annotation.text == \"A nice annotation\" assert annotation.privacy_level == 'private' assert annotation.type",
"first_page.count == 3 assert first_page.items[0].text == 'annotation 2' assert first_page.items[1].text == 'annotation 1'",
"1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation = file.add_sticky_note(\"annotation 1\", 100, 200, 1) sleep(2) file.add_sticky_note(\"annotation",
"page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items) == 2 assert page.count == 2 assert page.items[0].text",
"annotation.profile.id assert annotation.profile.display_name assert annotation.document().id == doc.id assert annotation.document().title == doc.title def test_should_page_through_annotations():",
"file.add_sticky_note(\"annotation 2\", 100, 200, 1) annotation3 = file.add_sticky_note(\"annotation 3\", 100, 200, 1) annotation1.delete()",
"get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation",
"assert annotation.text == \"A nice annotation\" assert annotation.privacy_level == 'private' assert annotation.type ==",
"1 assert page.count == 1 annotation = page.items[0] assert annotation.text == \"A nice",
"session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc = create_document(session, 'title 1') file =",
"1) annotation1.delete() sleep(2) annotation2.delete() annotation3.delete() page = session.annotations.list(deleted_since=annotation3.created.replace(seconds=+1)) assert len(page.items) == 2 assert",
"100, 200, 1) annotation1.delete() sleep(2) annotation2.delete() annotation3.delete() page = session.annotations.list(deleted_since=annotation3.created.replace(seconds=+1)) assert len(page.items) ==",
"1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items) == 2",
"def test_should_page_through_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc = create_document(session) file =",
"200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items) ==",
"file.add_sticky_note(\"annotation 1\", 100, 200, 1) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100,",
"with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc = create_document(session) doc.add_note(\"A nice annotation\") page = session.annotations.list() assert len(page.items)",
"doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation = file.add_sticky_note(\"annotation 1\", 100,",
"= get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt')",
"annotation1.delete() sleep(2) annotation2.delete() annotation3.delete() page = session.annotations.list(deleted_since=annotation3.created.replace(seconds=+1)) assert len(page.items) == 2 assert page.count",
"1' second_page = first_page.next_page assert len(second_page.items) == 1 assert second_page.count == 3 assert",
"'annotation 3' def test_should_list_annotations_deleted_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc = create_document(session,",
"= doc.attach_file('fixtures/resources/files/basket.txt') annotation1 = file.add_sticky_note(\"annotation 1\", 100, 200, 1) annotation2 = file.add_sticky_note(\"annotation 2\",",
"get_user_session, cassette, sleep from test.resources.documents import create_document, delete_all_documents def test_should_list_annotations(): session = get_user_session()",
"cassette, sleep from test.resources.documents import create_document, delete_all_documents def test_should_list_annotations(): session = get_user_session() delete_all_documents()",
"delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation1 =",
"200, 1) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) first_page",
"annotation\" assert annotation.privacy_level == 'private' assert annotation.type == 'note' assert annotation.last_modified assert annotation.profile.id",
"file.add_sticky_note(\"annotation 1\", 100, 200, 1) annotation2 = file.add_sticky_note(\"annotation 2\", 100, 200, 1) annotation3",
"annotation\") page = session.annotations.list() assert len(page.items) == 1 assert page.count == 1 annotation",
"= page.items[0] assert annotation.text == \"A nice annotation\" assert annotation.privacy_level == 'private' assert",
"file.add_sticky_note(\"annotation 1\", 100, 200, 1) sleep(2) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\",",
"assert page.items[1].text == 'annotation 3' def test_should_list_annotations_deleted_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'):",
"file = doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\", 100, 200, 1) file.add_sticky_note(\"annotation 2\", 100, 200, 1)",
"cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation = file.add_sticky_note(\"annotation 1\",",
"200, 1) page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items) == 2 assert page.count == 2",
"assert annotation.profile.display_name assert annotation.document().id == doc.id assert annotation.document().title == doc.title def test_should_page_through_annotations(): session",
"delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation =",
"== 2 assert first_page.count == 3 assert first_page.items[0].text == 'annotation 2' assert first_page.items[1].text",
"test.resources.documents import create_document, delete_all_documents def test_should_list_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc",
"200, 1) sleep(2) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1)",
"\"A nice annotation\" assert annotation.privacy_level == 'private' assert annotation.type == 'note' assert annotation.last_modified",
"200, 1) annotation2 = file.add_sticky_note(\"annotation 2\", 100, 200, 1) annotation3 = file.add_sticky_note(\"annotation 3\",",
"== 1 annotation = page.items[0] assert annotation.text == \"A nice annotation\" assert annotation.privacy_level",
"= create_document(session) doc.add_note(\"A nice annotation\") page = session.annotations.list() assert len(page.items) == 1 assert",
"= first_page.next_page assert len(second_page.items) == 1 assert second_page.count == 3 assert second_page.items[0].text ==",
"2' assert first_page.items[1].text == 'annotation 1' second_page = first_page.next_page assert len(second_page.items) == 1",
"assert annotation.last_modified assert annotation.profile.id assert annotation.profile.display_name assert annotation.document().id == doc.id assert annotation.document().title ==",
"annotation1 = file.add_sticky_note(\"annotation 1\", 100, 200, 1) annotation2 = file.add_sticky_note(\"annotation 2\", 100, 200,",
"== 3 assert second_page.items[0].text == 'annotation 3' def test_should_list_annotations_modified_since(): session = get_user_session() delete_all_documents()",
"test_should_list_annotations_deleted_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc = create_document(session, 'title 1') file",
"annotation.text == \"A nice annotation\" assert annotation.privacy_level == 'private' assert annotation.type == 'note'",
"200, 1) first_page = session.annotations.list(page_size=2) assert len(first_page.items) == 2 assert first_page.count == 3",
"= create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation = file.add_sticky_note(\"annotation 1\", 100, 200,",
"get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc = create_document(session) doc.add_note(\"A nice annotation\") page = session.annotations.list()",
"100, 200, 1) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1)",
"create_document(session) doc.add_note(\"A nice annotation\") page = session.annotations.list() assert len(page.items) == 1 assert page.count",
"== 'annotation 2' assert first_page.items[1].text == 'annotation 1' second_page = first_page.next_page assert len(second_page.items)",
"== 'annotation 3' def test_should_list_annotations_modified_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc =",
"file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1))",
"annotation = file.add_sticky_note(\"annotation 1\", 100, 200, 1) sleep(2) file.add_sticky_note(\"annotation 2\", 100, 200, 1)",
"delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc = create_document(session) file = doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\", 100, 200,",
"test import get_user_session, cassette, sleep from test.resources.documents import create_document, delete_all_documents def test_should_list_annotations(): session",
"2 assert page.items[0].text == 'annotation 2' assert page.items[1].text == 'annotation 3' def test_should_list_annotations_deleted_since():",
"len(second_page.items) == 1 assert second_page.count == 3 assert second_page.items[0].text == 'annotation 3' def",
"1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation1 = file.add_sticky_note(\"annotation 1\", 100, 200, 1) annotation2 =",
"first_page.next_page assert len(second_page.items) == 1 assert second_page.count == 3 assert second_page.items[0].text == 'annotation",
"nice annotation\") page = session.annotations.list() assert len(page.items) == 1 assert page.count == 1",
"nice annotation\" assert annotation.privacy_level == 'private' assert annotation.type == 'note' assert annotation.last_modified assert",
"doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\", 100, 200, 1) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\",",
"assert annotation.type == 'note' assert annotation.last_modified assert annotation.profile.id assert annotation.profile.display_name assert annotation.document().id ==",
"3\", 100, 200, 1) annotation1.delete() sleep(2) annotation2.delete() annotation3.delete() page = session.annotations.list(deleted_since=annotation3.created.replace(seconds=+1)) assert len(page.items)",
"doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation1 = file.add_sticky_note(\"annotation 1\", 100,",
"2 assert first_page.count == 3 assert first_page.items[0].text == 'annotation 2' assert first_page.items[1].text ==",
"assert first_page.items[1].text == 'annotation 1' second_page = first_page.next_page assert len(second_page.items) == 1 assert",
"with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation = file.add_sticky_note(\"annotation",
"1) annotation3 = file.add_sticky_note(\"annotation 3\", 100, 200, 1) annotation1.delete() sleep(2) annotation2.delete() annotation3.delete() page",
"from test import get_user_session, cassette, sleep from test.resources.documents import create_document, delete_all_documents def test_should_list_annotations():",
"= create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation1 = file.add_sticky_note(\"annotation 1\", 100, 200,",
"assert page.count == 2 assert page.items[0].text == 'annotation 2' assert page.items[1].text == 'annotation",
"annotation.profile.display_name assert annotation.document().id == doc.id assert annotation.document().title == doc.title def test_should_page_through_annotations(): session =",
"doc.id assert annotation.document().title == doc.title def test_should_page_through_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'):",
"delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc = create_document(session) doc.add_note(\"A nice annotation\") page = session.annotations.list() assert",
"annotation3 = file.add_sticky_note(\"annotation 3\", 100, 200, 1) annotation1.delete() sleep(2) annotation2.delete() annotation3.delete() page =",
"assert second_page.count == 3 assert second_page.items[0].text == 'annotation 3' def test_should_list_annotations_modified_since(): session =",
"file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) first_page = session.annotations.list(page_size=2)",
"== 2 assert page.count == 2 assert page.items[0].text == 'annotation 2' assert page.items[1].text",
"from test.resources.documents import create_document, delete_all_documents def test_should_list_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'):",
"== 'note' assert annotation.last_modified assert annotation.profile.id assert annotation.profile.display_name assert annotation.document().id == doc.id assert",
"session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc = create_document(session) doc.add_note(\"A nice annotation\") page",
"assert len(second_page.items) == 1 assert second_page.count == 3 assert second_page.items[0].text == 'annotation 3'",
"session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc = create_document(session) file = doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation",
"page.items[0].text == 'annotation 2' assert page.items[1].text == 'annotation 3' def test_should_list_annotations_deleted_since(): session =",
"'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation = file.add_sticky_note(\"annotation 1\", 100, 200, 1) sleep(2)",
"with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation1 = file.add_sticky_note(\"annotation",
"1 annotation = page.items[0] assert annotation.text == \"A nice annotation\" assert annotation.privacy_level ==",
"file.add_sticky_note(\"annotation 3\", 100, 200, 1) first_page = session.annotations.list(page_size=2) assert len(first_page.items) == 2 assert",
"test_should_list_annotations_modified_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc = create_document(session, 'title 1') file",
"2 assert page.count == 2 assert page.items[0].text == 'annotation 2' assert page.items[1].text ==",
"3' def test_should_list_annotations_deleted_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc = create_document(session, 'title",
"assert page.items[0].text == 'annotation 2' assert page.items[1].text == 'annotation 3' def test_should_list_annotations_deleted_since(): session",
"session.annotations.list(page_size=2) assert len(first_page.items) == 2 assert first_page.count == 3 assert first_page.items[0].text == 'annotation",
"first_page = session.annotations.list(page_size=2) assert len(first_page.items) == 2 assert first_page.count == 3 assert first_page.items[0].text",
"= session.annotations.list(page_size=2) assert len(first_page.items) == 2 assert first_page.count == 3 assert first_page.items[0].text ==",
"page.items[1].text == 'annotation 3' def test_should_list_annotations_deleted_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc",
"sleep(2) annotation2.delete() annotation3.delete() page = session.annotations.list(deleted_since=annotation3.created.replace(seconds=+1)) assert len(page.items) == 2 assert page.count ==",
"2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert",
"1) sleep(2) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) page",
"1\", 100, 200, 1) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200,",
"'private' assert annotation.type == 'note' assert annotation.last_modified assert annotation.profile.id assert annotation.profile.display_name assert annotation.document().id",
"100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items)",
"== 'annotation 1' second_page = first_page.next_page assert len(second_page.items) == 1 assert second_page.count ==",
"len(page.items) == 2 assert page.count == 2 assert page.items[0].text == 'annotation 2' assert",
"3 assert first_page.items[0].text == 'annotation 2' assert first_page.items[1].text == 'annotation 1' second_page =",
"doc = create_document(session) doc.add_note(\"A nice annotation\") page = session.annotations.list() assert len(page.items) == 1",
"file.add_sticky_note(\"annotation 3\", 100, 200, 1) annotation1.delete() sleep(2) annotation2.delete() annotation3.delete() page = session.annotations.list(deleted_since=annotation3.created.replace(seconds=+1)) assert",
"get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc = create_document(session) file = doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\", 100,",
"= file.add_sticky_note(\"annotation 1\", 100, 200, 1) sleep(2) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation",
"2' assert page.items[1].text == 'annotation 3' def test_should_list_annotations_deleted_since(): session = get_user_session() delete_all_documents() with",
"file.add_sticky_note(\"annotation 3\", 100, 200, 1) page = session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items) == 2 assert",
"file = doc.attach_file('fixtures/resources/files/basket.txt') annotation1 = file.add_sticky_note(\"annotation 1\", 100, 200, 1) annotation2 = file.add_sticky_note(\"annotation",
"second_page = first_page.next_page assert len(second_page.items) == 1 assert second_page.count == 3 assert second_page.items[0].text",
"page.count == 2 assert page.items[0].text == 'annotation 2' assert page.items[1].text == 'annotation 3'",
"annotation2.delete() annotation3.delete() page = session.annotations.list(deleted_since=annotation3.created.replace(seconds=+1)) assert len(page.items) == 2 assert page.count == 2",
"100, 200, 1) sleep(2) file.add_sticky_note(\"annotation 2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200,",
"doc.title def test_should_page_through_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc = create_document(session) file",
"3\", 100, 200, 1) first_page = session.annotations.list(page_size=2) assert len(first_page.items) == 2 assert first_page.count",
"= session.annotations.list(modified_since=annotation.created.replace(seconds=+1)) assert len(page.items) == 2 assert page.count == 2 assert page.items[0].text ==",
"create_document, delete_all_documents def test_should_list_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc = create_document(session)",
"create_document(session) file = doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\", 100, 200, 1) file.add_sticky_note(\"annotation 2\", 100, 200,",
"200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) first_page = session.annotations.list(page_size=2) assert len(first_page.items) ==",
"doc.attach_file('fixtures/resources/files/basket.txt') annotation1 = file.add_sticky_note(\"annotation 1\", 100, 200, 1) annotation2 = file.add_sticky_note(\"annotation 2\", 100,",
"= file.add_sticky_note(\"annotation 3\", 100, 200, 1) annotation1.delete() sleep(2) annotation2.delete() annotation3.delete() page = session.annotations.list(deleted_since=annotation3.created.replace(seconds=+1))",
"'annotation 2' assert first_page.items[1].text == 'annotation 1' second_page = first_page.next_page assert len(second_page.items) ==",
"assert len(page.items) == 1 assert page.count == 1 annotation = page.items[0] assert annotation.text",
"== 'private' assert annotation.type == 'note' assert annotation.last_modified assert annotation.profile.id assert annotation.profile.display_name assert",
"200, 1) annotation3 = file.add_sticky_note(\"annotation 3\", 100, 200, 1) annotation1.delete() sleep(2) annotation2.delete() annotation3.delete()",
"assert first_page.items[0].text == 'annotation 2' assert first_page.items[1].text == 'annotation 1' second_page = first_page.next_page",
"= doc.attach_file('fixtures/resources/files/basket.txt') annotation = file.add_sticky_note(\"annotation 1\", 100, 200, 1) sleep(2) file.add_sticky_note(\"annotation 2\", 100,",
"sleep from test.resources.documents import create_document, delete_all_documents def test_should_list_annotations(): session = get_user_session() delete_all_documents() with",
"== 'annotation 3' def test_should_list_annotations_deleted_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc =",
"100, 200, 1) annotation3 = file.add_sticky_note(\"annotation 3\", 100, 200, 1) annotation1.delete() sleep(2) annotation2.delete()",
"len(page.items) == 1 assert page.count == 1 annotation = page.items[0] assert annotation.text ==",
"def test_should_list_annotations_modified_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'): doc = create_document(session, 'title 1')",
"get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc = create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation1",
"delete_all_documents def test_should_list_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc = create_document(session) doc.add_note(\"A",
"1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) first_page = session.annotations.list(page_size=2) assert len(first_page.items) == 2",
"== doc.title def test_should_page_through_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc = create_document(session)",
"second_page.count == 3 assert second_page.items[0].text == 'annotation 3' def test_should_list_annotations_modified_since(): session = get_user_session()",
"= file.add_sticky_note(\"annotation 1\", 100, 200, 1) annotation2 = file.add_sticky_note(\"annotation 2\", 100, 200, 1)",
"annotation.privacy_level == 'private' assert annotation.type == 'note' assert annotation.last_modified assert annotation.profile.id assert annotation.profile.display_name",
"= create_document(session) file = doc.attach_file('fixtures/resources/files/basket.txt') file.add_sticky_note(\"annotation 1\", 100, 200, 1) file.add_sticky_note(\"annotation 2\", 100,",
"annotation = page.items[0] assert annotation.text == \"A nice annotation\" assert annotation.privacy_level == 'private'",
"'annotation 2' assert page.items[1].text == 'annotation 3' def test_should_list_annotations_deleted_since(): session = get_user_session() delete_all_documents()",
"100, 200, 1) first_page = session.annotations.list(page_size=2) assert len(first_page.items) == 2 assert first_page.count ==",
"'note' assert annotation.last_modified assert annotation.profile.id assert annotation.profile.display_name assert annotation.document().id == doc.id assert annotation.document().title",
"len(first_page.items) == 2 assert first_page.count == 3 assert first_page.items[0].text == 'annotation 2' assert",
"annotation2 = file.add_sticky_note(\"annotation 2\", 100, 200, 1) annotation3 = file.add_sticky_note(\"annotation 3\", 100, 200,",
"page = session.annotations.list() assert len(page.items) == 1 assert page.count == 1 annotation =",
"100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) first_page = session.annotations.list(page_size=2) assert len(first_page.items)",
"assert annotation.privacy_level == 'private' assert annotation.type == 'note' assert annotation.last_modified assert annotation.profile.id assert",
"= get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/list_annotations.yaml'): doc = create_document(session) doc.add_note(\"A nice annotation\") page =",
"def test_should_list_annotations_deleted_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc = create_document(session, 'title 1')",
"== 1 assert page.count == 1 annotation = page.items[0] assert annotation.text == \"A",
"1\", 100, 200, 1) annotation2 = file.add_sticky_note(\"annotation 2\", 100, 200, 1) annotation3 =",
"session.annotations.list() assert len(page.items) == 1 assert page.count == 1 annotation = page.items[0] assert",
"test_should_page_through_annotations(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/page_through_annotations.yaml'): doc = create_document(session) file = doc.attach_file('fixtures/resources/files/basket.txt')",
"2\", 100, 200, 1) file.add_sticky_note(\"annotation 3\", 100, 200, 1) first_page = session.annotations.list(page_size=2) assert",
"assert second_page.items[0].text == 'annotation 3' def test_should_list_annotations_modified_since(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/modified_since.yaml'):",
"== \"A nice annotation\" assert annotation.privacy_level == 'private' assert annotation.type == 'note' assert",
"create_document(session, 'title 1') file = doc.attach_file('fixtures/resources/files/basket.txt') annotation = file.add_sticky_note(\"annotation 1\", 100, 200, 1)",
"session = get_user_session() delete_all_documents() with cassette('fixtures/resources/annotations/list_annotations/deleted_since.yaml'): doc = create_document(session, 'title 1') file =",
"== 'annotation 2' assert page.items[1].text == 'annotation 3' def test_should_list_annotations_deleted_since(): session = get_user_session()",
"assert len(first_page.items) == 2 assert first_page.count == 3 assert first_page.items[0].text == 'annotation 2'",
"assert annotation.document().id == doc.id assert annotation.document().title == doc.title def test_should_page_through_annotations(): session = get_user_session()",
"== 1 assert second_page.count == 3 assert second_page.items[0].text == 'annotation 3' def test_should_list_annotations_modified_since():"
] |
[
"hive_sbi_api.core.models import Transaction class TransactionFilter(filters.FilterSet): account = filters.CharFilter( field_name='account__account', label='account', ) sponsor =",
"filters.CharFilter( field_name='sponsees__account__account', label='sponsee', ) class Meta: model = Transaction fields = ( 'source',",
"as filters from hive_sbi_api.core.models import Transaction class TransactionFilter(filters.FilterSet): account = filters.CharFilter( field_name='account__account', label='account',",
"import Transaction class TransactionFilter(filters.FilterSet): account = filters.CharFilter( field_name='account__account', label='account', ) sponsor = filters.CharFilter(",
"filters.CharFilter( field_name='account__account', label='account', ) sponsor = filters.CharFilter( field_name='sponsor__account', label='sponsor', ) sponsee = filters.CharFilter(",
"field_name='sponsor__account', label='sponsor', ) sponsee = filters.CharFilter( field_name='sponsees__account__account', label='sponsee', ) class Meta: model =",
"label='sponsor', ) sponsee = filters.CharFilter( field_name='sponsees__account__account', label='sponsee', ) class Meta: model = Transaction",
") sponsor = filters.CharFilter( field_name='sponsor__account', label='sponsor', ) sponsee = filters.CharFilter( field_name='sponsees__account__account', label='sponsee', )",
"= filters.CharFilter( field_name='account__account', label='account', ) sponsor = filters.CharFilter( field_name='sponsor__account', label='sponsor', ) sponsee =",
"model = Transaction fields = ( 'source', 'account', 'sponsor', 'status', 'share_type', 'sponsee', )",
"import rest_framework as filters from hive_sbi_api.core.models import Transaction class TransactionFilter(filters.FilterSet): account = filters.CharFilter(",
"from hive_sbi_api.core.models import Transaction class TransactionFilter(filters.FilterSet): account = filters.CharFilter( field_name='account__account', label='account', ) sponsor",
"filters.CharFilter( field_name='sponsor__account', label='sponsor', ) sponsee = filters.CharFilter( field_name='sponsees__account__account', label='sponsee', ) class Meta: model",
"filters from hive_sbi_api.core.models import Transaction class TransactionFilter(filters.FilterSet): account = filters.CharFilter( field_name='account__account', label='account', )",
"class TransactionFilter(filters.FilterSet): account = filters.CharFilter( field_name='account__account', label='account', ) sponsor = filters.CharFilter( field_name='sponsor__account', label='sponsor',",
"= filters.CharFilter( field_name='sponsor__account', label='sponsor', ) sponsee = filters.CharFilter( field_name='sponsees__account__account', label='sponsee', ) class Meta:",
"field_name='sponsees__account__account', label='sponsee', ) class Meta: model = Transaction fields = ( 'source', 'account',",
"class Meta: model = Transaction fields = ( 'source', 'account', 'sponsor', 'status', 'share_type',",
"field_name='account__account', label='account', ) sponsor = filters.CharFilter( field_name='sponsor__account', label='sponsor', ) sponsee = filters.CharFilter( field_name='sponsees__account__account',",
"Meta: model = Transaction fields = ( 'source', 'account', 'sponsor', 'status', 'share_type', 'sponsee',",
"account = filters.CharFilter( field_name='account__account', label='account', ) sponsor = filters.CharFilter( field_name='sponsor__account', label='sponsor', ) sponsee",
"TransactionFilter(filters.FilterSet): account = filters.CharFilter( field_name='account__account', label='account', ) sponsor = filters.CharFilter( field_name='sponsor__account', label='sponsor', )",
"Transaction class TransactionFilter(filters.FilterSet): account = filters.CharFilter( field_name='account__account', label='account', ) sponsor = filters.CharFilter( field_name='sponsor__account',",
"label='account', ) sponsor = filters.CharFilter( field_name='sponsor__account', label='sponsor', ) sponsee = filters.CharFilter( field_name='sponsees__account__account', label='sponsee',",
"from django_filters import rest_framework as filters from hive_sbi_api.core.models import Transaction class TransactionFilter(filters.FilterSet): account",
") class Meta: model = Transaction fields = ( 'source', 'account', 'sponsor', 'status',",
"= filters.CharFilter( field_name='sponsees__account__account', label='sponsee', ) class Meta: model = Transaction fields = (",
"sponsor = filters.CharFilter( field_name='sponsor__account', label='sponsor', ) sponsee = filters.CharFilter( field_name='sponsees__account__account', label='sponsee', ) class",
"django_filters import rest_framework as filters from hive_sbi_api.core.models import Transaction class TransactionFilter(filters.FilterSet): account =",
"rest_framework as filters from hive_sbi_api.core.models import Transaction class TransactionFilter(filters.FilterSet): account = filters.CharFilter( field_name='account__account',",
"label='sponsee', ) class Meta: model = Transaction fields = ( 'source', 'account', 'sponsor',",
") sponsee = filters.CharFilter( field_name='sponsees__account__account', label='sponsee', ) class Meta: model = Transaction fields",
"sponsee = filters.CharFilter( field_name='sponsees__account__account', label='sponsee', ) class Meta: model = Transaction fields ="
] |
[
"Graphcore Ltd. All rights reserved. class UnsupportedFormat(TypeError): pass class DimensionError(ValueError): pass class MissingArgumentException(ValueError):",
"Copyright (c) 2021 Graphcore Ltd. All rights reserved. class UnsupportedFormat(TypeError): pass class DimensionError(ValueError):",
"# Copyright (c) 2021 Graphcore Ltd. All rights reserved. class UnsupportedFormat(TypeError): pass class",
"Ltd. All rights reserved. class UnsupportedFormat(TypeError): pass class DimensionError(ValueError): pass class MissingArgumentException(ValueError): pass",
"rights reserved. class UnsupportedFormat(TypeError): pass class DimensionError(ValueError): pass class MissingArgumentException(ValueError): pass class InvalidPrecisionException(NameError):",
"UnsupportedFormat(TypeError): pass class DimensionError(ValueError): pass class MissingArgumentException(ValueError): pass class InvalidPrecisionException(NameError): pass class UnallowedConfigurationError(ValueError):",
"2021 Graphcore Ltd. All rights reserved. class UnsupportedFormat(TypeError): pass class DimensionError(ValueError): pass class",
"(c) 2021 Graphcore Ltd. All rights reserved. class UnsupportedFormat(TypeError): pass class DimensionError(ValueError): pass",
"pass class DimensionError(ValueError): pass class MissingArgumentException(ValueError): pass class InvalidPrecisionException(NameError): pass class UnallowedConfigurationError(ValueError): pass",
"reserved. class UnsupportedFormat(TypeError): pass class DimensionError(ValueError): pass class MissingArgumentException(ValueError): pass class InvalidPrecisionException(NameError): pass",
"class UnsupportedFormat(TypeError): pass class DimensionError(ValueError): pass class MissingArgumentException(ValueError): pass class InvalidPrecisionException(NameError): pass class",
"All rights reserved. class UnsupportedFormat(TypeError): pass class DimensionError(ValueError): pass class MissingArgumentException(ValueError): pass class"
] |